//Variable to store all Cross site and vendor data
var crossSiteResults =[];
//Indicates the current store/Vendor no
var parentStoreCount=0;
var keyword;
var asc;
var ajaxStoreDisplay=false;
var ajaxStoreDisplaycount=0;

//Array to store all the product count
var cookieStoreNames = [];
var cookieProdCnts = [];
var cookieName;
var cookieContent = '';
var storeDisplayCount=0;

//Global variables used for carousel implementation
var strategies = new Array();
var storeHrefs = new Array();
var onLoadFlag = true;
var footNotes = new Array();
var imgTagWidth = 0;
var imgTagHeight = 0;

$(document).ready(function($){

	storeId=altSearchProperties.storeId;
	parentStoreCount=altSearchProperties.parentStoreCount;
	keyword=replaceAll(replaceAll(gup('keyword'),'%20'," "),"+"," ");
	asc=parseInt(altSearchProperties.asc);
	cookieName = "ALTSEARCH_"+storeId+"_"+replaceAll(keyword," ","+");

	//Check Whether cookie already Exists
	if(!altSearchProperties.cookieValue){
	
		//Retrieve the cookie store names and corresponding product counts			
		for(var count = 0; count < asc; count++) {
  			cookieStoreNames[count] = altSearchProperties.config[count].ass;
  			cookieProdCnts[count] = getCookieProdCnt(altSearchProperties.config[count].ass);
	  	}
	  		
  		//display the product counts alone
		var thinResults = '<div id="crossSiteResultsThin" class="clearfix">';
		
		if(cookieStoreNames.length > 0 && cookieProdCnts.length > 0) {				
			for(var i=0; i < cookieStoreNames.length; i++) {
				if(cookieProdCnts[i] > 0) {
					var shopUrl = '';					
					//Check whether ajax Url is present
					if(altSearchProperties.config[i].asau != null && altSearchProperties.config[i].asau.length > 0) {
						shopUrl = altSearchProperties.config[i].assu+'search_'+modifyUrl(altSearchProperties.config[i].asau);
						if(altSearchProperties.config[i].asau.indexOf('?') > 0 ){
							shopUrl +='&keyword='+keyword+'&sid='+altSearchProperties.config[i].assid;
						}else{
							shopUrl +='?keyword='+keyword+'&sid='+altSearchProperties.config[i].assid;
						}
					} else {
						shopUrl = altSearchProperties.config[i].assu+keyword;
					}
					thinResults += '<div><h3>'+altSearchProperties.config[i].asname+' has '+cookieProdCnts[i]+' products for "'+
						unescape(keyword)+'"</h3><a target="_blank" href="'+shopUrl+'">Shop '+altSearchProperties.config[i].asname+'</a></div>';
				}
			}
		}
			thinResults += '</div>'; 
			hideCrossSite();
			document.getElementById('alternateStore').innerHTML=thinResults;
	} else {
		//Store all vendor site data here
		var ajaxstores= []; 
		var j=0;
		var storeCall=false;
		var ajaxCount=0;		
		var ajaxStoreCount;
		for(k=0; k < asc ;k++){	
			if(altSearchProperties.config[k].asau == null || altSearchProperties.config[k].asau.length == 0){
				crossSiteResults[k]=vendorProds.vendorStores[j];
				j++;
				storeDisplayCount++;
			}
			else {
				crossSiteResults[k]="";
				ajaxstores[ajaxCount]=k;
            	ajaxCount++;
			}
			cookieStoreNames[k] = altSearchProperties.config[k].ass;
		}
		if(ajaxstores.length>0) {
			ajaxStoreDisplay=true;
	        for(var ajaxCallCount = 0; ajaxCallCount < ajaxstores.length ; ajaxCallCount++) {       	
				var ajaxStoreCount = ajaxstores[ajaxCallCount];
	        	crossSiteAjaxCall(ajaxStoreCount);	        	
			}
		}
		else {	
			readyForDisplay();
		}
	}	
});

