
//
// CART JS
// (c) WeDoWebsites 2009
// Revison 0.67
// PS, 29 June
//



// init
window.onload= function () {

	//should be attach event listener, mumble mumble cross browser drama

	//dopreloads precaches images previously queued by preload()
	//doing it here ensures that normal images take priority in the load queue

	dopreloads();

	//mailto protectors
	//depending on how heavy your page is this may be too late to do it here
	//if thats the case insert into the bottom of your page body with: <script>convertmail()</script>
	// you can style mail class to look like your links
	convertmail();

}




//---------PRELOAD FNS-----------//

//globals for preloads
var preloadfiles = new Array;
var preloadimgs =  new Array;
var preloadindex=0;

//create a queue

function preload(file) {
	file= file.replace(/&amp;/ig,'&');
	preloadfiles[preloadindex] =  file;
	preloadindex++;
}

//action the preload queue on window load

function dopreloads() {
	var c;
	for (c=0;c<preloadindex;c++){
		preloadimgs[c] = new Image;
		preloadimgs[c].src = preloadfiles[c];
	}
}




//-------EMAIL FUNCTIONS---------//


//add antispam event handlers, and mailto tag in two seperate very very paranoid steps
//mail protector
//converts mail class to mailto: href

function convertmail(){
	var elements= document.all?document.all:document.getElementsByTagName('span');
	var i,obj,email;
	for (i=0; i< elements.length; i++) {
		if (elements[i].className =='mail'){
			obj=elements[i];
			email= obj.innerHTML;
			email= email.replace(/blablabla/ig,'');
			obj.innerHTML= email.replace(/ /g,'');
			obj.onmouseover= function (){ insertmailto(this);}
		}
	}
}
function insertmailto(obj) {
	var email = obj.innerHTML;
	email = email.replace(/blablabla/ig,'');
	email = email.replace(/ /g,'');
	obj.innerHTML = '<a href="mailto:'+email+'">'+email+'</a>';
	obj.onmouseover= function (){};
}




//---------SHOW PIECE FUNCTIONS----------//


// SHOWIMAGE
// replaces the main image with a chosen thumb

//this has got complex, and needs rewriting from first principles
//For now there are three args
//  obj is the calling anchor which is parent to the thumb we want
//  isrc is the src we want to insert into main image
//  ifilename is just the filename with imager specs, its this we use for lightbox

function showimage(obj,isrc,ifilename) {
	// thumbimgobj is only need for border changing later.
	// the calling thumb img node is the first child of obj (this)
	for (i=0;i<obj.childNodes.length;i++){
		if (obj.childNodes[i].nodeName=='IMG') {
			var thumbimgobj=obj.childNodes[i];
			break;
		}
	}

	//now the main image object
	var mainimgobj= document.getElementById('piecemainimage');

	//see if it has a lightbox parent A
	if (mainimgobj.parentNode.nodeName=='A') {
		var mainaobj=mainimgobj.parentNode;
		//change its href to ifilename for lightbox
		mainaobj.href=ifilename;
	}

	//change the main image
	mainimgobj.src=   isrc;
	mainimgobj.alt=   thumbimgobj.alt;

	//turn off old highlighted thumb border
	var elements= document.all?document.all:document.getElementById('piecethumbscontainer').getElementsByTagName('A');
	var i;
	for (i=0; i< elements.length; i++) {
		if (elements[i].className=='piecethumbsel')	elements[i].className ='piecethumb';
	}
	//turn on the recently clicked thumb border
	thumbimgobj.className= 'piecethumbsel';

	return false;
}



// UPDATEOPTION
// show an option image and update product price

