﻿	//Globals
	// Client Settings
	var SiteInfo4T = new Object();
	SiteInfo4T.baseURL = 'www.virginiacandle.com';
	SiteInfo4T.alias = 'Virginia';
	SiteInfo4T.enableGATracking = true;
	SiteInfo4T.GATrackID = "4TellRecs";
	SiteInfo4T.rotateTopSellers = true;
	SiteInfo4T.showLogo = false;
	SiteInfo4T.addCartMethod = "/add_cart.asp?quick=1&item_id=";
		
	// Page Settings
	//   The following are default tout settings. 
	//   Page specific choices should be set below in the get4TellPageSettings switch table 
	var FirstTout4T = new Object();
	FirstTout4T.enable = false;
 	FirstTout4T.divName = '#main4TellContainer'; // if class use '.' -- if id use '#'
	FirstTout4T.divPosition = 'replace'; //valid settings are 'replace', 'above', or 'below'
	FirstTout4T.caption = 'Suggestions for you...'; // caption for div1
	FirstTout4T.captionStyle = 'titles product4TCaption';
	FirstTout4T.resultType = 0; //Cross-sell
	FirstTout4T.numItems = 1;
	FirstTout4T.startPos = 1;	
	FirstTout4T.productStyle = 'Product4T';
	FirstTout4T.imageSize = "&maxx=130&maxy=120";
	FirstTout4T.callback = 'display4TellRecs1';
	FirstTout4T.showBuyButton = true;
	FirstTout4T.quickCart = true;
	FirstTout4T.toutType = ''; //fill with pageType-resultType for GA tracking

	var SecondTout4T = new Object();
	SecondTout4T.enable = false;
 	SecondTout4T.divName = '#second4TellContainer'; // if class use '.' -- if id use '#'
	SecondTout4T.divPosition = 'replace'; //valid settings are 'replace', 'above', or 'below'
	SecondTout4T.caption = 'Suggestions for you...'; // caption for div1
	SecondTout4T.captionStyle = 'titles product4TCaption2';
	SecondTout4T.resultType = 0; //Cross-sell
	SecondTout4T.numItems = 1;
	SecondTout4T.startPos = 1;
	SecondTout4T.productStyle = 'Product4T Product4T2';
	SecondTout4T.imageSize = "&maxx=130&maxy=120"
	SecondTout4T.callback = 'display4TellRecs2';
	SecondTout4T.showBuyButton = true;
	SecondTout4T.quickCart = true;
	SecondTout4T.toutType = ''; //fill with pageType-resultType for GA tracking

	// Other Settings
	var Global4T = new Object();
	Global4T.webService = 'www.4-Tell.net/Boost2.0/';
	Global4T.pageType = 'Home';
	Global4T.cartList = new Array();
	Global4T.cartCount = 0;
	Global4T.productList = new Array();
	Global4T.productCount = 0;
	Global4T.customerId = '';
	Global4T.lastDivIDs = new Array(); //used to exclude first div ids from second div
	var $jq = jQuery;	//mapped so no conflict with Prototype library
	
	 
	function get4TellPageSettings(pageType) {
		var inCart = false;
		
		// These are the tout settings for different pages of your site. 
		// You may add or remove page types here to match your site architecture.
		// Any settings not specified here will use the default values listed above
		switch (pageType) {
			case 'Home': //home page
				FirstTout4T.enable = false;
				FirstTout4T.resultType = 4; //Top-sellers
				FirstTout4T.numItems = 3;
				if (SiteInfo4T.rotateTopSellers) {
					var d = new Date();	
					FirstTout4T.startPos = d.getDay() + 1; //roatate start position by day of week
				}
				FirstTout4T.caption = 'Top Sellers';
				FirstTout4T.productStyle = 'Product4T product4Tpad';
				SecondTout4T.enable = false;
				break;
            case 'ProductDetail': //product detail page (PDP)
                FirstTout4T.enable = true;
                FirstTout4T.resultType = 0; //Cross-sell
                FirstTout4T.numItems = 3;
                FirstTout4T.caption = 'Our customers also bought...';
                FirstTout4T.imageSize = "&maxx=100&maxy=100";
                FirstTout4T.productStyle = 'Product4T Product4TSmall';
                SecondTout4T.enable = true;
                SecondTout4T.resultType = 3; //Similar
                SecondTout4T.numItems = 5;
                SecondTout4T.productStyle = 'product4T product4T2 product4TPD2';
                SecondTout4T.caption = 'Similar items...';
                break;		
			case 'Category': //category landing page 
				FirstTout4T.enable = true;
				FirstTout4T.resultType = 3; //Similar
				FirstTout4T.numItems = 4;
				FirstTout4T.caption = 'Related top sellers...';
				SecondTout4T.enable = false;
				break;
			case 'Search': //search results page 
				FirstTout4T.enable = true;
				FirstTout4T.resultType = 3; //Similar
				FirstTout4T.numItems = 4;
				FirstTout4T.caption = 'You may also like...';
				SecondTout4T.enable = false;
				break;		
			case 'AddToCart': //intermediate add to cart page
				FirstTout4T.enable = false;
				SecondTout4T.enable = true;
				SecondTout4T.resultType = 0; //Cross-sell
				SecondTout4T.numItems = 3;
				SecondTout4T.caption = 'You may also like...';
				inCart = true;
				break;
			default: //any page not listed
				FirstTout4T.enable = true;
				FirstTout4T.resultType = 2; //Blended
				FirstTout4T.numItems = 3;
				SecondTout4T.enable = false;
				break;
		}
		//setup toutType for GA tracking
		setGAToutType(pageType, FirstTout4T);
		setGAToutType(pageType, SecondTout4T);
		return inCart
	}
	
	function setGAToutType(pageType, tout) {
		
		if (!tout.enable) return; //nothing to do
		
		tout.toutType = pageType + '-';
		switch (tout.resultType)
		{
			case 0: //Cross-sell
				tout.toutType += 'Cross-sell';
				break;
			case 1: //Personalized
				tout.toutType += 'Personalized';
				break;
			case 2: //Blended
				tout.toutType += 'Blended';
				break;
			case 3: //Similar
				tout.toutType += 'Similar';
				break;
			case 4: //Top-sellers
				tout.toutType += 'Top-sellers';
				break;
			default:
				tout.toutType += tout.resultType;
				break;
		}
	}
	 
	function add4TellProductID(itemId) {
		if (itemId.length < 1) return;
		Global4T.productList[Global4T.productCount] = itemId;
		Global4T.productCount++;
	}

	function add4TellCartItem(itemId) {
		if (itemId.length < 1) return;
		Global4T.cartList[Global4T.cartCount] = itemId;
		Global4T.cartCount++;
	}
	
	function set4TellCustomerId(userId) {
		if (userId.length < 1) return;
		Global4T.customerId = userId;
	}
	
	function set4TellPageType(pageType) {
		if (pageType.length < 1) return;
		Global4T.pageType = pageType;
	}
	
	function check4TellOrderLog() {
		var sessionId = null;
		var orderID = 0;
		var orderUrl = 'http://' + Global4T.webService + 'sale/UploadData/singleSale';
		var oID = $$('.checkout-onepage-success div.wrapper div.page div.main div.col-main p a');
		
		if (oID && oID.length) {
			// Placed by user with an account
			orderID = oID[0].getInnerText();		
		} else {
			var oID = $$('.checkout-onepage-success div.wrapper div.page div.main div.col-main p');
			if (oID && oID.length) {
				// guest check out order
				oID = oID[0];
			
				var orderTextParts = oID.getInnerText().split(' ');
				for (var ot=0; ot<orderTextParts.length; ot++) {
					if (parseInt(orderTextParts[ot]) > 0) {
						orderID = parseInt(orderTextParts[ot]);
					}
				}
			}
		}
		
		if (orderID > 0) {
			new Ajax.JSONRequest(orderUrl, {
				method: 'get',
				parameters: {
					clientAlias:	SiteInfo4T.alias,
					orderID: 		orderID
				}
			});
		}
	}
	
	/* 
	 * getRecommendations:
	 * This function sets the number and type of recommendations based on the type of page
	 * where they will be displayed. Page specific settings are defined above.
	 *
	 */ 
	function get4TellRecommendations(pageType, productIDs) {
		var cartIDs = '';
		var blockIDs = '';
		
		// Page type can be passed in the call or pre-loaded into the global setting
		if (pageType == 'Auto')
			pageType = Global4T.pageType;
		
		//get rid of invalid id label like [catalog_ids]
		if (productIDs.indexOf(']') > 0)  productIDs = "";
		
		// Compile the list of product IDs
		// IDs can be sent in the call or pre-loaded into the array
		if (Global4T.productCount > 0) {
			if (pageType == 'Category') {
				productIDs = Global4T.productList[0]; //only use first item for category pages
			}
			else {
				var firstItem = true;
				if (productIDs != "") {
					firstItem = false; 
				}
				for (var i = 0; i < Global4T.productCount; i++) {
					if (firstItem) firstItem = false;						
					else productIDs += ',';
					productIDs += Global4T.productList[i];
				}
			}
		}
		
		// Compile the list of cart items
		if (Global4T.cartCount > 0) {
			var firstItem = true;
			for (var i = 0; i < Global4T.cartCount; i++) {
				if (firstItem) firstItem = false;						
				else cartIDs += ',';
				cartIDs += Global4T.cartList[i];
			}
		}

		//get page specific tout settings (see get4TellPageSettings above)
		var inCart = false;
		inCart = get4TellPageSettings(pageType);
		
		if (!FirstTout4T.enable && !SecondTout4T.enable) return; //nothing to do
		
		if (inCart && (cartIDs != '')) //on cart pages, use cart IDs directly instead of as influencers
		{
			FirstTout4T.quickCart = false;
			SecondTout4T.quickCart = false;
			if (productIDs != '')
				productIDs += ',';
			productIDs += cartIDs;
			cartIDs = '';
		}
		
		var numResults = FirstTout4T.numItems + SecondTout4T.numItems; //get extra in case of overlap
		if (FirstTout4T.enable)
			get4TellResults(FirstTout4T, productIDs, cartIDs, blockIDs, numResults);
		if (SecondTout4T.enable)
			get4TellResults(SecondTout4T, productIDs, cartIDs, blockIDs, numResults);
	}
	
	
	/*
	 * get4TellResults:
	 * This function sets the parameters and calls the 4-Tell Boost web service to retrieve
	 * recommended product data. This function is called by get4TellRecommendations above 
	 * 
	 */
	function get4TellResults(tout, productIDs, cartIDs, blockIDs, numResults) {
		var operation		= 'GetRecDisplayList';

					
		// Assemble the url to call
		var jsonUrl			=	Global4T.webService + 'rest/' + operation 
								+ '?clientAlias=' + SiteInfo4T.alias
								+ '&productIDs=' + productIDs
								+ '&cartIDs=' + cartIDs
								+ '&blockIDs=' + blockIDs
								+ '&customerID=' + Global4T.customerId
								+ '&numResults=' + numResults
								+ '&startPosition=' + tout.startPos
								+ '&resultType=' + tout.resultType 
								+ '&format=json'
								+ '&callback=' + tout.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);
		})();
	}
  		
  	
  	//Display Functions
  	// The following functions are used to display the recommendation touts. 
  	// The separate call-back functions define witch tout data to use.

  	function display4TellRecs1(data) {
  		display4TellDiv(data, FirstTout4T);
  	}
  	function display4TellRecs2(data) {  
  		display4TellDiv(data, SecondTout4T);
  	}
  	
  	function display4TellDiv(data, tout) {
		var validItems = 0;
  		try {
  			// If the data is passed in then proceed
			if (data) {
				var lastDivLoaded = false;
				if (Global4T.lastDivIDs.length > 0) lastDivLoaded = true;
				
				//set the main container
				var this4TellContainer = '';
				var location = $jq(tout.divName);
				if (location == null) 
					return; //unable to locate div
				if (tout.divPosition == 'replace')
					this4TellContainer = location;
				else
					this4TellContainer = $jq("<div class='"+ divID +"'></div>");

				//set the caption
				var caption = $jq("<div class='"+tout.captionStyle+"'>"+tout.caption+"</div>");
				caption.appendTo(this4TellContainer);

				//get the items array
				var items = data['GetRecDisplayListResult'];

				// Loop through each product
				$jq.each(items, function (i, itemdata) {

				    if (validItems >= tout.numItems) return false; //finished

				    if (lastDivLoaded) {
				        var found = false;
				        for (var q = 0; q < Global4T.lastDivIDs.length; q++) {
				            if (Global4T.lastDivIDs[q] == itemdata.productID)
				                found = true;
				        }
				        if (found)
				            return true; //skip this item
				    }
				    else
				        Global4T.lastDivIDs[validItems] = itemdata.productID;
				    validItems++;

				    // This is the main product container
				    var prod = $jq("<div class='" + tout.productStyle + "' />");

				    //construct a complete page link
				    var pageLink = 'http://' + SiteInfo4T.baseURL + '/' + itemdata.pageLink;

				    //setup onclick string
				    var trackFunc = 'onclick="TrackClick4T(' + "'" + tout.toutType + "','" + itemdata.productID + "',";
				    if (tout.quickCart)
				        trackFunc += 'true);"';
				    else
				        trackFunc += 'false);"';

				    // A wrapper for the image allows better size and position control
				    var prodImage = $jq("<div class='productImage' />");
				    // This is a image and gets wrapped by the link
				    var img = $jq("<img class='productImageImg' />");
				    img.attr("src", itemdata.imageLink + tout.imageSize);
				    img.appendTo(prodImage);
				    img.wrap("<a href='" + pageLink + "'" + trackFunc + ' ></a>');
				    prodImage.appendTo(prod);

				    // This is the title of the product and gets wrapped by the link
				    var prodTitle = $jq("<div class='productTitle'>" + itemdata.title + "</div>");
				    prodTitle.appendTo(prod);
				    prodTitle.wrap("<a class='home' href='" + pageLink + "'" + trackFunc + ' ></a>');

				    // This is the price of the product
				    if (itemdata.price == "$18.98")
				        itemdata.price = "$18.99";
				    $jq("<div class='productPrice'>" + itemdata.price + "</div>").appendTo(prod);

				    // This is the buy now buton
				    if (tout.showBuyButton) {
				        var buyWrapper = $jq("<div class='productBuy' />");
				        var buyBtn = $jq("<input type='button' value='Add to Cart' class='btn' onmouseout=this.className='btn' onmouseover=this.className='btn_over' " + trackFunc + " />");

				        buyBtn.appendTo(buyWrapper);
				        buyWrapper.appendTo(prod);
				    }
				    // Insert the product into the main product container
				    prod.appendTo(this4TellContainer);
				});
				if (SiteInfo4T.showLogo)
				{					
					if (navigator.appName == "Microsoft Internet Explorer") //special handling for IE
					{		
						if (tout.divName == "#second4TellContainer")	
						{
							var prod = $jq("<div class='product4T' style='background: none;'/>"); //one more product div to fix IE bug
							var img = $jq("<img src='http://www.4-tell.com/images/uploads/spacer.gif' width='200px' height='1px'/>");
							img.appendTo(prod);
							prod.appendTo(this4TellContainer);
						}			
					}	
						
					// A wrapper for the image allows better size and position control
					var poweredBy4T = $jq("<div/>");
					poweredBy4T.attr("class", "product4T poweredByImage4T");
					if (false && Global4T.pageType == "ProductDetail" && tout.divName == "#main4TellContainer") {
					    poweredBy4T.addClass("poweredByImage4TSmall");
					}
					
					// This is the image and gets wrapped by the link
					var logoImg4T = $jq("<img class='poweredByImageImg' />");
					logoImg4T.attr("src", "http://www.4-tell.com/images/uploads/Poweredby4Tell.png");
					logoImg4T.appendTo(poweredBy4T);
					logoImg4T.wrap('<a href="http://www.4-Tell.com" target="_blank"></a>');
  
					poweredBy4T.appendTo(this4TellContainer);
				}
				if (tout.divPosition == 'below')
					this4TellContainer.insertAfter(location);
				else if (tout.divPosition == 'above')
					this4TellContainer.insertBefore(location);
			}
		} catch (ex) { }

  	}

	function TrackClick4T(toutType, productID, quick)
	{		
		var newAddress = '';	 
		//if (quick)
			newAddress = 'http://' + SiteInfo4T.baseURL + SiteInfo4T.addCartMethod + productID;
		//else
		//	newAddress = 'http://' + SiteInfo4T.baseURL + SiteInfo4T.addCartMethod + productID;	
		window.location = newAddress;
		
		if (SiteInfo4T.enableGATracking) 
			_gaq.push(['_trackEvent', SiteInfo4T.GATrackID, toutType, productID]);
			//pageTracker._trackEvent(SiteInfo4T.GATrackID, toutType, productID); 
	}

