/* Really IE? You don't know index of? */
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
   for(var i=0; i<this.length; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  }
}

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;
}

var $get = MM_findObj;

//swap that image start
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_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_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];}
}
//swap that image end

//popUp that div start

var amID = "blank";
var faqId = "blank";
var sideNavId = "blank";
var sideLinkId = "blank";

function showFaq(divId, linkId){
    //show div
    showMe(divId);
    
    //hide old link
    if(faqId != "blank"){
            unActiveMe(faqId);            
      }
    //change link
    activeMe(linkId);
    faqId = linkId;
      
}

function unActiveMe(id){
    obj = MM_findObj(id);
      if (!obj) return;
      obj.className = '';
}
function activeMe(id){
    obj = MM_findObj(id);
      if (!obj) return;
      obj.className = 'active';
}

function showMe(containerId){

      if(amID != "blank"){

            hideMe(amID);
            
      }

      amID = containerId;

      showContainer(containerId);

}

function toggleMe(containerId){
      obj = MM_findObj(containerId);
      if (!obj) return;
      
      /*if(amID != "blank" && amID != containerId)
            hideMe(amID);

      amID = containerId;*/
      if(obj.style.display == 'block')
          obj.style.display = 'none';
      else
          obj.style.display = 'block';
}

function loginClick(containerId){

      if(amID != "blank"){

            hideMe(amID);
            
      }

      amID = containerId;
      showContainer(containerId);
      
      obj = MM_findObj("ctl02_Login1_tbUsername");
      obj.focus();
}

function showContainer(containerId){
      
      obj = MM_findObj(containerId);

      if (!obj) return;

      obj.style.display = 'block';
}

function hideMe(containerId){
      
      obj2 = MM_findObj(containerId)

      if (!obj2) return;

      obj2.style.display = 'none';

}

//popUp that div end


function changeColour(ddlColourId, ddlSizeId, pPriceId, productId) {
    alert(ddlColourId + "\r\n" + ddlSizeId + "\r\n" + pPriceId + "\r\n" + productId);
    //repopulate sizes ddl
    
    //change price
    updatePrice(ddlColourId, ddlSizeId, pPriceId, productId);
}

function updatePrice(ddlColourId, ddlSizeId, pPriceId, productId) {
    alert(ddlColourId + "\r\n" + ddlSizeId + "\r\n" + pPriceId + "\r\n" + productId);
}

function showSideMenu() {
      obj = MM_findObj(sideNavId);
      if (!obj) return;
      obj.style.display = 'block';
      
      obj = MM_findObj(sideLinkId)
      if (!obj) return;
      obj.className = "active";
}

function hideSideMenu() {
      obj = MM_findObj(sideNavId)
      if (!obj) return;
          obj.style.display = 'none';
      
      obj = MM_findObj(sideLinkId)
      if (!obj) return;
      obj.className = "";

}

function swapStyles(divId, linkId){
    //Hide current menu
    hideSideMenu();
    //Show new
    if(divId != sideNavId){
        sideNavId = divId;
        sideLinkId = linkId;
        showSideMenu();
    }
}

function getPrice(stockCode){
      for(i = 0; i < priceArray[0].length; i ++){
            if(priceArray[0][i] == stockCode)
                  return priceArray[1][i]
      }
      return '&nbsp;';
}
      
function setPrice(styleCode, isInit){

      //get stockcode
      objSlt = MM_findObj('slt' + styleCode);
      if(objSlt == null)
            return;

      price = getPrice(objSlt.value);     
      //set literal content
      objDiv = MM_findObj('div' + styleCode);
      if(objDiv == null)
            return;

    //Set Size
    sizDiv = MM_findObj('siz' + styleCode);
      if(sizDiv != null)
      {
          if(objSlt.selectedIndex > 0)
              sizDiv.innerHTML  = objSlt.options[objSlt.selectedIndex].text;
      }

    if(price == 'Out of Stock'){
        objDiv.innerHTML = 'Out of Stock';
        objOs = MM_findObj('os' + styleCode);
          if(objOs != null)
                objOs.style.display = 'block';
    }
    else{         
          objDiv.innerHTML = price;
          objOs = MM_findObj('os' + styleCode);
          if(objOs != null)
                objOs.style.display = 'none';
      }
}


//home page fady start

var myID = "blank";

function fadeMe() {
      opacity1('image1', 100, 0, 5000);
      setTimeout("opacity('image1', 0, 100, 5000)",1000); 
      setTimeout("opacity1('image2', 100, 0, 5000)",6000); 
      setTimeout("opacity('image3', 0, 100, 5000)",7000); 
      setTimeout("opacity('image4', 0, 100, 5000)",31000); 
      setTimeout("fadeMe2()",36000); 

}

