// cartAJAXfunctions.js
// Copyright 2009-2010 Elysium Software, Inc.
// All Rights Reserved
//
// Implements JavaScript code to handle AJAX methods for the
// cart
//
// Version 1.2
// February 9, 2010
// ========================================================================================

var base_url = "";
var cartPath = "cart_assets/";

// JavaScript Trim Function
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// ========================================================================================
// Promo code
// ========================================================================================
function AddPromoByCode (userid)
{		
	var postString = "&user_id=" + userid;
	postString += "&promocode=" + (document.getElementById("promocodeid").value);

	postData('addpromobycode.php', postString, AddPromoByCodeCallback);
}

function AddPromoByCodeCallback (resultText)
{
	// Refresh 
	if (resultText.trim() != "")
		document.getElementById("promocoderesult").innerHTML = '<b><font color="red">' + resultText + '</font></b>';
	else
    {
		document.getElementById("promocodeid").value = '';
		window.location.reload();
    }
}

// ========================================================================================
// Delete item from cart
// ========================================================================================
function DeleteItemFromCart(item_id)
{
	var item_size = "";
	var item_color = "";
	
	if($("#size_"+item_id).length)
		item_size = $("#size_"+item_id).val();
	if($("#color_"+item_id).length)
		item_color = $("#color_"+item_id).val();
	
	var dialog = '<div id="dialog" class="dialogz" title="Do you want to delete?">';
	dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
	dialog += '<div class="dialog_content">';
	dialog += 'Are you sure you want to delete this item?';
	dialog += '</div>';
	dialog += '</div>';
	$("body").append(dialog);
	$(".dialogz").dialog({
		dialogClass: 'alert',
		width: 500,
		modal: true,
		resizable: false,
		buttons: {
			Ok: function() {
				$.ajax({
					url: cartPath + 'deletefromcart.php',
					data: {
						itemid: item_id,
						itemsize: item_size,
						itemcolor: item_color
					},
					type: 'POST',
					success: DeleteItemFromCartCallback,
					error: ajax_error
				});
				$(this).dialog( "close" );
			},
			'Cancel': function() {
				$(this).dialog( "close" );
			}
		},
		close: function(){
			// remove once closed
			$(this).remove();
		}
	});
}

function DeleteItemFromCartCallback (data)
{
	//alert(data);	
	data = eval("("+data+")");
	
	// =============================================
	//	HANDLE ERRORS
	// =============================================
	if("error" in data)
	{
		var msg = "";
		
		msg += data['error']+"<br />";
		
		var dialog = '<div id="dialog" class="dialogz" title="Error">';
		dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += msg;
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
	}
	else
	{
		get_full_cart();
		showCart();
	}
}

// ========================================================================================
// 	ADD TO CART
//	AddToCart - Used with a simple button with no extra options needed
//	AddToCart_options - Used with a button that requires additional options
//	AddToCart_additional - Used after dialog with additional options are selected
// ========================================================================================
function AddToCartCallback(data)	
{
	//alert(data);	
	data = eval("("+data+")");
	
	// =============================================
	//	HANDLE ERRORS
	// =============================================
	if("error" in data)
	{
		var msg = "";
		
		for(var element in data['error'])
			msg += data['error'][element]+"<br />";
		
		var dialog = '<div id="dialog" class="dialogz" title="Error">';
		dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += msg;
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
	}
	else
	{
		var dialog = '<div id="dialog" class="dialogz" title="Added!">';
		dialog += '<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += 'You have successfully added the item to your cart!';
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
		showCart();
	}
}	   	

function AddToCart(calling_object, item_id)	
{
	calling_object = $(calling_object);
	
	$.ajax({
		url: cartPath + 'addtocart.php',
		data: {
			itemid: item_id,
			itemquantity: calling_object.find("input").val()
		},
		type: 'POST',
		success: AddToCartCallback,
		error: ajax_error
	});
}

function AddToCart_options(calling_object, item_id)
{
	//alert(item_id);
	calling_object = $(calling_object);
	
	$.ajax({
		url: cartPath + 'get_product_options.php',
		data: {
			itemid: item_id,
			itemquantity: calling_object.find("input").val()
		},
		type: 'POST',
		success: AddToCart_options_show_dialog,
		error: ajax_error
	});
}