function ajaxq(queue, options)
{
	// Initialize storage for request queues if it's not initialized yet
	if (typeof document.ajaxq == "undefined") document.ajaxq = {q:{}, r:null};	
	// Initialize current queue if it's not initialized yet
	if (typeof document.ajaxq.q[queue] == "undefined") document.ajaxq.q[queue] = [];
	
	if (typeof options != "undefined") // Request settings are given, enqueue the new request
	{
		// Copy the original options, because options.complete is going to be overridden

		var optionsCopy = {};
		for (var o in options) optionsCopy[o] = options[o];
		options = optionsCopy;
		
		// Override the original callback

		var originalCompleteCallback = options.complete;

		options.complete = function (request, status)
		{
			// Dequeue the current request
			document.ajaxq.q[queue].shift ();
			document.ajaxq.r = null;
			
			// Run the original callback
			if (originalCompleteCallback) originalCompleteCallback (request, status);

			// Run the next request from the queue
			if (document.ajaxq.q[queue].length > 0) document.ajaxq.r = jQuery.ajax (document.ajaxq.q[queue][0]);
		};

		// Enqueue the request
		document.ajaxq.q[queue].push (options);

		// Also, if no request is currently running, start it
		if (document.ajaxq.q[queue].length == 1) document.ajaxq.r = jQuery.ajax (options);
	}
	else // No request settings are given, stop current request and clear the queue
	{
		if (document.ajaxq.r)
		{
			document.ajaxq.r.abort ();
			document.ajaxq.r = null;
		}

		document.ajaxq.q[queue] = [];
	}
}
// To make the ajax calls for the required alternate stores
function crossSiteAjaxCall(ajaxStoreCount){	
	for(var count = 0; count < asc ; count++) {
		if(ajaxStoreCount==count){               	
                crossSiteAjaxUrl ='altsearch_'+altSearchProperties.config[count].asau;
                if(crossSiteAjaxUrl.indexOf('?') > 0 ) {
                	crossSiteAjaxUrl+='&keyword='+keyword+'&storeCount='+count;
                }else {
              	  	crossSiteAjaxUrl+='?keyword='+keyword+'&storeCount='+count;
                }

                ajaxq(ajaxStoreCount,{
				  type: "GET",
				  url: crossSiteAjaxUrl,
				  dataType: "json",
				  complete: readyForDisplay,
				  success: function(ajaxResult){
					if(ajaxResult.prodCnt > 0){
						ajaxStoreDisplaycount++;
						//get the store name and check its postion in the crossSiteArray
						crossSiteResults[ajaxStoreCount] = ajaxResult;
						storeDisplayCount++;						
					 }
					 else{
					 	crossSiteResults[ajaxStoreCount] = ajaxResult;
					 }
				 }
				});	
            break;
        }               
  	 }
  }
  
  
