<!-- #include file="fifo.js" -->

var xmlHttpGeneral;

/**************************************************************************************************************************
**	Function is called whenever the user selects a different category option in the category selection list
** OPTION 2 - user SELECTS A CATEGORY and returns a list of GROCERIES under that category
**************************************************************************************************************************/
function changeCategory(aCategory)
{ 
	showLoadingGif();
	
	escapedCat = escape(aCategory);
	thisCat = aCategory;

	var groceryStoreID = document.getElementById("browseByStore");

	var url = "getGroceriesByCategory.asp?category=" + escapedCat + "&groceryStoreID=" + groceryStoreID.value;
	xmlHttpGeneral = GetXmlHttpObject(stateChanged)
	xmlHttpGeneral.open("GET", url , true)
	xmlHttpGeneral.send(null)
} 

// changeCategory()
// gets the grocery list back from getGroceriesByCategory and displays the html for the DEFAULT.ASP page
function stateChanged() 
{ 
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{ 
		// a string containing a list of all the products in this category is returned from getGroceriesByCategory.asp
		// "~" is the delimiter for separating each product
		var productList = xmlHttpGeneral.responseText.split("~");

		/* 
		******************************************************************************************************
			Store all the items that the user has checked off from the shopping list into a string.
			This string is used for determining if the checkbox for each item should be checked off or not
		******************************************************************************************************
		*/
		var tempStr = "";		// string stores all the products in the shopping list
		var tempArray = new Array();
		var preserve=fifo_readbuffer();
		var elements=fifo_countelements();
		for (i=1; i<=elements; i++)
		{
			tempStr = fifo_popAll() + "";
			tempArray.push(tempStr);
		}
		// restore the original list after popping the items out
		fifo_writebuffer(preserve);
				
		/* 
		******************************************************************************************************
			Display each product in the category 	
		******************************************************************************************************
		*/
//@@		var html = "<div STYLE='height: 500px; width: 225px; overflow: auto;'><table><tr><th class='category'>" + thisCat + "</td></tr>"
		var html = "<center><span class='category bold largest'>" + thisCat + "</span></center><br/>";
		html += "<div class='listOfGroceriesByCategory'><table cellspacing=1 cellpadding=1>";

		var searchResult = -1;
		for (x=0; x<productList.length-1; x++)
		{
			var tempProduct = convertToJavascriptUse(productList[x]);

			// [0] is grocery name, [1] is grocery price
			var jsGroceryTuple = tempProduct.split("@");
			var jsGroceryName = jsGroceryTuple[0];

/*
	INCLUDED PRICE
			var groceryTuple = productList[x].split("@");
			var groceryName = groceryTuple[0];
			var groceryPrice = groceryTuple[1];
			var groceryImageName = GROCERY_IMAGES_PATH + groceryTuple[2];
*/

			var groceryTuple = productList[x].split("@");
			var groceryName = groceryTuple[0];
			var groceryImageName = GROCERY_IMAGES_PATH + groceryTuple[1];

/*
			if (groceryImageName.indexOf(".gif") == -1)
			{
				groceryImageName += ".gif";
			}
*/
			// check to see if the user had selected this
			// if so display the product with a check in the checkbox
			for (y=0; y<tempArray.length; y++)
			{
				if (tempArray[y] == groceryName)
				{
					searchResult = 1;
					break;
				}
				searchResult = -1;
			}

			if (searchResult != -1)
			{
/*
				html += "<tr><td><img src='" + groceryImageName + "' onLoad=\"javascript:validateImageNameSrc(this)\" /></td><td valign='bottom'><input type='checkbox' name='" + jsGroceryName;
				html += "' onClick=\"javascript:purchase_product('" + jsGroceryName + "')\" CHECKED></td><td valign='bottom'>" + groceryName + "</td>";
				html += "<td valign='bottom'>" + groceryPrice + "</td></tr>";
*/



				html += "<tr><td><img width='100px' height='100px' src='" + groceryImageName + "' onError=\"javascript:validateImageNameSrc(this)\" /></td><td><input type='checkbox' name='" + jsGroceryName;
				html += "' onClick=\"javascript:purchase_product('" + jsGroceryName + "')\" CHECKED></td><td>" + groceryName + "</td>";
// INCLUDED PRICE
//				html += "<td>" + groceryPrice + "</td>";
				html += "</tr>";

/*
				html += "<tr><td><input type='checkbox' name='" + jsGroceryName;
				html += "' onClick=\"javascript:purchase_product('" + jsGroceryName + "')\" CHECKED></td><td>" + groceryName + "</td>";
				html += "<td>" + groceryPrice + "</td></tr>";
*/
			}
			else
			{
/*
				html += "<tr><td><img src='" + groceryImageName + "' onLoad='javascript:validateImageNameSrc(this)' /></td><td valign='bottom'><input type='checkbox' name='" + jsGroceryName;
				html += "' onClick=\"javascript:purchase_product('" + jsGroceryName + "')\"></td><td valign='bottom'>" + groceryName + "</td>";
				html += "<td valign='bottom'>" + groceryPrice + "</td></tr>";
*/			



				html += "<tr><td><img width='100px' height='100px' src='" + groceryImageName + "' onError=\"javascript:validateImageNameSrc(this)\" /></td><td><input type='checkbox' name='" + jsGroceryName;
				html += "' onClick=\"javascript:purchase_product('" + jsGroceryName + "')\"></td><td>" + groceryName + "</td>";
// INCLUDED PRICE
//				html += "<td>" + groceryPrice + "</td>";
				html += "</tr>";	

/*
				html += "<tr><td><input type='checkbox' name='" + jsGroceryName;
				html += "' onClick=\"javascript:purchase_product('" + jsGroceryName + "')\"></td><td>" + groceryName + "</td>";
				html += "<td>" + groceryPrice + "</td></tr>";	
*/
			}
		}

		html += "</table></div>";
		document.getElementById("listOfGroceriesByCategory").innerHTML = html;

		hideLoadingGif();
	} 
} 

