
/**
 * Extended methods for bas JavaScript classes
 */

/**
 * Extends the base String class
 */
String.extend({
    
    /**
     * get the n left chars of the string
     * @param {Integer} iCHars number of chars to return
     */
    left: function(iChars) {
        
        return this.substr(0,iChars);
    },

    /**
     * get the n right chars of the string
     * @param {Integer} iCHars number of chars to return
     */
    right: function(iChars) {
        
        return this.substr(this.length-iChars,iChars);
    },
    
    /**
     * determine if a given substring is contained within the string
     * @param {String} sSearch substring to search for
     */
    contains: function(sSearch) {
        
        if(this.search(new RegExp(sSearch)) != -1)
            return true;
        else
            return false;
    },
    
    /**
     * parse a RCCL formatted date string into sortable string
     */
    parseRCCLDate: function() {
        
        var sNewDate = "";

		//use empty space in split instead of dash because the date 
		//returned is separated by empty space.        
        //var aDate = this.split("-");
        var aDate = this.split(" ");
        
        if(aDate.length == 3) {

            sNewDate += aDate[2];

            switch(aDate[1].toLowerCase()) {

                case "jan":
                    sNewDate += "01";
                    break;
                case "feb":
                    sNewDate += "02";
                    break;
                case "mar":
                    sNewDate += "03";
                    break;
                case "apr":
                    sNewDate += "04";
                    break;
                case "may":
                    sNewDate += "05";
                    break;
                case "jun":
                    sNewDate += "06";
                    break;
                case "jul":
                    sNewDate += "07";
                    break;
                case "aug":
                    sNewDate += "08";
                    break;
                case "sep":
                    sNewDate += "09";
                    break;
                case "oct":
                    sNewDate += "10";
                    break;
                case "nov":
                    sNewDate += "11";
                    break;
                case "dec":
                    sNewDate += "12";
                    break;
            }

            if(aDate[0].length == 1) {
                
                aDate[0] = "0"+aDate[0];
            }
            
            sNewDate += aDate[0];
        }

        return sNewDate;
    }
})

/**
 * Extends the base Array class
 */
Array.extend({
    
    /**
     * convert the Array to a string
     */
    serialize: function() {
        
        var sArray = "";

        for(var i=0; i < this.length; i++) {

            if(sArray != "")
                sArray += ","
            
            sArray += '"'+this[i]+'"'
        }

        return sArray;
    }
})

/**
 * Extends the mootools Element class
 */