function AddToCart_options_show_dialog(data)
{
	data = eval("("+data+")");
	var msg = "";
	
	// =============================================
	//	HANDLE ERRORS
	// =============================================
	if("error" in data)
	{
		for(var element in data['error'])
			msg += data['error'][element]+"<br />";
		
		var dialog = '<div id="dialog" class="dialogz" title="Error">';
		dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += msg;
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
	}
	else
	{
		// error container
		msg += '<div class="hidden_element dialog_error" id="error_container"></div>';
		
		// colours
		msg += '<div class="dialog_title">Available Colours</div>';
		if("colour" in data['options'])
		{
			for(var i = 0; i < data['options']['colour'].length; i++)
				msg += '<input type="radio" name="colour" value="'+data['options']['colour_id'][i]+'" /> - '+data['options']['colour'][i]+'<br />';
		}
		else
			msg += 'N/A<br />';
		
		msg += '<br />';
		
		// sizes
		msg += '<div class="dialog_title">Available Sizes</div>';
		if("size" in data['options'])
		{
			for(var i = 0; i < data['options']['size'].length; i++)
				msg += '<input type="radio" name="size" value="'+data['options']['size_id'][i]+'" /> - '+data['options']['size'][i]+'<br />';
		}
		else
			msg += 'N/A<br />';
		
		var dialog = '<div id="dialog" class="dialogz" title="Options">';
		dialog += msg;
		dialog += '</div>';
		$("body").append(dialog);
		$(".dialogz").dialog({
			dialogClass: 'alert',
			width: 500,
			modal: true,
			resizable: false,
			buttons: {
				'Add To Cart': function() {
					
					// ===============================
					//	MAKE SURE OPTIONS ARE SELECTED
					// ===============================
					var error_msgs = "";
					
					if($("input[name='colour']").length)
					{
						if(!$("input[name='colour']").is(":checked"))
							error_msgs += "Please select a colour for the item.<br />";
					}
					if($("input[name='size']").length)
					{
						if(!$("input[name='size']").is(":checked"))
							error_msgs += "Please select a size for the item.<br />";
					}
					
					if(error_msgs != "")
						$("#error_container").html(error_msgs).show();
					else
					{
						AddToCart_additional(data['item_qty'], data['item_id'], $("input[name='size']:checked").val(), $("input[name='colour']:checked").val());
						$(this).dialog( "close" );
					}
				},
				'Cancel': function() {
					$(this).dialog( "close" );
				}
			},
			close: function(){
				// remove once closed
				$(this).remove();
			}
		});
	}
}

function AddToCart_additional(item_qty, item_id, size_id, colour_id)	
{	
	$.ajax({
		url: cartPath + 'addtocart.php',
		data: {
			itemid: item_id,
			itemquantity: item_qty,
			itemsize: size_id,
			itemcolor: colour_id
		},
		type: 'POST',
		success: AddToCartCallback,
		error: ajax_error
	});
}

// ========================================================================================
//	Add to cart
// ========================================================================================
function AddItemIDToCartCallback (itemIndex)	
{
	var elementNameHeader = "add_to_cart_msg_";
	var elementName = '';
	
	// Clear out the existing ones first
	var totalToClear = 100;
	
	for (elementIndex = 0; elementIndex < totalToClear; elementIndex++)
	{
		elementName = elementNameHeader + elementIndex + "_id";
		var elementAddedObj = document.getElementById(elementName);
		if (elementAddedObj)
			document.getElementById(elementName).innerHTML = '';
	}

	elementName = elementNameHeader + itemIndex.trim() + "_id";
	document.getElementById(elementName).innerHTML = '<b>Added!</b>';
}	   	

function AddItemIDToCart (userid, itemIndex)	
{
	var postString = "";
		 
	var postItemIDName = ""
	var elementItemIDName = "";
		 
	var postQuantityName = ""
	var elementQuantityName = "";
		 
	var postSizeName = ""
	var elementSizeName = "";

	var postColorName = ""
	var elementColorName = "";

	postString = "&user_id=" + userid;
	postString += "&item_index=" + itemIndex;
		  
	postItemIDName = "&itemid_" + itemIndex;
	elementItemIDName = "itm_id_" + itemIndex + "_id";
	
	postQuantityName =  "&itemquantity_" + itemIndex;
	elementQuantityName = "qtytot_" + itemIndex + "_id";
		
	postSizeName =  "&itemsize_" + itemIndex;
	elementSizeName = "size_" + itemIndex + "_id";

	postColorName =  "&itemcolor_" + itemIndex;
	elementColorName = "color_" + itemIndex + "_id";

	postString += postItemIDName + "=" + (document.getElementById(elementItemIDName).value);
		
	postString += postQuantityName + "=" + (document.getElementById(elementQuantityName).value);
    
	var elementSizeNameObj = document.getElementById(elementSizeName); 
	if (elementSizeNameObj)
		postString += postSizeName + "=" + encodeURI(document.getElementById(elementSizeName).value);

	var elementColorNameObj = document.getElementById(elementColorName);
	if (elementColorNameObj)
		postString += postColorName + "=" + encodeURI(document.getElementById(elementColorName).value);

    document.getElementById(elementQuantityName).value = 0; //Clear out value

	cartPath = "modules/Cart/";

	postData(cartPath + 'addtocart.php', postString, AddItemIDToCartCallback);	
}