// This function determines if all the ajax calls and corresponding response functions are executed. 
// The crosssite results are ready for display
/* This method is modified to display the cross site results in Carousel format */
function readyForDisplay() {
	
	var hideCarouFlag = true;
	for(var i=0; i < asc; i++) {
		if(typeof crossSiteResults[i] != 'undefined' && crossSiteResults[i]!= null && 
			typeof crossSiteResults[i].products != 'undefined' && crossSiteResults[i].products.length > 0) {
			hideCarouFlag = false;
		}
	}
	
	//Hide the Carousel, if no Cross Site results found
	if(hideCarouFlag) {
		hideCrossSite();
		return;
	}
	
	//Set the cookie when the products are displayed for the first time
	setCrossSiteCookie();
	
	//Creating the tabs and populate the header and note contents
	var tabHtml = generateTabsAndStoreDetails();
	$('ul#carousel_3_tabs').html(tabHtml);
	$('ul#carousel_3_tabs li').click(function() {
		putNewHeader($(this).attr('id'));
		putNewNote($(this).attr('id'));
		setTimeout(updateAnchors, 100);
	});
	
	$("body").append('<div id="sstemp" style="display:none"></div>');
	
	//Array for holding the JSONs of all cross site stores
	var feeds = new Array();
	
	//Object for holding the entire details of a single store (this will be passed to Carousel thro feeds)
	function wideCrossFormat(){
		this.viewGuid = '';
		this.placements = '';
	}
	
	//Object for holding the placement details of a single store
	function placementValue() {
		this.placementType = '';
		this.strategy = '';
		this.items = '';
		
	}
	
	//Object for holding the details of a single product/item
	function itemsValue() {	
		this.itemId = '';
		this.itemScore = '';	
		this.name = '';
		this.url = '';
		this.image = '';
		this.desc = '';
		this.price = '';
		this.attr_savestory = '';
	}

	for(var i=0; i < asc; i++) {
		if(typeof crossSiteResults[i] != 'undefined' && crossSiteResults[i]!= null && 
			typeof crossSiteResults[i].products != 'undefined' && crossSiteResults[i].products.length > 0){
			
			//Parse and get the imgTagWidth and imgTagHeight from img tag
			if(imgTagWidth == 0 || imgTagHeight == 0) {
				getImgTagDim(crossSiteResults[i].products[0].vimg);
			}
			
			var noOfProducts=crossSiteResults[i].products.length;
			
			var tempWide = new wideCrossFormat();
			var tempPlace = new Array();
			var itemArray = new Array();
			
			tempPlace[0] = new placementValue();
			tempPlace[0].placementType="home_page.content";
			tempPlace[0].strategy="";
			tempPlace[0].items = itemArray;
			
			tempWide.viewGuid = "";
			tempWide.placements = tempPlace;
			
			for(var j=0; j < noOfProducts; j++){
				
				//Get the image url and product url
				var imageUrl = getImgUrl(crossSiteResults[i].products[j].vimg);
				var prodUrl = '';
				if( crossSiteResults[i].products[j].vurl.indexOf("http") >= 0 ) {
					prodUrl = crossSiteResults[i].products[j].vurl;
				}else{
					prodUrl = altSearchProperties.config[i].assu+crossSiteResults[i].products[j].vurl+'&sid='+altSearchProperties.config[i].assid;
				}
				
				//Disable the rebates in cross site products
				var saveStory = '';
				document.getElementById("sstemp").innerHTML = crossSiteResults[i].products[j].ss;
				$('div#sstemp div.rebates').find('a').each(function(){
						this.href="javascript:;";
				});
				saveStory = document.getElementById("sstemp").innerHTML;

				//Getting the details of current product
				var temp = new itemsValue();
				temp.itemId=crossSiteResults[i].products[j].no;
				temp.itemScore="";
				temp.name=crossSiteResults[i].products[j].na;
				temp.url=prodUrl;
			    temp.image=imageUrl;
			    temp.desc="";
			    temp.price='$'+crossSiteResults[i].products[j].price;
			    temp.attr_savestory=saveStory;
			    
			    itemArray.push(temp);
			}
			
			feeds.push(tempWide);
		}				
	}
	
	showCrossSite();
          function loadMultiCarousel(jsonIdx) {
            carousel_h1 = new cnCarousel($('#carousel_3'),feeds[jsonIdx].placements[0]);
            carousel_h1.onLoad = function() {
                            //if(onLoadFlag) {
				putNewHeader($('ul#carousel_3_tabs li.first').attr('id'));
				putNewNote($('ul#carousel_3_tabs li.first').attr('id'));
				updateAnchors();
				onLoadFlag = false;
                            //}
                            bindEventsForRR();
			}
        }
	if(storeId==10153){	
        loadMultiCarousel(0);
	}        
	else{
		var carusel_h1 = new Carusel(feeds[0], document.getElementById("carousel_3"), false, false, null,feeds,0);
		carusel_h1.onLoad = function() {
				if(onLoadFlag) {
					putNewHeader($('ul#carousel_3_tabs li.first').attr('id'));
					putNewNote($('ul#carousel_3_tabs li.first').attr('id'));
					updateAnchors();
					onLoadFlag = false;
				}
				bindEventsForRR();
				window.onresize = function() {
					carusel_h1.onCarouselResize();
				};
		};
        
	}
	if(ajaxStoreDisplay){
		if(crossSiteResults.length > 0 && storeDisplayCount>0){
			if(ajaxStoreDisplaycount>0){		
				if(crossSiteResults.length!=storeDisplayCount){
					setTimeout(function(){readyForDisplay(ajaxStoreDisplay)},10);
				}
			}
		}
	}
	if(storeId==10153){
        $("#carousel_3_tabs a").click(function(){
                 $(this).parents("ul").find("li").removeClass("selected");
                 if(!$(this).parents("li").hasClass("selected")){
                        $(this).parents("li").addClass("selected");
                        $('#carousel_3 .carousel_rail').html('');
                        carousel_h1 = null;
                        var tabChoice = $('#carousel_3_tabs li a').index(this);
                        loadMultiCarousel(tabChoice);
}
        });
}
}

