/**
 * Brandsnet Javascript Library
 *
 * @package brands.js
 * @author  Christian Hope <chope@pacbrands.com.au>
 * @copy    Pacific Brands 2003
 */


// This is run on the loading of each page in brandsnet
function brandsInit() {
    try {
        focusInit();
        multiboxInit();
        upperInit();
    } catch(e) {
        if (typeof(console) != 'undefined')
            console.error('brandsInit: '+e);
    }
}

// Load on Dom Ready
window.onDomReady(brandsInit);

function upperInit() {
    $$('.forceUpper').each(function(el) {
        el.addEvent('keyup',function(e) {
            var elem = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : e);
            elem.value = elem.value.toUpperCase();
        });
    });
}

function multiboxInit() {
    if ((typeof(MultiBox) != 'undefined') && ($$('.mb').length != 0))
        new MultiBox('mb', {showControls:true, useOverlay: true});

    if ((typeof(MultiBox) != 'undefined') && ($$('.mbc').length !=0))
        new MultiBox('mbc', {showControls:false, useOverlay: true});

    if ((typeof(MultiBox) != 'undefined') && ($$('.content-mb').length !=0))
        new MultiBox('content-mb', {showControls: false, useOverlay: true, onOpen: hideDD, onClose: showDD});
}

/**
 * Auto Height for Iframes -o0
 * eg <iframe onload="autoHeightIframe(this)" >
 */
function autoHeightIframe( frame ) {
    try{
        innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
        objToResize = ( (frame.height) ? frame : ( (frame.style) ? frame.style : frame ) ); 
        objToResize.height = innerDoc.body.scrollHeight + 10;
    } catch( err ) {
      return false;
    }
    return true;
}


/**
 * doubleClickCheck
 **/
var isClicked = 0;
function doubleClickCheck() {
  if ( isClicked == 0 ) {
    isClicked = 1;
    return true;
  }
  return false;
}


/**
 * Adds a option to a select list the DOM way
 * @param String    Option value
 * @param String    Option text
 * @param String    ID of select list to add option
 */
function addOption(val, txt, id) {

        /* Create a new option node */
        var myOption = document.createElement('option');
            myOption.setAttribute('value', val);
        var myText = document.createTextNode(txt);
            myOption.appendChild(myText);

        /* Append option to select list */
        var mySelect = document.getElementById(id);
            mySelect.appendChild(myOption);

}


/**
 * My slack attempt at adding support for getElementsByClassName
 *
 * Note: Should really append this to the DOM so it can be called like
 * other getElement* method eg. Document.getElementsByClassName('name');
 *
 * @param  String   Class Name
 * @param  Obj      Starting Object
 * @return Array    Array of elements
 */
function getElementsByClassName(name, obj) {

    // step 1. - get all the elements
    var allElements = obj.getElementsByTagName("*");

    if(allElements.length == 0) {
        allElements = obj.all;
    }


    // step 2. - loop thru filtering on given name
    var classCollection = new Array;
    for(n=0; n < allElements.length; n++) {

        if(allElements[n].className == name) {
            classCollection.push(allElements[n]);
        }
    }
    return classCollection;
}

/**
 * Fetch the value of a variable provided via HTTP GET
 *
 * Unlike PHP's $_GET, Javascript has no built in method
 * to fetch variables provided via HTTP GET.
 *
 * @param  String   Name of variable to fetch value of
 * @return String   Value of variable
 */
function getQueryVariable(variable) {

    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}

/**
 * Check/Uncheck all the checkboxes in the same row <tr> as this object <a href
 * Check status is indicated by the weight of the anchor text ie bold or normal
 * @param Obj   Anchor object
 */
function checkAllInSameRow(word) {

    var checkValue;

    colCell = word.parentNode;
    row = colCell.parentNode;

    elements = row.getElementsByTagName('input');

    if(word.style.fontWeight == 'bold') {
        checkValue = false;
        word.style.fontWeight = 'normal';
    } else {
        checkValue = true;
        word.style.fontWeight = 'bold';
    }

    // would be nice to see if this actually is a checkbox -o0
    for(var i=0;i<elements.length;i++) {
        elements[i].checked = checkValue;
    }

}

/**
 * Check/Uncheck all the checkboxes within the same table
 * and with the same class as the given anchor object.
 * The idea is a column (td) will all have the same class name
 *
 * @param Obj   Anchor tag
 */
