function postJSON(myurl, mydata, func){
	dispAjax();
	var myRequest = new Request({method: 'post', url: myurl,
		onSuccess: function(response){
			var result = $try(function(){return myObject = JSON.decode(response);},function(){ hideAjax(); return false;});
			if (result){ hideAjax(); func(result);}
			else{hideAjax(); errorMSG(response);}
		}, onFailure: function(response){hideAjax(); errorMSG('Error retrieving data from '+myurl);}
	}).send(mydata);
}

function errorMSG(msg){
	alert(msg);
}

function infoMSG(title, msg, timeout){
	var myChain = new Chain();
	var info;
	myChain.chain(
		function() { info = new fbPopup({'title':title, data: msg, allowEscape: false, closeButton:false, overlay:true});},
		function() { info.destruct(); }
	);
	window.setTimeout(function(){myChain.callChain()}, 200);
	window.setTimeout(function(){myChain.callChain()}, ((timeout * 1000) + 1500));
}

window.addEvent('domready', function(){
	$('manuf').inject($('contentholder'), 'top');
	$('contentholder').addClass('contentHolderJS');
	$('manuf').setStyle('display','block');
	if ($('productSelector')) $('productSelector').inject($('content'), 'top');
	$('content').getElements('table.p').each(function(tbl){
		tbl.addEvents({
			'mouseover': function(){tbl.setStyle('border', 'solid #baeeb9 1px');},
			'mouseout': function(){tbl.setStyle('border', 'solid #ffffff 1px');}
		});
		var pimg = tbl.getElement('td.i img');
		var pid = pimg.id;
		pimg.setStyle('cursor', 'pointer').addEvent('click', function(){displayProduct(pid)});
		var buyNow = tbl.getElement('td.p');
		if (buyNow)	var bnow = new Element('div', {'class':'buynow'}).addEvent('click', function(){displayProduct(pid)}).inject(buyNow);
	});
	genQL();
	if ($('productSelector') && $('heading')) {
		$('heading').inject($('productSelector'));
	}
	fixTargets();
});

function dispAjax(){
	var ajaxLoaderOverlay = new Element('div').setProperty('id', 'ajaxLoaderOverlay').injectInside(document.body);
	$('ajaxLoaderOverlay').setStyles({top: Window.getScrollTop()+'px', left: 0, height: Window.getHeight()+'px', width: Window.getWidth() + Window.getScrollLeft()+'px'});
}
function hideAjax(){
	if ($('ajaxLoaderOverlay')) $('ajaxLoaderOverlay').destroy();
}

