var submitted = false;

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

$(document).ready(function()
{
  $('input[type=submit].active').click(function(){
      if( submitted == true ) {
          return false;
      } else {
          submitted = true;
          width = $(this).width();
          $(this).css('background-color','grey');
          return true;
      }
  });
  $('input[type=button].active').click(function(){
      if( submitted == true ) {
          return false;
      } else {
          submitted = true;
          width = $(this).width();
          $(this).css('background-color','grey');
          return true;
      }
  });
});

function enableButtons() {
  submitted = false;
  $('input[type=submit].active').css('background-color','#567891');
  $('input[type=button].active').css('background-color','#567891');

}


function load() {

    // empty function, this can be overridden in the page

    // by any page where we need to call body onload event

}




// Round the argument to 2dp. Note that I

// used to use Number.toFixed() here but that

// failed with IE5.5 SP2 under W2k SP3...

function toFixed2(num) {

    num = Math.round(num * 100.0) / 100.0;

    var str = num + "";

    var index = str.indexOf('.');

    if (index < 0) {

        return num + ".00";

    }

    num += "00";

    return num.substring(0, index + 3);

}


function showImages() {

    for (i = 0; i < document.images.length; i++) {

        if (document.images[i].className == "mImg") {

            document.images[i].style.visibility = "visible";

        }

    }

    //document.getElementById("progressIndicator").style.background = "";

    document.getElementById("progressBar").style.visibility = "hidden";

}


// For submitting to a different action.

function submitForm(field, action) {

    field.form.action = action;

    field.form.submit();

}


// For submitting the enclosing form when the 'enter' key is pressed

function submitenter(form, listener, e)

{

    var keycode;

    if (window.event) keycode = window.event.keyCode;

    else if (e) keycode = e.which;

    else return true;


    if (keycode == 13)

    {

        Tapestry.submit_form(form, listener);

        return false;

    }

    else

        return true;

}


function disableAllSelectOptions(selectedElem) {

    var elems = document.getElementsByTagName("select");

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

        var elem = elems[i];

        elem.disabled = true;

    }

}


function doSubmit(button, url) {

    button.form.action = url;

    return true;

}


function setFormAction(form, url) {

    form.action = url;

    return true;

}


// For disabling just the submit button

function disableButton(button_name) {

    var buttonToDisable = document.getElementById(button_name);

    if (buttonToDisable == null) {

        // This is to handle the Mozilla case

        var buttonsToDisable = document.getElementsByName(button_name);

        if (buttonsToDisable != null)

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

                buttonToDisable = buttonsToDisable.item(i);

                if (buttonToDisable != null) {

                    buttonToDisable.disabled = true;

                }

            }

    }

    if (buttonToDisable != null) {

        buttonToDisable.disabled = true;

    }

}


function disableButtonInvokeLink(elem) {

    if (submitted == true) {

        return false;

    }


    elem.disabled = true;

    elem.parentNode.click();

    submitted = true;

}


function checkValidityAndDisable(elem) {

    if (submitted == true) {

        return false;

    }

    elem.disabled = true;

    submitted = true;

    elem.form.submit();

}


// wrapping text at a certain character.

function wrapText(txt, charPerLine) {

    var tempCharPerLine = charPerLine;

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

        if (i == tempCharPerLine) {

            document.write("<br>");

            tempCharPerLine = tempCharPerLine + charPerLine;

        }

        document.write(txt.charAt(i));

    }

}


var loadingInactiveCalled = false;

function setLoadingInactive() {

    loadingInactiveCalled = true;

}



function getElement(elemId) {

    var elem = document.getElementById(elemId);

    if (elem == null) {

        // This is to handle the Mozilla case

        var elems = document.getElementsByName(elemId);

        if (elems != null)

            elem = elems.item(0);

    }

    return elem;

}


// Detect browser is mozilla or not

var winNavUsrAgn = window.navigator.userAgent.toLowerCase();