/**************************************************************************************************************************
** MEMBERS AREA OPTION 2 - user selects a category in the MEMBERS area (EGROCERYLIST.ASP) and returns a list of general grocery categories
**************************************************************************************************************************/
function changeGeneralCategory(aCategoryID)
{
	generalCatID = aCategoryID;

	var url = "getGeneralGroceriesByCategory.asp?" + generalCatID;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedGeneralGrocery)
	xmlHttpGeneral.open("GET", url , true)
	xmlHttpGeneral.send(null)
} 

// changeGeneralCategory()
// gets the general groceries back from getGeneralGroceriesByCategory and displays the html for the member eGroceryList.asp
function stateChangedGeneralGrocery() 
{ 
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{ 
		// return result is a string containing a list of groceries and the category in the format of:
		// groceryName1~groceryName2~@groceryCategory
		var results = xmlHttpGeneral.responseText.split("@");
		var categoryName = results[1];

		// a string containing a list of all the products in this category is returned from getGroceriesByCategory.asp
		// "~" is the delimiter for separating each product
//		var productList = xmlHttpGeneral.responseText.split("~");
		var productList = results[0].split("~");

		// a string containing a list of all the products in this category is returned from getGroceriesByCategory.asp
		// "~" is the delimiter for separating each product
//		var productList = xmlHttpGeneral.responseText.split("~");


		/* 
		******************************************************************************************************
			Store all the items that the user has checked off from the shopping list into a string.
			This string is used for determining if the checkbox for each item should be checked off or not
		******************************************************************************************************
		*/
		var tempStr = "";		// string stores all the products in the shopping list
		var tempArray = new Array();
		var preserve=fifo_readbuffer();
		var elements=fifo_countelements();
		for (i=1; i<=elements; i++)
		{
			tempStr = fifo_popAll() + "";
			tempArray.push(tempStr);
		}
		// restore the original list after popping the items out
		fifo_writebuffer(preserve);
				
		/* 
		******************************************************************************************************
			Display each product in the category 	
		******************************************************************************************************
		*/
		var html = "<table><tr><th + categoryName >" + categoryName + "</th></tr>"
		var searchResult = -1;
		for (x=0; x<productList.length-1; x++)
		{
			var tempProduct = convertToJavascriptUse(productList[x]);
			// check to see if the user had selected this
			// if so display the product with a check in the checkbox

			for (y=0; y<tempArray.length; y++)
			{
				if (tempArray[y] == productList[x])
				{
					searchResult = 1;
					break;
				}
				searchResult = -1;
			}

			if (searchResult != -1)
			{
				html += "<tr><td><input type='checkbox' name='" + tempProduct + "' onClick=\"javascript:purchase_product('" + tempProduct + "')\" CHECKED>" + productList[x] + "</td></tr>"
			}
			else
			{
				html += "<tr><td><input type='checkbox' name='" + tempProduct + "' onClick=\"javascript:purchase_product('" + tempProduct + "')\";>" + productList[x] + "</td></tr>"
			}
		}

		html += "</table>";
		document.getElementById("listOfGroceriesByCategory").innerHTML = html;
	} 
} 