function updateoption(selobj) {
   //get the selection option object
   var optionobj=selobj.options[selobj.selectedIndex];

	//get variation and option id
	var variation_id = selobj.name.substring(selobj.name.indexOf('_')+1, selobj.name.length);
	var option_id =  selobj.value;

	//get data hidden input (if there is one)
	var dataobj;
	var elements= document.buyform.all?document.buyform.all:document.buyform.getElementsByTagName('input');
	for (i=0; i< elements.length; i++) {
		if (elements[i].name=='optinf_' + variation_id + '_' + option_id) { dataobj=elements[i]; break;}
	}

	//get the option data
	//it goes price,imagesrc,fullsize_src,caption

	if (dataobj && dataobj.value) {
		//get option image info
		var optionimagefile='';
		var optionimagesrc='';
		var optionimagecaption='';
		var args = dataobj.value.split(',');
		optionimagesrc =    args[1];
		optionimagefile=    args[2];
		optionimagecaption= args[3];

		//get option image node
		var optimgobj=document.getElementById('pieceoptionimage');

		if (optionimagesrc) {
			//see if it has a lightbox parent A
			//change its href to optionimagefile for lightbox
			if (optimgobj.parentNode.nodeName=='A') {
				var optionaobj=optimgobj.parentNode;
				optionaobj.href=optionimagefile;
			}

			//change option img src
			optimgobj.src=optionimagesrc;
			optimgobj.alt=optionimagecaption;
			optimgobj.title=optionimagecaption;

			optimgobj.className ='pieceoptionimageon';
			//else optimgobj.className ='pieceoptionimageoff';
		}
	}
	updateprice();
}

// UPDATEPRICE
// updates product total price upon any changes

function updateprice(){
	//rebuild prices
	//iterate thru each variation and add selected option prices
	var totalvariationcost=0;
	//first get all select objects
	var elements= document.buyform.all ? document.buyform.all : document.buyform.getElementsByTagName('SELECT');
	//sift out ones with name='variation_N' ,
	var dataobj; var selobj;
	for (i=0; i< elements.length; i++) {
		if (elements[i].nodeName=='SELECT' && elements[i].name.indexOf('variation')==0) {
			//get our hidden data
			selobj=elements[i];
			//get variation and option id
			var variation_id = selobj.name.substring(selobj.name.indexOf('_')+1, selobj.name.length);
			var option_id = selobj.value;
			if (option_id){
				var dataobj;
				//get hidden data obj
				var elements2= document.buyform.all?document.buyform.all:document.buyform.getElementsByTagName('input');
				for (ii=0; ii< elements2.length; ii++) {
					if (elements2[ii].name=='optinf_' + variation_id + '_' + option_id) { dataobj=elements2[ii]; }
				}
				if (dataobj) {
					var args = dataobj.value.split(',');
					if (args[0]) totalvariationcost+=parseFloat(args[0]);
				}
			}
		}
	}

	//get price span objects
	var obj_bp= document.getElementById('baseprice');
	var obj_vc= document.getElementById('variationscost');
	var obj_tc= document.getElementById('totalcost');
	var obj_st= document.getElementById('subtotal');
	var obj_d = document.getElementById('discount');
	var obj_g=  document.getElementById('gst');
	var obj_gt= document.getElementById('grandtotal');
	var obj_qty=document.getElementById('qty');


	//get constants
	var discount_percent = parseFloat(document.buyform.discount_percent.value);
	var gst_inclusive=     parseInt(document.buyform.gst_inclusive.value);
	var gst_percent=       parseFloat(document.buyform.gst_percent.value);

	//get the current figures
	var baseprice =      obj_bp.innerHTML.replace(/\$/,'');
	var qty=             obj_qty.value;

	//convert all to numerics
	var totalcost;
	var grandtotal;
	var subtotal;
	var discount;
	var gst;

	discount_percent=    parseFloat(discount_percent);
	gst_percent=         parseFloat(gst_percent);
	baseprice=          parseFloat(baseprice);
	totalvariationcost= parseFloat(totalvariationcost);
	qty=                parseInt(qty);

	//calc total cost, using the same algorythim as the php one ;-)
	totalcost =     baseprice+totalvariationcost;
	subtotal =      totalcost * qty;
	discount=       subtotal * discount_percent/100;
	var postdiscount= subtotal-discount;

	//gst
	if (gst_inclusive==1) {
		var gst=postdiscount-postdiscount/(100+gst_percent)*100;
		var grandtotal=  postdiscount;
	}
	else {
		var gst= postdiscount*gst_percent/100;
		var grandtotal=  postdiscount+gst_amount;
	}

	//rewrite the new costs
	obj_vc.innerHTML= moneyformat(totalvariationcost);
	obj_tc.innerHTML= moneyformat(totalcost);
	obj_st.innerHTML= moneyformat(subtotal);
	obj_gt.innerHTML= moneyformat(grandtotal);
	obj_g.innerHTML= moneyformat(gst);
	obj_d.innerHTML= moneyformat(discount);
}

