/**  Recently Viewed Feature
* Step 1 of 4: copy and paste this file into the merchant's assets/images/includes folder
 * Step 2 of 4: copy and paste this onto any page EXCEPT product page
 
	<script language="javascript" type="text/javascript" src="assets/images/includes/recentlyviewed.js"></script>
	 <!-- FEATURE BEGIN: RECENTLY VIEWED : YOURINITIALS 00/00/00 -->
		<script language="javascript">
			displayPV();
		</script>
	<!-- FEATURE END: RECENTLY VIEWED -->
	
* Step 3 of 4: copy and paste the following code onto product page only - Note how displayPV sends a boolean argument

	<script language="javascript" type="text/javascript" src="assets/images/includes/recentlyviewed.js"></script>
	 <!-- FEATURE BEGIN: RECENTLY VIEWED : YOURINITIALS 00/00/00 -->
		<script language="javascript">
			displayPV(true);
		</script>
	<!-- FEATURE END: RECENTLY VIEWED -->	
	
	
 *Step 4 of 4: Test this using multiple products, test on product page and other pages.
 */


var prodstoshow = ('undefined' == typeof(viewall)) ? 3 : viewall;		// ** SET HOW MANY PRODUCTS TO DISPLAY **, highly recommend no more than 4 or 5 
//alert(viewall);
var cookielen = 12;			// ** SET HOW MANY PRODUCTS TO STORE IN THE COOKIE
var pvcode = "";			// holds the HTML code for the previously viewed table
var objArr = new Array();	// holds json objects of each product
var cookieArr = new Array();
var isProductPage;
/**
 * Called from whatever page this script is included on. This function looks for the cookie that holds the previously viewed data. If a cookie is found, an ajax call is made for each product
 * specified in the cookie and each product is displayed on the page. If this script is called on a product page, the current product is not displayed in the table but is added to the cookie.
 * @param{boolean} isProductPage is not required and is set to true if being called from the product page.
 **/
function displayPV(isProductPage){
	document.write('<div id="pvDiv"></div>');
	
	// if true, we will re-set the previous viewed cookie at the end of this function
	isProductPage = (isProductPage == undefined || isProductPage == false)? false : true;	
	
	var cookie = getCookie('uu_bdw_pv');	// get the cookie if it exists and return the values
	var newcookie = "";						// will hold the value string of the new cookie
	
	// if the previously viewed cookie exists and has a value
	if(cookie != null && cookie != ""){
	
		cookieArr = cookie.split(",");								// split cookies into an array of pf_ids 

		// set the cookie length dependent on cookielen (defined above, unless there aren't enough to store 
		cookielen = (cookieArr.length >= cookielen)? cookielen : (cookieArr.length);	
		prodstoshow = (cookieArr.length > prodstoshow)? prodstoshow : (cookieArr.length);	
		
		getpvProd();	// call function that does all the AJAX calls
		
		// go through products and add them back to the cookie string
		for(var g = 0; g < (cookielen); g++){
			if(isProductPage){	// if product page, get prod info and do cookie stuff
				if(pf_id != cookieArr[g]){				// make sure the previous viewed item is not the current item if on a product page
					newcookie += "," + cookieArr[g];	// add to the new cookie string		
				}
			}
		}
		
		// add the currently viewed product's pfid to the cookie string
		if(isProductPage){ newcookie = (newcookie == "")? pf_id : pf_id + newcookie; }	
	}else{
		// if there are no recently viewed products, only add the current product to the cookie data
		if(isProductPage){ newcookie += pf_id; }
	}
	
	if(isProductPage){ 
		// set cookie with string of pfids
		setCookie('uu_bdw_pv', newcookie, 365); 
	}
}

/**
 * Called from displayPV(); This function builds and displays the HTML code for each product inside the table. 
 **/
