var gid;
var xmlHttp;
var sizeList;
var xhrTimeout;
var index;

function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=550,height=600');");
}

function parseWords() {

	sizeList.length = 0;
	var resultXML = xmlHttp.responseXML;
	var products = resultXML.getElementsByTagName("product");

	var listOptions = products[0].getElementsByTagName("options");
	if(listOptions.length < 1) {
		sizeList.options[0] = new Option("None Available",0,true,true);
		//setQuantity(0);
	}
	else {
		for(j=0; j<listOptions.length; j++) {
			var size = listOptions[j].getElementsByTagName("Size")[0];
			var addSurcharge = ""
			var surcharge = size.getAttribute('surcharge');
			if(surcharge > 0) addSurcharge = " (add $"+surcharge+")";
			if(size.getAttribute('stock') != null) {
				sizeList.options[j] = new Option(size.firstChild.nodeValue+addSurcharge+" (S=" + size.getAttribute('stock') + ", C=" + size.getAttribute('supplier_stock') + ")", size.getAttribute('value'), false, false);
			}
			else {
				sizeList.options[j] = new Option(size.firstChild.nodeValue+addSurcharge, size.getAttribute('value'), false, false);
			}
		}
	//checkQuantity(pid);
	}
}

/* More send to friend garbage; delete this if you see it again - RJC
function sendToFriend(productid) {
	popUp = window.open("/sendfriend/index.php?id=" + productid,"popUp","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,width=640,height=575,top=100,left=100");
	if (!popUp) {
		alert("The function you are trying to use requires a pop-up window.  Please disable any pop-up blockers on your system and try again.");
	} else {
		popUp.focus();
	}
}
*/
		
function handleUpdate() {
	
	if (xmlHttp.readyState == 1) {
		document.getElementById("helpful_"+gid).innerHTML = "Was this review helpful? Please Wait";
	}
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
		document.getElementById("helpful_"+gid).innerHTML = "Was this review helpful? Thank You";
		}
	}
}

function updateReview(id, type) {
	gid = id;
	createXMLHttpRequest();
	var query = "/customer/reviews.php?mode=update&id="+id+"&type="+type;
	xmlHttp.onreadystatechange = handleUpdate;
	xmlHttp.open("GET", query, true);
	xmlHttp.send(null);
}

function addReview() {
	createXMLHttpRequest();
	var productid = document.getElementById('productid').value;
	
	var review_body_o = document.getElementById('review_body');
	if(review_body_o != null) var review_body = encodeURI(review_body_o.value);
	else var review_body = "";
	
	var review_title_o = document.getElementById('review_title');
	if(review_title_o != null) var review_title = encodeURI(review_title_o.value);
	else var review_title = "";
	
	var reviewer_o = document.getElementById('reviewer');
	if(reviewer_o != null) var reviewer = encodeURI(reviewer_o.value);
	else var reviewer = "";
	
	var rating = document.getElementById('rating').value;
	
	if(rating > 0 && review_body != "") {
		var query = "/customer/reviews.php?mode=insert&productid="+productid+"&review_body="+review_body+"&review_title="+review_title+"&rating="+rating+"&name="+reviewer;
		xmlHttp.onreadystatechange = handleReview;
		xmlHttp.open("GET", query, true);
		xmlHttp.send(null);
	}
}

function handleReview() {
	
	if (xmlHttp.readyState == 1) {
	}
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
		var content = document.getElementById("review_content");
		var dod_content = document.getElementById("dod_add_review");
		if(content != null)
			content.innerHTML = "<table class=\"review_table\" cellpadding=\"2\" cellspacing=\"0\" width=\"100%\">\n<tr><td>\nThank you for your review.</td></tr><tr><td>It will show up on Getzs.com as soon as it passes our screening process.</td></tr></table>";
		else if(dod_content != null)
			dod_content.innerHTML = "<h5>Own this product? Please add a review.</h5><p>Thank you for your review. It will show up on Getzs.com as soon as it passes our screening process.</p>";
		}
	}
}

function handleSendToFriend() {
	
	if (xmlHttp.readyState == 1) {
	}
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
		var content = document.getElementById("recip_alert");
		content.innerHTML = "Thank you for your sharing this great deal with your friend.";
		}
	}
}

function dod_sendToFriend() {
	var productid = document.getElementById('productid').value;
	var sender = document.getElementById('dod_sender').value;
	var recipient = document.getElementById('dod_recipient').value;
	var result = true;
	
	if(!checkemail(sender)) {
		result = false;
		document.getElementById('sender_alert').innerHTML = "* Please enter your valid email addess";
	} 
	if(!checkemail(recipient)) {
		result = false;
		document.getElementById('recip_alert').innerHTML = "* Please enter a valid email addess";
	}
	
	if(result) {
		createXMLHttpRequest();
		var query = "/customer/ajax/dod.php?mode=send2friend&productid="+productid+"&sender="+sender+"&recipient="+recipient;
		xmlHttp.onreadystatechange = handleSendToFriend;
		xmlHttp.open("GET", query, true);
		xmlHttp.send(null);		
	}
}

function setStars(num) {
	var star_rating = document.getElementById('rating_stars');
	star_rating.style.backgroundPosition = "0 "+num*-16+"px";
	document.getElementById('rating').value = num;
}

function checkemail(str) {
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)) return true
	else return false
}