function checkAllInSameColumn(object) {
    var parent = object.parentNode;
    while(parent.tagName != 'TABLE') {
        parent = parent.parentNode;
    }

    var elements = getElementsByClassName(object.className, parent);

    var checkValue;
    var fontWeight;

    if(object.style.fontWeight == 'bold') {
        checkValue = false;
        fontWeight = 'normal';
    } else {
        checkValue = true;
        fontWeight = 'bold';
    }


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

        // If it's a link Bold/unbold
        if(elements[i].tagName == 'A') {
            elements[i].style.fontWeight = fontWeight;
        }

        // If it's a checkbox Check/Uncheck
        if(elements[i].tagName == 'INPUT' && elements[i].type == 'checkbox' ) {
            elements[i].checked = checkValue;
        }

    }
}

/**
 * Checks/Unchecks all the checkboxes for a table with the given object
 *
 * @param Obj   Anchor tag
 */
function checkAllForTable(object) {

    var parent = object;
    while(parent.tagName != 'TABLE') {
        parent = parent.parentNode;
    }

    var elements = parent.getElementsByTagName('input');

    var checkValue;
    var fontWeight;

    if(object.style.fontWeight == 'bold') {
        checkValue = false;
        object.style.fontWeight = 'normal';
    } else {
        checkValue = true;
        object.style.fontWeight = 'bold';
    }

    for(var i=0; i < elements.length ; i++) {
        /* HP CC 18-SEP-08: Added check to make sure only enabled checkboxes are affected by the Select/Unselect All functionality */
        if (elements[i].disabled == false)
            elements[i].checked = checkValue;
    }

}

/**
 * Used within the Collections Matrix
 * Checks or unchecks all the checkboxes associated with a colour
 *
 * @param Obj   Anchor tag
 */
function checkAllForColour(object) {

    var elements = getElementsByClassName(object.className, object.parentNode.parentNode.parentNode);
    var checkValue;
    var fontWeight;

    if(object.style.fontWeight == 'bold') {
        checkValue = false;
        object.style.fontWeight = 'normal';
    } else {
        checkValue = true;
        object.style.fontWeight = 'bold';
    }

    for(var i=0; i < elements.length ; i++) {
        if( elements[i].tagName != 'TR' )
            continue;

        var inputs = elements[i].getElementsByTagName('input');

        for(var j=0; j < inputs.length ; j++) {
            inputs[j].checked = checkValue;
        }
    }
}

/**
 * Check/Uncheck all the checkboxs on the page,
 * optionally limited by a class name
 *
 * DEPRECATED - use checkByClass -o0
 *
 * @param Obj       Checkbox indicating the state (checked/unchecked)
 * @param String    Name of the class to limit the checking to
 */
function checkAll(allCheckBox, className) {

    // parameter check
    if(!allCheckBox) {
        return false;
    }

    // step 1. fetch all the inputs
    var inputTags = document.getElementsByTagName('input');

    // step 2. Loop thru them all and check if of type checkbox
    for(i=0; i<inputTags.length; i++) {

        var type = inputTags[i].getAttribute('type');
        if(type=="checkbox") {

            // if the optional classname was passed limit to this class
            if(className) {
                if(inputTags[i].className == className) {
                    inputTags[i].checked=(allCheckBox.checked)?true:false;
                }
            }
            else {
                inputTags[i].checked=(allCheckBox.checked)?true:false;
            }
        }
    }

    return true;
}

/**
 * checkByClass(state,classSet)
 *
 * Instead of making ANOTHER SUPER SPECIFIC BLOAT FUNCTION:
 * This is a more generic version of the above.. -o0
 *
 * eg.. instead of checkall row.. add a row1 class to all checkbox in row one
 *      add col1 to all elements in col1
 *   for checkall.. add all items to a class and do the following in onclick:
 *   <input type="checkbox" name="checkall" onClick="checkByClass(this.value,'checkall')">
 *
 *
 * Define checkbox sets like so:
 *
 * <input type="checkbox" class="checkall checkset1">
 * <input type="checkbox" class="checkall checkset1 checkset2">
 * <input type="checkbox" class="checkall checkset2">
 * checkByClass(true, 'checkall') = checks all
 * checkByClass(false, 'checkall') = uncheckall
 * checkByClass(true, 'checkset1') = checks first and second
 * checkByClass(false,'checkset2') = unchecks second and third
 * checkByClass(false,'checkset1 checkset2') = unchecks all
 */