// SHOW PIECE FORM VALIDATION
// check to make sure any required variations are selected

function validateproduct(obj){
	//iterate thru each variation select and find required setting
	var badfields=''; var bcount=0;
	var elements= document.all?document.all:document.getElementsByTagName('select');
	for (i=0; i< elements.length; i++) {
		if (elements[i].name && elements[i].name.indexOf('variation')==0) {
			var args = elements[i].title.split(',');
			var isrequired= args[1];
			var sellabel = args[0];
			if (isrequired=='required' && elements[i].value=='') {
				if (badfields=='') badfields+= sellabel;
				else  badfields += ' and '+sellabel;
				bcount++;
			}
		}
	}
	if (badfields=='') return true;
	else {
		if (bcount==1) { var msg='The product variation '+badfields+ ' is required for this product'; }
		else           { var msg='Product variations '+badfields+ ' are required for this product'; }
		alert(msg);
		return false;
	}
}








/*-----------------CHECKOUT FUNCTIONS----------------------------*/


function checkof(){
	document.getElementById('of').checked=true;
}


//sum frieght + rd + post gst total

function checkoutcalc(){
	var carttotal=     parseFloat(document.checkout.pre_gst_total.value);
	var gstinclusive=  parseInt(document.checkout.gst_inclusive.value);
	var gstpercent=    parseFloat(document.checkout.gst_percent.value);

	//freight
	var freight_id=0;
	for (i=0;i<document.checkout.freight.length;i++) {
		if (document.checkout.freight[i].checked) freight_id= document.checkout.freight[i].value;
	}
	if (freight_id==0) var shipping=document.checkout.optional_shipping.value;
	else {
		var shipping=0;
		var elements= document.checkout.all?document.checkout.all:document.checkout.getElementsByTagName('input');
		for (ii=0; ii< elements.length; ii++) {
			if (elements[ii].name=='freight_cost_' + freight_id)  shipping=elements[ii].value;
		}
	}
	shipping=parseFloat(shipping);
	if (isNaN(shipping)) shipping=0;

	//rd
	var rd=0;
	if (document.checkout.rd_surcharge && document.checkout.rd_surcharge.checked) {
		rd= parseFloat(document.checkout.rd_surcharge.value);
		if (isNaN(rd)) rd=0;
	}

	var post_freight= carttotal+shipping+rd;

	//gst
	if (gstinclusive==1) {
		var gst_amount=post_freight-post_freight/(100+gstpercent)*100;
		var grand_total=  post_freight;
	}
	else {
		var gst_amount= post_freight*gstpercent/100;
		var grand_total=  post_freight+gst_amount;
	}

	document.checkout.shipping_total.value= zeropadtwodp(shipping+rd);
	document.checkout.gst_amount.value =    zeropadtwodp(gst_amount);
	document.checkout.grand_total.value =   zeropadtwodp(grand_total);
}

function settarget(url){
	document.checkout.action= url;
}

function validatecc1(){

	var frm=document.checkout;
	var allesgut = true;
	var msg = '';


	if (frm.cc_type.selectedIndex == -1){
		msg = msg+"Sorry, you have not entered a card type.\n";
		allesgut = false;
	}
	if (frm.cc_no.value.length == 0){
		msg = msg+"Sorry, you have not entered a credit card number.\n";
		allesgut = false;
	}
	else{
		var ccn= frm.cc_no.value;
		ccn =ccn.replace(/[^\d]/g,'');
		if (ccn.length != 16) {
			msg = msg+"Sorry, you have not entered a valid credit card number.\n";
			allesgut = false;
		}
	}

	if (frm.expiry_month.selectedIndex == -1 || frm.expiry_year.selectedIndex == -1){
		msg = msg+"Sorry, you have not entered an expiry date for your credit card.\n";
		allesgut = false;
	}

	if (frm.billing_address.value.length == 0){
		msg = msg+"Sorry, you have not entered a billing address.\n";
		allesgut = false;
	}

	if (allesgut == false) {
		alert(msg);
		return false;
	}
}

