/**
 * 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();
        rollupShowMore();
    } 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);
  //fix for IE calendar Issue in Order Status
  if( id=='fold-3' ){
      calendar_init();
  }
  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';
    }
    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));
        $(msg_id).adopt( new Element('div').addClass('bnMessageBoxClose').addEvent('click', function(){$(msg_id).empty();$(msg_id).remove();})).adopt( new Element('p').setHTML(message));
    } else {
        if($(id) && message != '' && msg_id != ''){
            // Specific Message
            $(id).adopt( new Element('div').addClass(type).adopt( new Element('div').addClass('bnMessageBoxClose').addEvent('click', function(){$(msg_id).empty();$(msg_id).remove();})).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();
    }
}

/*
 * START : Admin Export functionality
 */
function validateAndSubmit() {
    
    if (validateCheckBox() == true) {
        //form name is 'admin_export'
        document.admin_export.submit();
    }
    else {   
        return false;
    }
}

function validateCheckBox() {
    var chkList = document.getElementsByTagName("input");
    var msg = '';

    CountModule = 0;

    for (var i = 0; i < chkList.length; i++) {
        if(chkList[i].checked) { 
            CountModule=1;
        }
    }

    if (CountModule == 0) { 
        msg = "Please select an item"
    }
    if (msg!="") {
        alert(msg);
        return false;
    }
    else {   
        return true;
    }
}

/*
 * END : For Admin Export functionality
 */

/*
 * START : For Admin delete functionality
 */

function uncheck_threshold(threshold_id){ 
    $('ent_uncheck_threshold').value = 1;
    $('ent_threshold_id').value = threshold_id;
    $("ent_form").submit();
}


function uncheck_overpurchase(overpurchase_id){ 
    $('ent_uncheck_overpurchase').value = 1;
    $('ent_overpurchase_id').value = overpurchase_id;
    $("ent_form").submit();
}

function deleteKit() { 

    if($('kit_delete_flag') != undefined) {
         if($('kit_delete_flag').value == 'N') {
             return true;
         }
    }
    else {
        if(confirm('Are you sure you want to delete this?')) 
            return true;
    }

    return false;
}

function deleteKitGroup() {
    if($('kitgroup_delete_flag') != undefined) {
         if($('kitgroup_delete_flag').value == 'N') {
             return true;
         }
    }
    else {
        if(confirm('Are you sure you want to delete this?')) 
            return true;
    }

    return false;    
}

function deleteEclass() { 
    
    if($('eclass_delete_flag') != undefined) {
         if($('eclass_delete_flag').value == 'N') {
             return true;
         }
    }
    else {
        if(confirm('Are you sure you want to delete this?')) 
            return true;
    }

    return false;    
}

function uncheck_eclass(kit_id){
    $('ent_uncheck_eclass').value = 1;
    $('ent_kit_id').value = kit_id;
    document.ent_eclass_setup.submit();
}

function deleteEycle() { 
    
    if($('ecycle_delete_flag') != undefined) {
         if($('ecycle_delete_flag').value == 'N') {
             return true;
         }
    }
    else {
        if(confirm('Are you sure you want to delete this?')) 
            return true;
        
    }

    return false;    
}

function uncheck_threshold_in_ecycle(threshold_id){ 
    document.ent_ecycle_Delete.action.value='Edit'
    $('ent_uncheck_threshold').value = 1;
    $('threshold_id').value = threshold_id;
    //document.ent_ecycle_Delete.submit();
    $('ent_form').submit();
}


function deselect_ecycle_in_threshold(ecycle_id) {
   document.ent_threshold_Delete.action.value='Edit';
   $('ent_uncheck_ecycle').value = 1;
   $('ecycle_id').value = ecycle_id;
   $('ent_form').submit();
}

function deleteThreshold() { 

    if($('threshold_delete_flag') != undefined) {
         if($('threshold_delete_flag').value == 'N') {
             return true;
         }
    }
    else {
        if(confirm('Are you sure you want to delete this?')) 
            return true;
    }

    return false;    
}