function checkByClass(state, classSet) {
  try {
    var inputTags = document.getElementsByTagName('input');
    var count = 0;
    for ( i = 0; i<inputTags.length; i++ ) {
      var type = inputTags[i].getAttribute('type');
      if (type=="checkbox") {
        if (classSet) {
          if ( classNameMatch( classSet, inputTags[i].className) )
          {inputTags[i].checked=(state?true:false);
         count++;
          }
        } else {
          inputTags[i].checked=(state?true:false);
        }
      }
    }

  } catch (e) {
    return false;
  }

  if(document.getElementById('divStatusCount'))
  {
  document.getElementById('divStatusCount').innerHTML= count;
  document.getElementById('divStatusCount').style.display='';
  }

  return true;
}


function selectAllClass(classSet) {
  try {

    var i = 0;
    var state = false;

    // Inverse state if inconsistent
    var inputs = $$('input.'+classSet);
    for(i = 0; i < inputs.length; i++)
        if (inputs[i].checked == false) state = true;

    for(i = 0; i < inputs.length; i++)
        inputs[i].checked = state;

  } catch (e) {
    return false;
  }
  return true;
}



// Used in range ordering
function tux(matrix, myDate)
{
    matrixName='matrix['+matrix+'][order_date]';
    document.getElementsByName(matrixName).item(0).value=myDate;
    document.order_selected.submit();
}

/**
 * Hide an object by ID
 * @param String    The id of the object to show
 **/
function hideID( myId ) {
    // Hide or Show the object
    var myObj=document.getElementById(myId);
    if(myObj.style.display!='none') {
        myObj.style.display='none';
    }
    return true;
}

/**
 * Show an object by ID
 * @param String    The id of the object to show
 **/
function showID( myId ) {
    // Hide or Show the object
    var myObj=document.getElementById(myId);
    if(myObj.style.display!='') {
        myObj.style.display='';
    }
}

/**
 * Toggle the display on and off for a object  eg. A div or table
 * @param String    The id of the object to toggle
 * @param Obj       Optional image object.
 *                  If present the image (button) will be flipped (open/close)
 *                  based on the 'hide' & 'show' attributes in the 'img' tag.
 *
 * @usage           <img src='show.gif' show='show.gif' close='close.gif' onclick=showHide('box', this) />
 */
function showHide(myId, button) {

    // Hide or Show the object
    var myObj=document.getElementById(myId);
    if(myObj.style.display!='none') {
        myObj.style.display='none';
    }
    else {
        myObj.style.display='';
    }

    // Get the image to flip to from the attributes
    if(button) {
        var hide = button.getAttribute("hide");
        var show = button.getAttribute("show");

        if(button.src.indexOf(hide)==-1)
            button.src=hide;
        else
            button.src=show;
    }

}

/**
 * Displays a popup message to update browser
 * Redirects user to the mozilla site to download a Brandsnet compatible browser
 */
function updateBrowser() { return false; }

/**
 * Initialise keyboard focus
 *
 * @access public
 * @return bool
 */
function focusInit() {

    var i = 0;
    // Checkout Options
    if ($('bnCheckoutOptions')) {
        // Try match of first empty PO # Entry
        var inputs = $$('#bnCheckoutOptions .OrderHeaderPO');
        for(i = 0; i < inputs.length; i++) {
            if (inputs[i].value == '') {
                inputs[i].focus();
                window.documentFocusSet = true;
                return true;
            }
        }
    }

    // Checkout Payment
    if ($('bnCheckoutPayment')) {
        var inputs = $$('#bnCheckoutPayment .bnFormPaymentRadio');
        for(i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                inputs[i].focus();
                window.documentFocusSet = true;
                return true;
            }
        }
    }

    // Try bread crumb selection
    if ($('progress-step-next')) {
        $('progress-step-next').focus();
        window.documentFocusSet = true;
        return true;
    }

    // Default to product search box
     if ($('product-keyword-search')) {
        $('product-keyword-search').focus();
        window.documentFocusSet = true;
        return true;
     }

    // We didnt do anything! :D
    return false;
}


/**
 * Base64 Encode
 *
 * @param string
 * @return string
 */
function base64_decode(encStr) {

    var base64s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var bits, decOut = '', i = 0;

    for (; i<encStr.length; i += 4) {
        bits =
         (base64s.indexOf(encStr.charAt(i))    & 0xff) <<18 |
         (base64s.indexOf(encStr.charAt(i +1)) & 0xff) <<12 |
         (base64s.indexOf(encStr.charAt(i +2)) & 0xff) << 6 |
          base64s.indexOf(encStr.charAt(i +3)) & 0xff;
        decOut += String.fromCharCode(
         (bits & 0xff0000) >>16, (bits & 0xff00) >>8, bits & 0xff);
    }

    if (encStr.charCodeAt(i -2) == 61)
        undecOut=decOut.substring(0, decOut.length -2);
    else if (encStr.charCodeAt(i -1) == 61)
        undecOut=decOut.substring(0, decOut.length -1);
    else undecOut=decOut;

    return unescape(undecOut);
}


