//Studio 39 RL 2011
//21 Feb 2011 - fixed bug where dummy panel "stuck" when all panels were removed from stash. RL
var cookies = false;

$(document).ready(function(){

	if(typeof $.cookie !== 'undefined'){
	cookies = true;	
	}
});

function checkReferrer()
{
var dr = document.referrer;
if (dr.length < 1)
	{
	return;	
	}

var c = dr.indexOf("stash.php")
if (c>0)
	{
	return;
	}
saveStashReferrer();
}

function gotoreferrer()
{
var t=read_cookie($.cookie('STASH_REFERRER'));
var lp = t['URL'];
window.location = lp;
}

function saveStashReferrer() 
    {
       	var sUrl = document.referrer;
	var nHashPos = sUrl.lastIndexOf("#");		// Look for URL anchor
	if (nHashPos > 0)									// if it exists
	    {
	    sUrl = sUrl.substring(0,nHashPos);		// then remove it
	    }
	var URLC = new Array();
	URLC['URL']= sUrl;
	write_cookie("STASH_REFERRER", URLC);		// Emulates HTTP_REFERER
		
	    return null;
    }   

function read_cookie(cookie){
	
	var cookie_array = new Array();
	
	if(cookie){
	
	var cookie_elements = cookie.split(';');
	
		for(i=0;i<=cookie_elements.length;i++){
	
			if(cookie_elements[i]){
		
				cookie_data = cookie_elements[i].split('=');
			
				var key = cookie_data[0];

				cookie_array[key] = cookie_data[1];
			}
		
		}
	
	}
	return cookie_array;
}

function remove_cookie(name)
{
$.cookie(name, null);	
}

function write_cookie(name, cookie_array){
	
	var cookie_str = '';
	
	for (key in cookie_array){
		
		cookie_str += key+'='+cookie_array[key]+';';
		
	}
	
	$.cookie(name, cookie_str);
}

function getCartInfo()
{
var myblob  = document.getElementsByTagName ('Actinic:SECTION')[0];
var myblobname = myblob.getAttribute('blob');
var sid = document.getElementsByName('SID')[0].value;
var page = document.getElementsByName('PAGE')[0].value;
var pagefilename = document.getElementsByName('PAGEFILENAME')[0].value;
var myprices  = document.getElementsByTagName ('Actinic:PRICES')[0];
var myprod_ref = myprices.getAttribute('PROD_REF');
var myretail_price_prompt = myprices.getAttribute('RETAIL_PRICE_PROMPT');
var mypriceprompt = document.getElementById("RL");
var mypricetext = mypriceprompt.innerHTML;
mypricetext = mypricetext.replace('<br />','');
mypricetext = mypricetext.replace('<br>','');
var mypicdiv = $(".image_product");
var myimgtag = $("img", mypicdiv);
var mypic = myimgtag[0].src;

//test if cookie already exists for this item
var testforC = panelCookieExists(myprod_ref);

if (testforC==true)
	{alert ('This item is already in your stash');
	return ;
	}

var stash_items = new Array();

stash_items['prod_ref']=myprod_ref;
stash_items['blob']=myblobname;
stash_items['sid']=sid;
stash_items['page']=page;
stash_items['pagefilename']=pagefilename;
stash_items['price_prompt']=myretail_price_prompt;
//deal with charset dependancies for the pound sign
var rawprice = mypricetext.split('£');
stash_items['price_text']=rawprice[0];
stash_items['price_text2']=rawprice[1];
stash_items['pic']=mypic; 

var mypanelCount = addPanel();

write_cookie('stash_items_'+mypanelCount, stash_items)

var test = read_cookie($.cookie('stash_items_'+mypanelCount));
alert ('Successfully added to your Stash');
}