function deleteOverpurchase(){ 
    if($('overpurchase_delete_flag') != undefined) {
         if($('overpurchase_delete_flag').value == 'N') {
             return true;
         }
    }
    else {
        if(confirm('Are you sure you want to delete this?')) 
            return true;
        
    }

    return false;    
}

function deleteEmployee(emp_id, store_id, emp_name) {

    $('tl_search_flag').value = 'Y';
    $('tl_order_employee_id').value = emp_id;
    $('tl_del_emp_info').value = store_id+': '+emp_name;
    
    if($('tl_order_flag_'+emp_id) != undefined){
        if($('tl_order_flag_'+emp_id).value == 'N') {
             $('tl_delete_flag').value = 'N';
             document.tlindex.submit();
         }
    }
    else {
        if (confirm('Are you sure you want to delete this?')) {
            $('tl_delete_flag').value = 'Y';
            document.tlindex.submit();
        }
    }
}


function deleteLogins(login_id, mod_name){
    if (confirm('Are you sure you want to delete this?')) {
        document.location.href = "modules.php?op=modload&name="+ mod_name +"&file=index&act=manager&action=delete&login_id="+ login_id +"&menu=links";
    } else {
        return false;
    }
}
/*
 * END : For Admin delete functionality
 */


/*
 * START : Validate Add to cart with no quantity
 */