function validatecheckout2(){
	var msg='';
	var allesgut = true;
	var radioset=0;
	var i;
	for (i = 0; i < document.checkout.paykey.length; i++) {
		if (document.checkout.paykey[i].checked) {
			var radioset = document.checkout.paykey[i].value;
		}
	}
	if (!radioset){
		msg = msg+"Sorry, you have not selected a payment method.\n";
		allesgut = false;
	}
	if (document.checkout.terms_conditions.checked==false){
		msg = msg+"Sorry, you have not agreed to the terms and conditions.\n";
		allesgut = false;
	}


	if (allesgut == false) {
		alert(msg);
		return false;
	}
}






/*
USAGE NOTES
make sure that this file is called in a <script> call in the head of the page using it. rename file as needed, leave functionname alone
make sure that the form in question contains onsubmit="return validate();" in the <form> tag.
make sure that the form name matches the var frm=documnent.whatevertheformnameis; bit
make sure that every field validated in this function exists with EXACTLY the name specified

to validate that a textfield exists use the 4 lines after marker#1, making frm.whatevertheelementnameis whatever the element's name is
to validate that a textfield exists and is an email use the 11 lines after marker#2, making frm.whatevertheelementnameis whatever the element's name is
to validate that a textfield exists and is a phone number use the 9 lines after marker#3, making frm.whatevertheelementnameis whatever the element's name is
to validate that a radiobutton menu has something selected use the 12 lines after marker#4, making frm.whatevertheelementnameis whatever the element's name is

*/
function validate(){/* function always goes by this name and never accepts arguments. much like a woman actually */

	function is_phone(what){/* leave this alone - validates phone numbers - never needs changing */
		var i;/* instantiate variable */
		for (i=0; i<what.length; i++){  /* for each character in whatever is passed (the phone number) do the following */
			var c = what.charAt(i);/* read the character in question */
			if (!((c>='0'&&c<='9') || (c==' ') || (c=='+') || (c=='(') || (c==')') )){/* if it's not a valid character (0-9, plus, bracket, space)...)*/
				return false;/* return false (exist function)*/
			}
		}
		return true;/* return (3 lines up) will exit the function, so if we got here we know it's all hunky dory so return true (is_phone) */
	}

	var frm=document.checkout;/*document dot whateverthenameoftheformis */
	var allesgut = true;/* instantiates - leave alone */
	var msg = '';/* instantiates - leave alone */

	if(frm.realname.value.length == 0){/*realname is the name of the field. The rest doesnt change*/
		msg = msg+"Sorry, you have not entered a name.\n";/*append the errormessage if this check fails*/
		allesgut = false;/* tells function that at least one error was found*/
	}


	if(frm.delivery_address.value.length == 0){/* as above */
		msg = msg+"Sorry, you have not entered a delivery address.\n";
		allesgut = false;
	}

	if(frm.email.value.length == 0){/* frm.nameofemailfield.etc - whats between frm. and .value is all you muck with */
		msg = msg+"Sorry, you have not entered an email address.\n";
		allesgut = false;
	}
	var email_checkchar1=frm.email.value.indexOf("@");/* frm.nameofemailfield.etc - whats between frm. and .value is all you muck with */
	var email_checkchar2=frm.email.value.lastIndexOf(".");/* frm.nameofemailfield.etc - whats between frm. and .value is all you muck with */
	if((frm.email.value.length > 0)&&(email_checkchar1==-1 || email_checkchar2==-1 || email_checkchar2 < email_checkchar1)){/* if email exists and doesnt: contain @ or contais . or the @ is before the last . or there are letters inbetween... */
		msg = msg+"Sorry, you have not entered a valid email address.\n";/* then it cant be a real email */
		allesgut = false;
	}

	if(frm.phone.value.length==0){/* as before */
		msg = msg+"Sorry, you have not entered your contact phone number.\n";
		allesgut = false;
	}else{
		if(!(is_phone(frm.phone.value))){/* ...but if doesnt look like a real phone number (function at top) */
			msg = msg+"Sorry, you have not entered a valid telephone number (numbers only please).\n";
			allesgut = false;
		}
	}

	var shippingselected = false;
	var j;
	for (j=frm.freight.length-1;j>-1;j--) {
		if (frm.freight[j].checked) {
			shippingselected = true;
		}
	}
	if (shippingselected == false) {/*determined above*/
		msg = msg+"Sorry, you have not entered a freight option at the top of the form. Please select one.\n";
		allesgut = false;
	}


	if (allesgut == false) {/* if any errors, alert message and return false (stops form submitting) */
		alert(msg);
		return false;
	}
}