function fixTargets(){$(document.body).getElements('a').each(function(e){if (e.get('href').match(/^http:\/\//g)) e.set('target','_blank');});}

function updt(q, s){
	var blk = new Element('div');
	var ques = new Element('p', {'html':'Please enter the new quantity for this product:'}).inject(blk);
	var p = new Element('p',{'style':'text-align:center'}).inject(blk);
	var inpt = new Element('input', {'value':q, 'style':'padding:5px; width:60px', events:{
		'keyup': function(){ makeNumeric(inpt);}
	}}).inject(p);
	var updtbtn = new Element('input', {'type':'button','class':'button','value':'Update',events:{
		'click': function(){
			var myRequest = postJSON(base+'includes/cartupdate.php', 's='+s+'&q='+inpt.value, function(r){ window.location.reload();});
		}
	}}).inject(p);
	info = new fbPopup({'title':'Enter new quantity', data: blk, width: 400, allowEscape: false, closeButton:false, overlay:true});
}
function rmprod(s){
	var answer = confirm("Are you sure you wish to remove this product?");
	if (answer){
		var myRequest = postJSON(base+'includes/cartupdate.php', 's='+s+'&q=0', function(r){window.location.reload();});
	}
}

function displayProduct(i){
	var myRequest = postJSON(base+'includes/product.php', 'i='+i, function(r){
		var bigtbl = new Element('table');
		var productTable = new Element('tbody').inject(bigtbl);
		var myTr = new Element('tr').inject(productTable);
		var imgTD = new Element('td', {'class':'tdimg'}).inject(myTr);
		var lrgimg = new Element('img', {'src':base+'images/products/large/'+r.i+'.jpg'}).inject(imgTD);
		var frmTD = new Element('td', {'class':'tdfrm'}).inject(myTr);
		var myForm = new Element('form');
		var i = new Element('input', {'type':'hidden','name':'id','value':r.i}).inject(myForm);
		var tblholder = new Element('table').inject(myForm);
		var tbl = new Element('tbody');
		tbl.inject(tblholder);
		var price = new Element('tr').inject(tbl);
		var priceTD = new Element('td', {'class':'orderTD', 'html':'Item Price:'}).inject(price);
		if (r.p == '0.00') r.p = 'Phone for price';
		else  r.p = '$'+r.p;
		var priceTD = new Element('td', {'class':'selectTD', 'html':r.p}).inject(price);
		var shownElms = 0;
		var n = genSelectTR('Loft', 'loft', r.l); if(n){n.inject(tbl); shownElms++;}
		var n = genSelectTR('Shaft Flex', 'shaft_flex', r.sf); if(n){n.inject(tbl); shownElms++;}
		var n = genSelectTR('Shaft Type', 'shaft_type', r.st); if(n){n.inject(tbl); shownElms++;}
		var n = genSelectTR('Hand Type', 'hand_type', r.ht); if(n){n.inject(tbl); shownElms++;}
		var n = genSelectTR('Colour', 'colour', r.c); if(n){n.inject(tbl); shownElms++;}
		var n = genSelectTR('Size', 'size', r.s); if(n){n.inject(tbl); shownElms++;}
		var quantity = new Element('tr').inject(tbl);
		var qtyDesc = new Element('td', {'class':'orderTD', 'html':'Quantity:','style':'vertical-align:middle'}).inject(quantity);
		var qtyTD = new Element('td', {'class':'selectTD'}).inject(quantity);
		var qty = new Element('input', {'name':'qty','value':'1','style':'width:40px;margin-right: 10px;'}).inject(qtyTD);
		qty.set('autocomplete', 'off');
		qty.addEvent('keyup', function(){ makeNumeric(qty);});
		var atc = new Element('input', {'class':'addtoCart','type':'button', 'value':''}).inject(qtyTD);
		atc.addEvent('click', function(){
			var vals = myForm.toQueryString();
			var myRequest = postJSON(base+'includes/atc.php', vals, function(r){
				mesage.destruct();
				infoMSG('Product added to your cart', r.info, 4);
			});
		});
		myForm.inject(frmTD);
		myForm.set('onsubmit','return false');

		var head = new Element('p', {'html': 'Product Description', 'style':'font-weight: bold;margin:10px 0 2px;'}).inject(frmTD);
		var paddingtotop = 190 - (shownElms * 22);
		var descr = new Element('div', {'class':'description','html':r.d, 'style':'height: '+paddingtotop+'px'}).inject(frmTD);
		var mesage = new fbPopup({'title':r.n, data: bigtbl, width: 650,overlayOpacity: 0.8});
	});
}


function makeNumeric(el){
	var val = el.value;
	var newVal = val.replace(/[^0-9]/g, '');
	el.set('value', newVal);
}
function genSelectTR(d, n, vars){
	if (vars.length > 0){
		var myTr = new Element('tr');
		var tdName = new Element('td', {'class':'orderTD', 'html':d+':'}).inject(myTr);
		var choiceTd = new Element('td', {'class':'selectTD'}).inject(myTr);
		var selectItem = new Element('select',{'name':n}).inject(choiceTd);
		if (vars.length > 1){
			var plsSel = new Element('option', {'value':'NULL','html':'- Please Select -'}).inject(selectItem);
			vars.each(function(val){
				var newElm = new Element('option', {'value':val,'html':val}).inject(selectItem);
			});
		} else {
			var newElm = new Element('option', {'value':vars[0],'html':vars[0]}).inject(selectItem);
		}
		return myTr;
	} else {
		return false;
	}
}

function genQL(){
	if($('prodselect')){
		var holder = new Element('div', {'id':'productSelector'});
		var brandSelect = new Element('select').inject(holder);
		var first = new Element('option', {'value':'','html': '- Shop by Brand -'}).inject(brandSelect);
		var uls = $('prodselect').getElements('td.brand ul li a').each(function(item){
			var otns = new Element('option', {'value':item.get('href'), 'html': item.get('html')}).inject(brandSelect);
			if (item.hasClass('selected')) otns.set('selected', 'selected');
		});
		brandSelect.addEvent('change', function(){if(this.value != '')location.href=this.value;});
		holder.inject($('content'), 'top');
		holder.appendText(' or ');
		var categorySelect = new Element('select').inject(holder);
		var first = new Element('option', {'value':'','html': '- Shop by Category -'}).inject(categorySelect);
		var uls = $('prodselect').getElements('td.category ul li a').each(function(item){
			var otns = new Element('option', {'value':item.get('href'), 'html': item.get('html')}).inject(categorySelect);
			if (item.hasClass('selected')) otns.set('selected', 'selected');
		});
		categorySelect.addEvent('change', function(){if(this.value != '')location.href=this.value;});
		holder.inject($('content'), 'top');
		if ($('prodselect').hasClass('remain') == false) $('prodselect').destroy();
		if ($('heading')) $('heading').setStyle('margin-top', '20px');
	}
}

function validateEmail(emailaddress){ validRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i; if (emailaddress.search(validRegExp) == -1) return false; else return true; }
function checkDetails(){
	var elms = ['fname', 'lname', 'address1','city','phone','email'];
	var errors = false;
	elms.each(function(elm){
		var item = $('frm_'+elm);
		if(item.value.trim() == '') {item.setStyle('background', '#ff9a9a');errors=true;}
		else item.setStyle('background', 'white');
		if (elm == 'email'){if (!validateEmail(item.value.trim())){item.setStyle('background', '#ff9a9a');errors=true;}}
	});
	if (errors){ alert('Please fill in all required fields'); return false; }
	else return true;
}