//Function to get the product count for the respective store from the cookie value
function getCookieProdCnt(cookieKey) {
	
	//Get the cookie - if not taken already
	if(cookieContent == '') {
		var cookieStart = document.cookie.indexOf(cookieName+"=");
		var cookieEnd = '';
		if(cookieStart >= 0) {
			cookieEnd = document.cookie.indexOf(";", cookieStart);			
			if (cookieEnd < 0) {
				cookieEnd=document.cookie.length;
			}
	    	cookieContent=document.cookie.substring(cookieStart+(cookieName+"=").length, cookieEnd);
		}
	}
	
	//retrive the product count for given cookieKey from cookieContent
	var cookieKeyStart = cookieContent.indexOf(cookieKey+":");
	if(cookieKeyStart >= 0) {
		var cookieKeyEnd = cookieContent.indexOf("|",cookieKeyStart);
		if(cookieKeyEnd < 0) {
			cookieKeyEnd = cookieContent.length;
		}
		return cookieContent.substring(cookieKeyStart+(cookieKey+":").length, cookieKeyEnd);
	}			
	return 0;	
}

// function to set the cookie value for the respective alternate stores and their product counts
function setCrossSiteCookie() {
	var cookieValue = '';
	if((cookieStoreNames != null && cookieStoreNames.length > 0) && storeDisplayCount>0) {
		for(var i=0; i< storeDisplayCount; i++) {
			if(i != 0) {
				cookieValue += "|";
			}
			cookieValue += cookieStoreNames[i]+":"+crossSiteResults[i].prodCnt;
		}
		
		if(cookieValue.length > 0) {
			document.cookie = cookieName+"="+cookieValue;
		}
	}	
}

/*
 * jQuery AjaxQ - AJAX request queueing for jQuery
 *
 * Version: 0.0.1
 * Date: July 22, 2008
 *
 * Copyright (c) 2008 Oleg Podolsky (oleg.podolsky@gmail.com)
 * Licensed under the MIT (MIT-LICENSE.txt) license.
 *
 * http://plugins.jquery.com/project/ajaxq
 * http://code.google.com/p/jquery-ajaxq/
 */



//Replace all characters in a string with a specific character
function replaceAll(strChk, strFind, strReplace) {
  var strOut = strChk;
  while (strOut.indexOf(strFind) > -1) {
    strOut = strOut.replace(strFind, strReplace);
  }
  return strOut;
}

// Function to modify See <keyword> Now Url
function modifyUrl(strUrl) {
	var vertical = '';
	if(strUrl.indexOf('?') >=0){
		vertical ='?'+ strUrl.split('?')[1];
	}
	var baseUrl = strUrl.split('_');
	return baseUrl[0]+'_'+baseUrl[1] + vertical;
}

/* Methods added for implementing the Cross Site using Carousel - Starts Here */

//Function to get the image url from the <img> tag
function getImgUrl(vImg) {
	var url = '';
	if(vImg != null && vImg.length > 0) {
		var start = vImg.indexOf("src=");
		if(start > -1) {
			start += 5;
			var end = vImg.indexOf("'", start);
			if(end > -1) url = vImg.substring(start, end);
		}
	}
	return url;
}

//Generate the tabs and populate the details for tabs
function generateTabsAndStoreDetails() {

	//Get the number of tabs
	var numTabs = 0;
	var storeNames = new Array();
	var storeProdCnt = new Array();
	var images = new Array();
	
	for(var i=0; i < asc; i++) {
		if(typeof crossSiteResults[i] != 'undefined' && crossSiteResults[i] != null && 
			typeof crossSiteResults[i].products != 'undefined' && crossSiteResults[i].products.length > 0) {
			numTabs++;
			var store = unescape(altSearchProperties.config[i].asname);
			storeNames.push(store);
			storeProdCnt.push(crossSiteResults[i].prodCnt);

			images.push(jspStoreImgDir+"img/imgWide/misc/img_logo_"+store.replace(/\s+/g, "_").replace("'", "").toLowerCase()+".gif");

			var link = '';
			if(altSearchProperties.config[i].asau == null || altSearchProperties.config[i].asau.length <= 0 ) {
				link += altSearchProperties.config[i].assu+keyword;
			} else {
				var tempUrl=modifyUrl(altSearchProperties.config[i].asau);
				if(tempUrl.indexOf('?') > 0) {
					link += altSearchProperties.config[i].assu+'search_'+tempUrl+'&keyword='+keyword+'&sid='+altSearchProperties.config[i].assid;
				}else{
					link += altSearchProperties.config[i].assu+'search_'+tempUrl+'?keyword='+keyword+'&sid='+altSearchProperties.config[i].assid;
				}
			}
			storeHrefs.push(link);
			
			var h2Text = store+' has '+crossSiteResults[i].prodCnt+' products for \"'+unescape(keyword)+'\"';
			strategies.push(h2Text);
			
			var note = '<p><strong>PLEASE NOTE:</strong> Clicking on a <span class="storeID" id="storeID1">'+store+'</span> product will open a new window and allow you to shop '+altSearchProperties.sn+' and <span class="storeID" id="storeID2">'+store+'</span> simultaneously</p>';
			footNotes.push(note);
		}
	}
	var tabHtml = '';
	if(numTabs > 0) {
		for(var i=0; i < numTabs; i++) {
			if(i == 0) {
				tabHtml += '<li class="first selected" id="tab_'+i+'"><a href="javascript:;"><img alt="" src="';
			} else {
				tabHtml += '<li id="tab_'+i+'"><a href="javascript:;"><img alt="" src="';
			}
			tabHtml += images[i]+'"> (';
			tabHtml += storeProdCnt[i]+' results)';
			tabHtml += '</a></li>';			
		}
	}
	
	return tabHtml;
}

