/***************************
* Copyright (c) GrocerySavings.ca
* All Rights Reserved.
*
* Author: Ben Cho
* Website: grocerysavings.ca, localgrocerydeals.com
* CopyRight: 2007
*
* Utility file responsible for managing cookies
****************************/

	// global variables
	var ONE_YEAR_EXPIRY_DAYS = 365;
	var COOKIE_NAME_TYPED_IN_GROCERY_LIST = "typedInGroceryList";
	var COOKIE_NAME_PRINTABLE_GROCERY_LIST_BUFFER = "groceryListBuffer";
	var COOKIE_NAME_PRINTABLE_GROCERY_LIST_STORE_MATCHES_BUFFER = "groceryStoreMatchesBuffer";
	var COOKIE_NAME_PERSONAL_GROCERIES = "personalGroceries";
	var COOKIE_NAME_POSTAL_CODE = "postalCode";
	var COOKIE_NAME_TAB_PANEL_SELECTION = "tabPanelSelection";

	var COOKIE_NAME_VOTED_GROCERY_IDs = "votedGroceryIDs";
	var COOKIE_NAME_GROCERY_STORE_FILTER = "groceryStoreFilter";
	var COOKIE_NAME_FLYER_LISTING_CATEGORY = "flyerListingCategory";
	var COOKIE_NAME_PROVINCE_CODE = "provinceCode";
	var COOKIE_NAME_FLYER_CATEGORY_ID = "flyerCategoryID";
	var COOKIE_NAME_CITY = "city";

	var TAB_PANEL_OPTION_1 = "tabOption1";
	var TAB_PANEL_OPTION_2 = "tabOption2";

	// can be either postal code or full address
	var COOKIE_NAME_MAP_USER_ADDRESS = "userAddress";
	
	var COOKIE_NAME_QUICK_COMPARE_OPTION = "quickCompareOption";

	/*
	 * get the cookie value associated with the given cookieName
	 * @param	cookieName	name of the cookie
	 * @return	the value associated with the cookie name	
	 */
	function getCookie(cookieName)
	{
		if (document.cookie.length > 0)
		{ 
			// find the start of the cookieName-value pair
			// if c_start = -1 then this cookie name does not exist
			c_start = document.cookie.indexOf(cookieName + "=");
				if (c_start!=-1)
				{ 
					c_start = c_start + cookieName.length + 1;
					// find the end of the cookieName-value pair
					c_end = document.cookie.indexOf(";", c_start);
					
					if (c_end == -1) 
						c_end=document.cookie.length;

					return unescape(document.cookie.substring(c_start, c_end));
				} 
		}
		return null;
	}

	/*
	 * set the cookieName-value pair with an absolute expiry date
	 * @param	cookieName	name of the cookie
	 * @param	value		value associated with the cookie name
	 * @param	absoluteExpiryDate	the absolute date that the cookie will expire
	 *			eg. January 1, 2007
	 */	
	function setCookieWithAbsoluteExpiryDate(cookieName, value, absoluteExpiryDate)
	{
		document.cookie = cookieName + "=" + escape(value) +
		// if expireDays is null, then set it to never to expire
		((absoluteExpiryDate == null) ? "" : "; expires=" + absoluteExpiryDate.toGMTString())
	}

	/*
	 * set the cookieName-value pair with a relative number of days until expiry
	 * @param	cookieName	name of the cookie
	 * @param	value		value associated with the cookie name
	 * @param	expireDays	the number of days until the cookie expires
	 */	
	function setCookie(cookieName, value, expireDays)
	{
		var expiryDate = new Date()
		expiryDate.setDate(expiryDate.getDate() + expireDays)
		document.cookie = cookieName + "=" + escape(value) +
		// if expireDays is null, then set it to never to expire
		((expireDays == null) ? "" : "; expires=" + expiryDate.toGMTString())
	}

	// sets a cookie to expire on the coming wednesday or saturday depending on todays date
	function setCookieExpireWeekly(cookieName, value)
	{
		// get the appropriate expiry date to set for this cookie
		var expiryDate = getCookieExpiryDate();

		setCookieWithAbsoluteExpiryDate(cookieName, value, expiryDate);
	}

	/*
	 * get the saved grocery list in Option 2 from the cookie
	 * @return	not really a return, writes out the list of groceries in the saved grocery list in html
	 */	
	function getSavedShoppingListCookie()
	{
		var SHOPPING_LIST_COOKIE_NAME = "shoppingList";
		var html = "";

		// get the list of items from the cookie
		list = getCookie(SHOPPING_LIST_COOKIE_NAME);

		// list exists in the cookie
		if (list != null)
		{
			fifo_writebuffer(list);
			var numOfElements = fifo_countelements();

			html = "<table class='tableHeadingGroceryList' cellspacing=0><tr><th class='ESList' colspan='2'>Grocery List</th></tr>";
			for (i=1; i<=numOfElements; i++)
			{
				var product = fifo_popAll();
				var tempProduct = product.replace(/\'/g, "/");
//				var tempProduct = product.replace(/\'/g, "\\");
				html += "<tr><td>" + product + "</td><td><input type='button' onClick=\"remove('" + tempProduct + "')\" value='remove'></td></tr>";

			}
			html = html + "</table>"
			fifo_writebuffer(list);

//			domShoppingCart.innerHTML = html;
			document.getElementById("groceryListShoppingCart").innerHTML = html;
		}
	}

	// used by default.asp to save grocery store selections into cookie
	function saveGroceryStoreSelectionsCookie()
	{
		var COOKIE_NAME_GROCERY_STORE_SELECTION_LOBLAWS = "groceryStoreSelectionLoblaws";
		var COOKIE_NAME_GROCERY_STORE_SELECTION_NO_FRILLS = "groceryStoreSelectionNoFrills";
		var COOKIE_NAME_GROCERY_STORE_SELECTION_FOOD_BASICS = "groceryStoreSelectionFoodBasics";
		var COOKIE_NAME_GROCERY_STORE_SELECTION_PRICE_CHOPPER = "groceryStoreSelectionPriceChopper";
//		var COOKIE_NAME_GROCERY_STORE_SELECTION_DOMINION = "groceryStoreSelectionDominon";

		var ON = "on";
		var OFF = "off";

		var domLoblaws = document.getElementById("loblawsCB");
		var domNoFrills = document.getElementById("nofrillsCB");
		var domFoodBasics = document.getElementById("foodbasicsCB");
		var domPriceChopper = document.getElementById("pricechopperCB");
//		var domDominion = document.getElementById("dominionCB");



		if (domLoblaws.checked == true)
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_LOBLAWS, ON, ONE_YEAR_EXPIRY_DAYS);
		else
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_LOBLAWS, OFF, ONE_YEAR_EXPIRY_DAYS);

		if (domNoFrills.checked == true)
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_NO_FRILLS, ON, ONE_YEAR_EXPIRY_DAYS);
		else
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_NO_FRILLS, OFF, ONE_YEAR_EXPIRY_DAYS);

		if (domFoodBasics.checked == true)
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_FOOD_BASICS, ON, ONE_YEAR_EXPIRY_DAYS);
		else
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_FOOD_BASICS, OFF, ONE_YEAR_EXPIRY_DAYS);

		if (domPriceChopper.checked == true)
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_PRICE_CHOPPER, ON, ONE_YEAR_EXPIRY_DAYS);
		else
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_PRICE_CHOPPER, OFF, ONE_YEAR_EXPIRY_DAYS);
/*
		if (domDominion.checked == true)
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_DOMINION, ON, ONE_YEAR_EXPIRY_DAYS);
		else
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_DOMINION, OFF, ONE_YEAR_EXPIRY_DAYS);
*/
	}

	// 
	function restoreGroceryStoreSelectionsCookie()
	{

		var COOKIE_NAME_GROCERY_STORE_SELECTION_LOBLAWS = "groceryStoreSelectionLoblaws";
		var COOKIE_NAME_GROCERY_STORE_SELECTION_NO_FRILLS = "groceryStoreSelectionNoFrills";
		var COOKIE_NAME_GROCERY_STORE_SELECTION_FOOD_BASICS = "groceryStoreSelectionFoodBasics";
		var COOKIE_NAME_GROCERY_STORE_SELECTION_PRICE_CHOPPER = "groceryStoreSelectionPriceChopper";
//		var COOKIE_NAME_GROCERY_STORE_SELECTION_DOMINION = "groceryStoreSelectionDominon";

		var ON = "on";
		var OFF = "off";

		// if this is the first visit to this website, then default to all grocery store selections
		var firstTime = getCookie('firstTime');
		if (firstTime == null)
		{
			setCookie('firstTime', "no", 365);

			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_LOBLAWS, ON, ONE_YEAR_EXPIRY_DAYS);
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_NO_FRILLS, ON, ONE_YEAR_EXPIRY_DAYS);
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_FOOD_BASICS, ON, ONE_YEAR_EXPIRY_DAYS);
			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_PRICE_CHOPPER, ON, ONE_YEAR_EXPIRY_DAYS);