function buildProducts(){
	var cols = ('undefined' == typeof(viewall)) ? 1 : 4;		// ** DEVELOPER: SET # OF COLUMNS IN DISPLAY
	var colcounter = 0; 
	prodstoshow = (objArr.length > prodstoshow)? prodstoshow : objArr.length;

	// begin markup for Recently Viewed display
	pvcode += "<div class='pvLbl'>RECENTLY VIEWED</div><Table border='0' cellpadding='2' cellspacing='2' class='pvTbl'><tr>";
	
	// sort the objArr to match cookieArr - to fix delay issues in IE
	var tmpArr = new Array();
	for(var m = 0; m < cookieArr.length; m++){
		for(var l = 0; l < objArr.length; l++){
			if(cookieArr[m] == objArr[l].pf_id){
				tmpArr.push(objArr[l]);
			}
		}
	}
	objArr = tmpArr;
	
	// go through the object array which holds each product's data object
	for(var k = 0; k < (prodstoshow); k++){
		
		if(colcounter == cols){
			pvcode += "</tr><tr><td><div class='pvLine'></div></td></tr><tr>";
			colcounter = 0;
		}

		// building the link and image
		if(objArr[k].image_file != ""){
			// add quickview stuff
			pvcode += "<td valign=top><A HREF=\"product.asp?pf_id=" + objArr[k].pf_id + "\" onclick=\"return visitargs('product.asp','pf_id=" + objArr[k].pf_id + "')\"><img BORDER='0' ALT='" + objArr[k].name + "' SRC='assets/product_images/" + objArr[k].image_file + "' width='100'/></a><br/>";
			
			// -- uncomment 2 lines below for quickview & comment out line above --
			//pvcode += "<td><A HREF=\"product.asp?pf_id=" + objArr[k].pf_id + "\" onclick=\"return visitargs('product.asp','pf_id=" + objArr[k].pf_id + "')\"><img BORDER='0' ALT='" + objArr[k].name + "' SRC='assets/product_images/" + objArr[k].image_file + "' onmouseover=\"popQVIcon('qvicon_" + objArr[k].pf_id + "');\" onmouseout=\"hideQVIcon('qvicon_" + objArr[k].pf_id + "');\"  width='100'/></a>";
			//pvcode += draw_search_qv(objArr[k].pf_id, true);
			// -- uncomment 2 lines above for quickview --
			
			pvcode += "<br/>";
		}else{
			pvcode += "<td>";
		}
		
		
		// building the product name link
		pvcode += "<A HREF=\"product.asp?pf_id=" + objArr[k].pf_id + "\" onclick=\"return visitargs('product.asp','pf_id=" + objArr[k].pf_id + "')\" class=\"deptlinkPV\">" + objArr[k].name + "</a><br/>";
		
		// building the product prices
		if((objArr[k].on_sale).toLowerCase() == "true") {
			pvcode += "<span class='ListPricewSalePV'>" + objArr[k].list_price_str + "</span><br/>";
			pvcode += "<span class='SalePricePV'>" + objArr[k].sale_price_str + "</span></td>";
		}else{
			pvcode += "<span class='ListPricewoSalePV'>" + objArr[k].list_price_str + " </span></td>";
		}
		colcounter ++;
	}
	if ( cookieArr.length > prodstoshow ){
          pvcode += "</tr><tr><td><a href=\"text_1.asp?tx_id=60\" onclick=\"return(visitargs('text_1.asp','tx_id=60','');\">View All Recently Viewed</a></td>";
       }
	pvcode += "</tr></table>";
	// displaying the products on the page
	document.getElementById('pvDiv').innerHTML = pvcode;
	if (prodstoshow > 0){
		document.getElementById('pvDiv').style.display = "block";
	}
}

/**
 * Gets the cookie from the browser if it exists and returns its value.
 * @param{string} NameOfCookie is the name of the cookie of which the values will be returned.
 **/
function getCookie(NameOfCookie){ 
	if (document.cookie.length > 0){ 
		var begin = document.cookie.indexOf(NameOfCookie+"=");

		if (begin != -1){ 
			var end = document.cookie.indexOf(";", begin);

			if (end != -1){
				var tmpcookie = (document.cookie.substring(begin, end)).replace(NameOfCookie + "=", "");
				return unescape(tmpcookie); 
			}
		}
	}
	return null;
}

/**
 * Creates or re-sets a cookie on user's browser 
 * @param{string} NameOfCookie is the name which we will use to reference the cookie.
 * @param{string} value is the data we want to store in the cookie. In this case it is a string of pf_ids seperated by commas.
 * @param{integer} expiredays is the number of days the cookie will last in the browser
 **/
function setCookie(NameOfCookie, value, expiredays){ 
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
	document.cookie = NameOfCookie + "=" + escape(value) +
	((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

/**
 * Deletes the cookie
 * @param{string} NameOfCookie is the name of the cookie which will be deleted from the browser
 **/
function delCookie (NameOfCookie){ 
	if (getCookie(NameOfCookie)) {	
		document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}


/**
 * Calls the ajax request for product data
 * @param{string} pf_id is sent in the POST to specify which product's data we're requesting
 **/
var isIE6 = (window.ActiveXObject)? true : false;	// need this for ajax stuff
var prodcounter = 0;
function getpvProd(){
	var prodReq;
	if (!isIE6) { // iIE7, Mozilla, Safari, ...
		prodReq = new XMLHttpRequest();
		isIE6 = false;
	} else{ // IE6, below
		prodReq = new ActiveXObject("Microsoft.XMLHTTP");
		isIE6 = true;
	}
	
	if(isProductPage){
		if(cookieArr[prodcounter] != pf_id){
			// only request product info if not on the product page
			prodReq.open('GET', 'product_json.asp?pf_id=' + cookieArr[prodcounter], true);
			// NOTE TO DEVELOPER - additional query items you can use:
			// verbose=1 (to use for debugging)
			// inventory=1 (will return availability and out of stock messages)
		}
	}else{
		prodReq.open('GET', 'product_json.asp?pf_id=' + cookieArr[prodcounter], true);
	}
	
	  
	prodReq.setRequestHeader('Content-type', 'application/xml');
	prodReq.onreadystatechange = function(){
		try{
			if(prodReq.readyState == 4){
				if(prodReq.status == 200){
					var pvObj = eval('(' + prodReq.responseText + ')');	// parse returned json object for our javascript to read
					if(pvObj.pf_id != undefined){	// check if the product has been deleted/removed
						objArr.push(pvObj);
					}
					prodReq = null;
					prodcounter++;
					if(prodcounter < prodstoshow){
						getpvProd();		// call this function again to get the next product's data
					}else{
						buildProducts();	// or if finished getting all data, call function to build the markup for display
					}
				}else{
					return;
				}
			}else{
				return;
			}
		}catch(e){
			
		}
	}	// specify our callback function
	
	prodReq.send(null);
}




