// Shopping List Applet
// By Taylor Design (Daniel L. Taylor) http://www.taylor-design.com
// For Fisher Printing http://www.fisherprinting.com/
// Version: 1.3
// 2010-05-17
// Copyright (C) 2010 Fisher Printing, Inc. All Rights Reserved.
// Downloading and using this code without the permission of Fisher Printing is
// strictly prohibited.

// Note *************************************************
// The following variables are set in the container and shopping pages
// and are available to the code here when the applet is run.

	//// Basic Setup
	//var slBaseAdUrl = "weekly/v10/"; // The path to the associated ad files.
	//
	// Initial panel. One of: slPagePanel, slAllPagesPanel, slThumbPanel
	// var slInitialPanel = "slPagePanel";
	//
	//// Shopping List Setup
	//var slListAllow = true; // Display a shopping cart and allow users to add items to it?
	//
	//// Thumbnail Setup
	//var slThumbAllow = true; // Allow the user to see a thumbnail page?
	//var slThumbColumns = 3; // Columns in the thumbnail page.
	//var slThumbWidth = 150; // Width of each thumbnail.
	//var slThumbHeight = 200; // Height of each thumbnail.
	//
	//// PDF Setup
	//var slPdfAllow = true; // Display a Download PDF link?
	//
	// Layout
	// var slShoppingNavigationWidth = 775;
	// var slShoppingDisplayWidth = 825;
	// var slListPanelWidth = 250;
	//
	//// Web Ad Builder Variables - these are set
	//// by Web Ad Builder each week.
	//var slPageCount = /*PageCount*/; // The total number of pages.
	//var slMaxImageWidth = /*ImageWidth*/; // The maximum width of a full ad page.
	//var slMaxImageHeight = /*MaxImageHeight*/; // A random number that is set with each Ad upload.
	//var slCacheControl = '/*CacheControl*/' // Used to force a browser cache refresh for each new ad.
	//var slAdStartDate = '/*AdStartDate*/' // The date the ad starts.
	//var slAdEndDate = '/*AdEndDate*/' // The date the ad ends.
	
// Constants *************************************************
var slkAllPagesPanel = "slAllPagesPanel";
var slkPagePanel = "slPagePanel";
var slkThumbPanel = "slThumbPanel";

// These constants are used for cookie storage of the shopping list.
var slkRecord = String.fromCharCode(0);
var slkField = String.fromCharCode(1);
var slkListCookieName = 'FisherPrintingShoppingList';

// These constants specify the position of the page number in the All Pages panel.
var slkAllPages_PageNumber_Position_Top = "top";
var slkAllPages_PageNumber_Position_Bottom = "bottom";

// Global Variables *************************************************
var slPanelCurrent = '';
var slPageCurrent = 1;
var slListItems;
var strCacheControlPostfix = '';

// Setup *************************************************
function slOpen()
{
	// Call slOpen (usually in body onload) to initialize the applet.
	
	// Common Variables
	var obj;
	var i;
	
	// Init globals.
	slListItems = new Array();
	strCacheControlPostfix = '?slCacheControl=' + slCacheControl;
	
	// Get url variables.
	var urlVars = fpGetUrlVars();
	
	// Load the correct language.
	var strLanguage = urlVars['slLanguage'];
	slLanguageLoad(strLanguage);
	slLanguageFill();
	
	// Setup Layout
	obj = document.getElementById('slShoppingNavigation');
	obj.width = slShoppingNavigationWidth;
	obj.style.minWidth = slShoppingNavigationWidth + 'px';
	
	obj = document.getElementById('slShoppingDisplay');
	obj.width = slShoppingDisplayWidth;
	obj.style.minWidth = slShoppingDisplayWidth + 'px';
	
	// Initialize shopping list related features.
	slListShow(slListAllow);
	
	// Show the correct panel.
	slAllPagesPanelBuild();
	slPanelSelect(slInitialPanel);
	
	// Setup the menu.
	if (slThumbAllow == true)
	{
		obj = document.getElementById('slThumbShow');
		obj.style.visibility = "visible";
		slThumbBuild();
	}
	
	if (slPdfAllow == true)
	{
		obj = document.getElementById('slDownloadPdf');
		obj.style.visibility = "visible";
		
		obj = document.getElementById('slDownloadPdfLink');
		obj.href = slBaseAdUrl + 'shopping.pdf';
	}
	
	// Get the slPage url parameter.
	// < 0: display first page.
	// 0: display thumbnails if allowed, otherwise first page.
	// 1-n: display the page.
	// >n: display the last page.
	var intPage = urlVars["slPage"];
	
	if (intPage != parseInt(intPage))
		intPage = 1;
	
	if (intPage <= 0)
		intPage = 1;
		
	if (intPage > slPageCount)
		intPage = slPageCount;
	
	// Initialize the display.
	if (slPanelCurrent == slkPagePanel)
		slPageSet(intPage);
	
	// Load any stored shopping lists.
	slListLoadCookie();
}


