/**
###########################################################################
Cart function created by Omar M. Ali, (3oomar@gmail.com)
And is protected by copyright laws.
###########################################################################
**/
// Functions to handle cookies
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

// functions to handle cart

function emptyCart(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
	updateCart();
	return false;
}

// Adds items to shopping cart
function addToCart(itemname, itemprice, cartname)
{
	// if no cart name, assume default
	!cartname? cartname='cart' : '';
	if(getCookie(cartname))
	{
		// get cookie old value
		var oldCookieValue=getCookie(cartname);
		// search for the item in cookie
		var foundCookieItem=oldCookieValue.match(itemname);
		// if not found, add it
		if(!foundCookieItem)
		{
			var newCookieValue=oldCookieValue+"&"+itemname+"=1"+itemprice;
			setCookie(cartname, newCookieValue);
			updateCart();
		}
		// now to the real work, if we found the item added before
		else if(foundCookieItem)
		{
			// get cookie old value in a string
			var cookieString= new String(oldCookieValue);
			// split it to an array that will obviousely carray all items
			var cookieArray=cookieString.split("&");
			// working with the array
			for(var i=0; i<cookieArray.length; i++)
			{
				// convert the array's item to a string
				var itemTemp= new String(cookieArray[i]);
				// split the string to an array with item name and amount
				var itemTempArray=itemTemp.split("=");
				// check for the item
				if(itemTempArray[0]==itemname)
				{
					// if it has the item name we're searching
					if(itemprice)
					{
						// if price is specified
						// split the value part
						var itemTempValue= new String(itemTempArray[1]);
						// split the string to an array with item name and amount
						var itemTempValueArray=itemTempValue.split("$");
						// increase the amount by one
						var oldAmount=itemTempValueArray[0];
						itemTempValueArray[0]++;

						var newPrice=parseFloat(itemTempValueArray[1]);
						newPrice=newPrice+(newPrice/oldAmount);
						// manually round the number
						var floatPrice=new String(newPrice);
						var newPriceArray=floatPrice.split(".");
						var floatPart=new String(newPriceArray[1]);
						if(floatPart!=newPrice){
							floatPart=floatPart.substring(0,1);	
							var floatPart=parseFloat(floatPart);
							floatPart=floatPart*10;
							floatPart=Math.round(floatPart);
							floatPart=floatPart/10;
							if(floatPart){
							newPriceArray[1]=floatPart;
							newPrice=newPriceArray.join(".");
							}
						}
						itemTempValueArray[1]=newPrice;

						// get the array node as it was
						itemTempArray[1]=itemTempValueArray.join("$");
					}
					// if NO price was specified
					else if(!itemprice)
					{
						var tValue=itemTempArray[1];
						// a trick to make JS convert the string to a variable
						tValue++;
						tValue+=tValue;
						tValue=tValue-2;
						itemTempArray[1]=tt;
					}
				}
				// convert the item array back to string, and change the array
				cookieArray[i]=itemTempArray.join("=");
			}
			// converting the cookie array back to string
			cookieString=cookieArray.join("&");
			// finally, write all this to the cookie
			setCookie(cartname, cookieString);
			//updateCart();
		}
	}
	// if there's no cookie, i.e. this is the first item to add to the cookie
	else
	{
		var newCookieValue=itemname+"=1"+itemprice;
		var test = setCookie(cartname, newCookieValue);
		if(!test){
			return true;
		}
		//updateCart();
	}

	return false;

}