function validateAddToCart(product_count, alternative_kit_flag) {
    //var to flag matrix has value or not
    var is_entered_quantity = 0;

    //var to flag size matrix is active or inactive for one/multiple products (for two types of matrix display)
    var disabled_flag = 0;
    var tmp_disabled_flag = 1;
    var disabled_flag_arr = new Array();

    //var to flag item exist in the matrix
    var item_exist = 0;

    //vars to flag existing item matrix is changed or not (for two types of matrix display)
    var is_item_changed = 0;
    var is_item_changed_flag = 0;
    var tmp_is_item_changed_arr = new Array();

    //var to append msg for order my selections
    var msg_suffix = '';

    //var to flag the type of matrix currently have 0 -> latest matrix display, 1 -> old matrix display
    var type_flag = 0;

    //var to flag the matrix is having 0 for new product
    var matrix_empty = 0;

        if (product_count > 0) {
            if (product_count > 1) 
                msg_suffix = ' for any one of the selected products';

            //to count the number of inactive size matrix
            var matrix_inactive_cnt = 0;
            for (var i = 0; i < product_count; i++) {
                if ($('quantity_input_' + i)) {
                    //get the matrix value for the product which is set in alt attribute of the input control
                    var matrix_alt_value = $('quantity_input_' + i).getProperty("alt");

                    if($('quantity_input_' + i).value != '' && parseInt($('quantity_input_' + i).value) != parseInt(matrix_alt_value)) {
                            is_item_changed = 1;
                    }

                    //item already exist in the matrix
                    if (matrix_alt_value > 0) {
                        item_exist = 1;
                    }

                    //to check if different size matrix is available and it is enabled for the current product
                    if ($('quantity_input_' + i).disabled == false && $('product_size_' + i).value != -1) {
                        if ($('quantity_input_' + i) && $('quantity_input_' + i).value != '') {
                            if( ($('quantity_input_' + i).value > 0 || item_exist == 1) || 
                                ($('quantity_input_' + i).value == 0 && item_exist == 1) )
                                is_entered_quantity = 1;
                            else
                                matrix_empty = 1;
                        }
                        disabled_flag_arr[i] = 0;
                    }
                    //if size matrix is disabled just take the count and add 1 to the array
                    else { 
                        matrix_inactive_cnt++;
                        disabled_flag_arr[i] = 1;
                    }
                }

                //temp var to flag item in the all size matrix boxes are changed or not
                var tmp_is_item_changed = 0;

                // Check Matrix style contents
                var input_re = new RegExp('quantity_input_'+i+'_[0-9]+');
                $$('.matrixbox').each(function(inp) {
                    if (inp.getProperty('id').search(input_re) == -1) return;
                    type_flag = 1;

                    var matrix_value     = inp.getProperty('value');
                    if (matrix_value != '') {

                        var matrix_alt_value = inp.getProperty("alt");
                        if (parseInt(matrix_value) != parseInt(matrix_alt_value))
                            tmp_is_item_changed = 1;

                        if ((matrix_value  > 0 || matrix_alt_value > 0) ||
                            (matrix_value == 0 && matrix_alt_value > 0))
                             is_entered_quantity = 1;
                        else matrix_empty = 1;
                    }
                });

                //store the flag values 1/0 for item changed or not in the array
                if (type_flag == 1) {
                    tmp_is_item_changed_arr[i] = tmp_is_item_changed;
                }

            }
            
            //set the final flag for item in the matrix is changed or not
            if(tmp_is_item_changed_arr.length > 0) { 
                for(i=0; i<tmp_is_item_changed_arr.length; i++) {
                    if(tmp_is_item_changed_arr[i] == 1)
                        is_item_changed_flag = 1;
                }
                if (is_item_changed_flag == 1) {
                    is_item_changed = 1;
                }
            }

            //set the final flag for whether all the size matrix is disbaled or not
            if(disabled_flag_arr.length > 0) {
                for(i=0; i<disabled_flag_arr.length; i++) {
                    if(disabled_flag_arr[i] == 0) tmp_disabled_flag = 0;
                }
                if(tmp_disabled_flag == 1) disabled_flag = 1;
            }

            if(is_item_changed == 0 && is_entered_quantity == 1) {
                addMessage('entitlements_message', 'bnEntWarning', 'No changes to submit to cart', 'validateAddToCart');
                return false;
            }
            else if (is_entered_quantity == 0 && disabled_flag == 0 && matrix_empty == 0) {
                addMessage('entitlements_message', 'bnEntWarning', 'Please enter quantity' + msg_suffix, 'validateAddToCart');
                return false;
            }
            else if (is_entered_quantity == 0 && disabled_flag == 0 && matrix_empty == 1) {
                addMessage('entitlements_message', 'bnEntWarning', 'Please enter a valid quantity' + msg_suffix, 'validateAddToCart');
                return false;
            }
            else if (disabled_flag == 1 && matrix_inactive_cnt == product_count) {
                    addMessage('entitlements_message', 'bnEntWarning', 'Please select colour/fit/size', 'validateAddToCart');
                    return false;
            }

            if (alternative_kit_flag > 0) 
                validateAlternativeKit(alternative_kit_flag);

            return true;
        }

}
/*
* END : Validate Add to cart with no quantity
*/


/*
 * START : To check Qty select box value and to open a Qty text field when other is selected in the select box options.
 */
function validateQtyDropDown(val, matrix_count) {
    if(val == 'Other') {
        $('quantity_input_'+ matrix_count).value = '';
        $('quantity_input_'+ matrix_count).style.display = 'block';
    } else {
        $('quantity_input_'+ matrix_count).style.display = 'none';
        $('quantity_input_'+ matrix_count).value = val;
    }
}
/*
* END : To check Qty select box value and to open a Qty text field when other is selected in the select box options.
*/


/* START : To validate the data entered in quantity input box is product info pages.
 * 
 * 
 */
