/* site_functions.js
 * put site specific javascript functions here
 * is already included in header.tpl
 */

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 findPosX(obj){
	var curleft = 0;
	if(obj.offsetParent)
	    while(1) 
	    {
	      curleft += obj.offsetLeft;
	      if(!obj.offsetParent)
	        break;
	      obj = obj.offsetParent;
	    }
	else if(obj.x)
	    curleft += obj.x;
	return curleft;
}

function findPosY(obj){
	var curtop = 0;
	if(obj.offsetParent)
	    while(1)
	    {
	      curtop += obj.offsetTop;
	      if(!obj.offsetParent)
	        break;
	      obj = obj.offsetParent;
	    }
	else if(obj.y)
	    curtop += obj.y;
	return curtop;
}

function show_confirm(msg, loc){
	var r=confirm(msg);
	if (r==true){
		window.location = loc;
	}
}

function use_address(first_name, last_name, phone, address, address2, city, state, zip){
	document.getElementById("first_name").value = first_name;
	document.getElementById("last_name").value = last_name;
	document.getElementById("phone").value = phone;
	document.getElementById("address").value = address;
	document.getElementById("address2").value = address2;
	document.getElementById("city").value = city;
	document.getElementById("zip").value = zip;
	select_Value_Set("state", state);
}

function select_Value_Set(selectName, Value){
	//eval('selectObject = document.' + selectName + ';'); 
	selectObject = document.getElementById(selectName);
	for(index = 0; index < selectObject.length; index++){
		if(selectObject[index].value == Value){
			selectObject.selectedIndex = index; 
		}
	} 
}

function forgot_password(url){
	if(document.getElementById("email")){
		var email = document.getElementById("email").value;
		if(email == ''){
			document.getElementById("email").style.backgroundColor = "#AF231D";
			document.getElementById("email").style.color = "#fff";
			alert("Please enter your account email address into the field provided and try again.");
		} else {
			window.location = "actions/forgot_password.php?email=" + email;
		}
	}
}

function proceedToCheckout(){
	if(document.getElementById("cart")){
		// change the next step to the shipping address. default is the view cart page
		document.getElementById("nextStep").value = "address";
		
		// submit the form
		document.getElementById("cart").submit();
	}
}

function submitOrder(){
	if(document.getElementById("cart")){
		document.getElementById("cart").submit();
	}
}

function setShippingOption(itemId){
	if(document.getElementById(itemId)){
		document.getElementById(itemId).checked = true;
	}
}

function popup(url,width,height) {
	window.open(url, "", "resizable=1,height=" + height + ",width=" + width);
}

function updateDiv(destination, source) {
	if(document.getElementById(destination)){
		var sourceContent = document.getElementById(source).innerHTML;
		document.getElementById(destination).innerHTML = sourceContent;
	}
	
	if(destination == 'specifications_block'){
		// turn off all active tabs and turn on selected tab
		var tabs = new Array();
		var msg = "";
		tabs[1] = 'description';
		tabs[2] = 'related_products';
		tabs[3] = 'specifications';
		tabs[4] = 'reviews';
		for(i=1; i<5; i++){
			if(document.getElementById("tabs_" + tabs[i])){
				document.getElementById("tabs_" + tabs[i]).className = tabs[i] + "_tab";
				msg += "document.getElementById(tabs_" + tabs[i] + ").className = " + tabs[i] + "_tab\n";
			}
		}
		source = source.replace("content_", "");
		document.getElementById("tabs_" + source).className = source + "_sel";
		msg += "document.getElementById(tabs_" + source + ").className = " + source + "_sel\n";
		
		//alert(msg);
	}
}

function toggleUl(listId){
	if(document.getElementById(listId)){
		// make it show/hide
		var list = document.getElementById(listId).style;
		if (list.display == "block") {
			list.display = "none";
		} else {
			list.display = "block";
		} 
	}
}
// this is used for changing the product image. Also included in the selectbox for the per-color changer
function updateProductImage(imageUrl, popupUrl){
	if(document.getElementById("productImage")){
		document.getElementById("productImage").style.backgroundImage = "url(" + imageUrl + ")";
		document.getElementById("productImageLink").href = popupUrl;
		//document.getElementById("productImageLink").href = "javascript:popup('" +popupUrl+ "',800,600);";
	}
}

