/**
 * @projectDescription Ajax Library for Super Secure - Uses JSON API  
 * @copyright Super Secure 2008
 * @license commercial
 * @author Luke Moynihan
 * @version 2.7.1
 * @require prototypejs
 */
 
/**
 * SS_getKeyFromServer
 * gets the session key for communicating via proxy
 * sets the global variable `window.ssSession`
 * @param {Integer} ssAccountCode
 * @param {Function}
 */
function SS_getKeyFromServer(ssAccountCode, callback)
{
	var existingKey = SS_getKey();
	if (existingKey == null)
	{
		new Ajax.Request(SS_proxyProvider, {
		  method: 'get',
		  parameters: {'ss_action':'getKey', 'ss_json':1, 'ss_account_code':ssAccountCode} ,
		  onSuccess: function(transport, json) {
				var sessionInfo = transport.responseText.evalJSON(true);
				SS_setKeyCookie($H(sessionInfo));
				if (callback != null)
				{
					callback();	
				}
		  },
		  onFailure: function(transport) {
			if (console) {
				console.log(transport.responseText);
			}
				else if(SS_showAlerts)
				{
					alert(transport.responseText);
				}
		  }
		});
	}
	else
	{
		if (callback != null)
		{
			callback();	
		}
	}
}

function SS_getKey()
{
	
	if (window.ssSession) // already in memory
	{
		return window.ssSession;
	}
	else // stored in cookie
	{
		var sessionName = SS_readCookie('sessionName');
		var sessionKey = SS_readCookie('sessionKey');
		if (sessionName != null)
		{
			window.ssSession = new Hash();
			window.ssSession.set('sessionName', sessionName);
			window.ssSession.set('sessionKey', sessionKey);
			return window.ssSession
		}
		else
		{
			return null;
		}		
	}
}

/**
 * SS_setKeyCookie
 * persist super secure session key using a cookie
 * helps work around browsers that block third party cookies ( *cough* Safari *cough* )
 * @param {Hash} key
 */
function SS_setKeyCookie(key)
{
	/*
if one already exists then dont set it
otherwise save the cookie and place it in the global vars

	 */
	var existingKey = SS_getKey();
	if (existingKey == null)
	{
		window.ssSession = key;
		SS_writeCookie('sessionName', key.get('sessionName'));
		SS_writeCookie('sessionKey', key.get('sessionKey'));
	}
	
}

/**
 * SS_addProduct
 * add a product to the shopping cart
 * @param {String} productCode
 * @param {Integer} quantity
 * @param {Hash} atttributes
 * @param {Function} callback
 */
function SS_addProduct(productCode, quantity, attributes, callback)
{
	SS_showLoader();
	var ssRequest = new Hash();
	prodCode = 'ss_product_'+productCode;

	ssRequest.set(prodCode,quantity);	

	if (attributes != null)
	{
		attributes.each(function(attribute) {
			var productAttributeKey = 'ss_attributes_'+productCode+'_'+attribute.key;
			ssRequest.set(productAttributeKey, attribute.value);
		});
	}

	ssRequest.set('ss_account_code',window.SS_accountCode);
	ssRequest.set(window.ssSession.get('sessionName'), window.ssSession.get('sessionKey'));
	ssRequest.set('ss_json',1);	
	ssRequest.set('ss_random', Math.random()); // prevent caching by making the request unique
	
	new Ajax.Request(SS_proxyProvider, {
	  method: 'get',
	  parameters: ssRequest ,
	  onSuccess: function(transport) {
			var cartContents = transport.responseText.evalJSON(true);
			cartContents = $A(cartContents);
			
			if (callback!=null)
			{
				callback(cartContents);
			}
			else if(window.SS_addProductCallback != null)
			{
				window.SS_addProductCallback(cartContents);
			}
			
			if (SS_showAlerts)
			{
				alert('product added');
			}
			SS_hideLoader();
	  },
	  onFailure: function(transport) {
	  	SS_hideLoader();
		if (console) {
	  		console.log(transport.responseText);
	  	}
			else if(SS_showAlerts)
			{
				alert(transport.responseText);
			}
	  }
	});
	return false;
}

function SS_getProducts()
{
	// @TODO
}

function SS_removeProduct(productCode)
{
	// @TODO
}

function SS_hideLoader()
{
	var loader = $('ajaxLoading');
	if (loader != null)
	{
		loader.style.display = 'none';	
	}
}

function SS_showLoader()
{

	var loader = $('ajaxLoading');
	if (loader != null)
	{
		loader.style.display = 'block';	
	}
}

/**
 * SS_getCartContents
 * fetch cart contents and use supplied callback to display result
 * @param {Function} callback
 */
function SS_getCartContents(callback)
{
	if (window.ssSession==null)
	{
		// must have session information
		throw 'session information unavailable';
	}
	var ssRequest = new Hash();
	
	ssRequest.set('ss_account_code',window.SS_accountCode);
	ssRequest.set(window.ssSession.get('sessionName'), window.ssSession.get('sessionKey'));
	ssRequest.set('ss_action','jsonBasket');
	ssRequest.set('ss_json',1);
	ssRequest.set('ss_random', Math.random()); // prevent caching by making the request unique
	
	new Ajax.Request(SS_proxyProvider, {
	  method: 'get',
	  parameters: ssRequest ,
	  onSuccess: function(transport) {
			var cartContents = transport.responseText.evalJSON(true);
			cartContents = $A(cartContents);
			callback(cartContents);
	  },
	  onFailure: function(transport) {
	  	if (console) {
	  		console.log(transport.responseText);
	  	}
			else if(SS_showAlerts)
			{
				alert(transport.responseText);
			}
	  }
	});
}

/**
 * SS_cartRenderer
 * example callback function to illustrate displaying updated cart contents as a table
 * @param {Array} products
 */
function SS_cartRenderer(products)
{
	
	var newTable = '<table class="shoppingBasket" id="shoppingBasket"><thead><tr><th>Name</th><th>Qty</th><th>Price</th></tr></thead>';
	var grandTotal = 0;
		
	products.each(function(product) {
		//console.log(product);
		
		newTable += '<tr><td class="name">'+ product.name +'</td><td class="qty">'+ product.quantity +'</td><td class="price">'+ parseFloat(product.price).toFixed(2) +'</td></tr>';
		grandTotal += (product.price * product.quantity);
	});
	newTable += '<tfoot><tr><td colspan="3">Total: $'+ grandTotal.toFixed(2) +'</td></tr></tfoot></table>';

	$('cartContents').innerHTML = newTable;
}


function SS_goToBasket()
{
	var sessionInfo = SS_getKey();
	//console.log( SS_secureBasketUrl + '?ss_account_code='+SS_accountCode+'&ss_action=showCheckout&'+sessionInfo.get('sessionName')+'='+sessionInfo.get('sessionKey') );
	window.location = SS_secureBasketUrl + '?ss_account_code='+SS_accountCode+'&ss_action=showCheckout&'+sessionInfo.get('sessionName')+'='+sessionInfo.get('sessionKey');
}



function SS_writeCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function SS_readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function SS_deleteCookie(name) {
	createCookie(name,"",-1);
}

/**
 * SS_formFieldsToAttributes
 * @param {Array} elementIds
 */
function SS_formFieldsToAttributes(elementIds)
{
	var attributes = new Hash();
	elementIds.each(function(elementId) {
		attributes.set(elementId, $F(elementId));
	});
	return attributes;
}
