// "Internal" function to return the decoded value of a cookie

//

function getCookieVal (offset) {

  var endstr = document.cookie.indexOf (";", offset);

  if (endstr == -1)

    endstr = document.cookie.length;

  return unescape(document.cookie.substring(offset, endstr));

}

//

//  Function to correct for 2.x Mac date bug.  Call this function to

//  fix a date object prior to passing it to SetCookie.

//  IMPORTANT:  This function should only be called *once* for

//  any given date object!  See example at the end of this document.

//

function FixCookieDate (date) {

  var base = new Date(0);

  var skew = base.getTime(); // dawn of (Unix) time - should be 0

  if (skew > 0)  // Except on the Mac - ahead of its time

    date.setTime (date.getTime() - skew);

}

//

//  Function to return the value of the cookie specified by "name".

//    name - String object containing the cookie name.

//    returns - String object containing the cookie value, or null if

//      the cookie does not exist.

//

function GetCookie (name) {

  var arg = name + "=";

  var alen = arg.length;

  var clen = document.cookie.length;

  var i = 0;

  while (i < clen) {

    var j = i + alen;

    if (document.cookie.substring(i, j) == arg)

      return getCookieVal (j);

	i = document.cookie.indexOf(" ", i) + 1;

    if (i == 0) break; 

  }

  return null;

}

//

//  Function to create or update a cookie.

//    name - String object containing the cookie name.

//    value - String object containing the cookie value.  May contain

//      any valid string characters.

//    [expires] - Date object containing the expiration data of the cookie.  If

//      omitted or null, expires the cookie at the end of the current session.

//    [path] - String object indicating the path for which the cookie is valid.

//      If omitted or null, uses the path of the calling document.

//    [domain] - String object indicating the domain for which the cookie is

//      valid. If omitted or null, uses the domain of the calling document.

//    [secure] - Boolean (true/false) value indicating whether cookie transmission

//      requires a secure channel (HTTPS).  

//

//  The first two parameters are required.  The others, if supplied, must

//  be passed in the order listed above.  To omit an unused optional field,

//  use null as a place holder.  For example, to call SetCookie using name,

//  value and path, you would code:

//

//      SetCookie ("myCookieName", "myCookieValue", null, "/");

//

//  Note that trailing omitted parameters do not require a placeholder.

//

//  To set a secure cookie for path "/myPath", that expires after the

//  current session, you might code:

//

//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);

//

function SetCookie (name,value,expires,path,domain,secure) {

  document.cookie = name + "=" + escape (value) +

    ((expires) ? "; expires=" + expires.toGMTString() : "") +

    ((path) ? "; path=" + path : "") +

    ((domain) ? "; domain=" + domain : "") +

    ((secure) ? "; secure" : "");

}



//  Function to delete a cookie. (Sets expiration date to start of epoch)

//    name -   String object containing the cookie name

//    path -   String object containing the path of the cookie to delete.  This MUST

//             be the same as the path used to create the cookie, or null/omitted if

//             no path was specified when creating the cookie.

//    domain - String object containing the domain of the cookie to delete.  This MUST

//             be the same as the domain used to create the cookie, or null/omitted if

//             no domain was specified when creating the cookie.

//

function DeleteCookie (name,path,domain) {

  if (GetCookie(name)) {

    document.cookie = name + "=" +

      ((path) ? "; path=" + path : "") +

      ((domain) ? "; domain=" + domain : "") +

      "; expires=Thu, 01-Jan-70 00:00:01 GMT";

  }

}

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

var expDays=60;
var expDate = new Date();
expDate.setTime(expDate.getTime()+(expDays*24*60*60*1000))

function setCookie(name,id,imageurl,price,saleprice,man){
              // define the variables we want to use.
	var theCookie,totalCookie,nextCookie,cookieArray;
	var recentItems = 4;
	//cookie counter
	var ctr = 0;
	var recentItemArray = new Array();
	// get the cookie
	var the_cookie = unescape(document.cookie);
	// check to see if the product is already in the cookie, if so, we're good
	if(the_cookie.indexOf(id) > -1){
		var exists = true;
	}else{
	  // define the new cookie
		theCookie = escape("productName:" + name + "|id:"  + id + "|imageurl:" + imageurl + "|price:" + price + "|salepric:" + saleprice + "|man:" + man) + "; expires=" + expDate.toGMTString() + "; path=/";
		// if the old cookie is not null...
		if(the_cookie.length > 0){
		  // split the cookie at every semi colon
			var cookieArray = the_cookie.split(";");
			// for every cookie in the array... 
			for(i=0;i<cookieArray.length;i++){
			  // if this cookie is a recent items cookie...
				if(cookieArray[i].indexOf("invitationboxrecentitemsCookie") > -1){
				  // save the cookie to our array
					recentItemArray[ctr] = cookieArray[i];
					// increment our counter
					ctr = ctr + 1;
				}
			}
			// if we did find recent item cookies (counter > 0)
			if(ctr > 0){
			  // for ever counter
				for(i=0;i<ctr;i++){
				  // if we are at the value of recentItems already, just quit out
					if(i == recentItems) break;
					// next cookie is one greater than what we stop at...
					nextCookie = i + 1;
					// the cookie we pass (the newest, we are going fifo here..)
					passCookie = recentItemArray[i].split("==");
					// add the passed cookie to the document's cookies
					document.cookie = "invitationboxrecentitemsCookie" + nextCookie + "==" + passCookie[1] + "; expires=" + expDate.toGMTString() + "; path=/";
				}
				// add in our new cookie to the beginning
				document.cookie = "invitationboxrecentitemsCookie0==" + theCookie;
			}else{
			  // otherwise just write out the one cookie
				document.cookie = "invitationboxrecentitemsCookie0==" + theCookie;
			}
		}else{
		  // start the cookie!!
			document.cookie = "invitationboxrecentitemsCookie0==" + theCookie;
		}
	}
}


