// SparrowScripts Javascript Shopping Cart System
// written by Tan Ling Wee
// last updated 4 Oct 2005
// website : www.sparrowscripts.com
// ===================================================================

	var ssc_numItems;
	var ie=document.all;
	var dom=document.getElementById;
	var ns4=document.layers;
	var ssc_Show=false;
	var ssc_EnableCart=true;
	var ssc_receiptTotalQty=0;
	var ssc_receiptTotalAmt=0;
	var ssc_receiptTotalDisc=0;

	function ssc_Item(id, description, unitPrice, qty, maxQty, discount, checked){

		this.internalId=ssc_numItems;
		this.id=id;
		this.description=description.replace(",","&comma&");
		this.unitPrice=unitPrice;
		this.qty=parseInt(qty,10);
		this.discount=ssc_validateNumber(discount,2);
		this.price=ssc_validateNumber((this.unitPrice-this.discount)*this.qty,2);
		this.maxQty=maxQty;
		this.checked=checked;

		document.cookie="*p"+this.internalId+"="+id+","+this.description+","+unitPrice+","+qty+","+maxQty+","+discount+","+checked;
		ssc_numItems++;

		this.updateQty=function(qty){

			ssc_receiptTotalAmt-=parseFloat(this.price);
			ssc_receiptTotalQty-=this.qty;

			if ((qty>0)&&(this.qty==0))
			{
				this.checked=false;
			}
			
			if (qty>0)
			{
				this.price=ssc_validateNumber((this.unitPrice-this.discount)*qty,2);
			}

			if (this.qty>0) {
				document.getElementById("sscPrice"+this.internalId).innerHTML=this.price;
			}

			this.qty=qty;

			ssc_receiptTotalQty+=this.qty;
			ssc_receiptTotalAmt+=parseFloat(this.price);

			if (document.getElementById("sscSubtotalQty")!=null)
			{
				document.getElementById("sscSubtotalQty").innerHTML=ssc_receiptTotalQty;
				document.getElementById("sscSubtotalAmt").innerHTML=ssc_validateNumber(ssc_receiptTotalAmt,2);
			}

			document.cookie="*p"+this.internalId+"="+id+","+this.description+","+unitPrice+","+qty+","+maxQty+","+discount+","+this.checked;
		}

		this.updateCheck=function(checked){
			this.checked=checked;
			document.cookie="*p"+this.internalId+"="+id+","+this.description+","+unitPrice+","+qty+","+maxQty+","+discount+","+checked;
		}
	}

	var ssc_items=new Array();
	var checkboxIndex;

// check if browser supports cookies

	function ssc_CheckCookieSupport() {

		var fields=new Array();
		var strCookie, iItemEnd, sItemId;

		ssc_numItems=0;

		document.cookie="path=./;";

		if (document.cookie.length<=0) {

			if (document.cookie.length<=0) {

				ssc_EnableCart=false;

				ssc_UpdateStatus("<font color='#a00000'>"+ssc_Message[92]+"</font>"); 

				document.getElementById("sscCartContent").innerHTML="<table cellpadding=10px><tr><td><font class='ssc_cart_message_header'>"+ssc_Message[90]+"</font><div align='justify' class='ssc_cart_message'><BR>"+ssc_Message[91]+"</div></td></tr></table>";
			}
		}
		else {

			strCookie=document.cookie+";";

			iItemEnd=strCookie.indexOf("; ");			
			while (iItemEnd>=0)
			{
				// parse individual item

				sItemId=strCookie.substring(0,strCookie.indexOf("="));

				if ((sItemId!="path")&&(sItemId.substring(0,2)=='*p')) {
					sItem=strCookie.substring(strCookie.indexOf("=")+1,strCookie.indexOf(";"))+",";
					for (i=0;i<=6;i++)
					{
						fields[i]=sItem.substring(0,sItem.indexOf(","));
						sItem=sItem.substring(sItem.indexOf(",")+1);
					}

					if (fields[6]=="true")
					{
						bChecked=true;
					}
					else {
						bChecked=false;
					}
					ssc_internalAddItem(fields[0],fields[1],fields[2],fields[3],fields[4],fields[5],fields[6],bChecked);
				}

				// prepare for next item

				strCookie=strCookie.substring(iItemEnd+2);
				iItemEnd=strCookie.indexOf(";");			
			}

			ssc_refreshContent();
		}
	}

	function ssc_DeleteCookie (cookieName) { 
		var exp = new Date(); 
		exp.setTime (exp.getTime() - 1);  // This cookie is history 
		document.cookie = cookieName + "=; expires=" + exp.toGMTString(); 
	} 

