/* WPSHOP 1.8.56
   Released under the terms of the GPL (see COPYING) */

/**	@author <a href="mailto:x_terminat_or_3@yahoo.fr">Andy Pieters</a> For <a href="http://cregy.net">Cregy Web Design</a>
	@file client.js @brief clientside functions.

	Please note that all the functions in this file are in JavaScript and meant to be used client-side. */

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;


	/** @brief Find the TYPE attribute of an element */
	/** Searches attributes of element for a TYPE attribute.
		@param element reference to the element that is to be searched.
		@returns UPPERCASE value of TYPE attribute (if found) or NULL otherwise */
		
function typeOf(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;
}

/** @brief get value of a radio button by name */
/** Searches formName for radio buttons with optionName
	and returns the currently selected value.

	@param optionName Name of the radio button (or group of radio buttons)
	@param formName Name of the form that contains optionName
	@returns value if successfull, null on failure */
	
function getOptionValueByName(optionName,formName)
{
	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;
}

/** @brief Login a client with AJAX

	Initiates an AJAX request to log a client into the clientarea
	It reads the elements with id 'password' and 'email' to determine credentials.
	Also checks if the 'register' checkbox is ticked.
	
	@see ajax_client_login_callback()
	@see ajax_client_login_try()
	@see ajax_client_check_dupes() */

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;
}
/** @brief Callback for the client login AJAX request

	This function is called by the XMLHttpRequestObject when it
	has completed the request.

	@see ajax_client_login() */

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;
		}

	}
}

/** @brief Tries to login user via AJAX
	@param user username
	@param pass password
	@see ajax_client_login()
	@see ajax_client_login_callback() */
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);
}


/** @brief Callback for username dupplicate AJAX check

	@see ajax_client_login()
	@see ajax_client_login_callback() */

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;
		}
	}
}

/** @brief Check a username availability via AJAX
	@param user username
	@see ajax_client_dupes_callback()
	@see ajax_client_login() */
function ajax_client_check_dupes(user)
{
	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);
}


/** @brief Turn on Hourglass

	Shows an hourglass (or other image) while waiting for the AJAX request to complete */
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);
}

/** @brief Centers an object
	Centers an object on the screen
	
	@param object the object to center
	@param width the width of the object
	@param height the height of the object */
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';
	
}

/** @brief Updates the hourglass display

	Increments the progressbar or hourglass */
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.');
		}
	}
}

/** @brief Hides the hourglass/progressbar */
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;
	}
}

/** @brief Add a product to the cart via AJAX */
/** Initiates an AJAX request to add specified product to the client's cart.
	@param product id of product to add to cart
	@param qty qty of product to add to cart, defaults to 1
	@returns false
	@see wpshop_cart_callback()
	@see wpshop_cart_callback_add()  */
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;
}

/** @brief Edit qty of product in cart via AJAX */
/** Initiates an AJAX request to edit the qty of a given product
	in the client's shopping cart.
	@param product the id of the product to edit
	@param qty the new qty
	@param rowid id of the row that needs to be updated
	@returns false
	@see wpshop_cart_callback_edit()
	@see wpshop_cart_callback() */
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;
}

/** @brief Update display after AJAX call

	Update the cart displayed on the page with the results of
	the AJAX call.

	@param result an array containing the results of the AJAX call
	@see wpshop_edit_qty()
	@see wpshop_cart_callback() */
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);
	}
}

/** @brief Processes the result of the Add to cart AJAX request

	@param result array containing the result of the AJAX call
	@see wpshop_cart_callback()
	@see wpshop_add_to_cart_ajax() */
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);
	}
}

/** @brief determines which callback to call */
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;
		}
	}
}
/** @brief initialisation of the XMLHttpRequest object
	@returns XMLHttpRequest object */
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;
}

/** Show the login form */
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;
}

/** @brief Initialisation function for this file */
function wpshop_client_init()
{
	var nav=navigator.appName.toString();

	nav=nav.toLowerCase();

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

}

wpshop_client_init();

