/* WPSHOP
   File: client.js

   Contains JavaScript functions for the Client side of the WP Shop

   Author: Andy Pieters for Cregy Web Design
   x_terminat_or_3@yahoo.fr
   http://cregy.co.uk */


var http=wpshop_create_request_object_cart();
var wpshop_cart_call=null;
var wpshop_hourglass=null;
var wpshop_compat='\nThis shopping cart uses AJAX to improve your online experience.\n\nHowever, it seems that we are experiencing technical difficulties on your system.\n\nTo solve this we would like your feedback.  In the meantime, you can disable JavaScript and the alternative shopping cart will take over.\n\nPlease accept our apologies for the inconvience.';
var isDescentBrowser=true;
var progress_tick=0;
var progress_fail=0;

// Internet explorer does not support use of constants, so we'll have to define them as vars
var rpc_ok=0;
var rpc_rowid=1;
var rpc_line_qty=2;
var rpc_line_net=3;
var rpc_line_tax=4;
var rpc_line_total=5;
var rpc_items=6;
var rpc_total_net=7;
var rpc_total_tax=8;
var rpc_total_sub=9
var rpc_total_shipping=10;
var rpc_total_grand=11;

var HTTP_OK=4;
var CLIENT_USERNAME=0;

function wpshop_add_to_cart_ajax(product,qty)
{

	if(qty==null)
		qty=1;

	product=product*1;
    qty=qty*1;

	var request='./wp-content/plugins/wpshop/wpshop_rpc.php?procedure=add_to_cart&product='+product+'&qty='+qty;
	http.open('get',request,true);

	wpshop_cart_call='add';

	http.onreadystatechange=wpshop_cart_callback;

	wpshop_hourglass_on();

	http.send(null);

	return false;
}

function wpshop_edit_qty(product,qty,rowid)
{
	var probe=document.getElementById('wpshop_cart_row_'+rowid); //check if row DOES exists

	if(probe)
	{

		var oldqty=0;

		//detect current qty
		if(oldqty=document.getElementById('wpshop_cart_row_qty_'+rowid))
			oldqty=oldqty.innerHTML*1;

		qty=oldqty+qty;

		var request='./wp-content/plugins/wpshop/wpshop_rpc.php?'+
					'procedure=edit_cart'+
					'&product='+product+
					'&qty='+qty+
					'&rowid='+rowid;

		http.open('get',request,true);

		wpshop_cart_call='edit';

		http.onreadystatechange=wpshop_cart_callback;

		wpshop_hourglass_on();

		http.send(null);
	}

	return false;
}

function typeOf(element)
{
	/* Gets the TYPE attribute of element
	   Returns uppercase value of TYPE if found or null otherwise.

	   type=typeOf(HTML_Element) */

	var returnvalue=null;
	var attribs=null;
	var counter=0;
	var current=null;

	if(attribs=element.attributes)
	{
		for(counter=0; counter<attribs.length; counter++)
		{
			current=attribs[counter].name.toUpperCase();

			if(current=='TYPE')
			{
				return attribs[counter].value.toUpperCase();
			}
		}
	}

	return returnvalue;
}


function getOptionValueByName(optionName,formName)
{
	/* Get value of radio button by name.
	   Works best if you have many radio buttons with the same name

	   value=getOptionValueByName(optionName[,formName])

	   if formName is omitted, the first found form will be used

	   returns value on success, null on failure */

	var counter=0;
	var currentForm=null;
	var option;
	var current=null;

	if(document.forms.length>0)
	{
		for(counter=0; counter<document.forms.length; counter++)
		{
			currentForm=document.forms[counter];

			if( (currentForm.name==formName) || (formName==null))
			{
				if(current=currentForm.getElementsByTagName('input'))
				{
					for(var itterator=0; itterator<current.length; itterator++)
					{
						option=current[itterator];

						if( (typeOf(option)=='RADIO') && (option.name==optionName))
						{
							if(option.checked==true)
							{
								return option.value;
							}
						}
					}
				}
			}
		}
	}

	return null;
}

function ajax_client_login()
{
	var username=null;
	var password=null;
	var mode=null;

	if( (password=document.getElementById('password')) && (username=document.getElementById('email')))
	{
		password=password.value;
		username=username.value;

		mode=getOptionValueByName('wpshop_action','wpshop_clientlogin');

		if( (password.length>5) && (username.length>5) && (username.indexOf('@')>0))
		{
			switch(mode)
			{
				case 'login':		ajax_client_login_try(username,password);
									break;
				case 'register':	ajax_client_check_dupes(username,password);
									break;
			}
		}
		else
		{
			alert('Please enter a valid email address and a password of at least 5 characters long.');
		}
	}

	return false;
}