function addToCart(i) {
	index = i;
	var e = document.getElementById('orderform'+index).elements, i, q = "";
	for(i=0; i < e.length; i++) {
		q += e[i].name + "=" + e[i].value + "&";
	}
	//q += "index=" + index;
	q = q.substr(0, q.length-1);

	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handleAddToCart;
	xmlHttp.open("POST", "/customer/ajax/ajax_cart.php", true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", q.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(q);
}

function handleAddToCart() {
	if (xmlHttp.readyState == 1) {
		$("html, body").animate({scrollTop: 0}, 0);
		clearTimeout(mc.timeout);
		$('#mc-drop').slideUp();
		blackout.showLoader();
	}
	if (xmlHttp.readyState == 4) {
		blackout.hide();
		
		if (xmlHttp.status == 200) {
			var r = xmlHttp.responseXML, i = new miniCartItem();
			//var index = $(r).find("index").text();
			$('#orderform'+index).find('select').get(0).selectedIndex = 0;
			checkOption(index, 0);
			//$(document.orderForm).find('select').get(0).selectedIndex = 0;
			//checkOption(1);
			i.name = $(r).find("name").text();
			i.amount = parseInt($(r).find("amount").text());
			i.price = parseFloat($(r).find("price").text());
			i.thumbnail = $(r).find("thumbnail").text();
			i.color = $(r).find("color").text();
			i.size = $(r).find("size").text();
			i.style = $(r).find("style").text();
			mc.add(i);

			var nTotal = parseFloat($(r).find('newTotal').text()),
			    freeShip = parseFloat($(r).find('freeShip').text()),
					numInCart = $(r).find('numInCart').text();
					gift_amount = $(r).find('gift_amount').text();

			$('.mc-subtotal').text('$' + nTotal.toFixed(2));
			if($('#mc-totalItems').text().indexOf("Cart is empty") > -1) {
				$('.mc').bind("mouseover", function() {clearTimeout(mc.timeout); $('#mc-drop').slideDown(); } );
				$('.mc').bind("mouseout",  function() {mc.timeout = setTimeout("$('#mc-drop').slideUp();", 1500);});
			}

			$('#mc-totalItems').text(numInCart);
			if(freeShip > 0)
				$('#mc-freeShip').text("You are $"+freeShip.toFixed(2)+" away from free shipping!");
			else
				$('#mc-freeShip').text("You qualify for free shipping!");
			$('#mc-freeShip').show();

			mc.curIndex = mc.items.length - 1;
			mc.display();

			$('#mc-drop').slideDown();
			mc.timeout = setTimeout("$('#mc-drop').slideUp();", 2000);
			if(gift_amount) {
				$("#fg_amount").val(gift_amount);
				blackout.show("#free-gift-box");
			}
			else {
				blackout.hide("#free-gift-box");
			}
		}
		else if (xmlHttp.status == 425) {
			blackout.hide("#free-gift-box");
			blackout.error(xmlHttp.responseText);
		}
		else {
			showError("Sorry, but an unknown error occured. Reload the page and try to add the item again, or call us for further assistance.")
		}
	}
}

$(function() {
    $('a.lightbox').lightBox({
				imageLoading:	'/images/lightbox/lightbox-ico-loading.gif',		
				imageBtnPrev:	'/images/lightbox/lightbox-btn-prev.gif',	
				imageBtnNext:	'/images/lightbox/lightbox-btn-next.gif',
				imageBtnClose: '/images/lightbox/lightbox-btn-continue.gif',
				imageBlank:	'/images/lightbox/lightbox-blank.gif',
				fixedNavigation: true, 
				overlayOpacity: '0.6'
    });
});

$(function() {
    $('a.ls_lightbox').lightBox({
				imageLoading:	'/images/lightbox/lightbox-ico-loading.gif',		
				imageBtnPrev:	'/images/lightbox/lightbox-btn-prev.gif',	
				imageBtnNext:	'/images/lightbox/lightbox-btn-next.gif',
				imageBtnClose: '/images/lightbox/lightbox-btn-continue.gif',
				imageBlank:	'/images/lightbox/lightbox-blank.gif',
				fixedNavigation: true, 
				overlayOpacity: '0.6'
    });
});

$(function() {
    $('a.size_lightbox').lightBox({
				imageLoading:	'/images/lightbox/lightbox-ico-loading.gif',		
				imageBtnPrev:	'/images/lightbox/lightbox-btn-prev.gif',	
				imageBtnNext:	'/images/lightbox/lightbox-btn-next.gif',
				imageBtnClose: '/images/lightbox/lightbox-btn-continue.gif',
				imageBlank:	'/images/lightbox/lightbox-blank.gif',
				fixedNavigation: true, 
				overlayOpacity: '0.6'
    });
});

$(function() {
    $('a.view_lightbox').lightBox({
				imageLoading:	'/images/lightbox/lightbox-ico-loading.gif',		
				imageBtnPrev:	'/images/lightbox/lightbox-btn-prev.gif',	
				imageBtnNext:	'/images/lightbox/lightbox-btn-next.gif',
				imageBtnClose: '/images/lightbox/lightbox-btn-continue.gif',
				imageBlank:	'/images/lightbox/lightbox-blank.gif',
				fixedNavigation: true, 
				overlayOpacity: '0.6'
    });
});

function selectTab(tab) {
	$('.tabs > .tab').each(function(i){
		$(this).toggleClass('selected', $(this).attr('tabname') == tab);
	});
	
	$('.panel').each(function(t){
		var t = jQuery(this);
		if(t.hasClass(tab))
			t.show();
		else
			t.hide();
	});
	
	$('#lasttab').value = tab;
}

Array.prototype.sumStock=function(){return parseInt(this[0]) + parseInt(this[1]) + parseInt(this[2]);}
function min(a, b){if(a < b)return a;return b;}