// =============================================================================================================
//	THE CART HAS A DIFFERENT PATH
//	(ADDED FOR PAGES WITHIN MODULES FOLDER)
// =============================================================================================================
function AddItemIDToCart_once (userid, itemIndex)	
{		
	var postString = "";
		 
	var postItemIDName = ""
	var elementItemIDName = "";
		 
	var postQuantityName = ""
	var elementQuantityName = "";
		 
	var postSizeName = ""
	var elementSizeName = "";

	var postColorName = ""
	var elementColorName = "";

	postString = "&user_id=" + userid;
	postString += "&item_index=" + itemIndex;
		  
	postItemIDName = "&itemid_" + itemIndex;
	elementItemIDName = "itm_id_" + itemIndex + "_id";
	
	postQuantityName =  "&itemquantity_" + itemIndex;
	elementQuantityName = "qtytot_" + itemIndex + "_id";
		
	postSizeName =  "&itemsize_" + itemIndex;
	elementSizeName = "size_" + itemIndex + "_id";

	postColorName =  "&itemcolor_" + itemIndex;
	elementColorName = "color_" + itemIndex + "_id";

	postString += postItemIDName + "=" + (document.getElementById(elementItemIDName).value);
		
	postString += postQuantityName + "=" + (document.getElementById(elementQuantityName).value);
    
	var elementSizeNameObj = document.getElementById(elementSizeName); 
	if (elementSizeNameObj)
		postString += postSizeName + "=" + encodeURI(document.getElementById(elementSizeName).value);

	var elementColorNameObj = document.getElementById(elementColorName);
	if (elementColorNameObj)
		postString += postColorName + "=" + encodeURI(document.getElementById(elementColorName).value);

    document.getElementById(elementQuantityName).value = 0; //Clear out value

	cartPath = "";

	postData(cartPath + 'addtocart_once.php', postString, AddItemIDToCartCallback);	
}

// ========================================================================================
// 	Update cart
// ========================================================================================
function UpdateItemQuantityInCartCallback (data)
{
	data = eval("("+data+")");
	
	// =============================================
	//	HANDLE ERRORS
	// =============================================
	if("error" in data)
	{
		var msg = "";
		
		msg += data['error']+"<br />";
		
		var dialog = '<div id="dialog" class="dialogz" title="Error">';
		dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += msg;
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
	}
	else
	{
		get_full_cart();
		showCart();
	}
}	 

function UpdateItemQuantityInCart(calling_object)
{
	calling_object = $(calling_object);
	item_id = calling_object.attr("element");
	item_size = "";
	item_color = "";
	
	if($("#size_"+item_id).length)
		item_size = $("#size_"+calling_object.attr("element")).val();
	if($("#color_"+item_id).length)
		item_color = $("#color_"+calling_object.attr("element")).val();
	
	$.ajax({
		url: cartPath + 'updatefromcart.php',
		data: {
			itemid: item_id,
			itemquantity: $("input[name='quantity_"+calling_object.attr("element")+"']").val(),
			itemcolor: item_color,
			itemsize: item_size
		},
		type: 'POST',
		success: UpdateItemQuantityInCartCallback,
		error: ajax_error
	});
}

