// JavaScript Document

var cDestination = '';

// CODE FOR ROLLOVER IMAGES //
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_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 MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){  
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  } 
}


// Add an item to the cart
function add_to_cart( pid ) { 
    var inputName = "q-" + pid;
    frm = document.forms[1];
    q = frm[inputName].value;
    var cURL = cartURL + "?add=" + pid + "&q=" + q;
    document.location.href=cURL;
}


// Set Local from main image map
function setlocale( locale, destination ) { 

   cDestination = destination;

   eLocale = urlencode(locale);

   URL = "/Apps/locale.php?locale=" + eLocale;

   show_url( URL, render_output, "ajaxOut" );

}

// Simple call to jquery to load a URL and run a function, specifying an output target 
function show_url( cURL, fHandler, oTarget ) { 

    $.ajax({

      url: cURL,
      
      cache: false,
      
      beforeSend: function() { document.body.style.cursor = 'wait'; },

      complete:  function() { document.body.style.cursor = 'default'; },

      success: function(html){
         fHandler.apply(this,[html,oTarget]);
      }
    });
}

// Render jquery ajax loaded content into a named div
function draw_output(cText, oTarget) { 
     oTarget.innerHTML = cText;
}

// Render jquery ajax loaded content into a named div
function render_output(cText, oTarget) { 
     oTarget.innerHTML = cText;
     document.location.href=cDestination;
}

