window.INV = new Object();

window.INV.messages = {
	//"processing": "Checking Inventory... Please wait",
	//"inventory-good": "Inventory OK. Items available: ",
	"inventory-good": " ",
	"no-inventory": "Sorry this course is already Sold Out",
	"some-inventory": "We don't have this many items in inventory. Available items: ",
	"max-items": "Maximum amount you can order: ",
	"order-expires": "Your order will expire in 2 minutes due to inactivity. Do you want to extend the time to another 15 minutes?",
	"order-not-extended": "Order not extended. More than 2 minutes has passed. Your cart is emptied.",
	"order-is-extended": "Your cart items are reserved for another 15 minutes.",
	"order-cancelled": "Your cart is emptied.",
	"undefined-code": "ERROR: Undefined Item Code",
	"wrong-xml-file": "ERROR: Wrong Inventory File"
};
//alert(window.INV.messages['some-inventory']);

get_hostname();
switch(window.INV.hostname){
case 'localhost':
case '127.0.0.1':
case 'netsitetest.com':
case 'www.netsitetest.com':
	window.INV.inventoryFileName = 'inventory.xml';
	window.INV.phpFileName = 'update_inventory.php';
	break;
default:
	window.INV.inventoryFileName = 'foxy/inventory.xml';
	window.INV.phpFileName = 'foxy/update_inventory.php';
}
//alert(window.INV.inventoryFileName);

//alert(window.INV.hostname);

/*
window.clearedIndex = 0;
window.clearedSoonMsg=new Array();
window.clearedNow=new Array();
window.date = new Date();
/**/


function pausecomp(millis){
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while(curDate-date < millis);
}
/**/
// send http request
function loadXMLfile(){
	$.ajax({
		//type: "GET",
		//url: window.INV.inventoryFileName+"?"+Math.random(),
		url: window.INV.inventoryFileName,
		//data: "url="+currentURL,
		cache: false,
		success: function(xml){
			//alert("success: " + xml);
			
			if(typeof(window.INV.dataXML)=='undefined'){
				enable_buttons();					
				window.INV.dataXML = new Array();
			}
			
			window.INV.dataXML = xml.getElementsByTagName("item");
			//!!!
			if(FC.json.product_count > 0){
				fill_minicart();
			}
			/*
			window.INV.currentTime = new Date();
			fcc.cart_update.call(fcc);
			if((typeof(window.INV.lastOrderTime) != 'undefined') && (FC.json.product_count>0)){
				fill_minicart();
				//alert(window.INV.currentTime - window.INV.lastOrderTime);
				if(window.INV.currentTime - window.INV.lastOrderTime > 120000){//900000 = 15 mins
						//fcc.cart_update.call(fcc);
						//pausecomp(5000);
						//alert("PRE count: " + FC.json.product_count + " len: " + FC.json.products.length);

					if (confirm(window.INV.messages["order-expires"])){
						fcc.cart_update.call(fcc);
						//alert(FC.json.product_count);
						
						if(FC.json.product_count>0){
							//alert("You pressed OK!");
							window.INV.currentTime = new Date();
							if(window.INV.currentTime - window.INV.lastOrderTime > 150000){//1020000 = 17 mins
								//alert("1st: " + (window.INV.currentTime - window.INV.lastOrderTime));
								window.INV.lastOrderTime = new Date();
								saveFile(window.INV.messages["order-not-extended"], 0, "progress-remove");
								//alert(window.INV.messages["order-not-extended"]);
							} else {
								window.INV.lastOrderTime = new Date();
								alert(window.INV.messages["order-is-extended"]);
							}
						}
					} else {
						fcc.cart_update.call(fcc);
						//alert("CANCEL count: " + FC.json.product_count + " len: " + FC.json.products.length);
						
						if(FC.json.product_count>0){
							//alert("You pressed Cancel!");
							//alert("2nd: " + (window.INV.currentTime - window.INV.lastOrderTime));
							saveFile(window.INV.messages["order-cancelled"], 0, "progress-remove");
						}
					}
					
				}
				//alert(window.INV.currentTime - window.INV.lastOrderTime);
			}/**/

			setTimeout("loadXMLfile()", 15000);
			//alert(window.INVdataXML[1].attributes.getNamedItem("code").value);

			/*
			$(xml).find('item').each(function(){
				var id_text = $(this).attr('code');
				var name_text = $(this).find('item').text();
				//alert(id_text);
			});
			/**/
		},
		error: function(msg){
			alert("error: " + msg);
		}
	});
	//alert(a);
}