function updateProductImageOnColorChange(productId, colorId){
	imagePath = rootPath + "uploads/Product/";
	imageUrl = imagePath + "Product_" + productId + "_image_1_" + colorId + ".jpg";
	popupUrl = imagePath + "Product_" + productId + "_image_1_" + colorId + "_detail.jpg";
	updateProductImage(imageUrl, popupUrl);
}

// this is a plural version of the function above (which is no longer used).
// updates a SET of images on color change, including the thumbnail list
function updateProductImagesOnColorChange(productId, colorId){
	if(productColorImages[colorId]){
		var thumbnailHtml = "";
		var i=0;
		for(var n in productColorImages[colorId]){
			if(productColorImages[colorId][n]["image"]){
				image = productColorImages[colorId][n]["image"];
				thumb = productColorImages[colorId][n]["thumb"];
				detail = productColorImages[colorId][n]["detail"];
			
				thumbnailHtml += "<a href=\"#\" onmouseover=\"updateProductImage('"+ image + "','" + detail + "');\">";
				thumbnailHtml += "<img src=\"" + rootPath + "blank.gif\" style=\"background:#fff url('" + thumb + "') center no-repeat;\"";
				thumbnailHtml += " alt=\"Click to enlarge\" width=\"48\" height=\"40\" /></a>";
				
				if(i<1){
					var firstImage = image;
					var firstDetail = detail;
				}
				
				i+=1;
			}
		}
		
		// update the first big pic
		updateProductImage(firstImage, firstDetail);
		document.getElementById("productThumbs").innerHTML = thumbnailHtml;
	}
}

function hasSelectedColor(){ 
	if(document.getElementById("colorId")){
		var colorId = document.getElementById("colorId").options[document.getElementById("colorId").selectedIndex].value;
		if(!colorId || colorId == ''){
			return false;
		}
	}
	return true;
}

var colorErrorShown = false;
function selectAColorMessage(show){
	if(show == true){
		// show error bubble
		document.getElementById("color_warning").innerHTML = "Please select a color<br />option to continue.";
		document.getElementById("color_warning").style.visibility = "visible";
		colorErrorShown = true;
	} else {
		// hide the message
		document.getElementById("color_warning").style.visibility = "hidden";
		colorErrorShown = true;
	}
}

// check that quantity is divisible by packageOf
function confirmQuantity(quantity, packageOf){
	var divisor = (quantity / packageOf);
	if(isWholeNumber(divisor) == false || quantity < 1){
		document.getElementById("quantity_warning").innerHTML = "This product is sold in packages of " + packageOf + ".<br />Please enter a multiple of " + packageOf + ".";
		document.getElementById("quantity_warning").style.visibility = "visible";
		document.getElementById("quantity").className = "lanyards_quantity_error";
		document.getElementById("add_to_cart").disabled = true;
	} else {
		document.getElementById("quantity_warning").style.visibility = "hidden";
		document.getElementById("add_to_cart").disabled = false;
		document.getElementById("quantity").className = "lanyards_quantity";
		
		updatePriceEach(quantity);
		updatePriceTotal(quantity);
	}
}

function updatePriceEach(quantity){
	var price_each = priceEach(quantity);
	var total_cost = price_each * quantity;
	document.getElementById("total_cost").innerHTML = "$" + total_cost.toFixed(2);
}

function updatePriceTotal(quantity){
	var price_each = priceEach(quantity);
	document.getElementById("price_each").innerHTML = "$" + price_each + " each";
}

function priceEach(quantity){
	var key = fallsWithinPrice(quantity);
	return productPrice[key].toFixed(2);
}

function fallsWithinPrice(quantity){
	if(productPrice){ // defined in header.tpl
		var key = false;
		for(qty in productPrice){
			if(parseInt(qty) <= parseInt(quantity)){
				key = qty;
			}
		}
		return key;
	}
}