//  to remove items from cart
function removeFromCart(itemname, itemprice, cartname)
{
	// if no cart name, assume default
	!cartname? cartname='cart' : '';
	if(getCookie(cartname))
	{
		// get cookie old value
		var oldCookieValue=getCookie(cartname);
		// search for the item in cookie
		var foundCookieItem=oldCookieValue.match(itemname);
		// now to the real work
		if(foundCookieItem)
		{
			// get cookie old value in a string
			var cookieString= new String(oldCookieValue);
			// split it to an array that will obviousely carray all items
			var cookieArray=cookieString.split("&");
			// working with the array
			for(var i=0; i<cookieArray.length; i++)
			{
				// convert the array's item to a string
				var itemTemp= new String(cookieArray[i]);
				// split the string to an array with item name and amount
				var itemTempArray=itemTemp.split("=");
				// check for the item
				if(itemTempArray[0]==itemname)
				{
					// split the value part
					var itemTempValue= new String(itemTempArray[1]);
					// split the string to an array with item name and amount
					var itemTempValueArray=itemTempValue.split("$");
					// decrease the amount by one
						var oldAmount=itemTempValueArray[0];
						
						if(oldAmount==1){
							itemTempValueArray[0]=0;
							itemTempValueArray[1]=0;
						}
						else{
							itemTempValueArray[0]--;
						}
						// get the array node as it was
					itemTempArray[1]=itemTempValueArray.join("$");
					itemTempArray[1]=="0$0"? itemTempArray='' : '';
				}
				// convert the item array back to string, and change the array
				!itemTempArray[1] || itemTempArray[1]==''? xx=cookieArray.splice(i,1) : cookieArray[i]=itemTempArray.join("=");
			}
			// converting the cookie array back to string
			cookieString=cookieArray.join("&");
			// finally, write all this to the cookie
			setCookie(cartname, cookieString);
			updateCart();
		}
	}
	return false;
}
/*
Adds items to cart
*/