// Event Handlers *************************************************
function slMapClick()
{
	// This function is set as the map area click handler using jQuery.
	// Future variations should be coded in their own functions, and
	// slOpen should decide which to use based on easily set globals.
	
	// Also consider if any future modifications would be better
	// handled in slListAddItem.
	
	// Get click item data.
	var intId = $(this).attr('productid');
	var strTitle = $(this).attr('title');
	var dblPrice = $(this).attr('price'); 
	
	// Add to list.
	slListAdd(intId, strTitle, dblPrice);
}

function slListItemAddClick()
{
	// Get the text and check it for length.
	var strTitle = $('#slUserItem').attr('value');
	if (strTitle.length == 0)
		return;
	
	// Add to list.
	slListAdd(0, strTitle, 0);
	
	// Clear the field.
	$('#slUserItem').attr({ value: "" });
}

// Panel Management *************************************************
function slPanelHideAll()
{
	slPanelHide(slkThumbPanel);
	slPanelHide(slkPagePanel);
	slPanelHide(slkAllPagesPanel);
}

function slPanelSelect(strPanel)
{
	slPanelHideAll();
	
	switch(strPanel)
	{
		case slkAllPagesPanel:
			slAllPagesPanelShow();
			break;
		
		case slkThumbPanel:
			slThumbPanelShow();
			break;
		
		default:
			slPagePanelShow();
	}	
}

function slPanelHide(strId)
{
	// Hides a page panel. Not to be used with non-page elements.
	obj = document.getElementById(strId);
	if (obj == null)
		return;
	
	obj.style.visibility = "hidden";
	obj.style.display = "none";
}

function slPanelShow(strId)
{
	// Shows a page panel. Not to be used with non-page elements.
	obj = document.getElementById(strId);
	if (obj == null)
		return;
	
	obj.style.visibility = "visible";
	obj.style.display = "block";
}

// slAllPagesPanel Management *************************************************
function slAllPagesPanelShow()
{
	// Preflight
	if (slPanelCurrent == slkAllPagesPanel)
		return;
	
	// Hide others.
	slPanelHideAll();

	// Show.
	slPanelShow(slkAllPagesPanel);
	slPanelCurrent = slkAllPagesPanel;
	
	// Init mapping.
	for (i = 1; i <= slPageCount; i++)
		$('#slPageImage' + i).maphilight();
		
	// Adjust List Panel height.
	var objList;
	
	// Adjust SL height.
	if (slListAllow == true)
	{
		objList = document.getElementById('slListPanel');
		objList.style.minHeight = ((slMaxImageHeight * slPageCount) + (20 * slPageCount)) + 'px';
	}
	
	// Set the title.
	slSetPageTitle('&nbsp;');
	
	// Adjust the prev/next links.
	obj = document.getElementById("slPagePrev");
	obj.style.visibility = "hidden";
		
	obj = document.getElementById("slPageNext");
	obj.style.visibility = "hidden";
}

function slAllPagesPanelBuild()
{
	// Called from slOpen. This function builds the all pages panel.
	
	// Get the panel.
	var obj;
	obj = document.getElementById(slkAllPagesPanel);
	
	// Build the html.
	var strHtml = '';
	
	for (i = 1; i <= slPageCount; i++)
	{
		// Add page number to the top?
		if (slAllPages_PageNumber_Position == slkAllPages_PageNumber_Position_Top)
		{
			if (i > 1)
				strHtml += '<br/><br/>';
			
			strHtml += '<div id="slAllPages_PageNumber">' + lblPage + ' ' + i + '</div>';
			strHtml += '<br/>';
		}
		
		// Add image.
		strHtml += '<img src="' + slBaseAdUrl + i + '.jpg' + strCacheControlPostfix;
		strHtml += '" border="0" id="slPageImage' + i + '" usemap="#slPageMap' + i + '" /><br/>';
		
		// Add page number to the bottom?
		if (slAllPages_PageNumber_Position == slkAllPages_PageNumber_Position_Bottom)
		{
			strHtml += '<br/>';
			strHtml += '<div id="slAllPages_PageNumber">' + lblPage + ' ' + i + '</div>';
			strHtml += '<br/><br/>';
		}
	}
	
	obj.innerHTML = strHtml;
}

