/**
 * Midland Computers e-Commerce engine - ajax javascript
 * Written by Neil Williams neil.williams at midlandcomputers spam prevention co.uk
 *
 * 
 *
 */

// Browser specific XmlHttpRequest Object
function getXmlHttpRequestObject()
{
	if( window.XMLHttpRequest )
	{
		return new XMLHttpRequest(); // Not IE
	}
	else if( window.ActiveXObject )
	{
		return new ActiveXObject( "Microsoft.XMLHTTP" ); // IE
	}

	return false;
}

/* Simple and effective way to use AJAX - without the X.
 * Changes the contents of objID to that returned by fetching url.
 */
function ajaxBasic( objID, url )
{
	var obj = document.getElementById(objID);

	if( req = getXmlHttpRequestObject() )
	{
		req.open( "GET", url );
		req.onreadystatechange = function()
			{
				if (req.readyState == 4 && req.status == 200)
				{
					obj.innerHTML = req.responseText;
				}
			}

		req.send(null);
	}
}

function basketsubmit( id )
{
	//alert( $("basketform["+id+"]").serialize() );
	//alert( Form.serialize( $("basketform["+id+"]") ) );
	var urlargs = Form.serialize( $("basketform["+id+"]") );
	var urlscript = "dobasket.php?ajax=true&";

	basketmakeajax( urlscript+urlargs );
}

function basketsubmitsingle( pid, qty, opt )
{
	var urlargs = "action=add&item="+escape(pid)+"&qty="+escape(qty);
	if( opt != "" )
	{
		urlargs+="&opt[]="+escape(opt);
	}
	var urlscript = "dobasket.php?ajax=true&";

	basketmakeajax( urlscript+urlargs );
}

function basketmakeajax( url )
{
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			if( transport.responseText.match(/^error.*/) )
			{
				switch( /^error (.*)/.exec(transport.responseText)[1] )
				{
					case "NEEDOPTION":
						showBasketSaving("You must select an option for this product", "red");
						break;
					case "NEEDOPTIONMULTI":
						showBasketSaving("You must 'Choose Your Options'", "red");
						break;
					case "INVALIDDATA":
						showBasketSaving("Invalid data received", "red");
						break;
					case "UNKNOWNPRODUCT":
						showBasketSaving("Unknown product selected", "red");
					default:
						showBasketSaving("Error adding product to basket", "red");
						break;
				}
			}
			else
			{
				new Ajax.Updater('basket', 'ajax/basketdiv.php', { });
				showBasketSaving("Item Added to your Basket...", "green");
				$('basket').highlight();
			}
		},
		onFailure: function(transport) {
			alert( "An error occured when submitting your item.\nPlease reload the page and try again." );
		}
	});
}

