﻿/*
## FONTEF ########################################################################
## By Meir Sadan #################################################################
##################################################################################
## cart.js
##
## Functions and initializers for the shopping cart
##
##################################################################################
*/

// decodeItemsString: function for parsing a saved shopping cart

function decodeItemsString(str) {
	var typefaces=str.split(']');
	var typefaceDetails=new Array(), format=new String(), typefaceName=new String(), fontName=new String(), weights=new Array();
	var _doWeights = function(typeName, weightsData) {
		var weightData=new Array(), k=0;
		for (var j=0;j<cartData[typeName].weights.length;j++) {
			if (weightsData[k].length)
				weightData=weightsData[k].split(':');
			if (weightData[0]==j)
				k++;
			else
				toggleWeight(document.getElementById(typeName).getElementsByTagName('TD')[1].getElementsByTagName('LI')[j]);
		}
	}
	for (var i=0;i<typefaces.length-1;i++) {
		weights=typefaces[i].split('[');
		typefaceDetails=weights[0].split(':');
		typefaceName=typefaceDetails[0];
		format=typefaceDetails[1];
		weights=weights[1].split(';');
		fontName=typefaceName.substring(typefaceName.indexOf('_')+1,typefaceName.length);
		addToCart(document.getElementById(fontName).getElementsByTagName('SPAN')[3]);
		setTimeout(function() {
			changeFormat(document.getElementById(typefaceName).getElementsByTagName('TD')[2].getElementsByTagName('LI')[format]);
		}, 500);
		if (cartData[typefaceName].lock) {
			setTimeout(function() { _doWeights(typefaceName, weights) }, 500);
		}
	}
	setTimeout(function() { updateTotalSum(1); }, 2000);
}

// checkForOrder: see if there's an open session with an active shopping cart

function checkForOrder() {
	var _checkForOrder = function(req) {
		data = eval('('+req.responseText+')');
		if (data.o) decodeItemsString(data.o);
	}
	sendRequest(baseurl+"get_order.php", _checkForOrder);
}

// checkForDetails: checks for a cookie containing past user information

function checkForDetails() {
	var checkValue=false;
	var _checkForDetails = function(req) {
		data = eval('('+req.responseText+')');
		for (var formField in orderForm) {
			if (data[formField.substring(formField.indexOf('_')+1, formField.length)]) {
				document.getElementById(formField).value=data[formField.substring(formField.indexOf('_')+1, formField.length)];
				orderForm[formField].value=data[formField.substring(formField.indexOf('_')+1, formField.length)];
				checkValue=true;
			}
		}
		if (data.o) decodeItemsString(data.o);
		document.getElementById('rememberThis').checked=checkValue;
	}
	sendRequest(baseurl+"get_details.php", _checkForDetails);
}

// updateTotalSum: update total sum in shopping cart

function updateTotalSum(firstTime) {
	var totalSum=new Number();
	var formatString="",itemsString="",fontName="",count=0;
	totalSum=0;
	for (var cartItem in cartData)
		if (cartData[cartItem].active) {
			itemsString+=cartItem+":"+cartData[cartItem].curFormat+"[";
			formatString=cartData[cartItem].formats[cartData[cartItem].curFormat];
			totalSum+=cartData[cartItem].price();
			count=0;
			for (weight in cartData[cartItem].weights) { if (cartData[cartItem].breakWeights[weight]) itemsString+=count+":"+cartData[cartItem].weights[weight]+":"+cartData[cartItem].formats[cartData[cartItem].curFormat]+":"+cartData[cartItem].prices[cartData[cartItem].curFormat]+";"; count++;  }
			itemsString+="]";
		}
	document.getElementById('form_items').value=itemsString;
	document.getElementById('form_total').value=totalSum;
	document.getElementById('cart_items').nextSibling.firstChild.firstChild.lastChild.innerHTML=totalSum+" "+siteText['nis'];
	if (!firstTime) sendRequest(baseurl+"set_order.php", function() { }, "o="+encodeURIComponent(itemsString));
}

// addToCart: adds an item to the cart

function addToCart(that, update) {
	if ((!that) || (!that.style)) {
		var that=this;
		if (!update) var update=1;
	}
	var i=that.parentNode.getAttribute('id');
	var itemsEl=document.getElementById('cart_items');
	if (!cartData["cart_"+i].active) itemsEl.appendChild(initCartItem("cart_"+i));
	that.innerHTML="<a href='"+baseurl+siteLang+"/cart'><img src='"+imageurl+"cart.gif' width=19 height=16 border=0 alt='"+siteText['cart']+"' /></a>";
	that.onclick=function() { showCart(); return false; }
	if (update) updateTotalSum(0);
}