/**
 * Transfer iFrame content to Div
 *
 * @access public
 * @param object  iframe
 * @param object  div
 * @return bool
 */
function iFrameToDiv(iFrame, div) {

    try {

        // Get the document within the frame. This is where you will fail with 'permission denied'
        // if the document within the frame is not from the same domain as this document.

        // For NS6
        if (iFrame.contentDocument) {
            innerDoc = iFrame.contentDocument;

        // For IE5.5 and IE6
        } else if (iFrame.contentWindow) {
            innerDoc = iFrame.contentWindow.document;

        // For IE5
        } else if (iFrame.document) {
            innerDoc = iFrame.document;
        }

        // Switch over content
        if (innerDoc.body.innerHTML)
            div.innerHTML = innerDoc.body.innerHTML

    } catch(error) { alert(error); }

    return true;
}

// className set is an or
function classNameMatch( classSet1, classSet2 ) {

  try {
    var classNames1 = classSet1.split(' ');
    var classNames2 = classSet2.split(' ');

    for ( a=0; a<classNames1.length; a++ )
      for ( b=0; b<classNames2.length; b++ )
        if ( classNames1[a] == classNames2[b] )
          return true;
  } catch (e) {
  }
  return false;
}


function toggleClassNameById(id,class1,class2) {
  var myObj = document.getElementById(id);
  if (!myObj) return false;
  return toggleClassNameByObject(myObj,class1,class2);
}

// Widget javascript
function toggleClassNameByObject(obj,class1,class2) {
   if ( classNameMatch(obj.className,class1) ) {
     obj.className = class2;
   } else if ( classNameMatch(obj.className,class2) ) {
     obj.className = class1;
   }
   return true;
}



function modifyFold( id, state ) {
  var divControl = document.getElementById(id);
  var divControlImage = document.getElementById(id+'-image');
  if ( ! divControl )
    return false;

  divControl.className=divControl.getAttribute('class-prefix')+'-'+state;
  if (divControlImage) {
    var foldImg = divControlImage.getAttribute("src-"+state);
    if (foldImg) divControlImage.src=foldImg;
  }
  return true;
}

function openFold( id ) {
  return modifyFold( id, 'opened');
}

function closeFold( id ) {
  return modifyFold( id,  'closed');
}

function toggleFold( id ) {
  var divControl = document.getElementById(id);
  if (!divControl)
    return false;
  if ( classNameMatch(divControl.className, divControl.getAttribute('class-prefix')+'-opened') ) {
    return closeFold( id );
  } else {
    return openFold( id );
  }
  return true;
}

      function hoverTab(idobj,enable) {
        try {
         var bnTabClassName = 'bn-tab-';
         switch ( idobj.className ) {
           case 'bn-tab-selected-hover':
           case 'bn-tab-selected':
             bnTabClassName = bnTabClassName+'selected';
            break;
           case 'bn-tab-unselected-hover':
           case 'bn-tab-unselected':
           default:
             bnTabClassName = bnTabClassName+'unselected';
            break;
         }
         if ( enable ) {
           bnTabClassName = bnTabClassName+'-hover';
         }
         //alert(idobj.className+'->'+bnTabClassName);
         idobj.className = bnTabClassName;
        } catch (e) {
          return false;
        }
        return true;
      }

      function selectTab(idobj, code) {
        try {
         if (document.getElementById('bn-tab-value'))
            document.getElementById('bn-tab-value').value = code;

         for (var i = 1; i < 5; i++) {
            if (document.getElementById('bn-tab-'+i))
                document.getElementById('bn-tab-'+i).className = 'bn-tab-unselected';
         }

         idobj.className = 'bn-tab-selected';

        } catch (e) {
          return false;
        }
        return true;
      }

/* these really should be an error, and error_hidden class and set the class  -o0*/
/* otherwise these are exact copies of showID and hideID above  -o0 */
function errorShow(id, target) {
    if (errorMessage = document.getElementById(id))
        errorMessage.style.display = 'block';
    return true;
}

function errorHide(id) {
    if (errorMessage = document.getElementById(id))
        errorMessage.style.display = 'none';
    return true;
}

