/**
 * Common utility functions
 *
 * @author Alex Talib - Lava Consulting
 * @version $Id: sports.js,v 1.1 2007/11/29 10:09:30 ahallam Exp $
 */
 		 var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
 	
    /**
     * Actions 
     */
    var ACTION_VIEW_ADD = 0;
    var ACTION_VIEW_EDIT = 1;
    var ACTION_REMOVE = 2;
    var ACTION_ADD = 3;
    var ACTION_UPDATE = 4;
    var ACTION_CANCEL = 5;
    var ACTION_CHANGE_VIEW = 7;
    var ACTION_VIEW = 8;
    var ACTION_LANGUAGE = 9;
    var ACTION_OTHER = 10;
    	 
    /**
     * Log client side messages 
     * Set with enable-client-logging=true
     * 
     * @param elementId, the html id
     */
    var INFO = "info";
    var DEBUG = "debug";
    var TRACE = "trace";
    function log(priority, component, message) {
        var loggingDiv = document.getElementById('loggingcnt');

        if (loggingDiv != null) {
	        loggingDiv.innerHTML =  priority
	                              + " [" + component + "] " 
	                              + message 
	                              + "<br/>"
	                              + loggingDiv.innerHTML;
        }
    }
    
    /**
     * Disable all elements of a form 
     */
    function disableForm(theform) 
    {
        var msg = "";
        if (document.all || document.getElementById) 
        {
            msg += theform.length + " elements";
            for (i = 0; i < theform.length; i++) 
            {
                var tempobj = theform.elements[i];
                msg += "\n" + tempobj.name + ", type=" + tempobj.type + ", value=" + tempobj.value;
                if (   tempobj.type.toLowerCase() == "submit" 
                    || tempobj.type.toLowerCase() == "image"
                    || tempobj.type.toLowerCase() == "reset")
                {
                    tempobj.disabled = true;
                } 
                else 
                {
                    tempobj.readonly = true;
                }
            }
        }
        //alert(msg);
        return true;
    }
 		 
    /**
     * Set an html element visible or invisible by id
     * 
     * @param elementId, the html id
     */
    function setVisible(elementId, bState) { 
    		
        var obj = getElement(elementId);
        
        var oStyle = obj.style;
        
        //if (document.layers) {
        //    sVisible = 'show';
        //}
        
        if (bState)
            oStyle.visibility = 'visible';
        else 
            oStyle.visibility = 'hidden';
    }
 		 
    /**
     * Return an html element by Id
     * 
     * @param elementId, the html id
     */
    function getElement(elementId) { 
    	
        var obj;
        if (document.getElementById) {
            obj = document.getElementById(elementId);
        } else if (document.layers) { 
            obj = document.layers[elementId];
        } else if (document.all) { 
            obj = document.all(elementId);
        }
        //alert("getElement(" + elementId + ") = " + obj);
        return obj;
    }
 		    
				/**
     * Return the style of an element by Id
     * 
     * @param elementId, the html id
     */
    function getElementStyle(elementId) { 
    	
        var obj;
				    if (document.getElementById) {
            obj = document.getElementById(elementId).style;
        } else if (document.layers) { 
            obj = document.layers[elementId];
        } else if (document.all) { 
            obj = document.all(elementId).style;
        }
        return obj;
    }
    
    /**
     * Return an element, given the form and the element name.
     */
    function getElementByName( formname, elementname )
    { 
        var elements = eval( "document." + formname + ".elements" );
        for( var i = 0; i < elements.length; i++ )
        {
            if( elements[i].name == elementname )
            {
                return elements[i];
            }
        }
        return null;
    }
    
    /**
     * Set all the elements id's in a form to be the same as the element names
     */
    function setFormElementIdtoName( formname )
    { 
        var elements = eval( "document." + formname + ".elements" );
        for( var i = 0; i < elements.length; i++ )
        {    
            if (elements[i].name!="")
                elements[i].id = elements[i].name;
        }
    }
 		    
    /**
    * Append a parameter to a string
    */
 		 function appendParameter(p_args, p_name, p_value) {
        if (p_args == "")
		          return p_name+"="+escape(p_value);
		      else
		          return p_args+"&"+p_name+"="+escape(p_value);
    }
 
   /**
    * This variable defines a callback function to be used when the language
    * is changed. This function will be implemented by the main tile.
    * The intention is that if the language is changed and a form is half
    * complete that the values will be saved by the main form handler.
    */
    var changeLanguageHandler=null;
    
   /**
    * Allows the main tile to register it's form
    * 
    * @param func, a function that will implement 
    *              language changing while keeping 
    *              existing form data intact
    */
    function setChangeLanguageHandler(func) {
        changeLanguageHandler = func;
    }

   /**
    * Called by the change locale drop down menu when the user 
    * wants to see a different language. 
    * Calls doLocale if another tile has not implemented it's 
    * own implementation.
    * 
    * @param frm, the main form for this page
    */
    function changeLanguage(lang) {
    	   if (changeLanguageHandler==null) {
    	       window.location='doLocale.html?lang=' + lang;
    	   } else {
            changeLanguageHandler(lang);
    	   }
    }
 
 
    var myimages = new Array();
    
    /**
     * Pre-load browser images
     * 
     * @param any number of arguments which represent url to images to preload
     */
    function preloadImages() {
        log(TRACE, "preloadImages", "preloadImages");
        for (x=0; preloadImages.arguments.length>x; x++) {
            myimages[x] = new Image();
            myimages[x].src = preloadImages.arguments[x];
            log(TRACE, "preloadImages", preloadImages.arguments[x]);
        }
    }
    
    /**
     * Swap an image
     * 
     * @img, the image object
     * @name, the full URL to the image object
     */
    function swapImage(img, name) {
    	   img.src = name;
    }

    /**
     * Implementation of help text to be displayed in
     * the window status bar
     * 
     * @param help, the brief help text that will be displayed in the status bar
     * @param tip, extended tip message that will be displayed at the mouse position
     */
    function showHelp (help, tip) {
        window.status = help;
        if (tip != null && tip!='')
            showtip(tip);
    }
    
    function hideHelp () {
        window.status = '';
        popdown();
    }
    
    /**
    * Set the required process to be applied to this submitted form
    */
    function setFormAction(frm, formAction) {
        frm.formAction.value = formAction;
    }
    
    /**
    * Set the a struts validator form so that it can go back a step
    * without throwing validation errors.
    */
    function setFormAllowBack(frm, previousPage) {
        bCancel=true; 
        frm.page.value=frm.page.value - 1; 
        frm.action=previousPage;
        //alert("setFormAllowBack: frm.page.value: " + frm.page.value);
        //alert("setFormAllowBack: frm.action: " + frm.action);
    }
    
    /**
     * Implementation of help text to be displayed in
     * the window status bar.
     */
    