// ========================================================================================
function updateTotals()
{
	total_qty_in = document.getElementById("total_qty_id").value; 
	
	subtotal = 0;
	total = 0;
	
	for (itemnumber = 0; itemnumber < total_qty_in; itemnumber++)
	{
		qty_item_var = "qty_item_"+itemnumber;
		item_price_var = "item_price_"+itemnumber;
		sub_total_var = "item_subtotal_"+itemnumber;	
	
		item_qty = document.getElementById(qty_item_var).value;
		item_price = document.getElementById(item_price_var).value;

		subtotal = item_qty * item_price;
	 
		document.getElementById(sub_total_var).innerHTML = "$"+subtotal.toFixed(2); 

		total += subtotal;
	}

	document.getElementById("grand_total").innerHTML = "$"+total.toFixed(2); 
}
// ========================================================================================
// Submission functions
// ========================================================================================
function postData (url, data, callback)
{ 
	var XMLHttpRequestObject = false; 
	var urlRoot = '';
	
	if (window.XMLHttpRequest) 
		XMLHttpRequestObject = new XMLHttpRequest();
  
    if (XMLHttpRequestObject.overrideMimeType) 
    {
    	// Set type accordingly to anticipated content type
    	XMLHttpRequestObject.overrideMimeType('text/html');
    }
    else if (window.ActiveXObject) 
    {
    	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(XMLHttpRequestObject) 
    {
    	XMLHttpRequestObject.open("POST", urlRoot + url); 
    	XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
	
    	XMLHttpRequestObject.onreadystatechange = function() 
    	{ 
    		if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) 
    		{			
    			callback(XMLHttpRequestObject.responseText); 
    			delete XMLHttpRequestObject;
    			XMLHttpRequestObject = null;
    		} 
    		else
    		{
    			// document.getElementById("status").innerHTML = '<b>Processing...</b>';
    		}
    	}

    	XMLHttpRequestObject.send(data); 
    }
}

// ========================================================================================
//	GET FULL CART CONTENTS
// ========================================================================================
function get_full_cart()
{
	// set button behaviour
	$(".remove_item").live("click", function(){
		DeleteItemFromCart($(this).attr("remove_id"));
		return false;
	});
	
	$(".quantity_input").live("change", function(){
		$("#update_"+$(this).attr('name').substring(9)).removeClass("hidden_element");
	});
	
	$("#shopping_cart").fadeOut("fast", function(){
		$.ajax({
			url: cartPath + 'get_cart_contents.php',
			type: 'POST',
			success: get_full_cart_callback,
			error: ajax_error
		});
	});
}

function get_full_cart_callback(data)
{
	//alert(data);
	data = eval("("+data+")");
	
	// =============================================
	//	HANDLE ERRORS
	// =============================================
	if("error" in data)
	{
		var msg = "";
		
		for(var element in data['error'])
			msg += data['error'][element]+"<br />";
		
		var dialog = '<div id="dialog" class="dialogz" title="Error">';
		dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += msg;
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
	}
	else
	{
		msg = "";
		
		if(data['cart'].length == 0)
			msg = "Your cart is empty!";
		else
		{
			var i = 1;
			msg += '<table id="full_cart">';
			msg += '<tr class="titles">';
			msg += 		'<th></th>';
			msg += 		'<th>Qty:</th>';
			msg += 		'<th>Item Name:</th>';
			msg += 		'<th>Item Size:</th>';
			msg += 		'<th>Item Colour:</th>';
			msg += 		'<th class="item_price">Price:</th>';
			msg += '</tr>';
			for(var element in data['cart'])
			{
				msg += '<tr';
				if(i%2)
					msg += ' class="coloured_row"';
				msg += '>';
				msg += 		'<td class="remove_item"><img class="remove_item" remove_id="'+data['cart'][element]['id']+'" src="'+base_url+'images/delete.png" alt="Remove Item" /></td>';
				msg += 		'<td class="item_qty">';
				msg +=			'<input class="quantity_input" type="text" name="quantity_'+data['cart'][element]['id']+'" value="'+data['cart'][element]['quantity']+'" maxlength="4" />';
				msg +=			'<div class="hidden_element update_qty" onclick="UpdateItemQuantityInCart(this)" id="update_'+data['cart'][element]['id']+'" element="'+data['cart'][element]['id']+'">Update Qty</div>';
				msg +=		'</td>';
				msg += 		'<td class="item_title">'+data['cart'][element]['name']+'</td>';
				msg += 		'<td class="item_title">'+data['cart'][element]['size']+'<input type="hidden" id="size_'+data['cart'][element]['id']+'" value="'+data['cart'][element]['size_id']+'" /></td>';
				msg += 		'<td class="item_title">'+data['cart'][element]['color']+'<input type="hidden" id="color_'+data['cart'][element]['id']+'" value="'+data['cart'][element]['colour_id']+'" /></td>';
				msg += 		'<td class="item_price">$'+data['cart'][element]['price']+'</td>';
				msg += '</tr>';
				
				i++;
			}
			msg += '</table>';
			
			// PRICE TOTALS
			msg += '<table id="price_totals">';
			msg += '<tr class="sub_total">';
			msg += 		'<th>Sub Total</th>';
			msg += 		'<td class="item_price">';
			msg +=			'$'+data['orderSubTotal'];
			msg +=		'</td>';
			msg += '</tr>';
			msg += '<tr class="sub_total">';
			msg += 		'<th>Shipping</th>';
			msg += 		'<td class="item_price">';
			msg +=			'$'+data['shippingTotal'];
			msg +=		'</td>';
			msg += '</tr>';
			if(data['totalHST'] != "0.00")
			{
				msg += '<tr class="sub_total">';
				msg += 		'<th>HST</th>';
				msg += 		'<td class="item_price">';
				msg +=			'$'+data['totalHST'];
				msg +=		'</td>';
				msg += '</tr>';
				msg += '<tr class="sub_total">';
				msg += 		'<th>Grand Total</th>';
				msg += 		'<td class="item_price">';
				msg +=			'$'+data['orderGrandTotal'];
				msg +=		'</td>';
				msg += '</tr>';
			}
			msg += '<tr>';
			msg += 		'<td colspan="2" class="item_price">';
			msg += 			'<div class="submit_btn product_add set_size add_to_cart_btn" onClick="javascript: window.location = \''+base_url+'checkout?crt='+data['user_id']+'\'">';
			msg += 				'<div class="product_add_inner">';
			msg += 					'CHECKOUT';
			msg += 				'</div>';
			msg += 			'</div>';
			msg +=		'</td>';
			msg += '</tr>';
			/*msg += '<tr>';
			msg += 		'<td colspan="2" class="item_price">';
			msg +=			'<a href="'+base_url+'cart_assets/payPalECOrder.php?orderid='+data['user_id']+'"><img src="'+base_url+'images/paypal_checkout_btn.gif" alt="Process to PayPal" /></a>';
			msg += 		'</td>';
			msg += '</tr>';*/
			msg += '</table>';
		}
		
		$("#shopping_cart").html(msg);
		$("#shopping_cart").fadeIn("fast");
	}
}