function check_inventory(formID){
	window.INV.formID = formID;
	window.INV.lastOrderTime = new Date();
	/*
	$('form[action^=https://esoutherngolf.foxycart.com/cart]').append('<input type="hidden" name="h:LastOrderTime" value="' + window.INV.lastOrderTime +  '" />');
	/**/
	
	window.INV.quantityRequested = $("#" + window.INV.formID + " > input[name='quantity']").val();
	if(typeof(window.INV.quantityRequested) != 'undefined'){
		if(isNaN(window.INV.quantityRequested)){
			window.INV.quantityRequested = 1;
			$("#" + window.INV.formID + " > input[name='quantity']").val("1");
		} else if(window.INV.quantityRequested<0){
			window.INV.quantityRequested = 1;
			$("#" + window.INV.formID + " > input[name='quantity']").val("1");
		}
	} else {window.INV.quantityRequested = 1;}

	window.INV.itemCode = $("#" + window.INV.formID + " > input[name='code']").val();
	if(typeof(window.INV.itemCode) == 'undefined'){
		say_message(window.INV.messages["undefined-code"]);
		//trace(false, "undefined-code");
		return false;
	}
	
/*				
	//alert(window.INV.dataXML);
	//alert(window.INV.dataXML[0].childNodes[0].nodeValue);
	//alert(window.INV.dataXML[0].attributes.getNamedItem("code").value);
/**/				
	var i = 0;
	var firstFound = true;
	while((i<window.INV.dataXML.length)&&(firstFound)){
		if(window.INV.itemCode == window.INV.dataXML[i].attributes.getNamedItem("code").value){
			//alert(window.INV.dataXML[i].childNodes[0].nodeValue);
			
			window.INV.inProgress = window.INV.dataXML[i].attributes.getNamedItem("inprogress").value;
			window.INV.inStock = window.INV.dataXML[i].childNodes[0].nodeValue;
			window.INV.availableItems = window.INV.inStock-window.INV.inProgress;

			//set quantity_max as min of what is set in html form and what is left in inventory
			if(typeof($("#" + window.INV.formID + " > input[name='quantity_max']").val()) != 'undefined'){
				window.INV.quantity_max = $("#" + window.INV.formID + " > input[name='quantity_max']").val();
				if(!isNaN($("#" + window.INV.formID + " > input[name='quantity_max']").val())){
					window.INV.quantity_max = Math.min(window.INV.availableItems, $("#" + window.INV.formID + " > input[name='quantity_max']").val());
					$("#" + window.INV.formID + " > input[name='quantity_max']").val(window.INV.quantity_max);
					//$("#" + window.INV.formID + " > input[name='quantity_max']").val(Math.min(window.INV.availableItems, $("#" + window.INV.formID + " > input[name='quantity_max']").val()));
				}	//!!! else if isNan		
			} else {
				window.INV.quantity_max = window.INV.availableItems;
				$("#" + window.INV.formID).prepend('<input type="hidden" name="quantity_max" value="' + window.INV.availableItems + '" />');
			}
			//alert(window.INV.quantity_max);
			//alert($("#" + window.INV.formID + " > input[name='quantity_max']").val());
			
			firstFound = false;
		}
		i++;
	}

	//a little check of window.INV.inventoryFileName variable in case somebody hacks the script. It checks if the variable ends with ".xml"
	if(window.INV.inventoryFileName.slice(-4)!=".xml"){
		say_message(window.INV.messages["wrong-xml-file"]);
		//trace(false, "wrong-xml-file");
		return false;
	} else {
		if (window.INV.availableItems - window.INV.quantityRequested >= 0){
			var i = 0;
			var firstFound = true;
			while((i<FC.json.products.length)&&(firstFound)){
				/*
				alert("i: " + i + " FC: " + FC.json.products.length + 
					  "  c/pc: " + window.INV.itemCode + " " + FC.json.products[i].code +
					  " ?= " + (window.INV.itemCode == FC.json.products[i].code));
				/**/
				if(window.INV.itemCode == FC.json.products[i].code){
					//alert("jsQu: " + FC.json.products[i].quantity + " qR " + window.INV.quantityRequested + " qM " + window.INV.quantity_max);
					if(parseInt(FC.json.products[i].quantity) + parseInt(window.INV.quantityRequested) > window.INV.quantity_max){
						say_message(window.INV.messages["max-items"] + window.INV.quantity_max);
						return false;
					} else {
						saveFile(window.INV.itemCode, window.INV.quantityRequested, "progress");
						//say_message(window.INV.messages["inventory-good"] + window.INV.availableItems);
						//trace(true, "inventory-good");
						return true;
					}
					firstFound = false;
				}
				i++;
			}
			//if item was not shopped before (no such code found)
			if(firstFound){
				saveFile(window.INV.itemCode, window.INV.quantityRequested, "progress");
				//say_message(window.INV.messages["inventory-good"] + window.INV.availableItems);
				//trace(true, "inventory-good");
				return true;
			}
		} else {
			if(window.INV.availableItems <= 0){
				say_message(window.INV.messages["no-inventory"]);
			} else {
				say_message(window.INV.messages["some-inventory"] + window.INV.availableItems);
			}
			//trace(false, "no or some inventory");
			return false;
		}
	}
}