//return cookie value
function getCookie(uname)
{
    var dc = document.cookie;
    var prefix = uname + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
                begin += 2;
           }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

// this deletes the cookie when called
function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function openwindow() {
  var hlpfile="";
  window.open (hlpfile,"Help","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=no,copyhistory=no,width=600,height=400");
}

function showimage() {
    if (!document.images) return document.images.avatar.src= 'images/avatar/' + document.Register.user_avatar.options[document.Register.user_avatar.selectedIndex].value
}

// php clone
function number_format(a, b, c, d) {
    // number_format(number, decimals, comma, formatSeparator)
    a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
    e = a + '';
    f = e.split('.');
    if(!f[0]) f[0] = '0';
    if(!f[1]) f[1] = '';
    if(f[1].length < b){
        g = f[1];
        for(i = f[1].length + 1; i <= b; i++) {
            g += '0';
        }
        f[1] = g;
    }
    if(d != '' && f[0].length > 3) {
        h = f[0];
        f[0] = '';
        for(j = 3; j < h.length; j += 3) {
            i = h.slice(h.length - j, h.length - j + 3);
            f[0] = d + i +  f[0] + '';
        }
        j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
        f[0] = j + f[0];
    }
    c = (b <= 0) ? '': c;
    return f[0] + c + f[1];
}

    function toggleCheckbox(checkbox, othercheckbox) {
        if ((checkbox.checked) && (othercheckbox.checked = ! checkbox.checked)) {
            return true;
        }

        return false;
    }

    function toggleBlockMenu(id) {
        var d = document.getElementById(id);
        for (var i=0; i<=99; i++) {
            if (document.getElementById('smenu'+i)) {document.getElementById('smenu'+i).style.display='none';}
        }
        if (d) {d.style.display='block';}
    }


    function showHide2(toggleId) {
        var myObj=document.getElementById(toggleId);
        toggleBlockMenu("newAdminMenu");
        if(myObj.style.display!='none') {
            myObj.style.display='none';
        }
        else {
            myObj.style.display='';
        }
    }


    function activateAdminPageAJAX() {


        // Submit the form, the AJAX way ;)
        $('logins_form').addEvent('click', function(e) {

            var elem = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : e);
            if (elem.id == null) return false;

            assignAdminFormAction(elem);

            if (elem.id == 'btn_logins_maintain') {

                new Event(e).stop();
                var log = $('logins_block').empty().addClass('ajax-loading');
                this.send({
                    update: log,
                    onComplete: function() {
                        log.removeClass('ajax-loading');
                    }
                });

            } else if (elem.id == 'btn_logins_createnew') {

                new Event(e).stop();
                var log = $('logins_block').empty().addClass('ajax-loading');
                this.send({
                    update: log,
                    onComplete: function() {
                        log.removeClass('ajax-loading');
                    }
                });

            } else if (elem.id == 'btn_logins_batchprocessing') {

                new Event(e).stop();
                var log = $('logins_block').empty().addClass('ajax-loading');
                this.send({
                    update: log,
                    onComplete: function() {
                        log.removeClass('ajax-loading');
                    }
                });

            }
        });
    }

    function assignAdminFormAction(targ) {

        // Remove previous query variables
        document.logins_form.action = document.logins_form.action.replace('&submit_type=maintain','');
        document.logins_form.action = document.logins_form.action.replace('&submit_type=createnew','');
        document.logins_form.action = document.logins_form.action.replace('&submit_type=batchprocessing','');

        if (targ.name == 'btn_logins_maintain') {
            $('logins_form').action = document.logins_form.action + '&submit_type=maintain';
        } else if (targ.name == 'btn_logins_createnew') {
            $('logins_form').action = document.logins_form.action + '&submit_type=createnew';
        } else if (targ.name == 'btn_logins_batchprocessing') {
            $('logins_form').action = document.logins_form.action + '&submit_type=batchprocessing';
        }
    }

/**
 * Author: Scott Mackenzie - smackenzie at pacificbrands dot com dot au
 * Depedencies: MooTools.
 **/