function ajax_client_login_callback()
{
	var result=null;
	var extra=null;

	if(http.readyState==HTTP_OK)
	{
		result=http.responseText;

		if(result.indexOf('|')>0)
		{
			extra=result.split('|');
			result=extra.shift();
		}

		switch(result)
		{
			case 'OK':		alert('Welcome back '+extra[CLIENT_USERNAME]);
							showMyAccount();
							break;
			case 'PASS':	alert('Oops, wrong password!');
							break;
			case 'USER': 	alert('No such account!');
							break;
			default:		alert('Problem transmitting the data, please try again.\n\nIf the problem persists, please de-activate JavaScript');
							break;
		}

	}
}

function ajax_client_dupes_callback()
{
	var result=null;
	var extra=null;

	if(http.readyState==HTTP_OK)
	{
		result=http.responseText;

		if(result.indexOf('|')>0)
		{
			extra=result.split('|');
			result=extra.shift();	
		}

		switch(result)
		{
			case 'OK':		document.location=extra;
							break;
			case 'DUPE':	alert('This username is already taken.  Please choose another one.');
							break;
			default:		alert('An error occurred during the transmission.\n\nIf you continue to have problems, please disable JavaScript');
							break;
		}
	}
}

function ajax_client_login_try(user,pass)
{
	var request='./wp-content/plugins/wpshop/wpshop_rpc.php?procedure=client_login&email='
				+escape(user)+'&password='+escape(pass);

	http.open('get',request,true);

	http.onreadystatechange=ajax_client_login_callback;

	http.send(null);
}

function ajax_client_check_dupes(user,pass)
{
	var request='./wp-content/plugins/wpshop/wpshop_rpc.php?procedure=client_check_dupe&email='
				+escape(user);

	http.open('get',request,true);

	http.onreadystatechange=ajax_client_dupes_callback;

	http.send(null);
}



function wpshop_hourglass_on()
{
	var div=null;
	var progr=null;

	if(div=document.getElementById('wpshop_waitdiv'))
	{
		if(isDescentBrowser)
			div.style.background="url('./wp-content/plugins/wpshop/images/window.png')";

		centerMe(div,250,106);

		if(progr=document.getElementById('progress'))
			progr.style.width='1px';

		div.style.visibility='visible';

		progress_tick=0;
		progress_failsafe=0;
		
	}

	wpshop_hourglass=window.setInterval('wpshop_hourglass_update()',500);
}

function centerMe(object,width,height)
{
	var maxX=window.innerWidth/2;
	var maxY=window.innerHeight/2;

	maxY-=height/2;
	maxX-=width/2;

	object.style.left=maxX+'px';
	object.style.top=maxY+'px';
	
}
	
function wpshop_hourglass_update()
{
	if(div=document.getElementById('progress'))
	{
		progress_tick+=20;

		if(progress_tick>200)
			progress_tick=0;

		div.style.width=progress_tick+'px';

		if(progress_failsafe++>=120)
		{
			wpshop_hourglass_off();

			alert('You are waiting for over a minute now.\n\nMost likely a browser incompatibility issue is fouling up the AJAX Cart.\n\nIf you continue to have problems, please de-activate JavaScript for this site.');
		}
	}
}

function wpshop_hourglass_off()
{
	progress_tick=0;
	progress_failsafe=0;

	var targetElement=null;

	if(targetElement=document.getElementById('wpshop_waitdiv'))
		targetElement.style.visibility='hidden';

	if(!(wpshop_hourglass==null))
	{
		window.clearInterval(wpshop_hourglass);
		wpshop_hourglass=null;
	}
}