// slPagePanel Management *************************************************
function slPagePanelShow()
{
	// Preflight
	if (slPanelCurrent == slkPagePanel)
		return;
	
	// Hide others.
	slPanelHideAll();

	// Show.
	slPanelShow(slkPagePanel);
	slPanelCurrent = slkPagePanel;
	slPageSet(1);
}

function slPageNext()
{
	// Go to the next page after the currently displayed page.
	var intPage = slPageCurrent + 1;
	slPageSet(intPage);	
}

function slPagePrev()
{
	// Go to the previous page before the currently displayed page.
	var intPage = slPageCurrent - 1;
	slPageSet(intPage);
}

function slPageFirst()
{
	// Go to the first page.
	slPageSet(1);
}

function slPageLast()
{
	// Go to the last page.
	slPageSet(slPageCount);
}

function slPageSet(intPage)
{
	// Go to the input page number. If < 1, display page 1.
	// If > last page, display last page.
	
	// Preflight
	if (intPage < 1)
		intPage = 1;
		
	if (intPage > slPageCount)
		intPage = slPageCount;
		
	// Show page panel.
	if (slPanelCurrent != slkPagePanel)
		slPagePanelShow();

	// Set minimum height on slPagePanel. This prevents
	// the display from "jumping" during page switches
	// when the shopping list is deactivated.
	var obj;
	obj = document.getElementById(slkPagePanel);
	obj.style.minHeight = slMaxImageHeight + 'px';
	
	// Set current page number.
	slPageCurrent = intPage;
	
	// Set the image.
	// NOTE: this code builds the image element and sets the panel's innerHTML, then calls maphilight.
	// This is because on some web browsers it's not possible to directly set the src of an image element if
	// that element includes usemap.
	var strHtml;
	
	strHtml = '<img src="' + slBaseAdUrl + slPageCurrent + '.jpg' + strCacheControlPostfix + '" border="0" id="slPageImage" usemap="#slPageMap' + slPageCurrent + '" />';
	obj.innerHTML = strHtml;
	$('#slPageImage').maphilight();
	
	// Set the page title.
	slSetPageTitle(lblPage + ' ' + slPageCurrent + ' ' + lblOf + ' ' + slPageCount);
	
	// Adjust the prev/next links.
	obj = document.getElementById("slPagePrev");
	if (intPage == 1)
		obj.style.visibility = "hidden";
	else
		obj.style.visibility = "visible";
		
	obj = document.getElementById("slPageNext");
	if (intPage == slPageCount)
		obj.style.visibility = "hidden";
	else
		obj.style.visibility = "visible";
	
	// Adjust SL height.	
	if (slListAllow == true)
	{
		objList = document.getElementById('slListPanel');
		objList.style.minHeight = slMaxImageHeight + 'px';
	}
}

// slThumbPanel Management *************************************************
function slThumbPanelShow()
{
	// If allowed, displays the thumbnail page.
	// Preflight
	if (slThumbAllow == false)
		return;
	
	// Variables
	var obj;
	
	// Swap panels.
	slPanelHideAll();
	slPanelShow(slkThumbPanel);
	slPanelCurrent = slkThumbPanel;
	
	// Set the page title.
	slSetPageTitle(lblIndex);
	
	// Adjust the prev/next links.
	obj = document.getElementById("slPagePrev");
	obj.style.visibility = "hidden";
		
	obj = document.getElementById("slPageNext");
	obj.style.visibility = "visible";
	
	// Adjust SL height.	
	if (slListAllow == true)
	{
		objList = document.getElementById('slListPanel');
		objList.style.minHeight = slMaxImageHeight + 'px';
	}
}