function updateCart(cartname)
{
	// if no cart name, assume default
	!cartname? cartname='cart' : '';
	if(getCookie(cartname))
	{
		// get cookie old value in a string
		var cookieString= new String(getCookie(cartname));
		// split it to an array that will obviousely carray all items
		var cookieArray=cookieString.split("&");
		// initializing total
		var total=0;
		for(var i=0; i<cookieArray.length; i++)
		{
			// convert the array's item to a string
				var itemTemp= new String(cookieArray[i]);
				// split the string to an array with item name and amount
				var itemTempArray=itemTemp.split("=");
				// split the value part
				var itemTempValue= new String(itemTempArray[1]);
				// split the string to an array with item name and amount
				var itemTempValueArray=itemTempValue.split("$");
				// Calculate the total
				var ttempNumb=parseFloat(itemTempValueArray[1]);
				//ttempNumb=ttempNumb+1;
				//ttempNumb=ttempNumb-1;
				total=total+(ttempNumb*itemTempValueArray[0]);
				// now fix the x.xxxxxxxx error
				total=total*10;
				total=Math.round(total);
				total=total/10;
				// putting the "remove from cart" link
				var linkTempVar="<a href=\"add="+itemTempArray[0]+"\" style=\"border:1px solid #1369E0; text-decoration:none; background-color:#1369E0; color:#ffffff; padding-left:1px; padding-right:1px;\" onclick=\"return addToCart('"+itemTempArray[0]+"', '$"+itemTempValueArray[1]/itemTempValueArray[0]+"')\">+</a> <a href=\"remove="+itemTempArray[0]+"\" style=\"border:1px solid #1369E0; text-decoration:none; background-color:#1369E0; color:#ffffff; padding-left:3px; padding-right:3px;\" onclick=\"return removeFromCart('"+itemTempArray[0]+"', '$"+itemTempValueArray[1]/itemTempValueArray[0]+"')\">-</a> "+itemTempArray[0];
				itemTempArray[0]=linkTempVar;
				// get the array node as it was
				itemTempArray[1]=itemTempValueArray.join("</td>\r\n<td class=\"price\" width=\"10%\">");
				// convert the item array back to string, and change the array
				cookieArray[i]=itemTempArray.join("</td><td class=\"amount\" width=\"10%\">");
		}
		// creating table
		msg="<table width=\"100%\" cellspacing=\"1\" cellpadding=\"1\" class=\"carttable\">\r\n<tr>\r\n<td class=\"head\">محتويات السلة</td>\r\n</tr>\r\n<tr>\r\n<td>\r\n"
		// creating cart table
		msg+="<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\"><tr>\r\n<td width=\"80%\" class=\"item\">";
		// converting the cookie array back to string, addin it to the msg
		msg+=cookieArray.join("</td></tr>\r\n<tr><td class=\"item\">");
		// add the total
		if(total>0)
		msg+='\r\n</td>\r\n</tr>\r\n<tr class="total">\r\n<td class="item">القيمة الكلية: </td><td class="amount"></td><td class="price">جنيه '+total+'</td>\r\n</tr>\r\n';
        //add note to cart
        msg+='<tr>\r\n<td colspan="3"><div > لزيادة عدد المنتج المطلوب(+)<br>لتقليل عدد المنتج المطلوب(-)</div></td></tr>';
         // Add a link to empty the cart
		msg+='<tr>\r\n<td align="center" colspan="3"><a href="#" onclick="return emptyCart(\'cart\')">افرغ السلة</a> | <a href="#" onclick="window.opener=self; window.close();">استكمل التسوق</a> | <a href="cart.php?t=checkout">الدفع</a></td></tr>';
		// close the tabel
		msg+='\r\n</table>';
		// finally, write send all to the user
		document.getElementById('cart').innerHTML=msg;
		//alert(msg);
	}
	else
	document.getElementById('cart').innerHTML="<center>سلة التسوق فارغة</center>";
}
function prepareOrder(cartname)
{
	// if no cart name, assume default
	!cartname? cartname='cart' : '';
	if(getCookie(cartname))
	{
		// get cookie old value in a string
		var cookieString= new String(getCookie(cartname));
		// split it to an array that will obviousely carray all items
		var cookieArray=cookieString.split("&");
		// initializing total
		var total=0;
		for(var i=0; i<cookieArray.length; i++)
		{
			// convert the array's item to a string
			var itemTemp= new String(cookieArray[i]);
			// split the string to an array with item name and amount
			var itemTempArray=itemTemp.split("=");
			// split the value part
			var itemTempValue= new String(itemTempArray[1]);
			// split the string to an array with item name and amount
			var itemTempValueArray=itemTempValue.split("$");
			// Calculate the total
			var ttempNumb=itemTempValueArray[1];
			ttempNumb++;
			ttempNumb--;
			total+=ttempNumb;
			// putting the "remove from cart" link
			var linkTempVar="<a href=\"#\" onclick=\"return removeFromCart('"+itemTempArray[0]+"', '$"+itemTempValueArray[1]/itemTempValueArray[0]+"')\">"+itemTempArray[0]+"</a>";
			itemTempArray[0]=linkTempVar;
			// get the array node as it was
			itemTempArray[1]=itemTempValueArray.join("</td>\r\n<td class=\"price\" width=\"10%\"> ???? ");
			// convert the item array back to string, and change the array
			cookieArray[i]=itemTempArray.join("</td><td class=\"amount\" width=\"10%\">");
		}
		// creating table
		msg="<table width=\"100%\" cellspacing=\"1\" cellpadding=\"1\" class=\"carttable\">\r\n<tr>\r\n<td class=\"head\">Order Details:</td>\r\n</tr>\r\n<tr>\r\n<td>\r\n"
		// creating cart table
		msg+="<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\"><tr>\r\n<td width=\"80%\" class=\"item\">";
		// converting the cookie array back to string, addin it to the msg
		msg+=cookieArray.join("</td></tr>\r\n<tr><td class=\"item\">");
		// add the total
		if(total>0)
		msg+='\r\n</td>\r\n</tr>\r\n<tr class="total">\r\n<td class="item">القيمة الكلية</td><td class="amount"></td><td class="price">'+total+' جنيه </td>\r\n</tr>\r\n';
		// close the tabel
		msg+='\r\n</table>';
		// finally, write send all to the user
		document.getElementById('cart').value=msg;
		//alert(msg);
	}
	else
	document.getElementById('cart').innerHTML="<center>سلة التسوق فارغة</center>";
}