/**
 * struts-layout core javascript
 *
 * All rights reserved.
 */
// type checking functions

function checkValue(field, property, type, required) {

    if (field.value!="") {
    
        document.images[property + "required"].src= imgsrc + "clearpixel.gif";
        if (type=="NUMBER" && !isNumber(field.value)) document.images[property + "required"].src= imgsrc + "ast.gif";
        if (type=="DATE" && !isDate(field.value)) document.images[property + "required"].src = imgsrc + "ast.gif";
        if (type=="EMAIL" && !isEmail(field.value)) document.images[property + "required"].src= imgsrc + "ast.gif";
    
    } else {    
        if (required) document.images[property + "required"].src= imgsrc + "ast.gif";
    }
}


/**
 * Init dependent combo
 */
function initDependentComboHandler(masterSelectName, childSelectName, jsArrayName, jsChildArrayName) {
    // find the master select.
    var combo = findCombo(masterSelectName);
    if (combo!=null) {
        var customFunction = new Function("return updateCombo('" + masterSelectName + "', '" + childSelectName + "', " + jsArrayName + ", '" + jsChildArrayName + "');");
        combo.onchange = customFunction;
        combo.onchange();
    }
}

function findCombo(comboName) {
    var elements = document.getElementsByTagName("SELECT");
    var combo;
    for (i in elements) {
        if (elements[i].name == comboName) {
            combo = elements[i];
        }
    }
    return combo;
}

/**
 * Update dependent combo.
 * @param masterCombo : the main select object.
 * @param comboName : the name of the child select object.
 * @param jsData : the name of the js data array holding the data.
 * @param jsCollectionProperty : the name of the nested collection property.
 */
function updateCombo(masterComboName, childComboName, jsData, jsCollectionProperty) {
    var masterCombo = findCombo(masterComboName);
    var combo = findCombo(childComboName);

    // get the option list.
    var value = masterCombo.options[masterCombo.selectedIndex].value;

    // get the selected bean
    var selectedValue = masterCombo.options[masterCombo.selectedIndex].value;
    var masterSelectedOption;
    for (i=0; i < jsData.length; i++) {     
        if (jsData[i].value == selectedValue) {
            masterSelectedOption = jsData[i];
            break;
        }
    }

    // remove old options
    while (combo.options.length!=0) {
        combo.remove(0);
    }

    // add new options
    if (masterSelectedOption!=null) {
        var length = eval('masterSelectedOption.' + jsCollectionProperty + '.length'); 
        for (i = 0; i < length; i++) {
            var option = new Option(masterSelectedOption[jsCollectionProperty][i].label, masterSelectedOption[jsCollectionProperty][i].value);
            if (document.all) {
                combo.add(option);
            } else {
                combo.add(option, null);
            }
        }
    }
}


    /**
     * Overide a required validation message, this should 
     * be called after the page has loaded 
     * 
     * @param formName   : the name of the form 
     * @param fieldName  : the name of the field to alter valiation message for
     * @param newMessage : the new message to display instead of default required
     */
    function overideValidateRequiredMessage(formName, fieldName, newMessage) 
    {
        var functionText = paymentForm_required;
        var oRequired = eval('new ' + formName + '_required()');
        for (x in oRequired) 
        {
            if (oRequired[x][0] == fieldName)
            {
                functionText = paymentForm_required.toString().replace(oRequired[x][1], newMessage);
            }
        } 

        // remove function header, opening and closing '{'
        functionText = functionText.substring(functionText.indexOf("{")+1, functionText.length);
        functionText = functionText.substring(0, functionText.lastIndexOf("}"))
        
        // Redefine the required validation function with new messages 
        window.paymentForm_required = new Function(functionText);
    }