function slThumbBuild()
{
	// Called from slOpen. This function builds the thumbnail page.
	
	// Calculate cell width as percentage.
	var intCellWidth;
	intCellWidth = Math.round((1 / slThumbColumns) * 100);
	
	// Table Template
	var strRowHeader = '<tr align="center">';
	var strCellHeader = '<td align="center" width="' + intCellWidth + '%">';
	
	// Build table.
	var intColumn = 1;
	var intCell = 1;
	var strTable = '<table cellpadding="5" border="0">';
	
	while (intCell <= slPageCount)
	{
		// Start row.
		strTable += strRowHeader;
		
		// Add columns.
		intColumn = 1;
		while ((intColumn <= slThumbColumns) && (intCell <= slPageCount))
		{
			strTable += strCellHeader;
			strTable += '<a href="javascript:slPageSet(' + intCell + ');">';
			strTable += '<img src="' + slBaseAdUrl + intCell + '_thumbnail.jpg' + strCacheControlPostfix + '" ';
			strTable += 'border="0" style="max-width:' + slThumbWidth + 'px; max-height:';
			strTable += slThumbHeight + 'px;" id="slThumb' + intCell + '" />';
			strTable += '</a></td>'

			intColumn += 1;
			intCell += 1;
		}
		
		// Close row.
		strTable += '</tr>';
	}
	strTable += '</table>';

	// Set div.
	var obj;
	obj = document.getElementById('slThumbPanel');
	obj.innerHTML = strTable;
}

// List Management *************************************************

function slListShow(bolShow)
{
	// Setup the list box.
	var obj;
	obj = document.getElementById('slListPanel');
	
	var objCell;
	objCell = document.getElementById('slListPanelCell');
	
	if (bolShow == true)
	{
		// Set cell width.
		if (objCell != null)
		{
			objCell.width = slListPanelWidth;	
		}
		
		// Show.
		obj.style.visibility = "visible";
		obj.style.display = ""; // *** IMPORTANT NOTE: this has to be blank or jQuery scrollFollow will not work!
		obj.style.minHeight = slMaxImageHeight + 'px';
		
		// Init the list box.
		$('#slListBox').scrollFollow({ offset: 50 });
		
		// Init map clicks.
		for (i = 1; i <= slPageCount; i++)
		{
			$('#slPageMap' + i + ' area').click(slMapClick);
		}
		
		// Set the click handler for the shopping list Add button.
	    $('#slUserAdd').click(slListItemAddClick);
	}
	else
	{
		// Hide
		obj.style.visibility = "hidden";
		obj.style.display = "none";
		obj.style.minHeight = 0 + 'px';
	}
}

function slListItem(intId, strTitle, dblPrice, intQuantity)
{
	// Create a slListItem object to store the input values.
	// Preflight
	if (isNaN(intId) == true)
		intId = 0;
		
	if (isNaN(dblPrice) == true)
		dblPrice = 0;
		
	if (isNaN(intQuantity) == true)
		intQuantity = 1;
	
	// Store values.
	this.id = intId;
	this.title = strTitle;
	this.price = dblPrice;
	this.quantity = intQuantity;
}

function slListAdd(intId, strTitle, dblPrice, intQuantity, bolRender)
{
	// Normally we want to render the list, but functions can
	// pass false if they are making multiple changes and wish
	// to render only once when finished.
	if (bolRender == null)
		bolRender = true;
	
	// Create and store an item instance.
	var obj;
	obj = new slListItem(intId, strTitle, dblPrice, intQuantity);
	slListItems.splice(0, 0, obj);
	
	// Render?
	if (bolRender == true)
	{
		slListRender();
		
		// Scroll to top to show new item.
		var objDiv = document.getElementById("slListItems");
		objDiv.scrollTop = 0;
	}
}

function slListAppend(intId, strTitle, dblPrice, intQuantity, bolRender)
{
	// Normally we want to render the list, but functions can
	// pass false if they are making multiple changes and wish
	// to render only once when finished.
	if (bolRender == null)
		bolRender = true;
	
	// Create and store an item instance.
	var obj;
	obj = new slListItem(intId, strTitle, dblPrice, intQuantity);
	slListItems.push(obj);
	
	// Render?
	if (bolRender == true)
	{
		slListRender();
		
		// Scroll to top to show new item.
		var objDiv = document.getElementById("slListItems");
		objDiv.scrollTop = 0;
	}
}