function fadeMe2() {
      opacity1('image1', 100, 0, 5000);
      setTimeout("opacity('image1', 0, 100, 5000)",1000); 
      setTimeout("opacity1('image2', 100, 0, 5000)",6000); 
      setTimeout("opacity('image3', 0, 100, 5000)",7000); 
      setTimeout("opacity('image4', 0, 100, 5000)",31000); 
      setTimeout("fadeMe()",36000); 
}

function opacity(myId, opacStart, opacEnd, millisec) { 
      
      obj = MM_findObj(myId);
      obj.style.display = 'block';
      obj.style.opacity = 0;
    obj.style.MozOpacity = 0;
    obj.style.KhtmlOpacity = 0;
    obj.style.filter = "alpha(opacity=" + 0 + ")";
      
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens 
    /*if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + myId + "')",(timer * speed)); 
            timer++; 
        } 
    } else */if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + myId + "')",(timer * speed)); 
            timer++; 
        } 
    }

} 

function opacity1(myId, opacStart, opacEnd, millisec) { 
      
      obj = MM_findObj(myId);
      obj.style.display = 'block';
      obj.style.opacity = 100;
    obj.style.MozOpacity = 100;
    obj.style.KhtmlOpacity = 100;
    obj.style.filter = "alpha(opacity=" + 100 + ")";
      
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + myId + "')",(timer * speed)); 
            timer++; 
        } 
    } /*else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + myId + "')",(timer * speed)); 
            timer++; 
        } 
    }*/

} 

//change the opacity for different browsers 
function changeOpac(opacity, myId) { 
    var object = document.getElementById(myId).style; 
    object.opacity = (opacity / 100); //for newer Mozilla
    object.MozOpacity = (opacity / 100); //for older Mozilla
    object.KhtmlOpacity = (opacity / 100); //for Konquerer on Linux and Safari on Mac
    object.filter = "alpha(opacity=" + opacity + ")"; //for IE
}

//home page fady end

//clearing input fields start
function ClearInput(value, id){
var input = document.getElementById(id);
      if(value == input.value){
            input.value = '';
      }     
}
//clearing input fields end

function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+  
  num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + /*'$', NO dollar signs remember? Lol + */num + '.' + cents);
}

//class for managing the whole sale ordering process
var wholesale = {

    selectStyle: function(style) {
        if ($get("row" + style) != undefined)
            window.location.hash = "row" + style;
        else
            alert('Sorry but the style "' + style + '" could not be found on this page');
    },
    search: function(clicked, event) {
        //if clicked is true, they clicked the search button, rather than testing if it is the enter key
        if (clicked)
            wholesale.selectStyle($get("wholesaleSearch").value);
        else {
            if (event && event.keyCode == 13) {
                //TO FIX TO FIX TO FIX
                wholesale.selectStyle($get("wholesaleSearch").value);
                return false;
            }
            //else they are jsut typing
        }
        return false;
    },
    inputBlured: function() {
        var allInputs = this.myObject.inputs;
        var totalTotal = 0;
        for (var i = 0; i < allInputs.length; i++) {
            var currentInput = $get(allInputs[i]);
            var currentTotal = parseInt(currentInput.value);
            if (currentTotal.toString() != "NaN") {
                totalTotal += currentTotal;
            }
        }
        $get(this.myObject.units).value = totalTotal;
    },
    anInputIsEnabled: function(currentObject) {
        for (var i = 0; i < currentObject.inputs.length; i++) {
            if ($get(currentObject.inputs[i]).disabled.toString() == "false") {
                return true;
            }
        }
        return false;
    },
    focusMostReleventInput: function(originalObject, newObject, awayFromInput) {
        var originalIndex = originalObject.inputs.indexOf(awayFromInput);
        //first go left, if found go there, else go right
        for (var i = originalIndex; i > -1; i--) {
            if (newObject.inputs[i]) {
                var newInput = $get(newObject.inputs[i]);
                if (!newInput.disabled) {
                    newInput.focus();
                    return;
                }
            }
        }
        //no go right
        for (var i = originalIndex + 1; i < newObject.inputs.length; i++) {
            var newInput = $get(newObject.inputs[i]);
            if (!newInput.disabled) {
                newInput.focus();
                return;
            }
        }
    },
    navigateDown: function(currentObject, currentInputId) {
        var currentRowIndex = wholesaleValues.indexOf(currentObject);
        for (var i = currentRowIndex + 1; i < wholesaleValues.length; i++) {
            if (wholesale.anInputIsEnabled(wholesaleValues[i])) {
                wholesale.focusMostReleventInput(currentObject, wholesaleValues[i], currentInputId);
                return;
            }
        }
        //nothing relevent downwards
    },
    navigateUp: function(currentObject, currentInputId) {
        var currentRowIndex = wholesaleValues.indexOf(currentObject);
        for (var i = currentRowIndex - 1; i > -1; i--) {
            if (wholesale.anInputIsEnabled(wholesaleValues[i])) {
                wholesale.focusMostReleventInput(currentObject, wholesaleValues[i], currentInputId);
                return;
            }
        }
        //nothing relevent upwards
    },
    inputKeyPressed: function(event) {
        //God you're retarded IE
        if (!event)
            event = window.event;
        if (event.keyCode == 38) {
            //up was pressed
            wholesale.navigateUp(this.myObject, this.id);
        }
        else if (event.keyCode == 40) {
            //down was pressed
            wholesale.navigateDown(this.myObject, this.id);
        }
    },
    initializeOrder: function() {
        if (!wholesaleValues)
            throw "Wholesale definition failed to load, ";

        var lastItem = wholesaleValues.length - 1;
        for (var i = 0; i <= lastItem; i++) {
            var currentObject = wholesaleValues[i];

            for (var j = 0; j < currentObject.inputs.length; j++) {
                var currentInput = $get(currentObject.inputs[j]);
                currentInput.myObject = currentObject;
                currentInput.onblur = wholesale.inputBlured;
                currentInput.onkeydown = wholesale.inputKeyPressed;
            }
        }
    },
    clearAllValues: function() {
        if (!confirm("Are you sure you wish to remove ALL items?"))
            return;
        for (var i = 0; i < wholesaleValues.length; i++) {
            var currentObject = wholesaleValues[i];
            for (var j = 0; j < currentObject.inputs.length; j++)
                $get(currentObject.inputs[j]).value = "";
            $get(currentObject.units).value = "";
        }

    }
}