// shopping cart status panel

	function ssc_UpdateStatus(strStatus) {
		if (ssc_EnableCart)
		{
			if (ssc_Show)
			{
				document.getElementById("sscStatusText").innerHTML=strStatus+ " <font class='ssc_sub_status'>"+ssc_Message[3].replace("<","&lt;").replace(">","&gt;")+"</font>";
			} else {
				document.getElementById("sscStatusText").innerHTML=strStatus+ " <font class='ssc_sub_status'>"+ssc_Message[2].replace("<","&lt;").replace(">","&gt;")+"</font>";
			}
		}
		else {
			document.getElementById("sscStatusText").innerHTML=strStatus;
		}
	}

	document.write("<table id='sscStatus' cellpadding=0 cellspacing=0><tr><td>&nbsp;<img id='sscCartImage' src='"+ssc_ImagePath+"ssc_cartempty.gif' align='top'>&nbsp;</td><td id='sscStatusTd' class='ssc_status' onmouseover='this.className=\"ssc_status_hover\"' onmouseout='if(!ssc_Show){this.className=\"ssc_status\"}' onclick='if(!ssc_Show){ssc_showCart()}else{ssc_hideCart()}'><span id='sscStatusText'>"+ssc_Message[1]+" <font class='ssc_sub_status'>"+ssc_Message[2].replace("<","&lt;").replace(">","&gt;")+"</font></span></td></tr></table>");