//Function for applying the strategy and search link for clicked tab.
function putNewHeader(tabNo) {
	if(tabNo != null) {
		var index = tabNo.substring(tabNo.indexOf("_")+1, tabNo.length);
		var h2Text = strategies[index];
		var link = storeHrefs[index];
		var aText = "See \""+keyword+"\" now!";
		if(storeId==10153){
		$('div#carousel_3 a.seeresults').attr('href', link);
		$('div#carousel_3 a.seeresults').text(aText);
		$('div#carousel_3 h2').html(h2Text);		
	}
		else{
			$('div#carousel_3 div.carouselMask a.seeresults').attr('href', link);
			$('div#carousel_3 div.carouselMask a.seeresults').text(aText);
			$('div#carousel_3 div.carouselMask h2').html(h2Text);		

}
	}
}

//Function for applying the foot note for clicked tab.
function putNewNote(tabNo) {
	if(tabNo != null) {
		var index = tabNo.substring(tabNo.indexOf("_")+1, tabNo.length);
		var note = footNotes[index];
		$('div#carousel_3 div.note').html(note);
	}
}

//Function for updating the "a" tags to open the products in new window/tab
function updateAnchors() {
	if(storeId==10153){

	$('div#carousel_3 a.seeresults').attr('target','_blank');
	$('div#carousel_3 .carousel_rail').find('div.item').each(function() {
		$(this).children('h4').children('a').attr('target','_blank');
		$(this).children('p.placeimage').children('a').attr('target','_blank');
		$(this).children('a.view_more_btn').attr('target','_blank');
		$(this).children('p.placeimage').find('img').attr('width',imgTagWidth);
		$(this).children('p.placeimage').find('img').attr('height',imgTagHeight);
	});

}
	else{
		$('div#carousel_3 div.carouselMask a.seeresults').attr('target','_blank');
		$('div#carousel_3 div.carouselMask').find('div.item').each(function() {
				$(this).children('h4').children('a').attr('target','_blank');
				$(this).children('p.placeimage').children('a').attr('target','_blank');
				$(this).children('a.view_more_btn').attr('target','_blank');
				$(this).children('p.placeimage').find('img').attr('width',imgTagWidth);
				$(this).children('p.placeimage').find('img').attr('height',imgTagHeight);
			});
	}
}

//Function for hiding the Carousel and Tabs of Cross Site
function hideCrossSite() {
	$('ul#carousel_3_tabs').css('display', 'none');
	$('div#carousel_3').css('display', 'none');
}

//Function for showing the Carousel and Tabs of Cross Site
function showCrossSite() {
	$('ul#carousel_3_tabs').css('display', 'block');
	$('div#carousel_3').css('display', 'block');
}

//Function to get the width and height from the img tag
function getImgTagDim(vImg) {
	var width = 0;
	var height = 0;
	
	//Get the width
	if(vImg != null && vImg.length > 0) {
		var start = vImg.indexOf("width=");
		if(start > -1) {
			start += 7;
			var end = vImg.indexOf("'", start);
			if(end > -1) width = vImg.substring(start, end);
		}
	}
	
	//Get the height
	if(vImg != null && vImg.length > 0) {
		var start = vImg.indexOf("height=");
		if(start > -1) {
			start += 8;
			var end = vImg.indexOf("'", start);
			if(end > -1) height = vImg.substring(start, end);
		}
	}
	
	imgTagWidth = width;
	imgTagHeight = height;
}
/* Methods added for implementing the Cross Site using Carousel - Starts Here */