/**
 * SME base JavaScript.
 *
 * @package    SME
 * @subpackage UI
 * @copyright  Copyright 2009 Spenlen Media, Inc. (http://spenlen.com)
 * @version    $Id$
 */


/**
 * SME global namespace object.
 * @var Object
 */
var SME = {};



SME.Cookie = {
    
    /**
     * Returns the value of the specified cookie.
     *
     * @return String
     */
    get : function (cookieName)
    {
        var cookieValue = document.cookie.match(new RegExp('(^|;)\\s*' + escape(cookieName) + '=([^;\\s]*)'));
        return (cookieValue ? unescape(cookieValue[2]) : '');        
    },
    
    /**
     * Sets the specified browser cookie to the specified value.
     *
     * @param String cookieName
     * @param String cookieValue
     * @param Date   expirationDate (optional) If omitted, defaults to one year
     *   from today.
     */
    set : function (cookieName, cookieValue, expirationDate)
    {
        if (! expirationDate) {
            var expirationDate = new Date();
            expirationDate.setFullYear(expirationDate.getFullYear() + 1);
        }

        /** @todo Write a more appropriate path calculation. */
        newCookie = escape(cookieName) + '=' + escape(cookieValue)
                  + '; expires=' + expirationDate.toUTCString()
                  + '; path=/';
                  
        document.cookie = newCookie;        
    },

    /**
     * Sets the specified browser cookie to the specified value. Does not set
     * an expiration date, so the cookie will die with the browser session.
     *
     * @param String cookieName
     * @param String cookieValue
     */
    setSession : function (cookieName, cookieValue)
    {
        /** @todo Write a more appropriate path calculation. */
        newCookie = escape(cookieName) + '=' + escape(cookieValue)
                  + '; path=/';
                  
        document.cookie = newCookie;        
    }

};


SME.FlashMessage = {
    
    /**
     * Starting color for the color fade animation.
     */
    startColor: '#ffff33',
    
    /**
     * Registers the onclick handler to dismiss the flash message DIV.
     */
    init : function ()
    {
        var message = document.getElementById('flashMessage');
        if (message) {
            Event.observe(message, 'click', SME.FlashMessage.dismiss);
        }
    },

    /**
     * If the flash message DIV is present on the page, animates the background
     * color fading effect.
     */
    flash : function ()
    {
        var message = $('flashMessage');
        if (message) {
            var endColor = message.getStyle('backgroundColor');
            if (! endColor) {
                endColor = '#ffffda';
            } else {
                endColor = endColor.parseColor('#ffffda');
            }
            new Effect.Highlight(
                message,
                {duration:     2.0,
                 startcolor:   SME.FlashMessage.startColor,
                 endcolor:     endColor,
                 restorecolor: endColor}
                );
        }
    },

    /**
     * Dismisses the flash message.
     */
    dismiss : function ()
    {
        var message = document.getElementById('flashMessage');
        if (message) {
            Event.stopObserving(message, 'click', SME.FlashMessage.dismiss);
            new Effect.Opacity(
                message,
                {duration:   0.5,
                 transition: Effect.Transitions.linear,
                 from:       1,
                 to:         0}
                );
        }
        var container = document.getElementById('flashMessageContainer');
        if (container) {
            new Effect.Morph(
                container,
                {duration: 0.6,
                 style: {height: '0px'},
                 delay: 0.2}
                );
        }
    }

}
document.observe('dom:loaded', SME.FlashMessage.init);
Event.observe(window, 'load', SME.FlashMessage.flash);