/**************************************************************************************************************************
** OPTION 2 - user SELECTS A STORE and gets back a list of categories for that store
**************************************************************************************************************************/
function changeGroceryStore(storeID)
{
	showLoadingGif();

	var url = "getCategoriesByGroceryStore.asp?" + storeID;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedGroceryStore)
	xmlHttpGeneral.open("GET", url , true)
	xmlHttpGeneral.send(null)	
}

// changeStore()
// gets the list of categories back from getGeneralGroceriesByCategory and displays the html
function stateChangedGroceryStore() 
{ 
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{ 
		// a string containing a list of all the grocery categories is returned from getGroceriesByGroceryStore.asp
		// "~" is the delimiter for separating each grocery category
		var categoryNameList = xmlHttpGeneral.responseText.split("~");

		var NUMBER_OF_CATEGORIES_PER_SELECT_BOX = 10;

		/* 
		******************************************************************************************************
			Display each category in the listbox
		******************************************************************************************************
		*/
//		var html = "<select name='categories' size='26' onChange='changeCategory(this.options[this.selectedIndex].value)'>";

		// html for the "opening select tag"
		var htmlStartingSelectTag = "<select name='categories' size='" + NUMBER_OF_CATEGORIES_PER_SELECT_BOX + 
			"' onChange='changeCategory(this.options[this.selectedIndex].value); clearSelectedCategory(this);'>";
		var html = htmlStartingSelectTag;
		for (x=0; x<categoryNameList.length-1; x++)
		{

			if (x % NUMBER_OF_CATEGORIES_PER_SELECT_BOX == 0 && x != 0)
			{
				html += "</select>";
				html += htmlStartingSelectTag;
			}
			html += "<option value='" + categoryNameList[x] + "'>" + categoryNameList[x] + "</option>";		
		}
		html += "</select>";

		// whenever you change the store, clear the list of groceries by category
		document.getElementById("listOfGroceriesByCategory").innerHTML = "";
		document.getElementById("listboxCategory").innerHTML = html;

		hideLoadingGif();
	} 
} 

/**************************************************************************************************************************
** removes other selected categories when a new category is selected
**************************************************************************************************************************/
function clearSelectedCategory(currentSelectedListBox)
{
	// each select list box is named "categories"
	var arr = document.getElementsByName("categories");
	var domCategoryElement;

	// loop through all the select list boxes
	for (var i=0; i<arr.length; i++)
	{
		domCategoryElement = arr[i];
		// only remove other selected categories (not the currently selected list box)
		if (domCategoryElement != currentSelectedListBox )
		{
			domCategoryElement.selectedIndex = -1;		
		}
	}
}

/**************************************************************************************************************************
** @@ adding new store
** CompareFlyerDeals OPTION 1 - ajax for when user changes SORT BY selection in the option 1 result pages
**************************************************************************************************************************/
function changeSearchResultOption1SortBy(sortByType)
{
//document.write(new Date());
	var SORT_BY_TYPE_CATEGORY = 1;
	var SORT_BY_TYPE_STORE = 2;

	var searchByKeywords = document.getElementById("searchByKeywords").value;
	var dominion = document.getElementById("dominion").value;
	var foodbasics = document.getElementById("foodbasics").value;
	var loblaws = document.getElementById("loblaws").value;
	var nofrills = document.getElementById("nofrills").value;
	var pricechopper = document.getElementById("pricechopper").value;
// @@ adding new store

	var escapedSearchWords = escape(searchByKeywords);
	var url = "";

	if (sortByType == SORT_BY_TYPE_CATEGORY)
	{
		url = "compareFlyerDealsByCategory.asp?searchByKeywords=" + escapedSearchWords;
	}
	else
	{
		url = "compareFlyerDealsByStore.asp?searchByKeywords=" + escapedSearchWords;
	}
	url += "&dominion=" + dominion + "&foodbasics=" + foodbasics + "&loblaws=" + loblaws + "&nofrills=" + nofrills + "&pricechopper=" + pricechopper;
// @@ adding new store

	xmlHttpGeneral = GetXmlHttpObject(stateChangedSearchResultOption1SortBy)
	xmlHttpGeneral.open("GET", url , true)
	xmlHttpGeneral.send(null)	
}