var shoppingCart = {
  updateTotalTotal: function(){
    var total = 0;
    for(var i=0; i<cartItems.length; i++){
      var currentObject = cartItems[i];
      total += currentObject.currentQuantity * currentObject.unitPrice;
    }
    $get("pTotalTotal").innerHTML = "TOTAL (excluding freight) " + formatCurrency(total);
  },
  clearCart: function(){
    if(!confirm("Are you sure you wish to remove ALL items?"))
      return;
    for(var i=0; i<cartItems.length; i++){
      var currentObject = cartItems[i];
      $get(currentObject.state).value = "d";
      currentObject.currentQuantity = 0;
      $get(currentObject.itemWrapper).style.display = "none";
    }
    shoppingCart.updateTotalTotal();
  },
  removeClicked: function(event){
    if(!event)
      event = window.event;
    this.myObject.currentQuantity = 0;
    $get(this.myObject.state).value = "d";
    $get(this.myObject.itemWrapper).style.display = "none";
    shoppingCart.updateTotalTotal();
  },  
  quantityBlured: function(event){
    if(!event)
      event = window.event;
      
    var newQuantity = parseInt(this.value);
    if(newQuantity.toString() == "NaN"){
      // I guess we assume it's to be deleted?
      alert("Not a number bro");
      newQuantity = 0;
    }
    else{
      var newTotal = newQuantity * this.myObject.unitPrice;
      newTotal = formatCurrency(newTotal);
      $get(this.myObject.total).innerHTML = newTotal;      
    }
    this.myObject.currentQuantity = newQuantity;
    shoppingCart.updateTotalTotal();
  },
  quantityKeyDown: function(event){
    if(!event)
      event = window.event;
    
    if(event.keyCode == 38){
      if(this.objectAbove)
        $get(this.objectAbove.quantity).focus();
    }
    else if(event.keyCode == 40){
      if(this.objectBelow)
        $get(this.objectBelow.quantity).focus();
    }
  },  
  initializeCart: function() {
    if (!cartItems)
      throw "Cart JSON not loaded, something failed to work correctly...";
      
    for(var i=0; i< cartItems.length; i++){
      var currentObject = cartItems[i];
      var remove = $get(currentObject.remove);
      var quantity = $get(currentObject.quantity);
      
      remove.myObject = currentObject;
      remove.onclick = shoppingCart.removeClicked;
      
      quantity.myObject = currentObject;
      quantity.objectAbove = i > 0 ? cartItems[i-1] : null;
      quantity.objectBelow = (i + 1) < cartItems.length ? cartItems[i+1] : null;
      quantity.onblur = shoppingCart.quantityBlured;
      quantity.onkeydown = shoppingCart.quantityKeyDown;                 
    }  
  }
}