Element.extend({
    
    /**
     * show a DOM element
     */
    show: function() {
        this.removeClass("hidden");
        this.addClass("displayed");
    },
    
    /**
     * show a DOM element In-line
     * Ideally have a class displayedInline 
     * with style display:inline
     * above show function sets class displayed which uses 
     * style display:block
     */
    showInline: function() {
        this.removeClass("hidden");
        this.removeClass("displayed");
    },
    
    /**
     * hide a DOM element
     */
    hide: function() {
        this.removeClass("displayed");
        this.addClass("hidden");        
    },
    
    /**
     * toggle the display attribute of a DOM element
     */
    toggle: function() {
        
        var sDisplay = this.getStyle("display");

        if(this.hasClass("displayed") || sDisplay == null || sDisplay == "" || sDisplay != "none" )
            this.hide();
        else
            this.show();
    },
    
    /**
     * get the Inner Text of a DOM element
     */
    getInnerText: function() {
        
        if(this.getChildren().length == 0) {

            return this.innerHTML;
        
        } else {
            
            if(this.getElement("label") != null) {
                
                return this.getElement("label").innerHTML;

            } else {

                return this.getChildren()[0].innerHTML;
            }
        }
    },
    
    /**
     * enable PNG transparency for a PNG image in IE6
     */
    fixPNG: function() {

        if(window.ie && !this.src.contains("spacer.gif")) {

            var sRealSrc = this.src;

            this.setAttribute("jsPNGFixSrc",sRealSrc);
            this.src = "/cruisematch/img/spacer.gif";
            this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sRealSrc+"')";
        }
    },
    
    /**
     * get the src attribute of an image. taking into account the fact that the image src may have been modified by a PNG fix
     */
    getImgSrc: function() {
        
        if(window.ie && this.getAttribute("jsPNGFixSrc") != null && this.getAttribute("jsPNGFixSrc") != "") {

            return this.getAttribute("jsPNGFixSrc");
        
        } else {

            return this.src;
        }
    },
    
    /**
     * disable a button element
     */
    disableButton: function() {

        if((this.tagName == "IMG" || this.type == "image") && this.getImgSrc().search(new RegExp("Disabled")) == -1) {
            
            var sRealSrc = this.getImgSrc();
            var sExt = sRealSrc.substr(sRealSrc.length-4,4);

            this.src = sRealSrc.substr(0,sRealSrc.length-4)+"Disabled"+sExt;
            this.fixPNG();
            this.style.cursor = "default";
            
            if(this.tagName == "INPUT" && this.type == "image") {

                this.setAttribute("disabled","disabled");
            }

            this.removeEvents("click");
        }
    },
    
    /**
     * enable a button element
     */
    enableButton: function(sFunc) {
        
        if((this.tagName == "IMG" || this.type == "image") && this.getImgSrc().search(new RegExp("Disabled")) != -1) {

            var sRealSrc = this.getImgSrc();
            var sExt = sRealSrc.substr(sRealSrc.length-4,4);

            this.src = sRealSrc.substr(0,sRealSrc.length-12)+sExt;
            this.fixPNG();
            this.style.cursor = "pointer";
            
            this.removeEvents("click");
            
            if(this.tagName == "INPUT" && this.type == "image") {

                this.setAttribute("disabled","");
            }

            eval("this.addEvent('click',function() {"+sFunc+";})");
        }
    },
    
    /**
     * make a link element unclickable
     */
    nullifyLink: function() {
        
        this.href = "javascript:void(0);";
    },
    
    /**
     * disable a link element by removing the link tag
     */
    disableLink: function(sClass) {
        
        if(this.getChildren()[0]) {

            this.innerHTML = this.getChildren()[0].innerHTML;
            this.addClass(sClass);
        }
    },
    
    /**
     * enable a link element by creating the link tag
     */
    enableLink: function(sClass,sFunc) {
        
        if(!this.getChildren()[0]) {

            var elLink = new Element("a");
            
            elLink.href = "javascript:void(0);"
            elLink.innerHTML = this.getInnerText();
            elLink.addClass(sClass);
            
            eval("elLink.addEvent('click',function() {"+sFunc+";})");

            this.innerHTML = "";
            this.className = "";

            this.appendChild(elLink);
        }
    },
    
    /**
     * disable all form field elements within a form
     */
    disableForm: function() {

        for(var x=0; x < this.elements.length; x++) {

            $(this.elements[x]).disableInput();
        }
    },
    
    /**
     * enable all form field elements within a form
     */
    enableForm: function() {
        
        for(var x=0; x < this.elements.length; x++) {

            $(this.elements[x]).enableInput();
        }
    },
    
    /**
     * remove all rows (TR) from a table element
     */
    clearRows: function() {

        if(this.tagName == "TABLE") {

            for(var i=1; i < this.rows.length; i++) {

                $(this.rows[i]).remove();
                i--;
            }
        }
    },
    
    /**
     * get the value of a selected option in a dropdown (SELECT)
     */
    getSelectedValue: function() {
        
        return this.options[this.selectedIndex].value;
    },
    
    /**
     * set the selected option based on the value in a dropdown (SELECT)
     */
    setSelectedValue: function(sValue) {
	
	if(this.options != null){//added null checking on this.options - venitpjmm
        for(var i=0; i < this.options.length; i++)
            if(this.options[i].value == sValue)
                this.options[i].selected = true;
                }
    },
    
    /**
     * set the value of a form element (INPUT,SELECT)
     */
    injectFormValue: function(sValue) {
        
        if(this.tagName == "INPUT" && this.type == "text")
            this.value = sValue;

        if(this.tagName == "SELECT")
            this.setSelectedValue(sValue);
    },
    
    /**
     * style the rows (TR) of a table element with alternating colors
     */
    stripeTable: function() {

        for(var i=0; i < this.rows.length; i++) {
            
            if(i%2)
                $(this.rows[i]).removeClass("even");
            else
                $(this.rows[i]).addClass("even");
        }
    },
    
    /**
     * disable a form field element (INPUT,SELECT)
     */
    disableInput: function() {
        
        if(window.ie && this.tagName == "INPUT" && this.type == "text") {

            this.setStyle("border","1px solid #ccc");
            this.setStyle("padding","2px");
        }

        this.disabled = "disabled";
    },
    
    /**
     * enable a form field element (INPUT,SELECT)
     */
    enableInput: function() {
        
        if(window.ie && this.tagName == "INPUT" && this.type == "text") {
            
            this.setStyle("border","1px solid #7f9db9");
            this.setStyle("padding","2px");
        }

        this.disabled = "";
    },
    
    /**
     * disable a calendar link icon
     */
    disableCalendar: function() {
        
        this.setStyle("cursor","auto");
        this.src = "/cruisematch/img/icons/caretCalendarDisabled.png";
        this.removeEvents("click");
    },
    
    /**
     * enable a calendar link icon
     */
    enableCalendar: function(sFormField) {
        
        this.setStyle("cursor","pointer");
        this.src = "/cruisematch/img/icons/caretCalendar.gif";
        eval("this.addEvent('click',function(event) {jsCalendar.show(this,event,'"+sFormField+"');});");
    }

});