// ========================================================================================
//	GET CART PANO
// ========================================================================================
$(function(){
	
	// set up paths
	if($("#base_url").length)
		base_url = $("#base_url").html();
	cartPath = base_url+cartPath;
	
	// show cart overview
	showCart();
	
	// set button behaviour
	$(".add_to_cart_btn input").click(function(){
		return false;
	});
});

function showCart()
{
	$("#cart_pano").fadeOut("fast", function(){
		$.ajax({
			url: cartPath + 'get_cart_contents.php',
			type: 'POST',
			success: showCart_callback,
			error: ajax_error
		});
	});
}

function showCart_callback(data)
{
	//alert(data);
	data = eval("("+data+")");
	
	// =============================================
	//	HANDLE ERRORS
	// =============================================
	if("error" in data)
	{
		var msg = "";
		
		for(var element in data['error'])
			msg += data['error'][element]+"<br />";
		
		var dialog = '<div id="dialog" class="dialogz" title="Error">';
		dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
		dialog += '<div class="dialog_content">';
		dialog += msg;
		dialog += '</div>';
		dialog += '</div>';
		$("body").append(dialog);
		open_dialog();
	}
	else
	{
		msg = "";
		
		if(data['cart'].length == 0)
			msg = "Your cart is empty!";
		else
		{
			msg += "<table>";
			for(var element in data['cart'])
			{
				msg += '<tr>';
				msg += '<td class="item_title">'+data['cart'][element]['name']+'</td>';
				msg += '<td class="item_price">x'+data['cart'][element]['quantity']+'</td>';
				msg += '</tr>';
			}
			
			// SUB TOTAL
			msg += '<tr class="grand_total">';
			msg += 		'<td class="item_title">Sub Total</td>';
			msg += 		'<td class="item_price">$'+data['orderSubTotal']+'</td>';
			msg += '</tr>';
			
			msg += '</table>';
			msg += '<a href="https://www.spitsgear.com/view-cart?crt='+data['user_id']+'">View Cart</a>';
		}
		
		$("#cart_pano").html(msg);
		$("#cart_pano").fadeIn("fast");
	}
}

function ajax_error(XMLHttpRequest, textStatus, errorThrown)
{
	var dialog = '<div id="dialog" class="dialogz" title="Error">';
	dialog += '<span class="ui-icon ui-icon-circle-close" style="float:left; margin:0 7px 50px 0;"></span>';
	dialog += '<div class="dialog_content">';
	dialog += errorThrown;
	dialog += '</div>';
	dialog += '</div>';
	$("body").append(dialog);
	open_dialog();
}

function open_dialog()
{
	$(".dialogz").dialog({
		dialogClass: 'alert',
		zIndex: 30000,
		width: 500,
		modal: true,
		resizable: false,
		buttons: {
			Ok: function() {
				$(this).dialog( "close" );
			}
		},
		close: function(){
			// remove once closed
			$(this).remove();
		}
	});
}