// shopping cart

	document.write("<BR><div id='sscCart' style='z-index:+999;position:absolute;visibility:hidden;'><table bgcolor=#FFFFFF class='ssc_cart' cellspacing=0 width='"+ssc_cartWidth+"'><tr valign='center' class='ssc_cart_header'><td align='center' style='padding:6px 6px 0px 6px'><img id='ssc_headerImage' src='"+ssc_CompanyLogo+"'></td></tr><tr><td style='padding:3px 6px 6px 6px' align=center><table id='ssc_cart_content_table' cellpadding=0 cellspacing=0 class='ssc_cart_message_content' width='"+ssc_cartWidth+"'><tr><td><span id='sscCartContent' class='ssc_cart_message'><BR><center>"+ssc_Message[10]+"</center><BR></span></td></tr></table></td></tr><tr valign=bottom><td>");
	
	if (ssc_Message[100]!="")
	{
		document.write("<center><table class='ssc_cart_footnote' width='"+(ssc_cartWidth+2)+"' cellpadding=0 cellspacing=0><tr><td>"+ssc_Message[100]+"</td></tr></table></center><br>");
	}

	document.write("<center><input type='button' id='sscBtnRemoveChecked' class='ssc_button' value='"+ssc_Message[40]+"'  disabled='true' onclick='ssc_removeCheckedItems()'>&nbsp;<input type='button' id='sscBtnRemoveAll' class='ssc_button' value='"+ssc_Message[41]+"'  disabled='true' onclick='ssc_removeAllItems()'>&nbsp;<input type='button' disabled='true' id='sscBtnCheckOut' class='ssc_button' value='"+ssc_Message[42]+"' onclick='if (confirm(\""+ssc_Message[53]+"\")) {document.location.href=\""+ssc_checkoutPage+"\"}'>&nbsp;<input type='button' id='sscBtnHide' class='ssc_button' value='"+ssc_Message[43]+"' onclick='ssc_hideCart();document.getElementById(\"sscStatusTd\").className=\"ssc_status\";'></center><BR><BR>&nbsp;<a class='ssc_cart_footnote_link' href='http://www.sparrowscripts.com' target='_new'>"+ssc_Message[0]+"</a></td></tr></table></div>");

	var crossobj=document.getElementById("sscCart").style;

	ssc_CheckCookieSupport();

	function ssc_refreshButtons(bRemoveChecked, bRemoveAll, bCheckOut) {

		document.getElementById("sscBtnRemoveChecked").disabled = !bRemoveChecked;
		document.getElementById("sscBtnRemoveAll").disabled = !bRemoveAll;
		document.getElementById("sscBtnCheckOut").disabled = !bCheckOut;
	}

	function ssc_refreshContent() {

		var sHTML="";
		var gotChecked=false;
		ssc_receiptTotalQty=0;
		ssc_receiptTotalAmt=0;
		ssc_receiptTotalDisc=0;

		if ((ssc_EnableCart)&&(ssc_numItems>0))
		{
			// display header

			sHTML="<table bgcolor=#FFFFFF cellpadding=0 cellspacing=0 width='"+ssc_cartWidth+"'><tr nowrap>";

			sHTML+="<td class='ssc_listing_header'><input type='checkbox' id='sscMasterCheck' onclick='ssc_MasterCheck(this)'></td>";

			if (ssc_showProductId){
				sHTML+="<td class='ssc_listing_header'>"+ssc_Message[21]+"</td>";
			}

			if (ssc_showProductDescription){
				sHTML+="<td class='ssc_listing_header' width='*'>"+ssc_Message[22]+"</td>";
			}

			if (ssc_showProductUnitPrice){
				sHTML+="<td class='ssc_listing_header'>"+ssc_Message[27]+"</td>";
			}

			sHTML+="<td class='ssc_listing_header'>"+ssc_Message[24]+"</td>";

			if (ssc_showProductDiscount){
				sHTML+="<td class='ssc_listing_header'>"+ssc_Message[25]+"</td>";
			}

			if (ssc_showProductPrice){
				sHTML+="<td class='ssc_listing_header'>"+ssc_Message[26]+"</td>";
			}

			sHTML+="</tr>";

			checkboxIndex=0;

			for (i=0;i<ssc_numItems;i++)
			{
				if (ssc_items[i].qty>0)
				{
					sEvenOddLine=(checkboxIndex%2)+1;
					checkboxIndex++;

					ssc_receiptTotalQty+=ssc_items[i].qty;
					ssc_receiptTotalAmt+=parseFloat(ssc_items[i].price);
					ssc_receiptTotalDisc+=parseFloat(ssc_items[i].discount*ssc_items[i].qty);

					sHTML+="<tr nowrap valign=center><td class='ssc_listing_content_"+sEvenOddLine+"' align='center'><input type='checkbox' id='chk"+(checkboxIndex)+"' value='"+i+"' onclick='ssc_CheckItem(this)' "

					if (ssc_items[i].checked)
					{
						sHTML+="checked";
						gotChecked=true;
					}
					
					sHTML+="></td>";

					if (ssc_showProductId){
						sHTML+="<td class='ssc_listing_content_"+sEvenOddLine+"'>"+ssc_items[i].id+"</td>";
					}

					if (ssc_showProductDescription){
						sHTML+="<td class='ssc_listing_content_"+sEvenOddLine+"' width='*'>"+ssc_items[i].description.replace("&comma&",",")+"</td>";
					}

					if (ssc_showProductUnitPrice){
						sHTML+="<td class='ssc_listing_content_"+sEvenOddLine+"' align='right'>"+ssc_items[i].unitPrice+"</td>";
					}

					sHTML+="<td class='ssc_listing_content_"+sEvenOddLine+"' align='center' style='padding:1px'><input class='ssc_input' type='input' id='sscQuantity"+i+"' value='"+ssc_items[i].qty+"' size=3 onblur='ssc_validateCtl(this)'></td>";

					if (ssc_showProductDiscount){
						sHTML+="<td class='ssc_listing_content_"+sEvenOddLine+"' align='right'>"+ssc_items[i].discount+"</td>";
					}

					if (ssc_showProductPrice){
						sHTML+="<td class='ssc_listing_content_"+sEvenOddLine+"' align='right'><span id='sscPrice"+i+"'>"+ssc_items[i].price+"</span></td>";
					}

					sHTML+="</tr>"
				}
			}

			sHTML+="<tr height=25 valign='center'><td class='ssc_listing_summary' colspan=4 align='right'><B>"+ssc_Message[27]+"</B></td><td align='center' class='ssc_listing_summary'><B><span id='sscSubtotalQty'>"+ssc_receiptTotalQty+"</span></B></td>"

			if (ssc_showProductDiscount)
			{
				sHTML+="<td align='right' class='ssc_listing_summary'><B><span id='sscSubtotalAmt'>"+ssc_validateNumber(ssc_receiptTotalDisc,2)+"<span></B></td>";
			}
			
			sHTML+="<td align='right' class='ssc_listing_summary'><B><span id='sscSubtotalAmt'>"+ssc_validateNumber(ssc_receiptTotalAmt,2)+"<span></B></td></tr>";

			sHTML+="</table>";

			if (checkboxIndex>0)
			{
				document.getElementById("sscCartContent").innerHTML=sHTML;
				ssc_refreshButtons(gotChecked, true, true);
			}
			else {
				document.getElementById("sscCartContent").innerHTML="<BR><center>"+ssc_Message[10]+"</center><BR>";
				ssc_refreshButtons(false, false, false);
			}

			ssc_UpdateItemCount();
		}
	}

	function ssc_UpdateItemCount(){

		if (ssc_EnableCart) {
			if (ssc_receiptTotalQty>0)
			{
				ssc_UpdateStatus(ssc_Message[11].replace("[numItems]","<B>"+ssc_receiptTotalQty+"</B>"));
				document.getElementById("sscCartImage").src=ssc_ImagePath+"ssc_cartfilled.gif";
			}
			else {
				ssc_UpdateStatus(ssc_Message[10]);
				document.getElementById("sscCartImage").src=ssc_ImagePath+"ssc_cartempty.gif";
			}
		}
	}

	function ssc_AddItem(id, description, unitprice, quantity, maxQty, discount) {
		
		var bResult=false;

		if (ssc_EnableCart) {
			if (maxQty<quantity)
			{
				alert(ssc_Message[94].replace("[maxqty]",maxQty).replace("[description]",description));
			}
			else {
				bResult=ssc_internalAddItem(id, description, unitprice, quantity, maxQty, discount, false);
				if (bResult) {
					alert(ssc_Message[52].replace("[qty]",quantity).replace("[description]",description));
					ssc_refreshContent();
				}
			}
		} else {
			alert(ssc_Message[93]);
		}
	}

	function ssc_internalAddItem(id, description, unitprice, quantity, maxQty, discount, checked) { 

		var alreadyExists=false;

		if (ssc_EnableCart)
		{
			// check if this item already exists
			for (i=0;i<ssc_numItems;i++)
			{
				if (id==ssc_items[i].id)
				{
					alreadyExists=true;
					// modify quantity of last entry'
					if (ssc_items[i].qty+parseInt(quantity,10)>maxQty)
					{
						alert(ssc_Message[94].replace("[maxqty]",maxQty).replace("[description]",description));
						return false;
					}
					else {
						ssc_items[i].updateQty(ssc_items[i].qty+parseInt(quantity,10));
						ssc_refreshContent();
					}
				}
			}

			if(!alreadyExists){
				// add new entry
				if (checked=="true")
				{
					ssc_items[ssc_numItems]=new ssc_Item(id, description, unitprice, quantity, maxQty, discount, true);
				}
				else {
					ssc_items[ssc_numItems]=new ssc_Item(id, description, unitprice, quantity, maxQty, discount, false);
				}
				if (ssc_numItems==1)
				{
					document.getElementById("sscCartImage").src=ssc_ImagePath+"ssc_cartfilled.gif";
				}
			}
		}

		return true;
	}

	function ssc_MasterCheck (masterControl) {

		var i;
		var j=0;
		for (i=0;i<ssc_numItems;i++){
			if (ssc_items[i].qty>0)
			{
				j++;
				document.getElementById("chk"+j).checked=masterControl.checked;
				if (masterControl.checked)
				{
					ssc_items[document.getElementById("chk"+j).value].updateCheck(true);
				}
				else {
					ssc_items[document.getElementById("chk"+j).value].updateCheck(false);
				}
			}
		}

		if (masterControl.checked)
		{
			ssc_refreshButtons(true, true, true);
		}
		else {
			ssc_refreshButtons(false, true, true);
		}
	}

	function ssc_CheckItem(chkbox) {

		var allChecked=true;
		var numChecked=0;

		if (chkbox.checked)
		{
			ssc_items[chkbox.value].updateCheck(true);
		}
		else {
			ssc_items[chkbox.value].updateCheck(false);
		}

		for (i=1;i<=checkboxIndex;i++)
		{
			if (!document.getElementById("chk"+i).checked)
			{
				allChecked=false;
			}
			else {
				numChecked++;
			}
		}
		
		document.getElementById("sscMasterCheck").checked=allChecked;
		if (numChecked>0)
		{
			ssc_refreshButtons(true, true, true);
		}
		else {
			ssc_refreshButtons(false, true, true);
		}
	}

	function ssc_removeCheckedItems(){

		if (confirm(ssc_Message[50]))
		{
			for (i=1;i<=checkboxIndex;i++)
			{
				if (document.getElementById("chk"+i).checked)
				{
					ssc_items[document.getElementById("chk"+i).value].updateQty(0);
				}
			}
		}

		ssc_refreshContent();
	}

	function ssc_removeAllItems() {

		if (confirm(ssc_Message[51])){

			for (i=ssc_numItems-1;i>=0;i--)
			{
				ssc_items[i].updateQty(0);
			}
			ssc_refreshContent();
		}
	}

	function ssc_validateCtl(ctlThis) {

		var index=parseInt(ctlThis.id.substr(11));
		var value=ssc_validateNumber(ctlThis.value,0);
		var ivalue=parseInt(value,10);
		ctlThis.value=ivalue;
		if (ivalue>ssc_items[index].maxQty)
		{
			alert(ssc_Message[94].replace("[maxqty]",ssc_items[index].maxQty).replace("[description]",ssc_items[index].description.replace("&comma&",",")));
			ctlThis.focus();
		}
		else {
			ssc_items[index].updateQty(ivalue);
			if (ivalue==0)
			{
				ssc_refreshContent();
			}

			ssc_UpdateItemCount();
		}
	}

	function ssc_validateNumber(num, decimalPos) {

		var sNewString="";
		var cntDecimal=0;
		var i;
		var tmp;

		num=num+""; //convert to string

		for (i=0;i<num.length;i++){

			ch=num.charAt(i);

			if(((ch>='0')&&(ch<='9'))||((ch=='.')&&(cntDecimal==0))){

				if ((ch=='.')&&(i==0)) {
					sNewString="0";					
				}

				if (ch=='.') {
					cntDecimal++;
				}

				if (!((ch=='.')&&(i==num.length-1))) {
					sNewString+=ch;
				}
			}
		}

		if (sNewString=="") {
			sNewString="1";
		}

		decimalCount=sNewString.indexOf(".");

		if (decimalCount>=0) {
			// decimal point found
			tmp=Math.pow(10,decimalPos);
			sNewString=(Math.round(parseFloat(sNewString)*tmp)/tmp)+"";

			if (sNewString.length-decimalCount<=decimalPos+1){
				nCount=(decimalPos-sNewString.length+decimalCount+1);
				for (i=0;i<nCount;i++){
					sNewString+="0";
				}
			}
		}
		else {
			// decimal point not found

			if (decimalPos>0) {
				sNewString+="."
				for (i=0;i<decimalPos;i++){
					sNewString+="0";
				}
			}
		}

		return sNewString+"";
	}

	function ssc_hideCart() {
		crossobj.visibility="hidden"
		ssc_showElement( 'SELECT' );
		ssc_showElement( 'APPLET' );
		ssc_Show=false;
		ssc_UpdateItemCount();
	}

	function ssc_showCart() {

		var leftpos=0;
		var toppos=0;
		var ssc_statusbar;

		ctl=document.getElementById("sscStatus");
		aTag = ctl;
		do {
			aTag = aTag.offsetParent;
			leftpos	+= aTag.offsetLeft;
			toppos += aTag.offsetTop;
		} while(aTag.tagName!="BODY");

		crossobj.left =	ctl.offsetLeft	+ leftpos; 
		crossobj.top = ctl.offsetTop +	toppos + ctl.offsetHeight + 2;
		crossobj.visibility=(dom||ie)? "visible" : "show"

		ssc_hideElement( 'SELECT', document.getElementById("sscCart") );
		ssc_hideElement( 'APPLET', document.getElementById("sscCart") );			
		ssc_Show=true;
		ssc_UpdateItemCount();
	}

	// hides <select> and <applet> objects (for IE only)
	function ssc_hideElement(elmID, overDiv){
		if( ie ){
			for( i = 0; i < document.all.tags( elmID ).length; i++ ){
				obj = document.all.tags( elmID )[i];
				if( !obj || !obj.offsetParent ){
						continue;
				}
				  // Find the element's offsetTop and offsetLeft relative to the BODY tag.
				  objLeft   = obj.offsetLeft;
				  objTop    = obj.offsetTop;
				  objParent = obj.offsetParent;
				  while( objParent.tagName.toUpperCase() != "BODY" )
				  {
					objLeft  += objParent.offsetLeft;
					objTop   += objParent.offsetTop;
					objParent = objParent.offsetParent;
				  }
				  objHeight = obj.offsetHeight;
				  objWidth = obj.offsetWidth;
				  if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
				  else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
				  else if( overDiv.offsetTop >= ( objTop + objHeight + obj.height ));
				  else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
				  else
				  {
					obj.style.visibility = "hidden";
				  }
			}
		}
	}
		 
	//unhides <select> and <applet> objects (for IE only)
	function ssc_showElement( elmID ){
		if( ie ){
			for( i = 0; i < document.all.tags( elmID ).length; i++ ){
				obj = document.all.tags( elmID )[i];
				if( !obj || !obj.offsetParent ){
						continue;
				}
				obj.style.visibility = "";
			}
		}
	}
