﻿	//Globals
	var ClientAlias4T	= 'RoyalYar';
	var ImageSize4T = "&maxx=130&maxy=120";
	var DisplayLogo4T = false;
	var CustomerId4T = '';
	var CartList4T = new Array();
	var CartCount4T = 0;
	var PageType4T = 'Home';
	var LastDivIDs4T = new Array(); //used to exclude first div ids from second div
	var RecCaption4T = ''; // caption for div1
	var Rec2Caption4T = ''; // caption for div2
	var CaptionStyle4T = 'titles';
	var Caption2Style4T = 'titles';
	var NumItems4T = 1;
	var Num2Items4T = 1;
	 
	function add4TellCartItem(itemId) {
		CartList4T[CartCount4T] = itemId;
		CartCount4T++;
	}
	
	function set4TellCustomerId(userId) {
		CustomerId4T = userId;
	}
	
	function set4TellPageType(pageType) {
		PageType4T = pageType;
	}
	
	/* 
	 * getRecommendations:
	 * This function sets the number and type of recommendations based on the type of page
	 * where they will be displayed. You can use this function to set global policies or else
	 * you can call get4TellResults directly from each page.
	 *
	 */ 
	function get4TellRecommendations(pageType, productIDs) {
		var resultType = 0;
		var startPos = 1;
		var callBack = 'display4TellRecs1';
		var blockIDs = '';
		
		// Compile the list of cart items
		var cartIDs = '';
		if (CartCount4T > 0) {
			var firstItem = true;
			for (var i = 0; i < CartCount4T; i++) {
				if (firstItem) firstItem = false;						
				else cartIDs += ',';
				cartIDs += CartList4T[i];
			}
		}
		
		if (pageType == 'Auto')
			pageType = PageType4T;
		
		//These are example settings for different pages of your site. 
		//Feel free to add or remove page types here to match your site architecture.
		//you can also set numResults differently for each page if needed
		var inCart = false;
		switch (pageType) {
			case 'Home': //product detail page (PDP)
				resultType = 4; //Top-sellers
				NumItems4T = 4;
				startPos = 1;
				RecCaption4T = 'Top Sellers';
				CaptionStyle4T = 'menu-headers product4TCaption';
				break;		
			case 'ProductDetail': //product detail page (PDP)
				resultType = 0; //Cross-sell
				NumItems4T = 4;
				startPos = 1;
				RecCaption4T = 'Customers also bought...';
				CaptionStyle4T = 'menu-headers product4TCaption';
				break;		
			case 'ProductDetailSimilar': //product detail page (PDP)
				resultType = 3; //Similar
				Num2Items4T = 6;
				startPos = 1;
				Rec2Caption4T = 'Similar items...';
				Caption2Style4T = 'titles';
				callBack = 'display4TellRecs2'; //displays in second div element
				break;		
			case 'AddToCart': //intermediate add to cart page
				resultType = 0; //Cross-sell
				NumItems4T = 4;
				startPos = 1;
				RecCaption4T = ' You may also like...';
				CaptionStyle4T = 'titles2 product4TCaption';
				inCart = true;
				break;
			case 'OrderShipping': //delivery options page
				resultType = 0; //Cross-sell
				NumItems4T = 4;
				startPos = 1 + NumItems4T; //second block
				RecCaption4T = 'You may also like...';
				CaptionStyle4T = 'checkout-headers product4TCaption';
				inCart = true;
				break;
			case 'OrderPayment': //payment options page
				resultType = 2; //Blended
				NumItems4T = 4;
				startPos = 1;
				RecCaption4T = 'You may also like...';
				CaptionStyle4T = 'checkout-headers product4TCaption';
				inCart = true;
				break;
			case 'OrderConfirm': //order confirmation page
				resultType = 2; //Blended
				NumItems4T = 4;
				startPos = 1 + NumItems4T; //second block
				RecCaption4T = 'You may also like...';
				CaptionStyle4T = 'checkout-headers product4TCaption';
				inCart = true;
				break;
			case 'OrderComplete': //checkout complete page
				resultType = 2; //Blended
				NumItems4T = 4;
				startPos = 1 + (2 * NumItems4T); //third block
				RecCaption4T = 'Suggestions for you...';
				CaptionStyle4T = 'checkout-headers product4TCaption';
				break;
			default: //any page not listed
				resultType = 2; //Blended
				NumItems4T = 3;
				startPos = 1;
				RecCaption4T = 'Suggestions for you...';
				CaptionStyle4T = 'titles product4TCaption';
				break;
		}
		if (inCart && (cartIDs != '')) //on cart pages, use cart IDs directly instead of as influencers
		{
			if (productIDs != '')
				productIDs += ',';
			productIDs += cartIDs;
			cartIDs = '';
		}
		
		var numResults = (NumItems4T + Num2Items4T)*2;
		get4TellResults(resultType, numResults, startPos, productIDs, cartIDs, blockIDs, callBack);
	}
	
	/*
	 * get4TellResults:
	 * This function sets the parameters and calls the 4-Tell Boost web service to retrieve
	 * recommended product data. This function can be called directly or you can use GetRecommendations
	 * listed below to call by page type instead
	 * 
	 */
	function get4TellResults(resultType, numResults, startPos, productIDs, cartIDs, blockIDs, callBack) {
		var webService		= 'www.4-Tell.net/Boost2.0/rest/';
		var operation		= 'GetRecDisplayList';
					
		// Assemble the url to call
		var jsonUrl			=	webService + operation 
								+ '?clientAlias=' + ClientAlias4T
								+ '&productIDs=' + productIDs
								+ '&cartIDs=' + cartIDs
								+ '&blockIDs=' + blockIDs
								+ '&customerID=' + CustomerId4T
								+ '&numResults=' + numResults
								+ '&startPosition=' + startPos
								+ '&resultType=' + resultType 
								+ '&format=json'
								+ '&callback=' + callBack;	

		//document.writeln(jsonUrl);
		
		// Call the service, passing the results to the callback function
		(function() {
			var forTell = document.createElement('script'); forTell.type = 'text/javascript'; forTell.async = true;
			forTell.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + jsonUrl;
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(forTell, s);
		})();
	}
  		

  	function display4TellRecs1(data) {
  		display4TellDiv(data, 'product_recommendations_4T', RecCaption4T, CaptionStyle4T, NumItems4T)
  	}
  	function display4TellRecs2(data) { //second line on pages where we display more than one set
  		display4TellDiv(data, 'product_recommendations_4T_div2', Rec2Caption4T, Caption2Style4T, Num2Items4T)
  	}
  	
  	function display4TellDiv(data, divID, divCaption, divCaptionStyle, numItems) {
  	
  			// If the data is passed in then proceed
			if (data) {
				var lastDivLoaded = false;
				if (LastDivIDs4T.length > 0) lastDivLoaded = true;
				
				if (navigator.appName != "Microsoft Internet Explorer")
				{			  
					var items = data['GetRecDisplayListResult'];
					var prods = document.getElementById(divID);
					
					//set the caption
					var caption = document.createElement('div');
						caption.setAttribute('class', divCaptionStyle);
						caption.innerHTML = divCaption;
					prods.appendChild(caption);

					//setup each recommendation in the list
					var validItems = 0;
					for (var p=0; (p<items.length)&&(validItems<numItems); p++) {
					
						var found = false;
						if (lastDivLoaded) {
							for (var q=0; q<LastDivIDs4T.length; q++) {
								if (LastDivIDs4T[q] == items[p].productID) {
									found = true;
									break;
								}
							}
						}
						else 
							LastDivIDs4T[validItems] = items[p].productID;
							
						if (!found) {
							validItems++;
							
							// This is the main container for one product
							var prod = document.createElement('div');
							prod.setAttribute('class', 'product4T');
		
		
							// image wrapper (to keep fixed size)										
							var prodImage = document.createElement('div');
							prodImage.setAttribute('class', 'productImage');
							
							// link to the product page
							var link = document.createElement('a');
							link.setAttribute('href', items[p].pageLink);
							link.setAttribute('onClick', "pageTracker._trackEvent('Recs', '" +  items[p].productID + "');");
							
							var img = document.createElement('img');
							img.setAttribute('src', items[p].imageLink + ImageSize4T);
							//note: use the following lines if displayed on a tinted background
							//also, change css to:
							//	.product4T .productImage {
							//		background-color: #F3F2F2;
							//		height: 120px;
							//		width: 135px;
							//	}
							//img.setAttribute('src', items[p].imageLink + ImageSize4T);
							//if (img.width > 130) img.setAttribute('width', '130px');
							
							img.setAttribute('class', 'productImageImg');
							link.appendChild(img);
							prodImage.appendChild(link)
		
							// product title
							var prodTitle = document.createElement('div');
							prodTitle.setAttribute('class', 'productTitle');
							
							var prodTitleText = document.createElement('a');
							prodTitleText.setAttribute('class', 'productTitleText');;
							prodTitleText.setAttribute('href', items[p].pageLink);
							prodTitleText.setAttribute('onClick', "pageTracker._trackEvent('Recs', '" +  items[p].productID + "');");
							prodTitleText.innerHTML = items[p].title;
							prodTitle.appendChild(prodTitleText)
							
							// product price
							var prodPrice = document.createElement('div');
							prodPrice.setAttribute('class', 'productPrice');
							prodPrice.innerHTML = items[p].price;
							
							// Buy Now
							var prodBuy = document.createElement('div');
							prodBuy.setAttribute('class', 'productBuy');
							
							var prodBuyBtn = document.createElement('input');
							prodBuyBtn.setAttribute('type', 'button');
							prodBuyBtn.setAttribute('class', 'btn');
							prodBuyBtn.setAttribute('onmouseout', "this.className='btn'");
							prodBuyBtn.setAttribute('onmouseover', "this.className='btn_over'");
							prodBuyBtn.setAttribute('onclick', "javascript:pageTracker._trackEvent('Recs', '" +  items[p].productID + "'); window.location='add_cart.asp?quick=1&item_id=" + items[p].productID + "'");
							prodBuyBtn.setAttribute('value', 'Add to Cart');
							prodBuy.appendChild(prodBuyBtn);
							
							// Put the elements into the main product container 
							prod.appendChild(prodImage);
							prod.appendChild(prodTitle);
							prod.appendChild(prodPrice);
							prod.appendChild(prodBuy);
							
							// Put the main product container into the products container 
							prods.appendChild(prod);
						}
					}
					if (DisplayLogo4T)
					{
						//Powered By 4-Tell
						var poweredBy4T = document.createElement('div');
						poweredBy4T.setAttribute('class', 'product4T poweredByImage4T');					
						// link to 4-Tell
						var link4T = document.createElement('a');
						link4T.setAttribute('href', "http://www.4-Tell.com");
						link4T.setAttribute('target', "_blank");
						// logo					
						var logoImg4T = document.createElement('img');
						logoImg4T.setAttribute('src', 'http://www.4-tell.com/images/uploads/Poweredby4Tell.gif');
						logoImg4T.setAttribute('class', 'poweredByImageImg');
						link4T.appendChild(logoImg4T);
						poweredBy4T.appendChild(link4T)
						prods.appendChild(poweredBy4T);
					}					
				}
				else //special handling for IE
				{
					//set the caption
					var caption = $("<div class='"+divCaptionStyle+"'>"+divCaption+"</div>");
					caption.appendTo("#" + divID);
	
					//get the items array
					var items = data['GetRecDisplayListResult'];

					// Loop through each product
					var validItems = 0;
					$.each(items, function(i, itemdata) {
									
						if (validItems>=numItems) return false; //finished
						
						if (lastDivLoaded) {
							var found = false;
							for (var q=0; q<LastDivIDs4T.length; q++) {
								if (LastDivIDs4T[q] == itemdata.productID)
									found = true;
							}
							if (found)
								return true; //skip this item
						}
						else
							LastDivIDs4T[validItems] = itemdata.productID;
						validItems++;

						// This is the main product container
						var prod = $("<div class='product4T' />");
						
						// A wrapper for the image allows better size and position control
						var prodImage = $("<div class='productImage' />");					
						// This is a image and gets wrapped by the link
						var img = $("<img class='productImageImg' />");
						img.attr("src", itemdata.imageLink + ImageSize4T);
						img.appendTo(prodImage);
						img.wrap("<a href='" + itemdata.pageLink + "'" + ' onclick="pageTracker._trackEvent(' + "'Recs', '" + itemdata.productID + "');" + '"></a>');
						prodImage.appendTo(prod);
						
						// This is the title of the product and gets wrapped by the link
						var prodTitle = $("<div class='productTitle'>" + itemdata.title + "</div>");
						prodTitle.appendTo(prod);
						prodTitle.wrap("<a href='" + itemdata.pageLink + "'" + ' onclick="pageTracker._trackEvent(' + "'Recs', '" + itemdata.productID + "');" + '"></a>');

						
						// This is the price of the product
						$("<div class='productPrice'>" + itemdata.price + "</div>").appendTo(prod);
						
						// This is the buy now buton
						var buyWrapper = $("<div class='productBuy' />");
						var buyBtn = $("<input type='button' value='Add to Cart' class='btn' onmouseout=this.className='btn' onmouseover=this.className='btn_over' onclick=" + '"' + "javascript:pageTracker._trackEvent('Recs', '" + itemdata.productID + "');  window.location='/add_cart.asp?quick=1&item_id=" + itemdata.productID + "'" + '" />');

						buyBtn.appendTo(buyWrapper);
						buyWrapper.appendTo(prod);
						
						// Insert the product into the main product container
						prod.appendTo("#" + divID);
					});
					if (DisplayLogo4T)
					{
						//Powered By 4-Tell
						// A wrapper for the image allows better size and position control
						var poweredBy4T = $("<div/>");	
						if (divID == "product_recommendations_4T_div2")	
						{
							var prod = $("<div class='product4T'/>"); //one more product div to fix IE bug
							var img = $("<img src='http://www.4-tell.com/images/uploads/spacer.gif' width='300px' height='1px'/>");
							img.appendTo(prod);
							prod.appendTo("#" + divID);
							poweredBy4T.attr("class", "product4T poweredByImage4T");
						}			
						else
							poweredBy4T.attr("class", "product4T");	
						// This is the image and gets wrapped by the link
						var logoImg4T = $("<img class='poweredByImageImg' />");
						logoImg4T.attr("src", "http://www.4-tell.com/images/uploads/Poweredby4Tell.gif");
						logoImg4T.appendTo(poweredBy4T);
						logoImg4T.wrap('<a href="http://www.4-Tell.com" target="_blank"></a>');
						poweredBy4T.appendTo("#" + divID);
					}
				}
			}
  	}