var is_mozilla = winNavUsrAgn.indexOf("gecko") != -1;

var bookmarkAllowed = (document.all || window.sidebar);


function getCursorProperty() {

    var browser = navigator.appName;

    if (browser.indexOf("Netscape") >= 0) {

        return "pointer";

    } else {

        return "hand";

    }

}


function ToggleAll(pCheckAll, pCheckboxName, pForm) {

    if (pCheckAll) {

        CheckAll(pCheckboxName, pForm);

    } else {

        ClearAll(pCheckboxName, pForm);

    }

}


function CheckAll(pCheckboxName, pForm) {

    var ml = pForm;

    var len = ml.elements.length;

    for (var i = 0; i < len; i++) {

        var e = ml.elements[i];

        if (e.name == pCheckboxName) {

            e.checked = true;

        }

    }

}


function ClearAll(pCheckboxName, pForm) {

    var ml = pForm;

    var len = ml.elements.length;

    for (var i = 0; i < len; i++) {

        var e = ml.elements[i];

        if (e.name == pCheckboxName) {

            e.checked = false;

        }

    }

}


/**

 *  This function enables the user to add the specified url to the list of favorites in the browser.

 *  This function can be called in the onClick function of the corresponding anchor tag.

 */

function addBookmark(url, bookmarkTitle) {

    if (document.all) {

        window.external.AddFavorite(url, bookmarkTitle);

    } else if (window.sidebar) {

        window.sidebar.addPanel(bookmarkTitle, url, "");

    }

    return true;

}


function emailValidatorAndSubmit(elem, defaultPage) {

    var userTyped = prompt("Email this link to your friend?", "Please type in \"YOUR\" email address!");

    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

    if (userTyped != null) {

        if (userTyped.match(emailExp)) {

            var toEmail = emailValidatorToEmail();

            if (toEmail == null || toEmail == "") {

                alert("Invalid \"TO\" email address is provided. Please try again.");

                return false;

            } else {

                // Go to the new link

                elem.href = "/altos/partner/EmailLink.external?sp=S" + toEmail + "&sp=" + defaultPage + "&sp=" + '\"' + userTyped;

                return true;

            }

        } else {

            alert("Invalid \"FROM\" email address is provided. Please try again.");

            return false;

        }

    }

    return false;

}


function emailValidatorToEmail() {

    var userTyped = prompt("Email this link to your friend?", "Please type in your \"FRIEND'S\" email address!");

    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

    if (userTyped != null) {

        if (userTyped.match(emailExp)) {

            return userTyped;

        } else {

            return null;

        }

    }

    return null;

}


function emailValidatorLoggedIn(elem, defaultPage) {

    var userTyped = emailValidatorToEmail();

    if (userTyped == null || userTyped == "") {

        alert("Invalid email address is provided. Please try again.");

        return false;

    } else {

        // Go to the new link

        elem.href = "/altos/partner/EmailLink.external?sp=S" + userTyped + "&sp=" + defaultPage;

        return true;

    }

}


function usernameRecovery(elem) {

    var userTyped = prompt("Forgot your login name?", "Enter your email address here!");

    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

    if (userTyped != null) {

        if (userTyped.match(emailExp)) {

            // Go to the new link

            elem.href = "/altos/partner/UsernameRecovery.external?sp=S" + userTyped;

            return true;

        } else {

            alert("Invalid email address is provided. Please try again.");

            return false;

        }

    }


    return false;

}


function passwordRecovery(elem) {

    var userTyped = prompt("Forgot your password?", "Enter your login name here!");

    if (userTyped != null) {

        // Go to the new link

        elem.href = "/altos/partner/PasswordRecovery.external?sp=S" + userTyped;

        return true;

    }


    return false;

}


// Detect browser is mozilla or not

var ie = document.all ? true : false;