// simple way to urlencode a parameter for use in a jquery url
function urlencode( str ) {
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

// Used on the product page to change help text on the spec form

var defaultLow = 0;
var defaultHigh = 0;
var customFormErrors = new Array();

function changehelp( sel, helpid, input )
{
	oHelp = document.getElementById( helpid );
	
	var selected = sel.options.selectedIndex;
	var helptext = sel.options[selected].id;
	
	defaultLow = parseFloat( sel.options[selected].getAttribute('low') ) || 0;
	defaultHigh = parseFloat( sel.options[selected].getAttribute('high') ) || 0;
	
	oHelp.innerHTML = helptext ? helptext : 'Please select a type from the list.';
	checkRange( input );
}

function checkRange( fElement, low, high, refocus ) {
	
	fElement = document.getElementById( fElement );
	
	var value = parseFloat( fElement.value );
	var name = fElement.id;
	
	if ( !low ) { low = parseFloat( defaultLow ); }
	if ( !high ) { high = parseFloat( defaultHigh ); }
	
	// Make sure all input is numeric and within range
	if ( !value || isNaN( value ) || value < low || value > high )
	{
		fElement.style.background='red';
		fElement.style.color='white';
		customFormErrors[ name ] = 0;
	}
	else {
		fElement.style.background='white';
		fElement.style.color='black';
		customFormErrors[ name ] = 1;
	}
}

function validateProductForm( form, fields ) {

	var cMissing = '';
	var cErrors = '';
	var nErrors = 0;
		
	for ( x in fields ) {

	   var fieldname = fields[ x ];
	   
	   input = form[ fieldname ];
	   
	   value = input.value;

	   if ( input && value=='' ) { 
		   cMissing = cMissing + '    ' + fieldname + '\n'; 
		   nErrors++;
	   }
	   else if ( !customFormErrors[ fieldname ] ) {
		   cErrors = cErrors + '    ' + fieldname + '\n';
		   nErrors++;
	   }
	}

	var cMessage = '';
	
	if ( nErrors >= 1 ) {
	   if ( cMissing != '' ) {
		   cMessage = 'The following specifications need to be customized:\n\n' + cMissing + '\n\n';
	   }
	   if ( cErrors != '' ) {
		   cMessage += 'The following specification values are invalid:\n\n' + cErrors;
	   }

	   alert('An Error Occurred while adding this item to your cart:\n\n' + cMessage);

	   return false;
	}
	
	return true; // change to true after testing
	
}

// Shopping Cart: Copy over the billing address
function copy_to_shipping() {

    frm = document.forms[1];

    frm.txtShipFirstName.value = frm.txtBillFirstName.value;
    frm.txtShipLastName.value = frm.txtBillLastName.value;
    frm.txtShipCompany.value = frm.txtBillCompany.value;
    frm.txtShipDepartment.value = frm.txtBillDepartment.value;
    frm.txtShipAddress.value = frm.txtBillAddress.value;
    frm.txtShipAddress2.value = frm.txtBillAddress2.value;
    frm.txtShipCity.value = frm.txtBillCity.value;
    frm.txtShipStateProvince.value = frm.txtBillStateProvince.value;
    frm.selShipCountryCode.options.selectedIndex = frm.selBillCountryCode.options.selectedIndex;
    frm.txtShipPostalCode.value = frm.txtBillPostalCode.value;
    frm.txtShipPhone.value = frm.txtBillPhone.value;
    frm.txtShipFax.value = frm.txtBillFax.value;
	
}

// Shopping Cart: Display the shipping address

function show_shipping_address() {

    frm = document.forms[1];

    frm.txtShipFirstName.value = '';
    frm.txtShipLastName.value = '';
    frm.txtShipCompany.value = '';
    frm.txtShipDepartment.value = '';
    frm.txtShipAddress.value = '';
    frm.txtShipAddress2.value = '';
    frm.txtShipCity.value = '';
    frm.txtShipStateProvince.value = '';
    frm.selShipCountryCode.options.selectedIndex = '';
    frm.txtShipPostalCode.value = '';
    frm.txtShipPhone.value = '';
    frm.txtShipFax.value = '';

    document.getElementById('shipping_address').style.display='block';
	
}


// Shopping Cart: Pull in an address from JSON
   function loadAddress(id,fldname) {
   
      frm = document.forms[1];
      fld = document.getElementById(fldname);
      fld.value=id;
      
      var cURL = '/Cart/ajax-address.php?address_id=' + id;

      $.getJSON(
            cURL,

            function(data){
            
                if ( fldname == "billing_address_id" ) {
                    frm.txtBillFirstName.value = data.customer_address_first_name;
                    frm.txtBillLastName.value = data.customer_address_last_name;
                    frm.txtBillCompany.value = data.customer_address_company_name;
                    frm.txtBillDepartment.value = data.customer_address_department;
                    frm.txtBillAddress.value = data.customer_address_street;
                    frm.txtBillAddress2.value = data.customer_address_street2;
                    frm.txtBillCity.value = data.customer_address_city;
                    frm.txtBillStateProvince.value = data.customer_address_state_province_id;
                    frm.txtBillPostalCode.value = data.customer_address_zip_postal;
                    frm.txtBillPhone.value = data.customer_address_phone;
                    frm.txtBillFax.value = data.customer_address_fax;
                    frm.txtBillEmail.value = data.customer_address_email;
                    frm.txtBillAddressName.value = data.address_name;
                }
                else if ( fldname == "shipping_address_id" ) {
                    frm.txtShipFirstName.value = data.customer_address_first_name;
                    frm.txtShipLastName.value = data.customer_address_last_name;
                    frm.txtShipCompany.value = data.customer_address_company_name;
                    frm.txtShipDepartment.value = data.customer_address_department;
                    frm.txtShipAddress.value = data.customer_address_street;
                    frm.txtShipAddress2.value = data.customer_address_street2;
                    frm.txtShipCity.value = data.customer_address_city;
                    frm.txtShipStateProvince.value = data.customer_address_state_province_id;
                    frm.txtShipPostalCode.value = data.customer_address_zip_postal;
                    frm.txtShipPhone.value = data.customer_address_phone;
                    frm.txtShipFax.value = data.customer_address_fax;
                    frm.txtShipAddressName.value = data.address_name;
                }

            }
      );
      
   }

// Used in the product kits to peek at an item in the list.
function peekAt(nID) {

    var productID = document.getElementById( 'sel' + nID ).value;

    if (productID > 0) {
       cURL = '/item/view/p/' + productID;
       window.open(cURL);
    }

}

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
     document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
        
        document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")

      } else {
        document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}