// If this breaks for any reason entire site fallsback to non bling mode !! :D
var bnHoverEffect = new Class({

    setOptions: function(options){
        this.options = {
            transitionStart: Fx.Transitions.sineInOut,
            transitionEnd: Fx.Transitions.sineInOut,
            transitionEffect: {},
            fxDuration: 150,
            timeOut: 100,
            onElementInit: function( el ) { return true; },
            onElementShow: function( el ) {},
            onElementHide: function( el ) {},
            onElementEvent: function( el ) {}
        }
        Object.extend(this.options, options || {});
        this.options.onElementInit
         = this.options.onElementInit.bind( this );
        this.options.onElementShow
         = this.options.onElementShow.bind( this );
        this.options.onElementEvent
         = this.options.onElementEvent.bind( this );
    },

    initialize: function(triggerElements, targetElement, options ){

        this.elements = triggerElements;
        this.target = $(targetElement);
        this.setOptions(options);

        this.fx = new Fx.Styles( this.target, { duration: this.options.fxDuration, wait: false } );

        this.to = {};
        this.from = {};
        for ( var p in this.options.transitionEffect ) {
          this.to[p] = this.options.transitionEffect[p][0];
          this.from[p] = this.options.transitionEffect[p][1];
        }
        this.target.setStyles(this.to);
        this.fx.set( this.to );

        $A(triggerElements).each(function(el){
           if ( this.options.onElementInit( el ) ) {
             el.onmouseover = function(){
                 this.show(el);
                 return false;
             }.bind(this);
             el.onmousemove = this.locate.bindAsEventListener(this);
             el.onmouseout = function(){
                 this.timer = $clear(this.timer);
                 this.disappear(el);
             }.bind(this);
           }
        }, this);
    },

    show: function(el) {
        this.options.onElementShow( el );
        this.timer = $clear(this.timer);
        this.fx.options.transition = this.options.transitionStart;
        this.timer = this.appear.delay(this.options.timeOut, this);
    },

    appear: function(){
        this.fx.start( this.to );
    },

    locate: function(evt){
        this.options.onElementEvent( evt );
    },

    disappear: function( el ){
        this.fx.options.transition = this.options.transitionEnd;
        this.fx.start( this.from );
        this.options.onElementHide( el );
    }

});

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function ocCustomChange(elem, id){
    var select = $(elem+'Select-'+id);
    var custom = $(elem+'Custom-'+id);
    if (select.options[select.selectedIndex].id == 'custom') {
        custom.style.display = '';
        custom.focus();
    } else {
        custom.style.display = 'none';
        custom.value = "";
    }
    return true;
}
//Header Account Change js
window.addEvent('domready', function() {
    if($('bnHeaderAccountSelection')){
        var change_link = new Fx.Slide('customer_change');
        var orgianl_text = $('bnHeaderAccountSelection').innerHTML;
        change_link.hide();
        $('bnHeaderAccountSelection').addEvent('click', function(e) {
            new Event(e).stop();
            var time = new Date().getTime();
            if(!change_link.open){
                var request = new Ajax(
                            'modules.php?op=modload&name=TradingLevel&file=change_customer&t='+time, {
                            evalScripts: true,
                            update: $('customer_change'),
                            onRequest: function (){ $('bnHeaderAccountSelection').setHTML('Please Wait...');},
                            onComplete: function(){
                                change_link.slideIn();
                                $('bnHeaderAccountSelection').setHTML('Cancel Change');
                            }
                }).request();
            }else{
               $('bnHeaderAccountSelection').setHTML(orgianl_text);
                change_link.slideOut();
            }
        });
    }
});

function loadJs(source, onload) {
    if(typeof source == 'undefined') return;
    var head = document.getElementsByTagName("head")[0];
    if (!head)  return;

    var script = document.createElement('script');
    script.type = 'text/javascript';
    if(typeof onload != 'undefined'){
        script.onload = onload;
        if (script.readyState)  //IE
            script.onreadystatechange = onload;
    }
    script.src = source;
    head.appendChild(script);
}

function addMessage(id, type, message, msg_id) {
    if ($(msg_id)) {
        // If we already have the message then update it
        $(msg_id).setHTML('');
        $(msg_id).adopt( new Element('p').setHTML(message));
    } else {
        if($(id) && message != '' && msg_id != ''){
            // Specific Message
            $(id).adopt( new Element('div').addClass(type).adopt( new Element('p').setHTML(message)).setProperty('id', msg_id));
        }else if($(id) && message != ''){
            // General Message
            $(id).adopt( new Element('div').addClass(type).adopt( new Element('p').setHTML(message)));
        }

    }
}

function clearMessages(id) {
    // Removes all message for this id
    if ($(id)) {
        $(id).setHTML('');
    }
}

function clearMessage(id, msg_id) {
    // Removes just the specified message
    // TODO: Need to fix to make it only for this id - davismic
    if ($(msg_id)) {
        $(msg_id).remove();
    }
}