function stateChangedSearchResultOption1SortBy() 
{ 
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{ 
		// a string containing a list of all the grocery categories is returned from getGroceriesByGroceryStore.asp
		// "~" is the delimiter for separating each grocery category
	
		var searchResults = document.getElementById("searchResults");
		searchResults.innerHTML = xmlHttpGeneral.responseText;

//searchResults.innerHTML = searchResults.innerHTML + new Date();
		// hide the loading gif once the results are done loading
		hideLoadingGif();
	} 
} 


/**************************************************************************************************************************
** @@ adding new store
** compareFlyerPrices OPTION 2 - ajax for when user changes SORT BY selection in the option 2 result pages
**************************************************************************************************************************/
function changeSearchResultOption2SortBy(sortByType)
{
	var SORT_BY_TYPE_CATEGORY = 1;
	var SORT_BY_TYPE_STORE = 2;

	var bufferedGroceryList = document.getElementById("thebuffer").value;
	var brand = document.getElementById("brand").value;

	var dominion = document.getElementById("dominion1").value;
	var foodbasics = document.getElementById("foodbasics1").value;
	var loblaws = document.getElementById("loblaws1").value;
	var nofrills = document.getElementById("nofrills1").value;
	var pricechopper = document.getElementById("pricechopper1").value;

// @@ adding new store

	var escapedBufferedGroceryList = escape(bufferedGroceryList);
	var url = "";

	if (sortByType == SORT_BY_TYPE_CATEGORY)
	{
		url = "compareFlyerPricesByCategory.asp?thebuffer=" + escapedBufferedGroceryList;
	}
	else
	{
		url = "compareFlyerPricesByStore.asp?thebuffer=" + escapedBufferedGroceryList;
	}
// @@ adding new store
	// create url for method="GET" passing which stores the user selected and branding type
	url += "&dominion1=" + dominion + "&foodbasics1=" + foodbasics + "&loblaws1=" + loblaws + "&nofrills1=" + nofrills + "&pricechopper1=" + pricechopper;
	url += "&brand=" + brand;

	xmlHttpGeneral = GetXmlHttpObject(stateChangedSearchResultOption2SortBy)
	xmlHttpGeneral.open("GET", url , true)
	xmlHttpGeneral.send(null)	

}

function stateChangedSearchResultOption2SortBy() 
{ 
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{ 
		// a string containing a list of all the grocery categories is returned from getGroceriesByGroceryStore.asp
		// "~" is the delimiter for separating each grocery category
	
		var searchResults = document.getElementById("searchResults");
		searchResults.innerHTML = xmlHttpGeneral.responseText;

		// hide the loading gif once the results are done loading
		hideLoadingGif();
	} 
}


/**************************************************************************************************************************
**	GET list of grocery store links by province
**************************************************************************************************************************/
function getGroceryLinksByProvince(provinceCode)
{
	var code = escape(provinceCode);

	var url = "getGroceryLinksByProvince.asp?provinceCode=" + code;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetGroceryLinksByProvince);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedGetGroceryLinksByProvince()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domGroceryStoresByProvince = document.getElementById("groceryStoresByProvince");
		domGroceryStoresByProvince.innerHTML = xmlHttpGeneral.responseText;	
	}
}

/**************************************************************************************************************************
**	GET list of COUPONS links by all 3 criterias: province, store, category			
**************************************************************************************************************************/
function getCouponsByAllCriterias(searchType)
{
	showLoadingGif();

	var provinceCode;
	var storeID;
	var categoryID;

	// link was clicked - view all coupons
	if (searchType == 1)
	{
		provinceCode = "";
		storeID = 0;
		categoryID = 0;
	}
	// coupon search through all 3 criterias (drop downs)
	else
	{
		var domProvinceCode = document.getElementById("groceryCouponLinksByProvince");
		var domStoreID = document.getElementById("groceryCouponLinksByStore");
		var domCategoryID = document.getElementById("groceryCouponLinksByCategory");
		var domCouponTypeID= document.getElementById("couponCategories");

		provinceCode = domProvinceCode.options[domProvinceCode.selectedIndex].value;
		storeID = domStoreID.options[domStoreID.selectedIndex].value;
		categoryID = domCategoryID.options[domCategoryID.selectedIndex].value;
		couponTypeID = domCouponTypeID.options[domCouponTypeID.selectedIndex].value;
	}

	var url = "getCouponsByAllCriterias.asp?provinceCode=" + provinceCode + 
		"&storeID=" + storeID + 
		"&categoryID=" + categoryID +
		"&couponTypeID=" + couponTypeID;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetCouponsByAllCriterias);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);

}