function showBasketSaving(message, bgcolour)
{
	var savingMessage = $("basketsaving");

	var pos;
	if( window.innerHeight )
	{
		pos = window.pageYOffset
	}
	else if( document.documentElement && document.documentElement.scrollTop )
	{
		pos = document.documentElement.scrollTop
	}
	else if( document.body )
	{
		pos = document.body.scrollTop
	}

	if (self.innerWidth)
	{
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
	else return;

	//savingMessage.style.display="block";
	savingMessage.style.top = ((frameHeight/2)-(90/2))+pos+"px";
	savingMessage.innerHTML = message;
	
	switch( bgcolour )
	{
		case "red":
			savingMessage.style.backgroundColor = "red";
			break;
		case "green":
			savingMessage.style.backgroundColor = "green";
			break;
		default:
			savingMessage.style.backgroundColor = "black";
			break;
	}


	Effect.Appear("basketsaving", { duration: 0.5, queue: 'end'});
	setTimeout( clearBasketSaving, 2000 );
}

function clearBasketSaving()
{
	var savingMessage = $("basketsaving");
	//savingMessage.style.display="none";
	Effect.SwitchOff("basketsaving", { duration: 0.5, queue: 'end'});
}

function InputNumberSpinner_Up(id, inc)
{
	var curval = parseInt( $(id).value );
	if( curval < 999 )
	{
		$(id).value = parseInt( $(id).value ) + inc;
	}
}

function InputNumberSpinner_Down(id, inc)
{
	var curval = parseInt( $(id).value );
	if( curval > 1 )
	{
		$(id).value = parseInt( $(id).value ) - inc;
	}
}



function Filtering_ResetSubtype()
{
	var select = $("filter_subtype");

	for( i = select.length - 1; i>=1; i-- )
	{
		select.remove(i);
	}

	select.selectedIndex = 0;
	select.disabled = true;
}

var Filtering_CurrentObject = null;
function Filtering_UpdateSubType(itemtoselect)
{
	// Determine the product type.
	var objecttype = $F('filter_objecttype');

	if( objecttype != "" )
	{
		if( objecttype != Filtering_CurrentObject )
		{
			Filtering_CurrentObject = objecttype;
			var url = 'ajax/filter_getsubtypes.php?type=' + encodeURIComponent(objecttype);

			new Ajax.Request(url, {
				onSuccess: function(transport) {
					var opts;
					try
					{
						opts = transport.responseText.evalJSON(true);

						var select = $("filter_subtype");

						for( i = select.length - 1; i>=1; i-- )
						{
							select.remove(i);
						}

						if( opts != null )
						{
							var opttoselect = 0;

							for( var i=0; i<opts.length; i++ )
							{
								opt = opts[i];
								var newopt = document.createElement('option');
								newopt.text = opt;
								newopt.value = opt;

								if( itemtoselect == opt )
								{
									opttoselect = i+1;
								}

								try
								{
									select.add(newopt, null); // standards
								}
								catch(ex)
								{
									select.add(newopt); // IE only
								}
							}

							select.selectedIndex = opttoselect;
							select.disabled = false;
						}
					}
					catch(err)
					{
						// Most exceptions will be due to null JSON strings.
						// Either way, no subtypes are selectable.
						//alert( err.description );
						Filtering_ResetSubtype();
					}

				},
			onFailure: function(transport) {
				Filtering_ResetSubtype();
			}
			});
		}
	}
	else
	{
		Filtering_ResetSubtype();

		Filtering_CurrentObject = "";
	}
}




function Filtering_ResetCat(id)
{
	var select = $(id);

	for( i = select.length - 1; i>=1; i-- )
	{
		select.remove(i);
	}

	select.selectedIndex = 0;
	select.disabled = true;
}

// Use Array to store associative elements using Object syntax.
var Filtering_UpdateCat_Store = new Array();
// parentcatid - select returning the Id of parent category
// selectid - where to set the result.
// itemtoselect - select this in the result.
// whendonefire - on a successful AJAX response, fire off this javascript in an eval().
function Filtering_UpdateCat(parentcatid,selectid,itemtoselect,whendonefire)
{
	// Determine the parent category.
	var parentcatid = $F(parentcatid);

	if( parentcatid != "" )
	{
		if( parentcatid != Filtering_UpdateCat_Store[selectid] )
		{
			Filtering_UpdateCat_Store[selectid] = parentcatid;
			var url = 'ajax/filter_getsubcats.php?parent=' + encodeURIComponent(parentcatid);

			new Ajax.Request(url, {
				onSuccess: function(transport) {
					var opts;
					try
					{
						optsuper = transport.responseText.evalJSON(true);
						optids = optsuper[0];
						opttitles = optsuper[1];

						var select = $(selectid);

						for( i = select.length - 1; i>=1; i-- )
						{
							select.remove(i);
						}

						if( optids != null )
						{
							var opttoselect = 0;

							for( var i=0; i<optids.length; i++ )
							{
								optid = optids[i];
								opttitle = opttitles[i];

								var newopt = document.createElement('option');
								newopt.text = opttitle;
								newopt.value = optid;

								if( itemtoselect == optid )
								{
									opttoselect = i+1;
								}

								try
								{
									select.add(newopt, null); // standards
								}
								catch(ex)
								{
									select.add(newopt); // IE only
								}
							}

							select.selectedIndex = opttoselect;
							select.disabled = false;

							eval(whendonefire);
						}
					}
					catch(err)
					{
						// Most exceptions will be due to null JSON strings.
						// Either way, no subtypes are selectable.
						//alert( err.description );
						Filtering_ResetCat(selectid);
					}

				},
			onFailure: function(transport) {
				Filtering_ResetCat(selectid);
			}
			});
		}
	}
	else
	{
		Filtering_ResetCat(selectid);

		Filtering_UpdateCat_Store[selectid] = "";
	}
}