// toggleWeight: toggles weight in the shopping cart

function toggleWeight(that) {
	if ((!that) || (!that.style)) {
		var that=this;
		var update=1;
	}
	var i=that.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute('id');
	if (that.style.backgroundColor!='white') {
		that.style.backgroundColor='white';
		that.style.color="rgb(96, 96, 96)";
		cartData[i].weightsNum++;
		cartData[i].breakWeights[that.value]=1;
	} else if (cartData[i].lock<cartData[i].weightsNum) {
		that.style.backgroundColor='';
		cartData[i].weightsNum--;
		cartData[i].breakWeights[that.value]=0;
	}
	that.parentNode.parentNode.nextSibling.nextSibling.innerHTML=cartData[i].price() + " " + siteText['nis'];
	if (update) updateTotalSum(0);
}

// changeFormat: changes the selected format in the shopping cart

function changeFormat(that) {
	if ((!that) || (!that.style)) {
		var that=this;
		var update=1;
	}
	var i=that.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute('id');
	if (that.style.backgroundColor!='white') {
		that.parentNode.childNodes[cartData[i].curFormat].style.backgroundColor='';
		that.style.backgroundColor='white';
		that.style.color="rgb(96, 96, 96)";
		cartData[i].curFormat=that.getAttribute('value');
		that.parentNode.parentNode.nextSibling.innerHTML=cartData[i].price() + " " + siteText['nis'];
		if (update) updateTotalSum(0);
	}
}

// initCartItem: utility function for fully building and initializing a cart item

function initCartItem(i) {
	var falseEl=document.createElement('DIV');
	falseEl.innerHTML=cartProt;
	cartEl=falseEl.firstChild;
	cartEl.id = i;
	var titleEl=cartEl.firstChild.firstChild.firstChild;
	titleEl.innerHTML=cartData[i].title + "<br />(<a href='#' onclick=\"destroyCartItem('"+i+"'); return false;\" class='cartAction'>"+siteText['remove']+"</a>)";
	var weightsExpEl=titleEl.nextSibling.firstChild;
	if (!cartData[i].lock) weightsExpEl.innerHTML=siteText['weights_no_break']; else weightsExpEl.innerHTML=siteText['weights_break'].replace('%', cartData[i].lock);
	var weightsEl=weightsExpEl.nextSibling;
	for (var j=0; j<cartData[i].weights.length; j++) {
		weightsEl.innerHTML += "<li value="+j+">" + cartData[i].weights[j]+"</li>";
	}
	for (j=0;j<weightsEl.childNodes.length;j++) {
		weightsEl.childNodes[j].style.backgroundColor='white';
		if (cartData[i].lock) {
			weightsEl.childNodes[j].style.cursor='pointer';
			weightsEl.childNodes[j].onclick=toggleWeight;
			weightsEl.childNodes[j].onmouseover=function() { if (this.style.backgroundColor!='white') { this.style.backgroundColor='rgb(161, 174, 217)'; this.style.color='white'; } }
			weightsEl.childNodes[j].onmouseout=function() { if (this.style.backgroundColor!='white') { this.style.backgroundColor=''; this.style.color='rgb(96, 96, 96)'; } }
		}
	}
	var formatsEl=weightsEl.parentNode.nextSibling.lastChild;
	for (var j=0; j<cartData[i].formats.length; j++) {
		formatsEl.innerHTML += "<li value='"+j+"'>" + cartData[i].formats[j]+"</li>";
	}
	for (j=0;j<formatsEl.childNodes.length;j++) {
		if (j==cartData[i].curFormat) formatsEl.childNodes[j].style.backgroundColor='white';
		formatsEl.childNodes[j].style.cursor='pointer';
		formatsEl.childNodes[j].onclick=changeFormat;
		formatsEl.childNodes[j].onmouseover=function() { if (this.style.backgroundColor!='white') { this.style.backgroundColor='rgb(161, 174, 217)'; this.style.color='white'; } }
		formatsEl.childNodes[j].onmouseout=function() { if (this.style.backgroundColor!='white') { this.style.backgroundColor=''; this.style.color='rgb(96, 96, 96)'; } }
	}
	var priceEl=formatsEl.parentNode.nextSibling;
	priceEl.innerHTML=cartData[i].price()+" " + siteText['nis'];
	cartData[i].active=1;
	return cartEl;
}