function removePanel(panelNumber)
{
var ct = read_cookie($.cookie('stashPanels'));
var mypc = parseFloat(ct['panelCount']);
if (typeof mypc == 'undefined' )
{
//no panels. Give up
return;
}

		var i = 1
		while (i<= mypc)
		{
		//re-number any cookie numbered higher than the removed one
		var mytc = read_cookie($.cookie('stash_items_'+i));
		if (i==panelNumber)
		//Delete the stash details cookie for the panel 
		{
		remove_cookie('stash_items_'+panelNumber);
		};
		//if i < panelNumber
		//do nothing
		if (i>panelNumber)
		{
		//write the cookie with decremented number
		write_cookie('stash_items_'+(i-1), mytc);
		}
		
		i++;
		};
//delete the now orphaned highest number cookie		
		remove_cookie('stash_items_'+mypc);
//Rewrite the panel count cookie with 1 less panel
if (typeof mypc !== 'undefined' )
{
	var stash_panels = {panelCount: mypc-1};
	if (mypc < 1)
	{
	//do not want 0 count cookie - delete it and all the others instead
	delete_cookie('stashPanels');
	delete_cookie('panel_positions');
	delete_cookie('collapsed');

	}
	if (mypc > 1)
	{
	write_cookie('stashPanels', stash_panels);
	}
};

window.location="stash.php";
}

function panelCookieExists(pref)
{
var ct = read_cookie($.cookie('stashPanels'));
var mypc = parseFloat(ct['panelCount']);

if (typeof mypc !== 'undefined' )
	{
		var i = 1
		while (i<= mypc)	{
		var mytc = read_cookie($.cookie('stash_items_'+i));
		var cProd = mytc['prod_ref'];
		if (cProd == pref){return true};
		i++;
		};
	return false;
	}
else
	{
	return false;
	};
return 1; //catchall return
}


function addPanel()
{
var ct = read_cookie($.cookie('stashPanels'));
var mypc = ct['panelCount'];
//test that the existing panel 1 is not the dummy i.e. with no settings cookie
var testfordummy = read_cookie($.cookie('stash_items_'+mypc));
	try
		//look for a cookie element length
		{var tfd=testfordummy['blob'].length;} 
	catch (e)
		{var tfd=0};

//if there is a panel count and a real panel cookie
if ((typeof mypc !== 'undefined' ) &  (tfd >0))
	{
	var stash_panels = {panelCount: parseFloat(mypc) + 1};
	write_cookie('stashPanels', stash_panels);
	addPanelCookie(parseFloat(mypc) + 1);
	return parseFloat(mypc) + 1;
	}
else
	{
	var stash_panels = {panelCount: 1}
	write_cookie('stashPanels', stash_panels);
	addPanelCookie(1)
	return 1;
	};
return 1
}

function addPanelCookie(newCount)
{
	var panel_positions = read_cookie($.cookie('panel_positions'));
	
	var moved_panel_id = 'panel-'+newCount;

	var moved_to_column_id = 'column-1';
	var order_in_column = 0;
	
	//iterate the cookie to establish:
	//	- lowest available row
	//	- the column it is in
	var col1 = 0;
	var col2 = 0;
	var col3 = 0;
	var thiscol = 0;
	var i = 1
	
	//deal with the first 3 - so for the others we "know" if the 0 means position 0 or no panel
	if (newCount == 1)
		{
		// take column 1
		panel_positions[moved_panel_id] = 'column-1:0';
		write_cookie('panel_positions', panel_positions);
		return } ;
	if (newCount == 2)
		{
		// take column 2
		panel_positions[moved_panel_id] = 'column-2:0';
		write_cookie('panel_positions', panel_positions);
		return};
	if (newCount == 3)
		{panel_positions[moved_panel_id] = 'column-3:0';
		write_cookie('panel_positions', panel_positions);
		return};
	
		
	while (i<= newCount-1)	{
        var mykey = 'panel-'+i;
	var h = panel_positions[mykey];
	var colinfo = h.split(":");
	var ccount = parseFloat(colinfo[1]);
	if (colinfo[0]== "column-1")
		{if(ccount> col1) {col1 = ccount};
		};
	if (colinfo[0]== "column-2")
		{if(ccount> col2) {col2 = ccount};
		};
	if (colinfo[0]== "column-3")
		{if(ccount> col3) {col3 = ccount};
		};
	i++;
	};
	
	// if 2 < 1 use 2. If 2 < 3 use 2
	var coltoUse = "column-2";
	var nextpos = col2 + 1;
	if (col2 > col1)
		{var coltoUse = "column-1";
		var nextpos=col1 + 1};
	if (col2 > col3)
		{var coltoUse = "column-3";
		var nextpos = col3 + 1};
	
	panel_positions[moved_panel_id] = coltoUse +':'+nextpos;

			
	write_cookie('panel_positions', panel_positions);
		
	
}