/*    Script: modalizer.js
    Provides functionality to overlay the window contents with a semi-transparent layer that prevents interaction with page content until it is removed.
    
    Dependencies:
    Mootools - <Moo.js>, <Array.js>, <String.js>, <Function.js>, <Utility.js>, <Dom.js>, <Element.js>
    CNET - <element.cnet.js>
    
    Author:
    Aaron Newton (aaron [dot] newton [at] cnet [dot] com)

    Class: Modalizer
    Provides functionality to overlay the window contents with a semi-transparent layer that prevents interaction with page content until it is removed. This class is intended to be implemented into other classes to provide them access to this functionality.
*/

var Modalizer = new Class({

    getModalOptions: function(){
        return this.modalOptions || {
            elementsToHide: 'select',
            onModalHide: Class.empty,
            onModalShow: Class.empty,
            hideOnClick: true,
            modalStyle: {}
        }
    },
    getDefaultModalStyle: function() {
        return {
            'display':'block',
            'position':'fixed',
            'top':'0px',
            'left':'0px',    
            'width':(window.getScrollWidth()+300)+'px',
            'height':(window.getScrollHeight()+300)+'px',
            'z-index':5000,
            'background-color':'#333',
            'opacity':.8
        }
    },
    /*    Property: setOptions
        Sets the options for the modal overlay.
        
        Arguments:
        options - an object with name/value definitions
        
        See documentation above for options list.
    */
    setModalOptions: function(options){
        this.modalOptions = Object.extend(this.getModalOptions(), options || {});
    },
    /*    Property: setModalStyle
            Sets the style of the modal overlay to those in the object passed in.
            
            Arguments:
            styleObject - object with key/value css properties
            
            Default styleObject:
            (start code){
                'display':'block',
                'position':'fixed',
                'top':'0px',
                'left':'0px',    
                'width':'100%',
                'height':'100%',
                'z-index':this.modalOptions.zIndex,
                'background-color':this.modalOptions.color,
                'opacity':this.modalOptions.opacity
            }(end)

    The object you pass in can contain any portion of this object, and the options you specify will overwrite the defaults; any option you do not specify will remain.        
    */
    setModalStyle: function (styleObject){
        this.modalOptions.modalStyle = styleObject;
        this.modalStyle = Object.extend(this.getDefaultModalStyle(), styleObject);
        if($('modalOverlay'))$('modalOverlay').setStyles(this.modalStyle);
        return(this.modalStyle);
    },
    /*    Property: modalShow
        Shows the modal window.
        
        Arguments:
        options - key/value options object
        
        Options:
        elementsToHide - comma seperated string of selectors to hide when the overlay is applied;
            example: 'select, input, img.someClass'; defaults to 'select'
        modalHide - the funciton that hides the modal window; defaults to 
            "function(){if($('modalOverlay'))$('modalOverlay').hide();}"
        modalShow - the function that shows the modal window; defaults to
            "function(){$('modalOverlay').show('block');}"
        onModalHide - function to execute when the modal window is removed
        onModalShow - function to execute when the modal window appears
        hideOnClick - allow the user to click anywhere on the modal layer to close it; defaults to true.
        modalStyle - a css style object to apply to the modal overlay. See <setModalStyle>.
    */
    modalShow: function(options){
        var overlay = null;
        if($('modalOverlay')) overlay = $('modalOverlay');
        this.setModalOptions(options);
        if(!overlay){
            overlay = new Element('div').setProperty('id','modalOverlay').injectInside(document.body);
        }
        overlay.setStyles(this.setModalStyle(this.modalOptions.modalStyle));
        if(window.ie6) overlay.setStyle('position','absolute');
        if(this.modalOptions.hideOnClick) {
            $('modalOverlay').removeEvents('click').addEvent('click', function(){
                this.modalHide();
            }.bind(this));
        }
        this.modalOptions.onModalShow();
        $('modalOverlay').show('block');
        return this;
    },
    
    /*    Property: modalHide
        Hides the modal layer.
    */
    modalHide: function(){
        this.togglePopThroughElements(1);
        this.modalOptions = this.getModalOptions();
        this.modalOptions.onModalHide();
        if($('modalOverlay'))$('modalOverlay').hide();
        return this;
    },
    togglePopThroughElements: function(opacity){
        this.modalOptions = this.getModalOptions();
        $$(this.modalOptions.elementsToHide).each(function(sel){
            sel.setStyle('opacity', opacity);
        });
    }
});