// destroyCartItem: remove a specific item from the cart

function destroyCartItem(i) {
	var cartItemEl=document.getElementById(i);
	var _destroyCartItem = function () {
		document.getElementById('cart_items').removeChild(cartItemEl);
		cartData[i].active=0;
		updateTotalSum();
		var buyEl=getBuyEl(document.getElementById(i.substring(5, i.length)));
		buyEl.innerHTML="<a href='"+baseurl+"cart/"+i+"'>"+siteText['buy']+" &gt;</a>";
		buyEl.onclick=function() { addToCart(this, 1); return false; };
		buyEl.onmouseover=function() {
			this.style.backgroundColor='rgb(161, 174, 217)'; 
			this.firstChild.style.color='white';
		};
		buyEl.onmouseout=function() {
			this.style.backgroundColor='white'; 
			this.firstChild.style.color='rgb(96, 96, 96)';
		};
	}
	if (cartItemEl.clientHeight) {
		var height=cartItemEl.clientHeight; target=0; delta=height/deltaSteps;
		cartItemEl.style.height=height+'px';
		cartItemEl.style.overflow='hidden';
		var destroyItemFunc = function () { height-=delta; cartItemEl.style.height=height+'px'; if (height>target) destroyItemRef = window.setTimeout(destroyItemFunc, 25); else { cartItemEl.style.height='0px'; destroyItemRef = window.setTimeout(_destroyCartItem, 25); } };
		var destroyItemRef = window.setTimeout(destroyItemFunc, 25);
	} else {
		_destroyCartItem();
	}
}

function destroyCartItems() {
	for (var i in cartData) {
		if (cartData[i].active) destroyCartItem(i);
	}
}

// showCart: show cart container and hide font container

function showCart() {
	var client=getClientSizes();
	var fontsEl=document.getElementById('fonts_container');
	var cartEl=document.getElementById('cart_container');
	setScroll(0, 0);
	if (fontsEl.style.display!='none') {
		var fontsX=containerX, cartX=client.w;
		if (siteLang=='heb') {
			fontsEl.style.right=fontsX+'px';
			cartEl.style.right=cartX+'px';
		} else if (siteLang=='eng') {
			fontsEl.style.left=fontsX+'px';
			cartEl.style.left=cartX+'px';
		}
		cartEl.style.display='block';
		if (document.getElementById('pic_container').style.display=='block') {
			document.getElementById('pic_container').firstChild.lastChild.onclick();
		}
		delta = Math.round((client.w-containerX)/deltaSteps);
		var showCartFunc = function() { fontsX+=delta; cartX-=delta; delta--; if (siteLang=='heb') { fontsEl.style.right=fontsX+'px'; cartEl.style.right=cartX+'px'; } else if (siteLang=='eng') {fontsEl.style.left=fontsX+'px'; cartEl.style.left=cartX+'px'; } if ((cartX>containerX) && (delta>0)) { showCartRef = setTimeout(showCartFunc, 25); } else { if (siteLang=='heb') cartEl.style.right=containerX+'px'; else if (siteLang=='eng') cartEl.style.left=containerX+'px'; fontsEl.style.display='none'; } };
		var showCartRef = setTimeout(showCartFunc, 25);
	}
}

// closeCart: hide cart container and show font container

function closeCart() {
	var client=getClientSizes();
	var fontsEl=document.getElementById('fonts_container');
	var cartEl=document.getElementById('cart_container');
	setScroll(0, 0);
	if (cartEl.style.display=='block') {
		var cartX=containerX, fontsX=client.w;
		if (siteLang=='heb') {
			cartEl.style.right=cartX+'px';
			fontsEl.style.right=fontsX+'px';
		} else if (siteLang=='eng') {
			cartEl.style.left=cartX+'px';
			fontsEl.style.left=fontsX+'px';
		}
		fontsEl.style.display='block';
		delta = Math.round((client.w-containerX)/deltaSteps);
		var hideCartFunc = function() { cartX+=delta; fontsX-=delta; delta--; if (siteLang=='heb') { cartEl.style.right=cartX+'px'; fontsEl.style.right=fontsX+'px'; } else if (siteLang=='eng') { cartEl.style.left=cartX+'px'; fontsEl.style.left=fontsX+'px'; } if ((fontsX>containerX) && (delta>0)) { hideCartRef = setTimeout(hideCartFunc, 25); } else { if (siteLang=='heb') fontsEl.style.right=containerX+'px'; else if (siteLang=='eng') fontsEl.style.left=containerX+'px'; cartEl.style.display='none'; } };
		var hideCartRef = setTimeout(hideCartFunc, 25);
	}
}