function stateChangedGetCouponsByAllCriterias()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domCouponSearchResults = document.getElementById("couponSearchResults");
		if (domCouponSearchResults != null)
		{
			domCouponSearchResults.innerHTML = xmlHttpGeneral.responseText;

			// call this to apply filter, sorting and paging
			Table.resetFilter();
			Table.auto();
		}

		hideLoadingGif();
	}
}


/**************************************************************************************************************************
**	saved coupon clicked link history int o DB
**************************************************************************************************************************/
function saveCouponClickedLinkHistory(couponID)
{
	// get postal code stored in cookie
	var postalCode = getCookie(COOKIE_NAME_POSTAL_CODE);
	
	var url = "/saveCouponClickedLinkHistory.asp?couponID=" + couponID + "&postalCode=" + postalCode;

	xmlHttpGeneral = GetXmlHttpObject(stateChangedSaveCouponClickedLinkHistory);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedSaveCouponClickedLinkHistory()
{
}


/**************************************************************************************************************************
**	GET PRICE BOOK HISTORY 
**************************************************************************************************************************/
function getGroceryPriceBookHistory()
{
	showLoadingGif();

	var domEnteredGroceryName = document.getElementById("enteredGroceryName");	
	var escapedValue = escape(domEnteredGroceryName.value);

	var url = "getGroceryPriceBookHistory.asp?enteredGroceryName=" + escapedValue;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetGroceryPriceBookHistory);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);

}

function stateChangedGetGroceryPriceBookHistory()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domGroceryPriceBookHistoryResults = document.getElementById("groceryPriceBookHistoryResults");
		if (domGroceryPriceBookHistoryResults != null)
		{
			domGroceryPriceBookHistoryResults.innerHTML = xmlHttpGeneral.responseText;
			
			// call this to apply filter, sorting and paging
			Table.resetFilter();
			Table.auto();
		}

		hideLoadingGif();
	}
}

/**************************************************************************************************************************
**	GET CANADA ONLINE PRICE BOOK
**************************************************************************************************************************/
function getOnlineGroceryPriceBook(enteredGroceryName)
{
	showLoadingGif();

	var domProvince = document.getElementById("province");
	var domCity = document.getElementById("city");

	// the only value enteredGroceryName can ever hold is "%%%", this means that a view all entries for a province and city link was clicked
	// else it is a regular search where the user types in a grocery name to search
	if (isEmpty(enteredGroceryName))
	{
		enteredGroceryName = document.getElementById("enteredGroceryName").value;
	}

	var url = "getOnlineGroceryPriceBook.asp?province=" + domProvince.value + 
		"&city=" + encodeURIComponent(domCity.value) + "&enteredGroceryName=" + encodeURIComponent(enteredGroceryName);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetOnlineGroceryPriceBook);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedGetOnlineGroceryPriceBook()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domGroceryPriceBookHistoryResults = document.getElementById("groceryPriceBookHistoryResults");
		if (domGroceryPriceBookHistoryResults != null)
		{
			domGroceryPriceBookHistoryResults.innerHTML = xmlHttpGeneral.responseText;

			// call this to apply filter, sorting and paging
			Table.resetFilter();
			Table.auto();		
		}

		hideLoadingGif();
	}
}

/**************************************************************************************************************************
**	create a html drop down list of all exact names
**************************************************************************************************************************/
function getExactNames(brand, generalName)
{
	var url = "getExactNames.asp?brand=" + escape(brand) + "&generalName=" + escape(generalName);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetExactNames);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedGetExactNames()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domRowNumber = document.getElementById("rowNumber");
		var rowCount = domRowNumber.value;

		var domExactNames = document.getElementById("tdExactNames" + rowCount);
		domExactNames.innerHTML = "<select id='exactNames" + rowCount + "' class='masterFieldTextSize'>" + xmlHttpGeneral.responseText + "</select>";
	}
}