function slListRemoveByIndex(intIndex, bolRender)
{
	// Normally we want to render the list, but functions can
	// pass false if they are making multiple changes and wish
	// to render only once when finished.
	if (bolRender == null)
		bolRender = true;
		
	// Preflight - validate intIndex.
	if (intIndex < 0)
		return;
		
	if (intIndex >= slListItems.length)
		return;
	
	// Remove the item.
	slListItems.splice(intIndex, 1);
	
	// Render?
	if (bolRender == true)
		slListRender();
}

function slListClear(bolUserConfirm)
{
	// Defaults
	if (bolUserConfirm == null)
		bolUserConfirm = true;
		
	// Preflight - if the list is empty then we don't need to do anything.
	if (slListItems.length <= 0)
		return;
		
	// User confirmation.
	if (bolUserConfirm == true)
	{
		var bolUserResponse;
		bolUserResponse = confirm(msgConfirmRemoveListItem);
		if (bolUserResponse == false)
			return;
	}
	
	// 
	slListItems = new Array();
	slListRender();
}

function slListPrint()
{
	// Is the list empty?
	if (slListItems.length <= 0)
	{
		alert(msgNoItemsToPrint);
		return;
	}
	
	// Get the list content.
	var strContent = slListRender(true);
	
	// Setup print window.
	var objPrintWindow = window.open('','print_content','width=500,height=500');
	objPrintWindow.document.open();
	objPrintWindow.document.write('<html><body onload="window.print()"><h3>' + lblYourList + '</h3>' + strContent + '</body></html>');
	objPrintWindow.document.close();
	
	// Close timer.
	setTimeout(function(){objPrintWindow.close();}, 1000);
}

function slListRender(bolForPrint)
{
	// Defaults
	if (bolForPrint == null)
		bolForPrint = false;
	
	// Variables
	var strHtml = '';
	var i = 0;
	var c = slListItems.length;
	var intIndex = 1;
	var obj;
	
	// Render each item.
	for (i = 0; i < c; i++)
	{
		obj = slListItems[i];
		strHtml += slListRenderItem(obj, intIndex, bolForPrint);
		intIndex++;
	}
	
	// Set the container to the new html if for screen.
	// Otherwise return the content.
	if (bolForPrint == false)
	{
		var objList;
		objList = document.getElementById('slListItems');
		objList.innerHTML = strHtml;
		slListStoreCookie();
		
		// Test
		// var obj; obj = fpGetCookie(slkListCookieName); alert(obj);
	}
	else
		return strHtml;
	
}

function slListRenderItem(obj, intIndex, bolForPrint)
{
	//Render an individual shopping list item to HTML.
	var strHtml = '';
	strHtml += '<div id="slListItem">';
	strHtml += '<div style="float:left; width:32px;">' + intIndex + '</div>';
	strHtml += '<div style="margin-left:36px;">' + obj.title;
	
	if ((isNaN(obj.price) == false) && (obj.price != 0))
		strHtml += '&nbsp;' + slFormatPrice(obj.price);
		
	if (obj.quantity > 1)
		strHtml += '&nbsp;Qty: ' + obj.quantity;
	
	if (bolForPrint == false)
		strHtml += '&nbsp;&nbsp;<a href="javascript:slListRemoveByIndex(' + (intIndex - 1) + ');">(' + lblRemove + ')</a>';
	
	strHtml += '</div><br /></div>';
	return strHtml;
}

function slListStoreCookie()
{
	// Variables
	var strCookie = '';
	var i = 0;
	var c = slListItems.length;
	var obj;
	
	// Stream objects to cookie string.
	for (i = 0; i < c; i++)
	{
		obj = slListItems[i];
		strCookie += obj.id + slkField + obj.title + slkField + obj.price + slkField + obj.quantity + slkRecord;
	}
	
	// Store.
	strCookie = slCacheControl + slkRecord + strCookie;
	fpSetCookie(slkListCookieName, strCookie, '30', '/', '', '');
}