function say_message(message){
	//alert(message);
	$("#" + window.INV.formID + " > span[class='messages']").html(message);
}

function trace(bool, message){
	alert("trace " + message);
}

/*
function updateTimeout(bool, message){
	//var d = new Date();
	//alert(d - window.date);
	window.date = new Date();
	//alert(window.date);
	if (confirm("Press a button")){
		alert("You pressed OK!");
	} else {
		alert("You pressed Cancel!");
	}
	window.clearedSoonMsg[window.clearedIndex]=setTimeout("alert('emptying in 2 seconds!')",3000);
	window.clearedNow[window.clearedIndex]=setTimeout("saveFile(window.INV.itemCode, window.INV.quantityRequested, 'progress-remove')", 5000);
	//clearTimeout(t);
	
}

function newDate(){
	window.d=new Date();
	alert("date " + window.d);
	setTimeout('newDate()', 5000);
}
/**/

function disable_buttons(){
	//disable all form buttons
	$("input[type='submit']").attr("disabled", "disabled");
	$("input[type='image']").attr("disabled", "disabled");
	//alert($("#" + formID + " > input[type='submit']").val());
	//alert($("#" + formID + " > span[class='messages']").val());
}

function enable_buttons(){
	//enable all form buttons
	$("input[type='submit']").attr("disabled", "false");
	$("input[type='submit']").removeAttr('disabled')
	
	$("input[type='image']").attr("disabled", "false");
	$("input[type='image']").removeAttr('disabled')
}