/**************************************************************************************************************************
**	MASTER.asp populate the rest of the fields given brand and exact name
**************************************************************************************************************************/
function getMasterAllFieldsFromBrandExactName(brand, exactName, storeID)
{
	var url = "getMasterAllFieldsFromBrandExactName.asp?brand=" + encodeURIComponent(brand) + 
		"&exactName=" + encodeURIComponent(exactName) + "&storeID=" + storeID;

	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetMasterAllFieldsFromBrandExactName);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedGetMasterAllFieldsFromBrandExactName()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domRowNumber = document.getElementById("rowNumber");
		var rowCount = domRowNumber.value;

		var domGroceryName = document.getElementById("name" + rowCount); 
		var domDescription = document.getElementById("description" + rowCount); 
		var domDisplayPrice = document.getElementById("displayPrice" + rowCount); 
		var domPrice = document.getElementById("price" + rowCount); 
		var domPackaging = document.getElementById("packaging" + rowCount); 
		var domImageName = document.getElementById("imageName" + rowCount); 

		var entry;
		var results = xmlHttpGeneral.responseText.split("~");

		if (!isEmpty(results[0]))
		{
			domGroceryName.value = trimString(results[0]);
		}

		if (!isEmpty(results[1]))
		{
			domDescription.value = results[1];
		}

		if (!isEmpty(results[2]))
		{
			domDisplayPrice.value = results[2];
		}

		if (!isEmpty(results[3]))
		{
			domPackaging.value = results[3];
		}

		if (!isEmpty(results[4]))
		{
			domImageName.value = results[4];
		}


		// @@ hardcoded - if ever need price double data type column, need to get rid of this and parseDouble from display price
//		domPrice.value = "0.1";
	}
}

/**************************************************************************************************************************
**	MASTER.asp populate the image name given brand and exact name
**************************************************************************************************************************/
function getMasterImageNameFromBrandExactName(brand, exactName, storeID)
{
	var url = "getMasterImageNameFromBrandExactName.asp?brand=" + encodeURIComponent(brand) + 
		"&exactName=" + encodeURIComponent(exactName) + "&storeID=" + storeID;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetMasterImageNameFromBrandExactName);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedGetMasterImageNameFromBrandExactName()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domRowNumber = document.getElementById("rowNumber");
		var rowCount = domRowNumber.value;

		var domImageName = document.getElementById("imageName" + rowCount);
		var domPackaging = document.getElementById("packaging" + rowCount);
		var domDisplayPrice = document.getElementById("displayPrice" + rowCount); 
		var domPrice = document.getElementById("price" + rowCount); 

		var results = xmlHttpGeneral.responseText.split("~");		

		if (!isEmpty(results[0]))
		{
			domImageName.value = trimString(results[0]);
		}

		if (!isEmpty(results[1]))
		{
			domPackaging.value = results[1];
		}

		if (!isEmpty(results[2]))
		{
			domDisplayPrice.value = results[2];
		}
		
//		domImageName.value = xmlHttpGeneral.responseText;
	}
}

/**************************************************************************************************************************
**	MASTER.asp populate the image name given brand and exact name and pin pointing it with the size
**************************************************************************************************************************/
function getMasterImageNameFromSize(brand, exactName, storeID, size)
{
	var url = "getMasterImageNameFromSize.asp?brand=" + escape(brand) + 
		"&exactName=" + escape(exactName) + "&storeID=" + storeID +
		"&size=" + escape(size);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedGetMasterImageNameFromBrandExactName);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

function stateChangedGetMasterImageNameFromSize()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domRowNumber = document.getElementById("rowNumber");
		var rowCount = domRowNumber.value;

		var domImageName = document.getElementById("imageName" + rowCount);

		var imageName = xmlHttpGeneral.responseText;

		if (!isEmpty(imageName))
		{
			domImageName.value = imageName;
		}
	}
}

/**************************************************************************************************************************
**	save vote of grocery into DB
**************************************************************************************************************************/
function incrementGroceryVote(groceryID)
{
	var url = "setGroceryVote.asp?groceryID=" + escape(groceryID);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedIncrementGroceryVote);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);	
}

function stateChangedIncrementGroceryVote()
{
/*
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
//		alert(xmlHttpGeneral.responseText);
	}
*/
}

/**************************************************************************************************************************
**	check forum username to see if it is available
**************************************************************************************************************************/
function checkUserName(userName)
{
	var url = "getIsUserNameAvailable.asp?userName=" + escape(userName);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedCheckUserName);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);	
}

function stateChangedCheckUserName()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		// check to see if user name is available
		// return values: 1 -> is available
		//				  2 -> not available
		var domIsUserNameAvailable = document.getElementById("isUserNameAvailable");
		domIsUserNameAvailable.value = xmlHttpGeneral.responseText;

		var domUsernameErrorMsg = document.getElementById("usernameErrorMsg");
		if(domIsUserNameAvailable.value == 0)
		{
			domUsernameErrorMsg.innerHTML = "<font class='orangeBold'>This user name is NOT available, please try a different one.</font>";
		}
		else if (domIsUserNameAvailable.value == -1)
		{
			domUsernameErrorMsg.innerHTML = "<font class='orangeBold'>Please select a user name to use on the forums!</font>";
		}
		else
		{
			domUsernameErrorMsg.innerHTML = "";
		}
	}
}