// submitForm: an AJAX method of submitting the order form

function submitForm() {
	var formFail=0;
	var queryString="";
	var messageEl=this.lastChild.firstChild.lastChild.firstChild;
	var formApproved = function(req) {
		stopPleaseWait();
		if (req.responseText=="OK") { 
			messageEl.innerHTML=siteText['sent_ok']; 
			destroyCartItems(); 
		} else
			messageEl.innerHTML=siteText['sent_error'];
	}
	messageEl.innerHTML=siteText['loading'];
	for (fieldName in orderForm) {
		var curFieldEl=document.getElementById(fieldName);
		if ((!curFieldEl.value) && (orderForm[fieldName].required)) {
			curFieldEl.parentNode.previousSibling.style.color="red";
			formFail=1;
		} else {
			if (fieldName.indexOf('email')>-1) if (!validateEmail(curFieldEl.value)) { messageEl.innerHTML=siteText['invalid_email']; return false; }
			orderForm[fieldName].value=curFieldEl.value;
			curFieldEl.parentNode.previousSibling.style.color="";
		}
		queryString+=orderForm[fieldName].name + "=" + orderForm[fieldName].value + "&";
	}
	if (formFail) { messageEl.innerHTML=siteText['sent_empty']; return false; }
	if (document.getElementById('rememberThis').checked)
		sendRequest(baseurl+"set_details.php", function() { }, queryString);
	else
		sendRequest(baseurl+"delete_details.php", function() { });
	queryString+="&items="+document.getElementById('form_items').value;
	if (queryString.lastIndexOf(']')>0) {
		pleaseWait();
		sendRequest(baseurl+"order.php", formApproved, queryString);
	} else {
		messageEl.innerHTML=siteText['sent_nofonts'];
	}
	return false;
}

// initForm: initialize order form

function initForm(data) {
	var formEl=document.getElementById('order_form');
	var code="";
	code+="<input type='hidden' style='display: none;' id='form_items' name='items' /><input type='hidden' style='display: none;' id='form_total' name='total' /><table class='cart' cellspacing=5>";
	for (var item in data) code+=data[item].code();
	code+="<tr><td colspan=2 class='totalCaption'><input type=checkbox id='rememberThis' name='rememberThis' value=0 style='display: inline; width: auto;' /> <label for='rememberThis'>"+siteText['remember']+"</label></td></tr></table><table class='cart' cellspacing=5><tr><td colspan=2 class='totalCaption'><div style='width: 650px; height: 200px; padding: 5px 10px; overflow: auto; white-space: normal;'>"+licenseText+"</div></td></tr><tr><td class='totalCaption'></td><td class='totalSum'><input type='submit' class='submit' value='"+siteText['send_order']+" &gt;' /></td></tr></table>";
	formEl.innerHTML=code;
	formEl.onsubmit=submitForm;
	updateTotalSum(1);
}

// Cart: constructor function for cart item data type

function Cart(title, weights, formats, prices, lock) {
	this.title = title;
	this.weights = weights;
	this.formats = formats;
	this.prices = prices;
	this.lock=lock;
	this.weightsNum = new Number();
	this.weightsNum = weights.length;
	this.curFormat = new Number();
	this.curFormat = 0;
	this.active = new Number();
	this.active = 0;
	this.breakWeights = new Array();
	for (i in weights) this.breakWeights[i]=1;
	this.price = function () { return this.weightsNum*this.prices[this.curFormat]; };
}

// FormField: constructor function for form fields

function FormField(title, name, value, required) {
	this.title=title;
	this.name=name;
	this.value=value;
	this.required=required;
	this.code = function() {
		if (!this.required) var notrequired=" "+siteText['form_optional']; else var notrequired="";
		return "<tr><td class='totalSum'><label for='form_"+this.name+"'>"+this.title+notrequired+"</label></td><td class='totalCaption'><input type='text' id='form_"+this.name+"' name='"+this.name+"' value=\""+this.value+"\" /></td></tr>";
	}
}

// cartProt: prototype for cart item HTML element
var cartProt = "<table class='cart' cellspacing=5><tbody><tr><td class='title'></td><td class='weights'><div></div><ul></ul></td><td class='formats'><div>"+siteText['choose_format']+"</div><ul></ul></td><td class='price'></td></tr></tbody></table>";