var isIE7up = (winNavUsrAgn.indexOf('msie') != -1) && (winNavUsrAgn.indexOf('msie 4.') == -1) && (winNavUsrAgn.indexOf('msie 5.') == -1) && (winNavUsrAgn.indexOf('msie 6.') == -1);


/* hides <select> and <applet> objects (for IE only) */

function hideIeElement(elmID, overDiv)

{

    if (ie && !isIE7up)

    {

        for (i = 0; i < document.all.tags(elmID).length; i++)

        {

            obj = document.all.tags(elmID)[i];

            if (!obj || !obj.offsetParent)

            {

                continue;

            }


            // Find the element's offsetTop and offsetLeft relative to the BODY tag.

            objLeft = obj.offsetLeft;

            objTop = obj.offsetTop;

            objParent = obj.offsetParent;


            while (objParent.tagName.toUpperCase() != "BODY")

            {

                objLeft += objParent.offsetLeft;

                objTop += objParent.offsetTop;

                objParent = objParent.offsetParent;

            }


            objHeight = obj.offsetHeight;

            objWidth = obj.offsetWidth;


            if (( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft);

            else if (( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop);

            else if (overDiv.offsetTop >= ( objTop + objHeight ));

                else if (overDiv.offsetLeft >= ( objLeft + objWidth ));

                    else

                    {

                        obj.style.visibility = "hidden";

                    }

        }

    }

}


/*

 * unhides <select> and <applet> objects (for IE only)

 */

function showIeElement(elmID)

{

    if (ie && !isIE7up)

    {

        for (i = 0; i < document.all.tags(elmID).length; i++)

        {

            obj = document.all.tags(elmID)[i];


            if (!obj || !obj.offsetParent)

            {

                continue;

            }


            obj.style.visibility = "";

        }

    }

}


function showOrHideIeElem(pShow, pId) {

    if (pShow) {

        showIeElement('SELECT');

        showIeElement('APPLET');

        showIeElement('OBJECT');

    } else {

        hideIeElement('SELECT', document.getElementById(pId));

        hideIeElement('APPLET', document.getElementById(pId));

        hideIeElement('OBJECT', document.getElementById(pId));

    }

}


// create the prototype on the String object

String.prototype.trim = function() {

    // skip leading and trailing whitespace

    // and return everything in between

    var x = this;

    x = x.replace(/^\s*(.*)/, "$1");

    x = x.replace(/(.*?)\s*$/, "$1");

    return x;

}


// Used to populate the select with the array of [value, label] pairs

function msp_populate_single(selectName, values) {

    var select = document.getElementById(selectName);

    var options = select.options;

    var i;

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

        var newOption = document.createElement("OPTION");

        var vals = values[i];

        newOption.value = vals[0];

        if (vals.length >= 2) {

            newOption.text = vals[1];

        } else {

            newOption.text = newOption.value;

        }

        options[i] = newOption;

    }

    options.length = i;

}


// js Abbreviate

function abbrEnd(pText, pLength) {

    var txtStr = pText;

    if (txtStr != null && txtStr.length > pLength) {

        txtStr = txtStr.substring(0, pLength) + ' ...';

    }

    return txtStr;

}


// Generate a Random Number

function getRandom(pMaxLimit) {

    var randNum = Math.floor(Math.random() * pMaxLimit + 1);

    if (randNum > pMaxLimit) {

        randNum = pMaxLimit;

    }

    return randNum;

}


// validate email address

function isValidEmail(pEmailAddr) {

    var validEmail = true;


    var AT_CHAR = "@";

    var DOT_CHAR = ".";

    var VALID_EMAIL_CHARS = "";

    var INVALID_EMAIL_CHARS = " /\\*#&+|()[]{}=^%$!~`<>?,\":;";


    var VALID_DOMAIN_NAME_SUFFIX_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    var INVALID_DOMAIN_NAME_SUFFIX_CHARS = "";


    var MIN_USER_NAME_LEN = 1;

    var MIN_DOMAIN_NAME_LEN = 1;

    var MIN_DOMAIN_NAME_SUFFIX_LEN = 2;

    var MAX_DOMAIN_NAME_SUFFIX_LEN = 4;


    var MIN_DOMAIN_LEN = (MIN_DOMAIN_NAME_LEN + 1 + MIN_DOMAIN_NAME_SUFFIX_LEN);

    var MIN_EMAIL_LEN = (MIN_USER_NAME_LEN + 1 + MIN_DOMAIN_LEN);


    if (pEmailAddr == null) {

        validEmail = false;

    } else {

        // Check Minimum length of valid email

        if (pEmailAddr.trim().length < MIN_EMAIL_LEN) {

            validEmail = false;

        } else {

            // Check valid/invalid charecters if specified

            if (VALID_EMAIL_CHARS.length > 0) {

                validEmail = checkValidChars(pEmailAddr.trim(), VALID_EMAIL_CHARS);

            } else if (INVALID_EMAIL_CHARS.length > 0) {

                validEmail = !checkInValidChars(pEmailAddr.trim(), INVALID_EMAIL_CHARS);

            }

        }


        if (validEmail) {

            var emailTokens = pEmailAddr.split(AT_CHAR);

            // Check there is text on both sides of @

            if (emailTokens.length != 2) {

                validEmail = false;

            } else {

                var userName = emailTokens[0];

                var domain = emailTokens[1];

                // Check Minimum Username and Domain length

                if (userName.length < MIN_USER_NAME_LEN || domain.length < MIN_DOMAIN_LEN) {

                    validEmail = false;

                } else {

                    // Check there is text on both sides of .

                    var domainTokens = domain.split(DOT_CHAR);

                    var domainTokensSize = domainTokens.length;

                    if (domainTokensSize < 2) {

                        validEmail = false;

                    } else {

                        var domainName = domainTokens[0];

                        // Check minimum domain name length

                        if (domainName.length < MIN_DOMAIN_NAME_LEN) {

                            validEmail = false;

                        } else {

                            var domainSuffix = domainTokens[domainTokensSize - 1];

                            // Check the domain name suffix

                            if (domainSuffix.length < MIN_DOMAIN_NAME_SUFFIX_LEN || domainSuffix.length > MAX_DOMAIN_NAME_SUFFIX_LEN) {

                                validEmail = false;

                            } else {

                                // Check valid/invalid charecters if specified

                                if (VALID_DOMAIN_NAME_SUFFIX_CHARS.length > 0) {

                                    validEmail = checkValidChars(domainSuffix, VALID_DOMAIN_NAME_SUFFIX_CHARS);

                                } else if (INVALID_DOMAIN_NAME_SUFFIX_CHARS.length > 0) {

                                    validEmail = !checkInValidChars(domainSuffix, INVALID_DOMAIN_NAME_SUFFIX_CHARS);

                                }

                            }

                        }

                    }

                }

            }

        }

    }


    return validEmail;

}


// Checks whether the passed in String has only allowed charecters.

function checkValidChars(pStr, pValidChars) {

    var validChars = true;

    if (pStr != null) {

        for (var charIdx = 0; charIdx < pStr.length; charIdx++) {

            var char = pStr.charAt(charIdx);

            if (pValidChars.indexOf(char) == -1) {

                validChars = false;

                break;

            }

        }

    }

    return validChars;

}


// Checks whether the passed in String has any unallowed charecters.

function checkInValidChars(pStr, pInValidChars) {

    var inValidChars = false;

    if (pStr != null) {

        for (var charIdx = 0; charIdx < pInValidChars.length; charIdx++) {

            var char = pInValidChars.charAt(charIdx);

            if (pStr.indexOf(char) != -1) {

                inValidChars = true;

                break;

            }

        }

    }

    return inValidChars;

}