/**************************************************************************************************************************
**	save flyer to favourites list
**************************************************************************************************************************/
function saveFavouriteFlyer(uniqueCode, storeLinkID, provinceName)
{
	showLoadingGif();

	var url = "saveFavouriteFlyer.asp?uniqueCode=" + escape(uniqueCode) + "&storeLinkID=" + escape(storeLinkID) + "&provinceName=" + escape(provinceName);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedSaveFavouriteFlyer);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);	
}

function stateChangedSaveFavouriteFlyer()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domFavouriteFlyersList = document.getElementById("favouriteFlyersList");

		var ajaxResponse = xmlHttpGeneral.responseText.split(SEPARATOR_MAIN_INFO);

		var favouriteFlyersList = ajaxResponse[0].split(SEPARATOR_STORE);
		var uniqueCode = ajaxResponse[1];

		var addUniqueCodeToUrl = false;
		if (ajaxResponse.length == 3)
		{
			if (ajaxResponse[2] == "addUniqueCodeToUrl")
			{
				addUniqueCodeToUrl = true;
			}
		}

		domFavouriteFlyersList.innerHTML = generateHtmlFavFlyersList(favouriteFlyersList, uniqueCode);

		var form = document.getElementById("formStoreFlyers");

		// a unique code was returned from ajax servlet
		// meaning this is the first time this user created a favourite flyers list
		// so add the unique code to the url
		if (uniqueCode != null && uniqueCode != "" && addUniqueCodeToUrl == true)
		{
			form.elements["u"].value = uniqueCode;
			form.submit();
		}

		hideLoadingGif();
	}
}

/**************************************************************************************************************************
**	save flyer to favourites list
**************************************************************************************************************************/
function deleteFavouriteFlyer(uniqueCode, storeLinkID, provinceName)
{
	showLoadingGif();

	var url = "deleteFavouriteFlyer.asp?uniqueCode=" + escape(uniqueCode) + "&storeLinkID=" + escape(storeLinkID) + "&provinceName=" + escape(provinceName);

	xmlHttpGeneral = GetXmlHttpObject(stateChangedDeleteFavouriteFlyer);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);	
}

function stateChangedDeleteFavouriteFlyer()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var ajaxResponse = xmlHttpGeneral.responseText.split(SEPARATOR_MAIN_INFO);

		var domFavouriteFlyersList = document.getElementById("favouriteFlyersList");

		if (ajaxResponse != "")
		{
			var favouriteFlyersList = ajaxResponse[0].split(SEPARATOR_STORE);
			var uniqueCode = ajaxResponse[1];
			domFavouriteFlyersList.innerHTML = generateHtmlFavFlyersList(favouriteFlyersList, uniqueCode);
		}
		else
		{
			domFavouriteFlyersList.innerHTML = "<div style='border: 1px solid'><div class='brightGreenBG white largest' style=\"padding:2px\">My Favourite Flyers</div><table cellpadding='4px'></div></div>";
		}
		hideLoadingGif();
	}
}

/**************************************************************************************************************************
**	save grocery store info to favourites list
**************************************************************************************************************************/
function saveFavouriteGroceryStoreInfo(storeInfoID)
{
	if (checkUserRequiredLogin())
	{
		return;
	}

	showLoadingGif();

	var url = "saveFavouriteGroceryStoreInfo.asp?";
	var parameters = "storeInfoID=" + escape(storeInfoID);

	url += parameters;
	xmlHttpGeneral = GetXmlHttpObject(stateChangedSaveFavouriteGroceryStoreInfo);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);	
}

function stateChangedSaveFavouriteGroceryStoreInfo()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
		var domFavouriteStoreInfoList = document.getElementById("favouriteStoreInfoList");

		var ajaxResponse = xmlHttpGeneral.responseText;
		if (isEmpty(ajaxResponse))
		{
			domFavouriteStoreInfoList.innerHTML = "";
		}
		else
		{
			var favouriteStoreInfoList = ajaxResponse.split(SEPARATOR_STORE);

			domFavouriteStoreInfoList.innerHTML = generateHtmlFavStoreInfoList(favouriteStoreInfoList);
		}
		hideLoadingGif();

		// show the favourite store info list whenever adding a store
		domFavouriteStoreInfoList.className = "showField";
	}
}