function slListLoadCookie()
{
	// Allow list?
	if (slListAllow == false)
		return;
	
	// Get the cookie value. Test for null.
	var strCookie = fpGetCookie(slkListCookieName);
	if (strCookie == null)
		return;
		
	// Split to array.
	var strRecords = strCookie.split(slkRecord, 1000);
	var c = strRecords.length;
	if (c < 1)
		return;
		
	// Check cache control.
	if (strRecords[0] != slCacheControl)
	{
		fpDeleteCookie(slkListCookieName, '/', '');
		return;
	}
	
	// Parse records.
	var strRecord;
	var strFields;
	var objItem;
	
	slListClear(false);
	
	for (i = 1; i < c; i++)
	{
		strRecord = strRecords[i];
		strFields = strRecord.split(slkField, 5);
		if (strFields.length >= 4)
			slListAppend(strFields[0], strFields[1], strFields[2], strFields[3], false);
	}
	
	slListRender();
}

// Language Management *************************************************
var lblDownloadPdf;
var lblThumbnails;
var lblPreviousPage;
var lblNextPage;
var lblPage;
var lblOf;
var lblIndex;
var lblYourList;
var lblNewList;
var lblPrintList;
var lblAdd;
var lblRemove;
var msgConfirmRemoveListItem;
var msgNoItemsToPrint;

function slLanguageFill()
{
	// Called from slOpen to set the labels in the shopping page.
	document.getElementById('lblDownloadPdf').innerHTML = lblDownloadPdf;
	document.getElementById('lblThumbnails').innerHTML = lblThumbnails;
	document.getElementById('lblPreviousPage').innerHTML = lblPreviousPage;
	document.getElementById('lblNextPage').innerHTML = lblNextPage;
	
	document.getElementById('lblNewList').innerHTML = lblNewList;
	document.getElementById('lblPrintList').innerHTML = lblPrintList;
	document.getElementById('slUserAdd').value = lblAdd;
}

function slLanguageLoad(strLanguage)
{
	// Future web sites will use a more comprehensive architecture for languages across the site
	// design. Existing sites need the applet to be able to set its language.
	// Default is English.
	switch(strLanguage)
	{
		case "Spanish":
			// These items appear in the shopping.htm file and
			// have to be set using JavaScript.
			lblDownloadPdf = "Bajar PDF";
			lblThumbnails = "Fotos Chicas";
			lblPreviousPage = "P&#225;gina Anterior";
			lblNextPage = "P&#225;gina Pr&#243;xima";
			lblNewList = "Lista Nueva";
			lblPrintList = "Imprimir Lista";
			lblAdd = "Agregar";
			
			// These items are used in this code file.
			lblPage = "P&#225;gina";
			lblOf = "y";
			lblIndex = "Indice";
			lblYourList = "Su Lista Del Mandado";
			lblRemove = "quite";
			
			// These items are displayed in alert boxes and CANNOT have accented characters.
			msgConfirmRemoveListItem = "Esta seguro que quiere quitar todos los articulos que estan en su lista actualmente?";
			msgNoItemsToPrint = "No hay articulos para imprimir. Puede agregar articulos a su lista del mandado haciendo clic en las paginas de las especiales.";
			break;
			
		default:
			lblDownloadPdf = "Download PDF";
			lblThumbnails = "Thumbnails";
			lblPreviousPage = "Previous Page";
			lblNextPage = "Next Page";
			lblPage = "Page";
			lblOf = "of";
			lblIndex = "Index";
			lblYourList = "Your Shopping List";
			lblNewList = "New List";
			lblPrintList = "Print List";
			lblAdd = "Add";
			lblRemove = "remove";
			msgConfirmRemoveListItem = "Are you sure you want to remove all items from your current shopping list?";
			msgNoItemsToPrint = "There are no items to print. You can add items to your shopping list by clicking on the ad.";
	}
}

// Utilities *************************************************
function slSetPageTitle(strTitle)
{
	obj = document.getElementById("slPageTitle");
	if (obj == null)
		return;
	obj.innerHTML = strTitle;
}

function slFormatPrice(dblPrice)
{
	dblPrice = Math.round(dblPrice * 100) / 100;
	return '$' + dblPrice;
}

function fpGetUrlVars()
{
	// Read a page's GET URL variables and return them as an associative array.
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


// Cookie management from: http://techpatterns.com/downloads/javascript_cookies.php
// with some modifications.
function fpSetCookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" + escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function fpGetCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function fpDeleteCookie( name, path, domain ) {
	if ( fpGetCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
