// JavaScript Document

var cartURL = "/Cart/";

var cDestination = '';

var npp = 10;

// JQuery Event Handlers
$(document).ready(function() {

    // Search Box: Toggle background
    $("#query").focus(function() {
        $(this).css("background","#e0e0e0");
    });

    $("#query").change(function() {
        if ( $(this).val() != '' )
            $(this).css("background","#e0e0e0");
        else
            $(this).css("background","transparent");
    });

    // Cart: Disable saved orders -- handle the click.
	$(".deleteSavedOrder").click( function() {
		
		var myParent = $(this).parent().parent();
		var cURL = '/Cart/ajax-shopping-cart.php?action=remove_saved_cart&order_id=' + $(this).attr("orderID");

		$.getJSON(
			cURL,                    
			function(data){
				if ( data.success >= 1 ) {
					myParent.remove();
				}
				else {
					alert("Error Removing Saved Cart");
				}
			}
		);
		
	});
	
	// Form Validation
	if ( $("#hamiltonForm").length ) {
	
		$("#hamiltonForm").validate({

		// Fade In/Out to capture attention
			highlight: function(element, errorClass) {
				 $(element).fadeOut(function() {
					 $(element).fadeIn();
					 $(element).addClass('badinput');
				 });
			},

		// This hides the error message itself as it's tough to place them properly in an address form
			errorPlacement: function(error, element) {
				error.hide();
			},

		// Plugin defaults to "error".  this uses the current hamilton form error class.
			errorClass: "badinput",

			invalidHandler: function() {
				return false;
			},

		// Check every field, every time it loses focus.
			onfocusout: function(element) {
				if ( !this.checkable(element) ) {
					this.element(element);
				}
			},

		// Do not validate every keystroke
			onkeyup: false,

		// Remove the "badinput" class while you are editing a field that had an error in it.
			focusCleanup: true
			
		});	
	}
	
});



// 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";
      }
    }
  } 
}




function show_filter_help() { 

	$("#basicModalContent").dialog({
		autoOpen: false,
		modal: true,
		height: 498,
		width: 745,
		resizable: false,
		draggable: false,
		zIndex:3000
	});

	$("#basicModalContent").dialog("open");
	$('#accordion').accordion('resize'); 
	
}

// View Shopping Cart -- Either popup a login box, or go to the cart page //
function view_cart( nLoggedIn ) {

	// No more login required, go right to the cart (6.8.11 / JC)
	window.location = cartURL;
	return;

	var qpURL = cartURL + "/quickPurchase.php";
	
	if ( nLoggedIn ) {
		window.location = qpURL;
	}
	else {
		var encURL = urlencode(qpURL);
		cart_login_dialog( encURL );
	}

}

// Add an item to the cart
function add_to_cart( pid, formName ) { 

	frm = document.getElementById(formName);

	var inputName = "q";
	var qname = "q-" + pid;
	if ( frm[qname] ) { inputName = qname; }

	q = frm[inputName].value;
    
	var cURL = cartURL + "?add=" + pid + "&q=" + q;
    var encURL = urlencode( cURL );
	
    window.location = cURL;

}

// Modal Pop-Up for logging in / adding to cart
function cart_login_dialog( page ) { 

	var url = cartURL + "modalLogin.php?page=" + page;

	$("#loginform").dialog({
		autoOpen: false,
		modal: true,
		height: 420,
		width: 510,
		resizable: false,
		draggable: false,
		zIndex:3000,
		closeText: ''
	});

	$("#loginform").dialog("open");
	$("#modalIframeId").attr("src",url);

}


// 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" );

}

function show_locale_dialog() { 

	$("#localeModalContent").dialog({
		autoOpen: false,
		modal: true,
		height: 410,
		width: 475,
		resizable: false,
		draggable: false,
		closeOnEscape: false,
		zIndex:3000
	});

	$("#localeModalContent").dialog("open");

}

// To load the product lists via Ajax
function load_product_page( category, page, npp ) {
	// Generate a search result

	cURL = '/Apps/ajax-category-product-list.php?c=' + category + '&page=' + page + "&npp=" + npp;
	var oTgt = document.getElementById('product_list');
	show_url( cURL, draw_output, oTgt );
}

// 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 in the product kits to validate selections
function validateKitForm() {
   	
    var valid = true;
    var myForm = document.forms.kitForm;
    var elLength = myForm.elements.length;
    
    // check each of the select options
    for ( i=0; i < elLength-1; i++ ) {	
        var type = myForm.elements[i].type;
       	if ( type=='select-one' ){
       		if ( myForm.elements[i].options[myForm.elements[i].selectedIndex].value == '' ) { valid = false; }
       	}
    }
       
    if ( valid == false ) { alert("Please select an option from all drop downs."); }
    return valid;
}

// Used in the product kits to update the price based on selected items in the list.
function updateKit() {
   	
    var kitTotal = 0;
       
    var myForm = document.forms.kitForm;
    var elLength = myForm.elements.length;

    // total the selections
    for ( i=0; i < elLength-1; i++ ) {
        var type = myForm.elements[i].type;
        if ( type=='checkbox' ) {
            if ( myForm.elements[i].checked ){ 
                if ( myForm.elements[i].title == '0.00' ) {
               	    kitTotal = 'RFQ';
                }else{
                    if ( kitTotal != 'RFQ' ) { kitTotal += Number(myForm.elements[i].title); }
                }
            }
        }else if ( type=='select-one' ){
            if ( myForm.elements[i].options[myForm.elements[i].selectedIndex].title == '0.00' ) {
                kitTotal = 'RFQ';
            }else{
                if ( kitTotal != 'RFQ' ) { kitTotal += Number(myForm.elements[i].options[myForm.elements[i].selectedIndex].title); }
            }
        }else{
            if ( myForm.elements[i].title == '0.00' ) {
                kitTotal = 'RFQ';
            }else{
                if ( kitTotal != 'RFQ' ) { kitTotal += Number(myForm.elements[i].title); }
            }
        }
    }
       
    //add a hidden field to pass the kitTotal
    var element = document.createElement('input');

    // assign attributes to the element.
    element.setAttribute('type', 'hidden');
    element.setAttribute('value', kitTotal);
    element.setAttribute('name', 'kitTotal');

    // append the element to 'kitForm'
    myForm.appendChild(element);
       
    // update the total on the page
    if ( kitTotal != 'RFQ' ) { kitTotal = "$" + kitTotal.toFixed(2); }
    divTotal = document.getElementById('kitTotal');
    divTotal.innerHTML = "<h1 class='bigred'>" + kitTotal + "</h1>";
    //alert("kitTotal is: $" + kitTotal);
}

// 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);
    }else{
       alert("Please make a selection from the drop down.");
    }

}

function is_array(input){
	return typeof(input)=='object'&&(input instanceof Array);
}


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>")
  }
}