/**************************************************************************************************************************
**	save grocery store info to favourites list
**************************************************************************************************************************/
function deleteFavouriteGroceryStoreInfo(storeInfoID)
{
	showLoadingGif();

	var url = "deleteFavouriteGroceryStoreInfo.asp?";
	var parameters = "storeInfoID=" + escape(storeInfoID);

	url += parameters;
	// use the same state change funtion as saveFavouriteGroceryStoreInfo (stateChangedSaveFavouriteGroceryStoreInfo)
	// so since it will be the same, so no need to be redundant
	xmlHttpGeneral = GetXmlHttpObject(stateChangedSaveFavouriteGroceryStoreInfo);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);	
}

/**************************************************************************************************************************
**	save grocery route to DB
**************************************************************************************************************************/
function saveGroceryRouteToDB(distance, time, gasCost, storeInfo)
{
	var url = "saveHistoryGroceryRoute.asp?";
	var parameters = "distance=" + escape(encodeURI(distance)) + 
		"&time=" + escape(encodeURI(time)) + 
		"&gasCost=" + escape(encodeURI(gasCost)) +
		"&storeInfo=" + escape(encodeURI(storeInfo));
	url += parameters;

	xmlHttpGeneral = GetXmlHttpObject(stateChangedSaveGroceryRouteToDB);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

// dummy function
function stateChangedSaveGroceryRouteToDB()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
	}
}

/**************************************************************************************************************************
**	generates a link to view all online price book entries for a province and city
**************************************************************************************************************************/
function getOnlinePriceBookLinkForProvinceCity()
{
	var domProvinceCode = document.getElementById("province");
	var domCity = document.getElementById("city");
	if (domProvinceCode != null && domCity != null)
	{
		var url = "getOnlinePriceBookLinkForProvinceCity.asp?";
		var parameters = "provinceCode=" + domProvinceCode.value + 
			"&city=" + encodeURIComponent(domCity.value);
		url += parameters;

		xmlHttpGeneral = GetXmlHttpObject(stateChangedGetOnlinePriceBookLinkForProvinceCity);
		xmlHttpGeneral.open("GET", url , true);
		xmlHttpGeneral.send(null);
	}
}

function stateChangedGetOnlinePriceBookLinkForProvinceCity()
{
	if (isAjaxResponseReady())
	{
		var ajaxResponse = xmlHttpGeneral.responseText;
		if (!isEmpty(ajaxResponse))
		{
			var domCityResults = document.getElementById("provinceCityResults");
			if (domCityResults != null)
			{
				domCityResults.innerHTML = ajaxResponse;
			}
		}
	}
}

var CLICK_HISTORY_FLYERS = "flyers";
var CLICK_HISTORY_STORE_LOCATOR = "storeLocator";
var CLICK_HISTORY_COUPONS = "coupons";

// keeps track of what links the user has clicked on
function trackUserClickedLinks(ID, type)
{
	var url = "/trackUserClickedLinks.asp?";
	var parameters = "ID=" + escape(encodeURI(ID)) + 
		"&type=" + escape(encodeURI(type));
	url += parameters;

	xmlHttpGeneral = GetXmlHttpObject(stateChangedTrackUserClickedLinks);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

// dummy function
function stateChangedTrackUserClickedLinks()
{
	if (xmlHttpGeneral.readyState==4 || xmlHttpGeneral.readyState=="complete")
	{
	}
}

// reports a page not found error by sending email
function reportPageNotFound()
{
	var url = "http://www.grocerysavings.ca/reportPageNotFound.asp?";
	var parameters = "path=" + escape(encodeURI(document.location.pathname));
	url += parameters;

	xmlHttpGeneral = GetXmlHttpObject(stateChangedTrackUserClickedLinks);
	xmlHttpGeneral.open("GET", url , true);
	xmlHttpGeneral.send(null);
}

/**************************************************************************************************************************
**	create xml http object
**************************************************************************************************************************/
function GetXmlHttpObject(handler)
{ 
	// cancel any previous ajax requests
	if (xmlHttpGeneral)
	{
		xmlHttpGeneral.abort();
	}

	var objXmlHttp=null

	if (navigator.userAgent.indexOf("Opera")>=0)
	{
		alert("This example doesn't work in Opera") 
		return 
	}

	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP"
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP"
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName)
			objXmlHttp.onreadystatechange=handler 
			return objXmlHttp
		} 
		catch(e)
		{ 
			alert("Error. Scripting for ActiveX might be disabled") 
			return 
		} 
	} 

	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest()
		objXmlHttp.onload=handler
		objXmlHttp.onerror=handler 
		return objXmlHttp
	}
}

function isAjaxResponseReady()
{
	if (xmlHttpGeneral.readyState == 4 || xmlHttpGeneral.readyState == "complete")
	{
		return true;
	}
	return false;
}