function wpshop_cart_callback_edit(result)
{

	var cart_sidebar=null;

	if(result.substr(0,5)=='ERROR')
	{
		error=result.substr(6);
		switch(error)
		{
			case 'PRODUCT': alert('The product you tried to edit no longer exists.');
							break;
			default:		alert('An unexpected error occurred ('+error+')\nPlease file a bug report for this.'+
								  wpshop_compat);
							break;
		}
	}
	else
	{
		if(result.substr(0,3)=='OK|')
		{
			var cartinfo=result.split('|'); //expecting array of 11
			var rowid=cartinfo[rpc_rowid];
			var rowqty=cartinfo[rpc_line_qty];

			if( (rowqty==0) || (rowqty=='EMPTY') ) //remove whole row from document tree
			{
				if(currentrow=document.getElementById('wpshop_cart_row_'+rowid))
			 	{ 
					if(rowparent=document.getElementById('wpshop_viewcart_body'))
			  		{
						var garbage=rowparent.removeChild(currentrow);
			  		}
			 	}
			}
			else
			{
				if(current=document.getElementById('wpshop_cart_row_qty_'+rowid))
					current.innerHTML=rowqty;

				if(current=document.getElementById('wpshop_cart_row_net_'+rowid))
					current.innerHTML=cartinfo[rpc_line_net];

				if(current=document.getElementById('wpshop_cart_row_sub_'+rowid))
					current.innerHTML=cartinfo[rpc_line_total];

				if(current=document.getElementById('wpshop_cart_row_tax_'+rowid))
					current.innerHTML=cartinfo[rpc_line_tax];

				if(current=document.getElementById('wpshop_net_total'))
					current.innerHTML=cartinfo[rpc_total_net];

				if(current=document.getElementById('wpshop_tax_total'))
					current.innerHTML=cartinfo[rpc_total_tax];

				if(current=document.getElementById('wpshop_sub_total'))
					current.innerHTML=cartinfo[rpc_total_sub];

				if(current=document.getElementById('wpshop_total_shipping'))
					current.innerHTML=cartinfo[rpc_total_shipping];

				if(current=document.getElementById('wpshop_grand_total'))
					current.innerHTML=cartinfo[rpc_total_grand];
			}

			if(rowqty=='EMPTY') //hide table altogether
			{
				if(current=document.getElementById('wpshop_viewcart'))
					current.style.display='none';

				if(current=document.getElementById('wpshop_cart_empty'))
					current.innerHTML='<em>Your cart is <strong>empty</strong>.</em>';

				cart_sidebar='<em>Your cart is <strong>empty</strong>.</em>';

			}
			else
			{
				cart_sidebar=cartinfo[rpc_items]+' item'+(cartinfo[rpc_items]==1?'':'s')+' in Cart<br />'+
										 '<strong>Total: </strong>'+cartinfo[rpc_total_grand];
			}

			if(current=document.getElementById('wpshop_cart_content'))
				current.innerHTML=cart_sidebar;
		}
		else
			alert('An unexpected answer was received from the server ('+result+')'+wpshop_compat);
	}
}

function wpshop_login()
{
	var current=null;

	if(current=document.getElementById('wpshop_login'))
	{
		if(isDescentBrowser)
			current.style.background="url('./wp-content/plugins/wpshop/images/window.png')";
		else
		{
			current.style.background='#dedede';
			current.style.border='2px outset black';
		}
		centerMe(current,200,106);
		current.style.visibility='visible';
	}
	else
	 return true; //didn't find login form, use failsafe login method

	return false;
}

function wpshop_cart_callback_add(result)
{


	if(result.substr(0,5)=='ERROR')
	{
		error=result.substr(6);
		switch(error)
		{
			case 'PRODUCT':	alert('The product you tried to add to the cart no longer exists.');
							break;
			default:		alert('An unexpected error occurred ('+error+')\nPlease file a bug report for this.'+
								  wpshop_compat);
							break;
		}
	}
	else
	{
		if(result.substr(0,3)=='OK|')
		{
			var cartinfo=result.split('|');
			//first index should contain #items, second index total
			document.getElementById('wpshop_cart_content').innerHTML=
				cartinfo[1]
				+' item'
				+(cartinfo[1]==1?'':'s')
				+' in Cart<br />'
				+'<strong>Total: </strong>'+cartinfo[2];
		}
		else
			alert('An unexpected answer was received from the server ('+result+')'+wpshop_compat);
	}
}

function wpshop_cart_callback()
{
	if(http.readyState==HTTP_OK)
	{
		wpshop_hourglass_off();
		result=http.responseText;
		switch(wpshop_cart_call)
		{
			case 'add':		wpshop_cart_callback_add(result);
							break;
			case 'edit':	wpshop_cart_callback_edit(result);
							break;
		}
	}
}
	
function wpshop_create_request_object_cart() // initialisation of XMLHTTP object
{
	var reqobj;
	var browser=navigator.appName;

	if(browser.indexOf('Microsoft')!=-1)
		reqobj=new ActiveXObject('Microsoft.XMLHTTP');
	else
		reqobj=new XMLHttpRequest();
	return reqobj;
}

function wpshop_client_init()
{
	var nav=navigator.appName.toString();

	nav=nav.toLowerCase();

	if(nav.indexOf('microsoft')>=0)
		isDescentBrowser=false;

}

wpshop_client_init();