function writeCookie(){
	var name,man,id,imageurl,price,saleprice,Lname,Lid,Limageurl,Lprice,Lsaleprice,cookieVal
	// define the labels
	Lname = "productName:";
	Lid = "id:";
	Lman = "man:";	
	Limageurl = "imageurl:";
	Lprice = "price:";
	Lsaleprice = "salepric:";
	
	// define some variables...
	var nvp = new Array();
	var recentItemArray = new Array();
	var the_cookie = unescape(document.cookie);
	var ctr = 0 ;
	// if the cookie is not null
	if(the_cookie.length > 0){
	  // bring out the cookies.... all of them.
		var cookieArray = the_cookie.split(";");
		// for every cookie...
		for(i=0;i<cookieArray.length;i++){
		  // if the cookie is a recent item cookie...
			if(cookieArray[i].indexOf("invitationboxrecentitemsCookie") > -1){
			  // add it to the recent Item array list...
				recentItemArray[ctr] = cookieArray[i];
				// increment our counter
				ctr = ctr + 1;
			}
		}
		if(recentItemArray.length>0){
		   // this is where the output happens... this will need to change with the new formats...
		   // recently viewed items tag, starts a table the entire width, this can stay but needs new formatting.
		   document.write("<div class='recentitemstitleback'><div class='recentitemstitle'>Recently Viewed Items</div></div>");
		   // new formats, another table, 100%
           document.write("<div class='recentitemslowerframe'><span id='body'><div class='topsectioncontents'><table class='vertical' id='contents-table' width='100%'><tbody><tr>");
		   // cookie processing, this is where we take out each cookie and process it...
		   	for(j=0;j<recentItemArray.length;j++){
		   		name = "";
		   		id = "";
		   		imageurl = "";
		   		price = "";
		   		saleprice = "";							
		   		man = "";
		   		cookieVal = unescape(recentItemArray[j])
          cookieVal = cookieVal.substr(cookieVal.indexOf("productName"));
		   		nvp = cookieVal.split("|");
		   		for(k=0;k<nvp.length;k++){
		   			if(nvp[k].indexOf("productName:") > -1)
		   				name = nvp[k].substr(Lname.length);
		   			if(nvp[k].indexOf("id:") > -1)
		   				id = nvp[k].substr(Lid.length);
		   			if(nvp[k].indexOf("imageurl:") > -1)
		   				imageurl = nvp[k].substr(Limageurl.length);
		   			if(nvp[k].indexOf("price:") > -1)
		   				price = nvp[k].substr(Lprice.length);
             if(nvp[k].indexOf("salepric:") > -1)
               saleprice = nvp[k].substr(Lsaleprice.length);
             if(nvp[k].indexOf("man:") > -1)
               man = nvp[k].substr(Lman.length);
		   		}
		   		// this should change to div's, right now it is a TD that takes up 33% of the screen.  Change to
		   		// div's and make take up the right amount of space and format the way it should be, congruent
		   		// with the rest of the page
		   		document.write("<td class='horizontal-seperator vertical-seperator' width='16%'><div class='topitemimage'><table align='center' border='0' cellpadding='0' cellspacing='0'><tbody><tr align='center' valign='middle'><td class='topsectionimage' align='center' valign='middle' width='105'><a href=" + id + " class='sectionimage'><img src=" + imageurl + " align='middle' border='0' hspace='0' vspace='0'></a></td></tr></tbody></table></div>");
		   		document.write("<div class='itemname'><a href=" + id + "><b>" + name + "</b></a></div>");				
		   		if(man != "")
		   			document.write("<div class='itemprice'>" + man + "</div>");
//		   		if(price != "")
//		   			document.write("<div class='itemprice'>" + price + "</div>");
//		   		if(saleprice != "")
//		   			document.write("<div class='saleprice'>" + saleprice + "</div></td>");
}
		document.write("</tr></tbody></table></div></span></div><div class='tabwidefooter'></div>");
		}		
	}
}