function empty_cart(){
	//empty cart
	//alert("empty cart called " + storedomain + " " + fcc.session_get());
	//$.getJSON('https://'+storedomain+'/cart?empty=true&cart=view' + fcc.session_get(), function(data){
	//$.getJSON('https://'+storedomain+'/cart?empty=true' + fcc.session_get(), function(data){
	$.getJSON('https://'+storedomain+'/cart?output=json&empty=true&callback=?' + fcc.session_get(), function(data){
		//alert(data);
		//alert("cart emptied");
		fcc.cart_update.call(fcc);
		//alert("empty cart json finished");
		//!!! mayble clear all messages in span.messages here
		$('form[action^=https://esoutherngolf.foxycart.com/cart] > span[class="messages"]').each(function(index) {
			$(this).html(' ');
		});
	});
}

function saveFile(code, amount, type){
	disable_buttons();
	//alert("saveFile " + code);
	
	/*
	window.INV.products = {
		"c1": "first",
		"c2": "second"
	};
	//alert(window.INV.products);
	var recursiveEncoded = $.param(window.INV.products);
	var recursiveDecoded = decodeURIComponent($.param(window.INV.products));
	/**/
	
	//alert(recursiveEncoded);
	//alert(recursiveDecoded);
	//alert(jQuery(window.INV.products).serialize());

	if(type == 'progress'){
		//alert(window.INV.inProgress +  " " + amount);
		window.INV.inProgress = parseInt(window.INV.inProgress) + parseInt(amount);
		//alert(window.INV.inProgress +  " " + amount);
		window.INV.availableItems = window.INV.inStock-window.INV.inProgress;
		
		$.ajax({
		   type: "POST",
		   url: window.INV.phpFileName,
		   data: "filename="+window.INV.inventoryFileName+"&code="+code+"&amount="+amount+"&type="+type,
		   success: function(msg){
			 //alert("Data Saved: " + msg );
			 enable_buttons();
		   }
		 });
	}
	if(type == 'progress-remove'){
		//alert(fcc.session_get(), " removing reserved");
		
		//alert("remove: " + FC.json.product_count);
		//alert("remove: " + FC.json.products.length);
		for(var i=0; i<FC.json.products.length; i++){
			//alert(FC.json.products[i].code);
			//alert(FC.json.products[i].options.HostWebsite);
			//!!! implement www
			//if(FC.json.products[i].options.HostWebsite == window.INV.hostname){
				//alert("i: " + i + " " + FC.json.products[i].options.HostWebsite);
				$.ajax({
				   type: "POST",
				   url: window.INV.phpFileName,
				   data: "filename="+FC.json.products[i].options.HostWebsite+"&code="+FC.json.products[i].code+"&amount="+FC.json.products[i].quantity+"&type="+type,
				   success: function(msg){
						//alert("POST: " + msg );
						//alert("Data Saved: " + i);
						//enable_buttons();
				   },
				   error: function(msg){
						//alert("ERROR: " + msg.responseText );
						//alert("Data Saved: " + i);
						//enable_buttons();
				   }
				 });
			//}
			if(i==FC.json.products.length-1){enable_buttons();}
		}
		alert(code);
		//alert("prog rem: " + code);
		empty_cart();
	}
}

function get_hostname(){
	window.INV.hostname = window.location.hostname;
	//alert(window.INV.hostname);
	if(window.location.hostname.substr(0, 4) == 'www.'){
		window.INV.hostname = window.location.hostname.substr(4);
		//alert(window.INV.hostname);
	}
}

function fill_minicart(){
	//!!! maybe its undefined???
	//if(parseInt(FC.json.products.length) != 0){
		var minicart = '<table border="0" cellspacing="0"><tr><th>Name</th><th>Quantity</th></tr>';
		//alert(FC.json.products.length);
		for(var i=0; i<FC.json.products.length; i++){
			if(i!=(FC.json.products.length-1)){
				minicart += '<tr>';
			} else {
				minicart += '<tr class="last">';
			}
			minicart += '<td class="products_minicart_name">'+FC.json.products[i].name+'</td>';
			minicart += '<td class="products_minicart_quantity">'+FC.json.products[i].quantity+'</td></tr>';
			//if(i!=FC.json.products.length){minicart = minicart + '<br />';}
		}
		minicart += '</table>';
		$('#products_minicart').html(minicart);
	//}
	/**/
	//alert(minicart);
}
/*
<td></td>
<td></td>

/**/