//			setCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_DOMINION, ON, ONE_YEAR_EXPIRY_DAYS);
		}		

		// get grocery store selections from the cookies
		var cookieLoblaws = getCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_LOBLAWS);
		var cookieNoFrills = getCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_NO_FRILLS);
		var cookieFoodBasics = getCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_FOOD_BASICS);
		var cookiePriceChopper = getCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_PRICE_CHOPPER);
//		var cookieDominion = getCookie(COOKIE_NAME_GROCERY_STORE_SELECTION_DOMINION);


		if (cookieLoblaws == ON)
			setGroceryStoreSelection("loblaws", ON);
		else
			setGroceryStoreSelection("loblaws", OFF);

		if (cookieNoFrills == ON)
			setGroceryStoreSelection("nofrills", ON);
		else
			setGroceryStoreSelection("nofrills", OFF);

		if (cookieFoodBasics == ON)
			setGroceryStoreSelection("foodbasics", ON);
		else
			setGroceryStoreSelection("foodbasics", OFF);

		if (cookiePriceChopper == ON)
			setGroceryStoreSelection("pricechopper", ON);
		else
			setGroceryStoreSelection("pricechopper", OFF);
/*
		if (cookieDominion == ON)
			setGroceryStoreSelection("dominion", ON);
		else
			setGroceryStoreSelection("dominion", OFF);
*/
	}

	function setGroceryStoreSelection(groceryStore, val)
	{
		var domElementCB = document.getElementById(groceryStore + "CB");
		var domElement = document.getElementById(groceryStore);
		var domElement1 = document.getElementById(groceryStore + "1");

		if (val == "on")
			domElementCB.checked = true;
		else
			domElementCB.checked = false;

		domElement.value = val;
		domElement1.value = val;
	}

	// used by default.asp to save typed in grocery list into cookie
	function saveTypedInGroceryList()
	{
		var domTypedInGroceryList = document.getElementById("searchWord")
		setCookie(COOKIE_NAME_TYPED_IN_GROCERY_LIST, domTypedInGroceryList.value, ONE_YEAR_EXPIRY_DAYS);
	}

	// used by default.asp to retreive saved typed in grocery list from cookie
	function getTypedInGroceryList()
	{
		var domTypedInGroceryList = document.getElementById("searchWord")

		var cookieValue = getCookie(COOKIE_NAME_TYPED_IN_GROCERY_LIST);
//alert(cookieValue);
		// only prepopulate if the cookie value is not empty
		if (cookieValue != null)
		{
			domTypedInGroceryList.value = cookieValue;
		}
	}

	// saves postal code from default.asp to cookie
	function savePostalCode()
	{
		var domPostalCode = document.getElementById("postalCodeTB");
		setCookie(COOKIE_NAME_POSTAL_CODE, domPostalCode.value, ONE_YEAR_EXPIRY_DAYS);
	}

	// load postal code from cookie to default.asp
	function loadPostalCode()
	{
		var domPostalCode = document.getElementById("postalCodeTB");

		var cookieValue = getCookie(COOKIE_NAME_POSTAL_CODE);

		if (cookieValue != null)
		{
			domPostalCode.value = cookieValue;
			// this function resides in homePage.js
			setPostalCode(domPostalCode);
		}
	}

	// used by uiSearchResultIncludes.html to save printable grocery list and grocery store matches into cookie
	function savePrintableGroceryList()
	{
		// get the value from the grocery shopping cart and save it into the cookie
//		setCookie(COOKIE_NAME_PRINTABLE_GROCERY_LIST_BUFFER, getGroceryPrintOutBuffer(), ONE_YEAR_EXPIRY_DAYS);	
		// get the value from the grocery shopping cart and save it into the cookie
//		setCookie(COOKIE_NAME_PRINTABLE_GROCERY_LIST_STORE_MATCHES_BUFFER, getGroceryStoreMatchesBuffer(), ONE_YEAR_EXPIRY_DAYS);

		setCookieExpireWeekly(COOKIE_NAME_PRINTABLE_GROCERY_LIST_BUFFER, getGroceryPrintOutBuffer());
		setCookieExpireWeekly(COOKIE_NAME_PRINTABLE_GROCERY_LIST_STORE_MATCHES_BUFFER, getGroceryStoreMatchesBuffer());
	}

	// used by printGroceryList.asp to save personal groceries into the cookie
	function savePersonalGroceriesCookie()
	{
		var domPersonalGroceries = document.getElementById("additionalGroceries");
		setCookie(COOKIE_NAME_PERSONAL_GROCERIES, domPersonalGroceries.value, ONE_YEAR_EXPIRY_DAYS);
	}

	// used by printGroceryList.asp to get personal groceries from the cookie
	function getPersonalGroceriesCookie()
	{
		var domPersonalGroceries = document.getElementById("additionalGroceries");

		var cookieValue = getCookie(COOKIE_NAME_PERSONAL_GROCERIES);
		// only prepopulate if the cookie value is not empty
		if (cookieValue != null)
		{
			domPersonalGroceries.value = cookieValue;
		}
	}

	// retreive the grocery shopping print list from the cookie and populate it into grocery shopping list buffer
	function getPrintableGroceryList()
	{
		var cookieValue = getCookie(COOKIE_NAME_PRINTABLE_GROCERY_LIST_BUFFER);
		if (cookieValue != null)
			return getCookie(COOKIE_NAME_PRINTABLE_GROCERY_LIST_BUFFER);

		return "";
	}

	// retreive the grocery store matches from the cookie and populate it into grocery store matches buffer
	function getPrintableGroceryListStoreMatches()
	{
		var cookieValue = getCookie(COOKIE_NAME_PRINTABLE_GROCERY_LIST_STORE_MATCHES_BUFFER);
		if (cookieValue != null)
			return getCookie(COOKIE_NAME_PRINTABLE_GROCERY_LIST_STORE_MATCHES_BUFFER);

		return "";
	}

	// saves the users tab panel selection on the DEFAULT.asp
	function saveTabPanelSelectionInCookie()		     
	{
		var domTab1Focus = document.getElementById("tabOption1Focus");
		// holds the name of the tab option that was selected,
		//	"tabOption1" or "tabOption2"
		var tabOptionSelected = "";

		if (domTab1Focus.style.display == "block")
		{
			tabOptionSelected = TAB_PANEL_OPTION_1;
		}
		else
		{
			tabOptionSelected = TAB_PANEL_OPTION_2;
		}
//alert(tabOptionSelected);
		setCookie(COOKIE_NAME_TAB_PANEL_SELECTION, tabOptionSelected, ONE_YEAR_EXPIRY_DAYS);
	}

	// get the saved tab panel selection from the cookie and restore the view accordingly
	function restoreTabPanelSelectionFromCookie()
	{

		var cookieValueTabOptionSelected = getCookie(COOKIE_NAME_TAB_PANEL_SELECTION);
		if (cookieValueTabOptionSelected == null)
			return;

		// get all the dom elements that need to be set
		var domTab1Focus = document.getElementById("tabOption1Focus");
		var domTab1Ready = document.getElementById("tabOption1Ready");

		var domTab2ocus = document.getElementById("tabOption2Focus");
		var domTab2Ready = document.getElementById("tabOption2Ready");

		var domContentOption1 = document.getElementById("contentOption1");
		var domContentOption2 = document.getElementById("contentOption1");

		if (cookieValueTabOptionSelected == TAB_PANEL_OPTION_1)
		{
/*			domTab1Focus.style.display = "block";
			domTab1Ready.style.display = "none";

			domTab1Focus.style.display = "block";
			domTab1Ready.style.display = "none";
*/		

			manageTabPanelDisplay(TAB_PANEL_OPTION_1, TAB_PANEL_OPTION_2, 'contentOption1', 'contentOption2');
		}
		else
		{
			manageTabPanelDisplay(TAB_PANEL_OPTION_2, TAB_PANEL_OPTION_1, 'contentOption2', 'contentOption1');
		}
	}

	// store list of already voted for grocery IDs
	function setVotedGroceryIDs(groceryID)
	{
		groceryID = groceryID + "";
		// if cookie does not exist, create a new one
		var cookieValue = getVotedGroceryIDs();

		var date = getFridayExpiryDate();

		// cookie does not exist, so create new one
		if (cookieValue == "")
		{
			setCookieWithAbsoluteExpiryDate(COOKIE_NAME_VOTED_GROCERY_IDs, groceryID, date);
		}
		// cookie exists, so get existing values and appending to it
		else
		{
			// append grocery id to the end of list
			cookieValue = cookieValue + "," + groceryID;
			setCookieWithAbsoluteExpiryDate(COOKIE_NAME_VOTED_GROCERY_IDs, cookieValue, date);
		}
	}

	// get a list of grocery ids that the user has voted for in this week
	function getVotedGroceryIDs()
	{
		var cookieValue = getCookie(COOKIE_NAME_VOTED_GROCERY_IDs);
		if (cookieValue != null)
			return cookieValue;

		return "";
	}

	// save the grocery store filter entered in the textbox into cookie
	// set expiry to one year from now
	function setGroceryStoreFilter(domGroceryStoreTextbox)
	{
		if (domGroceryStoreTextbox != null)
		{
			setCookie(COOKIE_NAME_GROCERY_STORE_FILTER, domGroceryStoreTextbox.value, ONE_YEAR_EXPIRY_DAYS);
		}
	}

	// get the grocery store filter saved in cookie
	function getGroceryStoreFilter()
	{
		var cookieValue = getCookie(COOKIE_NAME_GROCERY_STORE_FILTER);
		if (cookieValue != null)
			return cookieValue;

		return "";
	}

	// try to delete
	// save the province for the flyer listings into the cookie
	function setFlyerListingCategory(selectedCategoryIndex)
	{
		if (selectedCategoryIndex != null)
		{
			setCookie(COOKIE_NAME_FLYER_LISTING_CATEGORY, selectedCategoryIndex, ONE_YEAR_EXPIRY_DAYS);
		}
	}

	// try to delete
	// get the province for the flyer listings saved in cookie
	function getFlyerListingCategory()
	{
		var cookieValue = getCookie(COOKIE_NAME_FLYER_LISTING_CATEGORY);
		if (cookieValue != null)
			return cookieValue;

		return "";
	}

	// saves the province code
	function setProvinceCode(provinceCode)
	{
		if (provinceCode != null)
		{
			setCookie(COOKIE_NAME_PROVINCE_CODE, provinceCode, ONE_YEAR_EXPIRY_DAYS);
		}
	}

	// get the province code
	function getProvinceCode()
	{
		var cookieValue = getCookie(COOKIE_NAME_PROVINCE_CODE);
		if (cookieValue != null)
			return cookieValue;

		return "";
	}

	// save the flyer category id saved in cookie
	function setFlyerCategoryID(selectedCategoryID)
	{
		if (selectedCategoryID != null)
		{
			setCookie(COOKIE_NAME_FLYER_CATEGORY_ID, selectedCategoryID, ONE_YEAR_EXPIRY_DAYS);
		}
	}

	// get the flyer category id saved in cookie
	function getFlyerCategoryID()
	{
		var cookieValue = getCookie(COOKIE_NAME_FLYER_CATEGORY_ID);
		if (cookieValue != null)
			return cookieValue;

		return "";
	}

	// saves postal code from default.asp to cookie
	function setMapUserAddressToCookie(domElement)
	{
//		var domMapUserAddress = document.getElementById("userAddress");
		setCookie(COOKIE_NAME_MAP_USER_ADDRESS, domElement.value, ONE_YEAR_EXPIRY_DAYS);
	}

	// gets postal code from cookie to default.asp
	function getMapUserAddressFromCookie(domElementID)
	{
		// dom element - map user address
		var domMapUserAddress = document.getElementById(domElementID);

		// get the user address saved into the cookie from canada grocery map
		var mapUserAddressCookieValue = getCookie(COOKIE_NAME_MAP_USER_ADDRESS);

		// check if user's map address is saved in cookie
		if (mapUserAddressCookieValue != null)
		{
			domMapUserAddress.value = mapUserAddressCookieValue;
			return mapUserAddressCookieValue;
		}
		// get the postal code value saved into the cookie from default.asp
		else
		{
			var postalCodeCookieValue = getCookie(COOKIE_NAME_POSTAL_CODE);

			if (postalCodeCookieValue != null)
			{
				domMapUserAddress.value = postalCodeCookieValue;
				return postalCodeCookieValue;
			}
		}
	}

	// saves the quick compare option for compareGroceryStorePrices.asp
	function setQuickCompareOptionToCookie(domElement)
	{
		setCookie(COOKIE_NAME_QUICK_COMPARE_OPTION, domElement.selectedIndex, ONE_YEAR_EXPIRY_DAYS);
	}

	// gets the quick compare option for compareGroceryStorePrices.asp
	function getQuickCompareOptionFromCookie(domElementID)
	{
		var domQuickCompareOption = document.getElementById(domElementID);
		var quickCompareOptionCookieValue = getCookie(COOKIE_NAME_QUICK_COMPARE_OPTION);

		if (quickCompareOptionCookieValue != null)
		{
			domQuickCompareOption.selectedIndex = quickCompareOptionCookieValue;
			return quickCompareOptionCookieValue;
		}
		
		return null;
	}

	function displayFirstTimeUserMsg()
	{
		// check to see if its the first time the user is using the website
		var firstTime = getCookie('firstTime');
		if (firstTime == null)
		{
//			alert('Join now, Regristration is Free!!! Go to About page to learn more! \n Please NOTE: Cookies must be enabled to properly maneuver this website.');
			setCookie('firstTime', "no", 365);
		}		
	}