SME.ModalDialog = {
    
    inDialog: false,
    refocusElement: null,
    
    init : function ()
    {
        $$('A.runModal').each(function (link) {
            Event.observe(link, 'click', SME.ModalDialog.runModalLinkClick.bindAsEventListener(link));            
        });
    },
    
    /**
     * 'onclick' handler for "runModal" navigation links. Opens the link's href
     * in a "modal" dialog DIV.
     *
     * @param Event theEvent
     */
    runModalLinkClick : function (theEvent)
    {
        if (theEvent.preventDefault) {
          theEvent.preventDefault();
        } else {
          theEvent.returnValue = false;
        }
        SME.ModalDialog.start(this.href);        
    },
    
    start : function (requestURI)
    {
        if (SME.ModalDialog.inDialog) {
            return;
        }
        SME.ModalDialog.inDialog = true;
        new Ajax.Updater('modalDialogContent', requestURI,
            {evalScripts: true,
             onComplete: function () {
                 var focusElement = SM_FormMagic_GetElementWithFocus();
                 if (focusElement) {
                     SME.ModalDialog.refocusElement = focusElement;
                     elementWithFocus.blur();
                 }
                 var link = document.createElement('a');
                 link.appendChild(document.createTextNode('Close'));
                 link.id    = 'modalDialogCloseBox';
                 link.title = 'Close';
                 $('modalDialogContent').appendChild(link);
                 SME.ModalDialog.wireDefaultEvents();
                 new Effect.Opacity('modalDialog',
                     {duration: 0.4, from: 0, to: 1,
                      beforeStart: function () {
                          $('modalDialog').setStyle({opacity: 0, display: 'block'});
                      }
                     }
                 );             
             }
            }
        );
        
    },
    
    wireDefaultEvents : function ()
    {
        var link = $('modalDialogCloseBox');
        if (link) {
            Event.observe(link, 'click', SME.ModalDialog.end.bindAsEventListener(link));
        }
        $$('#modalDialogContent .cancelButton').each(function (button) {
            Event.observe(button, 'click', SME.ModalDialog.end.bindAsEventListener(button));
        });
    },

    /**
     * @param Event theEvent (optional)
     */
    end : function (theEvent)
    {
        if (theEvent) {
            Event.stop(theEvent);
        }
        if (! SME.ModalDialog.inDialog) {
            return;
        }
        if (SME.ModalDialog.refocusElement) {
            SME.ModalDialog.refocusElement.focus();
            SME.ModalDialog.refocusElement = null;
        }
        new Effect.Opacity('modalDialog',
            {duration: 0.4, to: 0,
             afterFinish: function () {
                 $('modalDialog').setStyle({display: 'none'});
                 $('modalDialogContent').update('');
                 var successAlert = $('modalDialogSuccessAlert');
                 if (successAlert) {
                     successAlert.remove();
                 }
                 SME.ModalDialog.inDialog = false;
             }                
            }
        );
    },
    
    successAlert : function (messageText)
    {
        var message = $(document.createElement('p'));
        message.appendChild(document.createTextNode(messageText));
        message.id = 'modalDialogSuccessAlert';
        // message.setStyle({opacity: 0});
        $('modalDialog').appendChild(message);

        new Effect.Highlight(
            message,
            {duration:     1,
             startcolor:   '#ffff33',
             endcolor:     '#ffffda',
             restorecolor: '#ffffda',
             afterFinish:  function () { window.setTimeout(SME.ModalDialog.end, 1000); }
            }
        );
    }
    
};
document.observe('dom:loaded', SME.ModalDialog.init);



if (Autocompleter.Base) {
    Autocompleter.Base.addMethods({
        startIndicator : function()
        {
            if (this.options.indicator) {
                if (this.options.onStartIndicator) {
                    this.options.onStartIndicator(this.options.indicator);
                }
                Element.show(this.options.indicator);
            }
        }
    });
}

SME.Form = {
    submitAction : function (button)
    {
        var el = $(button.form).down('input[name="submitButton"]');
        if (el) {
            el.value = button.id.slice(13);
        }
        if (SM_FormMagic_validateForm(button.form)) {
            button.form.submit();
        }
    }
};

SME.Form.Utility = {
    
    progressIndicator: null,
    
    getProgressIndicator : function ()
    {
        if (! SME.Form.Utility.progressIndicator) {
            SME.Form.Utility.progressIndicator = $(document.createElement('DIV'));
            SME.Form.Utility.progressIndicator.id = 'SME_Form_Utility_ProgressIndicator';
            SME.Form.Utility.progressIndicator.setStyle({
                backgroundImage: "url('/images/progress_indicator_form.gif')",
                backgroundPosition: 'center center',
                backgroundRepeat: 'no-repeat',
                display: 'none',
                width: '16px',
                height: '16px',
                position: 'absolute'
            });
            document.body.appendChild(SME.Form.Utility.progressIndicator);
        }
        return SME.Form.Utility.progressIndicator;
    }
    
};