//legacy namespace
var modalizer = Modalizer;

/**
 * binds all JavaScript funcitonality based on class names and the bindings listed in bindings.js
 */
var Unobtrusive = {

    modules: new Array(),
    
    /**
     * initializes all JavaScript functionality based on class names and bindings
     * @param {Object} scope - the scope of the class name search, defaults to the document body
     */
    init: function(scope) {
        
        if(!scope) { scope = $(document.body); }
		var els = scope.getElementsByTagName("*");
		for(var i=0; i < els.length; i++) {
           	if(els[i].className.length < 1 || els[i].className.indexOf("js") == -1) continue; // skip anything without a className
			var classes = els[i].className.split(" ");
			for(var k=0; k < classes.length; k++) {
				if(classes[k].indexOf("js") == -1) continue;
				var aArgs = classes[k].split("_");
				for(var j=0; j < this.modules.length; j++) {
					if(this.modules[j].name == aArgs[0]) {
						var module = this.modules[j];
						if(module.event == "method") {    
							eval("$(els[i])."+module.func+"();");
						} else if(module.event == "init") {
							eval(module.func+"($(els[i]),["+aArgs.serialize()+"]);");
						} else {
							eval("$(els[i]).addEvent(module.event,function() {"+module.func+"(this,["+aArgs.serialize()+"]);})");
						}
					}
				}
            }
        }
    },
    
    /**
     * adds a JavaScript functionality module to the binding list
     * @param {Object} module - the module object to be added
     */
    addModule: function(module) {
        
        this.modules.push(module);
    }
}

/**
 * creates a page title element for use in printable page layouts
 */
window.addEvent("load", function() {
    var titleImages = $$("div.compCommandLine").getElements("img");
    titleImages.each(function(img) {
        var src = img.getProperty("src")[0];
        //Added null checking - venitfmm
        if(src != null && src.indexOf("spacer.gif") > -1 ) {
            var span = new Element("span");
            span.innerHTML = img.getProperty("alt")[0];
            var header = $$("div.compCommandLine").getElement("h1");
            header.adopt(span);
        }        
    });
});