fcc.events.cart.preprocess.add(function(e, arr) {
	var href = '';
	if (e.tagName == 'A') {
		href = e.href;
		return true;
	} else if (e.tagName == 'FORM') {
		href = 'https://'+storedomain+'/cart?'+jQuery(e).serialize();
	}
	if (!href.match("cart=(checkout|updateinfo)") && !href.match("redirect=")) {
		//alert(e.getAttribute('code'));
		//alert("preprocess: " + FC.json.product_count);
		//alert(arr.code);
		return check_inventory(e.getAttribute('id'));
		//alert("preprocess called");
		return false;
	}
});

/*
fcc.events.cart.process.add(function(e){
	alert('lala');
	//fcc.events.cart.postprocess.execute(e);
	return false;
});
fcc.events.cart.process.add_pre(function(e, arr) {
	//fcc.cart_update.call(fcc);
	//alert("process pre: " + FC.json.product_count);
	
	return true;
});
/**/
/*
fcc.events.cart.process.add(function(e){
	alert('lala');
	alert(FC.json.product_count);
	var href = '';
	if (e.tagName == 'A') {
		href = e.href;
	} else if (e.tagName == 'FORM') {
		href = 'https://'+storedomain+'/cart?'+jQuery(e).serialize();
	}
	if (href.match("cart=(checkout|updateinfo)") || href.match("redirect=")) {
		return true;
	} else {
		return true;
	}
});
/**/

/*
fcc.events.cart.postprocess.add(function(){
	//alert('xoxo');
	//fcc.cart_update.call(fcc);
	//alert("postprocess: " + FC.json.product_count);
});
/**/

/*
// execute program when page is loaded
window.onload=function(){
    // check if browser is DOM compatible
    if(document.getElementById&&document.getElementsByTagName&&document.createElement){
    }
}
/**/

// <![CDATA[
$(document).ready(function() {
	/*
	var dir = location.pathname.substring(0,location.pathname.lastIndexOf('/')+1);
	alert("dir: " + dir + "");
	/**/
	
	//alert(FC.json.products);
	//alert(window.location.hostname);
	//add HostWebsite hidden input to each form
	//get_hostname();
	$('form[action^=https://esoutherngolf.foxycart.com/cart]').each(function(index) {
		$(this).append('<input type="hidden" name="HostWebsite" value="' + window.INV.hostname +  '" />')
		//alert($(this).html());
		//alert($(this).attr('title'));
	});
	
	//$('#nitro-banner').append('<div id="products_minicart"></div>');
	$('.fc_minicart').append('<div id="products_minicart"></div>');
	$('#products_minicart').css("display","none");
	//$('#products_minicart').css("top", $(".fc_minicart").css('bottom'));
	setTimeout('fill_minicart()', 3000);
	$(".fc_minicart").hover(
		function () {
			//$(this).append("<strong>Hello</strong>");
			$('#products_minicart').css("display","block");
		},
		function () {
			//$(this).removeClass("hover");
			$('#products_minicart').css("display","none");
		}
	);
	/**/



	//!!! add a hidden date and check if its been more than 15 mins the user opened the page
	/*
	if(FC.json.product_count>0){
		fcc.cart_update.call(fcc);
		alert(FC.json.custom_fields.LastOrderTime);
		alert("lala");
		//window.INV.currentTime = new Date();
		//empty_cart();
	}
	/**/
	if(typeof(window.INV.dataXML)=='undefined'){
		//dataXML is undefined, which means this is the first loading of XML file. Disable submit buttons till XML loads
		disable_buttons();
	}
	// load XML file
	loadXMLfile();
});
//--><!]]>
/**/