function checkMatrixBoxData(val, qty_input_id) {
    if (val == '') {
        clearMessages('entitlements_message');
        return;
    }

    if (isNaN(val)) {
        addMessage('entitlements_message', 'bnEntWarning', 'Please enter a valid quantity', 'validateAddToCart');

        //For multiple quantity input boxes for more than one size 
        var x = $$('input.matrixbox');
        //For new UI of quantity input box with size in dropdown
        var y = $$('input.bnProductQuantity');

        x.each(function(item, index){
            if (isNaN(item.value)) {
                item.value = '';
            } 
        });


        y.each(function(item, index){
            if (isNaN(item.value)) {
                item.value = '';
            }
        });

    } else {

        var hdn_min_order_input_id = qty_input_id.replace('quantity_input','min_order');
        if($(hdn_min_order_input_id)) {
            var hdn_min_order_val = $(hdn_min_order_input_id).value;

            if((val % hdn_min_order_val) != 0) {
                addMessage('entitlements_message', 'bnEntWarning', 'Quantity ordered must be a multiple of Quantity per Pack ('+hdn_min_order_val+')', 'validateAddToCart');
                // AT: Disabled, so we enable entry of things like 10, 100, etc. without clearing it on them
                // the shopping cart does the final check anyway
                //$(qty_input_id).value ='';
            } else {
                clearMessages('entitlements_message');
            }
        } else {
            clearMessages('entitlements_message');
        }
        
    }
}


/*
 * START : For 'Select All/UnSelect All' functionality in produc list page
 */
function addSelectedProducts(kit_path, cache_val, option){
    var list_select = 0;

    //when clicking 'SelectAll'
    if (document.list['selectBox[0]'].checked == true || option == 'select'){
        list_select = 1;
        $('selectBox1').style.display = 'none';
        $('selectBox2').style.display = 'block';
        document.list['selectBox[0]'].checked = false;
    }
    //when clicking 'UnselectAll'
    else if (document.list['selectBox[1]'].checked == true || option == 'unselect') {
        $('selectBox1').style.display = 'block';
        $('selectBox2').style.display = 'none';
        document.list['selectBox[1]'].checked = false;
    }

    var url = 'modules.php?action=select_all.php&cache='+cache_val+'&limit[start]=0&list_select='+list_select+'&kitPath='+kit_path+'&op=modload&name=PostTep&file=index';

    var request = new Ajax(
                            url, {
                            method: 'post',
                            evalScripts: true,
                            onRequest: function() { $('bnProductSelectAll').setHTML('<div align="center"><img src="images/loading-slow.gif" class="centrebox_loader" alt="Loading.."></div>'); },
                            onSuccess: function() {
                                $('bnProductSelectAll').setHTML();
                                updateViewSelectionsLink();
                            }
                            }).request();
}

function updateViewSelectionsLink(){

    var url = 'modules.php?op=modload&name=PostTep&file=index&action=update_view_selections_link.php';
    
    // this is the ajax call to update the view selections link in the product block
    if ($('bnViewSelections')) {
        new Ajax(url, {
            method: 'post',
            update: $('bnViewSelections'),
            onRequest: function(e){
                $('bnViewSelections').setHTML('<div align="center"><img src="images/loading-slow.gif" class="centrebox_loader" alt="Loading.."></div>');
            },
            onComplete: function(){
            }
        }).request();
    }
}
/*
 * END : For 'Select All/UnSelect All' functionality in produc list page
 */


function rollupShowMore(){
//Create roll up with "show more(x)" if ul/table has more that one item
$$(".rolluper").each( function(ele){
    var child_count = ele.getChildren().length;
    if (child_count > 1){
        var ul = new Element('ul', {'id':'rollerupper', 'class':'bnCartWarnings'});
        var showMore = new Element("a", {'class':'showMore', 'href':'#'}).setHTML("Show more ("+(child_count-1)+")");
        ele.getChildren().each( function(el, index){
           el.setStyle('display', '');
           if(index!=0) ul.adopt(el);
        });
        ul.injectAfter(ele);
        showMore.injectAfter(ul);
        var ul_slide = new Fx.Slide(ul).hide();
        showMore.addEvent('click', function(e){
            new Event(e).stop();
            ul_slide.toggle();
            showMore.setHTML('Show less');
            if(showMore.hasClass('showLess')) showMore.setHTML("Show more ("+(child_count-1)+")");
            showMore.toggleClass('showLess');
        });
    }
});
}