function isWholeNumber(inputStr) 
{
    //get the inputStr of the input string
	str = inputStr.toString();
	
	//now we need to loop through the length
	//of the input value
	for(var i=0; i < str.length; i++)
	{
	    //use charAt to get the current value
		var curValue = str.charAt(i);
		
		//check the value of the current value, if it's less
		//than 0 (zero) and more than 9 we know the value
		//isnt a whole number
		if(curValue < "0" || curValue > "9")
		{
			return false;	
		}
	}
	return true;
}

function alignColumns(){
	if(document.getElementById("center_column") && document.getElementById("right_column")){
		right_column_height = document.getElementById("right_column").offsetHeight;
		if(document.getElementById("center_column").offsetHeight < right_column_height){
			document.getElementById("center_column").style.height = right_column_height + "px"
		}
	}
}

function mega_dropdown(divId){
	if(!divId){
		// hide all dropdowns
		hide_mega_dropdowns();
		
	} else {
		hide_mega_dropdowns();
		var showDiv = document.getElementById("dropdown_" + divId);
	
		if(showDiv){
			document.getElementById("img_" + divId).src = rootPath + "images/buttons/nav_" + divId + "_sel.gif";
			showDiv.style.visibility = "visible";
		}
	}
}

function hide_mega_dropdowns(){
	document.getElementById("dropdown_access_control").style.visibility = "hidden";
	document.getElementById("img_access_control").src = rootPath + "images/buttons/nav_access_control_ini.gif";
	document.getElementById("dropdown_badge_reels_and_lanyards").style.visibility = "hidden";
	document.getElementById("img_badge_reels_and_lanyards").src = rootPath + "images/buttons/nav_badge_reels_and_lanyards_ini.gif";
	document.getElementById("dropdown_id_card_printers").style.visibility = "hidden";
	document.getElementById("img_id_card_printers").src = rootPath + "images/buttons/nav_id_card_printers_ini.gif";
	document.getElementById("dropdown_id_card_printer_supplies").style.visibility = "hidden";
	document.getElementById("img_id_card_printer_supplies").src = rootPath + "images/buttons/nav_id_card_printer_supplies_ini.gif";
	document.getElementById("dropdown_visitor_management").style.visibility = "hidden";
	document.getElementById("img_visitor_management").src = rootPath + "images/buttons/nav_visitor_management_ini.gif";
	document.getElementById("dropdown_id_systems_and_software").style.visibility = "hidden";
	document.getElementById("img_id_systems_and_software").src = rootPath + "images/buttons/nav_id_systems_and_software_ini.gif";
	document.getElementById("dropdown_badge_holders_and_clips").style.visibility = "hidden";
	document.getElementById("img_badge_holders_and_clips").src = rootPath + "images/buttons/nav_badge_holders_and_clips_ini.gif";
	
	// does not have a mega drop down
	//document.getElementById("dropdown_accessories").style.visibility = "hidden";
	//document.getElementById("dropdown_services").style.visibility = "hidden";
}

var leaving = true;
function checkUrl(href) {
	leaving = (((href.indexOf("://") > -1) || (href.indexOf("www.") > -1)) && (href.indexOf(window.location.host) == -1));
}

function leave_too_soon(){
	if(leaving){ 
		//alert("Leaving? Running background scripts");
		//runPhpScript(rootPath + "actions/leave_too_soon.php");
	}
}

var req;
function runPhpScript(url) {
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.open("GET", url, true);
		req.send(null);
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.open("GET", url, true);
			req.send();
		}
	}
}

var t;
function showNoEditWarning(obj){
	var bubble = document.getElementById("noEdit_warning");
	bubble.innerHTML = "To change quantity, remove from cart<br />and re-add from the detail page.";
	bubble.style.visibility = "visible";
	
	bubble.style.left = (findPosX(obj) - 88) + "px";
	bubble.style.top = (findPosY(obj) - 48) + "px";
	
	// set timeout to hide bubble
	clearTimeout(t);
	t = setTimeout("hideNoEditWarning()", 3500);
}

function hideNoEditWarning(){
	var bubble = document.getElementById("noEdit_warning");
	bubble.innerHTML = " ";
	bubble.style.visibility = "hidden";
	clearTimeout(t);
}