//-------HOUSEKEEPING FUNCTIONS---------//

function moneyformat(wk){
	wk=parseFloat(wk);
	wk=Math.round(wk*100)/100;
	if (parseInt(wk)==wk) return ('$'+wk+'.00');
	if (parseInt(wk*10)==(wk*10)) return ('$'+wk+'0');
	return ('$'+wk);
}
function zeropadtwodp(wk){
	wk=parseFloat(wk);
	wk=Math.round(wk*100)/100;
	if (parseInt(wk)==wk) return (wk+'.00');
	if (parseInt(wk*10)==(wk*10)) return (wk+'0');
	return (wk);
}

function twodp(wk){
	wk=Math.round(wk*100)/100;

	return(wk);
}




//FUNCTIONS TO DIVIDE A FILENAME INTO PARTS
//wrapper fucntions for getquery and fileparts
// you could do this in like 3 lines in php

function getbasename(wk) {
	var parts= new Array();
	parts=  fileparts(wk);
	var basename=  parts[1];
	var query=     parts[4];
	return (basename);
}
function getquery(wk) {
	var parts= new Array();
	parts=  fileparts(wk);
	var basename=  parts[1];
	var query=     parts[4];
	return (query);
}
function getqueryvalue(a,wk) {
	var pairs= new Array();
	pairs=  splitquery(a);
	if (pairs[wk]) {
		return (pairs[wk]);
	}
	else return ('');
}


// USAGE CORE FUNCTIONS
// myarray=fileparts(filename)
// myarray[0]=path
// myarray[1]=basename
// myarray[2]=barename
// myarray[3]=suffix
// myarray[4]=query

// myarray= splitquery(query){
// myarray[keys]=values


//fn to split a query string

function splitquery(query){
	var ret = new Array();
	var wk =  new Array();
	var pair=  new Array();
	wk= query.split('&');
	for (c=0; c< wk.length; c++) {
		if(wk[c].indexOf('=')>0){
			pair=wk[c].split('=');
			ret[pair[0]]=pair[1];
		}
	}
	return (ret);
}



//fn to divide full filepath into path, basename, and query string

function fileparts (wk){
	var ret = new Array();
	var path;
	var basename;
	var barename;
	var suffix;
	var query;
	var balance;

	//get path
	var i = wk.lastIndexOf('/')
	if (i>0) {
		path=     wk.substring(0,i);
		wk =      wk.substring(i+1);
	}
	else  path='';

	//get basename and query
	i = wk.indexOf('?')
	if (i>0) {
		basename = wk.substring(0,i);
		query=     wk.substring(i+1);
		wk=basename;
	}
	else  {  basename = wk; query=''; }

	//get suffix
	i = wk.lastIndexOf('.')
	if (i>0) {
		barename = wk.substring(0,i);
		suffix=     wk.substring(i+1);
	}
	else  {  barename = wk; suffix=''; }

	ret[0]=path;
	ret[1]=basename;
	ret[2]=barename;
	ret[3]=suffix;
	ret[4]=query;
	return (ret);
}





