var comparecheckboxcounter = 0;

$(document).ready(function() {  
	 
	 initializeImageChanger();
	 
	 initializeResetCheckboxListener();
	
	 initializeFacettedSearchCheckboxListener();
	 
	 setMinWidthOnSelectField();
	 
	 initializeCompareLink();	 
	 initializeGoogleEventTrackingForSliders();
	 
	 initializeGoogleEventTrackingForOutboundLinks();
	 
	 initializeGoogleEventTrackingForOutboundLinksInSliders();

	 initializeOnMainSearchFormSubmit();

});


function loadImageForZoom(image){
	$("#pdpImage").remove();
		var iviewer = {};
		
		$("#viewer").iviewer(
		   {
			src:image, 
		   	initCallback: function ()
		   {
		      var object = this;
			  $("#in").click(function(){ object.zoom_by(1);}); 
			  $("#out").click(function(){ object.zoom_by(-1);}); 
			  $("#fit").click(function(){ object.fit();}); 
			  
			  iviewer = this;
		   }
		});
		$("#pdpImage").attr('height','240');
		$("#pdpImage").removeAttr('width');
		getFromColorBox(this);
}
function initializeCompareLink() {
	$("a.jqCompareLink").click(
		function(event){
			var fireLink = false;
			$.ajaxSetup ({
				cache: false
			});
			var loadUrl = "/app/ProductCompareController";
			var queryString = "function=checkIfEnoughCompareProducts";

			$.ajax({
				  url: loadUrl + "?" + queryString,
				  async: false,
				  dataType: 'json',
				  success: function(jsonObject) {
						if(jsonObject.errorMessage == null) {
							fireLink = true;
						}
						else {
							alert(jsonObject.errorMessage);
							fireLink = false;
						}
				  }
			});
			//only if firelink = true, than the link goes to the compare-page
			return fireLink;
		}
	);
}

 /**
  * the mainProductPicture should be in the html-format: <a href="<zoompicture>"><img src="<mainpicture"/></a>
  * the pictureSelectorLink should be in the html-format: <a href="<mainpicture>"><img></a>
  * 
  * use id #mainProductPicture for the Product Picture to change.
  * use class pictureSelectorLink for the selector-Links.
  * @return
  */
function initializeImageChanger() {
	$("a.pictureSelectorLink").click(
			function(event){
				//change the mainProductPicture
				event.preventDefault();
				var defaultPictureSRC = $(this).attr("href");
				$("#mainProductPicture").attr("src", defaultPictureSRC);
				
				//change the class of the selectorpictures
				//var pictureSelectorImages = $("a.pictureSelectorLink").find("img");
				var pictureSelectorImages = $("a.pictureSelectorLink");
				pictureSelectorImages.removeClass("act");
				//var selectedImage = $(this).find("img");
				var selectedImage = $(this);
				selectedImage.addClass("act");
				
				//add the zoompicture-src
				var zoomPictureSRC = $(this).find("span").text();
				var zoomPictureLinkElement = $("#mainProductPicture").parent("a");
				zoomPictureLinkElement.attr("href", zoomPictureSRC);
				
				//jqzoom: load new largeimage
				myJqzoomObject.changeLargeImageUrl(zoomPictureSRC);
			}
	);
}
 

function changeUrl(selectDropdown) {
	 var selectedIndex = $(selectDropdown).attr("selectedIndex");
     if(selectedIndex >= 0) {
    	 window.location = $(selectDropdown).val();
     }	
}


function initializeResetCheckboxListener() {
	//reset the checkboxes if reset-button is clicked
	$(".resetSelection").live("click",function(event){
		event.preventDefault();
		$('#watchfinderSearchform :checkbox').attr('checked', false);
		getFacetedSearchResult();
	});
}

function initializeFacettedSearchCheckboxListener() {
	$("#watchfinderSearchform :checkbox").click(function(){
		getFacetedSearchResult();
	});
}

function getFacetedSearchResult() {
	$.ajaxSetup ({
		cache: false
	});
	var ajax_load = "<div class='ajax-loading'><img src='/images/ajax/big_circle_ball_red.gif' alt='loading...' /></div>";
//	load() functions
	var loadUrl =  window.location.pathname;
	var queryString = $("#watchfinderSearchform").serialize();
	$("#watchfinderResultarea").html(ajax_load).load(loadUrl + "?" + queryString + " #watchfinderResultarea",function(){
		initializeCufon();
	});
}

//used for pagination-calls
function makeAjaxCall(link) {
	$.ajaxSetup ({
		cache: false
	});
	var ajax_load = "<div class='ajax-loading'><img src='/images/ajax/big_circle_ball_red.gif' alt='loading...' /></div>";
//	load() functions
	var loadUrl =  window.location.pathname;
	
	var queryStringForm = $("#watchfinderSearchform").serialize();
	var paginationLinkUrl = $(link).attr("href");
	var queryStringPagination = extractQueryString(paginationLinkUrl);
	var finalQueryString = queryStringForm + "&" + queryStringPagination;
	$("#watchfinderResultarea").html(ajax_load).load(loadUrl + "?" + finalQueryString + " #watchfinderResultarea",function(){
		initializeCufon();
	});
	return false;
}

function extractQueryString(wholeUrl) {
	var arrUrl = wholeUrl.split("?");
	if(arrUrl.length==2) {
		var queryString = arrUrl[1];
		return queryString;
	}
	return "";
}

/**
 * set the high of the footer
 */
function setFooterHigh(){
	
	 footer = $(".footerWrap");
	 var footerPosition = footer.position();
	 
	 if($(document).height() <= ($(window).height()+footer.height())){
		 var footerHighDif = $(window).height() - (footerPosition.top + 30);
		 footer.css("height", footerHighDif + "px");
	 }
}

/**
 * select min-width for dropdown on product detail page. (ie 6 and 7 can't use the css comment min-widht on select field)
 */
function setMinWidthOnSelectField(){
	
	var dropdownElements = ["#sizeDropdown","#colorDropdown"];
	var minWidth = 150;
	
	$.each(dropdownElements, function(index, element) { 
		width = $(element).width();
		
		if(width <= minWidth){
			$(element).css("width", minWidth + "px");
		}
		
	});
}

/**
 * Special Flyout menu
 */

function getLayer( strID )
{
	if( document.all && !window.opera )
		return document.all[ strID ];
	else
		return document.getElementById( strID );
}

function getClassName(element) {
	if(element == null) {
		return "";
	}
	var className = document.all && !window.opera ? element.className : element.getAttribute("class");
	return className == null ? "" : className;
}

sfHover = function() {
	
	if(document.getElementById("subnavigation")){

		var sfEls = document.getElementById("subnavigation").getElementsByTagName("LI");
		
		
	
		if(sfEls){
		
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);


// Class Flyout, Constructor
function Flyout(/*String*/ id, /*int*/ type) {
	this.id = id;
	this.type = type;
	this.active = false;

	// Get Layer for this Flyout
	if (id) { this.flyout = getLayer(id);}

	// Check and extend global Flyout list if necessary
	if (!Flyout.flyouts[type]) {Flyout.flyouts[type] = new Array();}

	// Add flyout to global Flyout object
	Flyout.flyouts[type][id] = this;
	
	// Add event listener for this flyout
	if (this.flyout) {
		addEvent(this.flyout, "mouseover", function() {Flyout.flyouts[type][id].activate() }, true);
		addEvent(this.flyout, "mouseout", function() { Flyout.flyouts[type][id].deactivate() }, true);
	}
}

var /*Boolean*/ ms_setIFrameHeight_stopper = false;
function ms_setIFrameHeight(/*String*/flyoutId) {
	// Only IE6
	if (!window.attachEvent || window.opera || window.XMLHttpRequest) return;
	// Get IFrame and FlyOut element
	if (flyoutId == '') return;
	// Only CORE NAV Flyout Type 2
	
	var flyout = document.getElementById(flyoutId);
	var /*XMLNode*/ iframe = flyout.getElementsByTagName("iframe")[0];
	if (!iframe) return;
	var /*XMLNode*/ list = flyout.getElementsByTagName("ul")[0];
	if (!list) return;
	var /*NodeList*/ lists = flyout.getElementsByTagName("ul");
	if (!lists) return;
	var /*int*/ height = 0;
	for (var i = 0; i < lists.length; i++) {
		height += lists.item(i).offsetHeight;
	}
			
	flyout.style.display = "";
	if (!ms_setIFrameHeight_stopper) {
		// Sometimes IE needs some time to render the hidden
		// elements, so we give it 25 additional milliseconds.
		ms_setIFrameHeight_stopper = true;
		setTimeout("ms_setIFrameHeight('" + flyoutId + "')", 25);
		return;
	} else if (ms_setIFrameHeight_stopper) {
		ms_setIFrameHeight_stopper = false;
	}
	
	// Set height on IFrame. In some cases the height of the iframe must be
	// larger than that of the list because the whole flyout is larger.
	if(iframe.parentNode.className == 'flyContent2'){
		iframe.style.height = (height + 18) + "px";
	}
	else if(iframe.parentNode.className == 'flyWrap'){
		iframe.style.height = 390 + "px";
	}
	
	else{
		iframe.style.height = height + "px";
	}
}



// Methods
Flyout.prototype.activate = function() {
	// Clear Closing Timeout
	clearTimeout(Flyout.changeTimeout[this.type]);
	clearTimeout(Flyout.closeTimeout[this.type]);

	// Closing all independend, open menus
	for (var type in Flyout.openFlyout) {
		var /*boolean*/ isIndependend = true;
		
		isIndependend = ((type != Flyout.TYPE_CORENAV1) && (type != Flyout.TYPE_CORENAV2));
			
		// If current flyout type is independend and has open flyouts, close them
		if (isIndependend && Flyout.openFlyout[type]) {
			Flyout.closeAll(type);
		}
	}

	if (Flyout.openFlyout[this.type] == undefined) {
		// If no Flyout Menu is open, strictly open the current one
		this.handleActivate();
	} else if (Flyout.openFlyout[this.type] != this) {
		Flyout.changeTimeout[this.type] = setTimeout("Flyout.change(\"" + this.id + "\", \"" + this.type + "\")", Flyout.ACTIVATION_TIMEOUT[this.type]);
	}
}

Flyout.prototype.handleActivate = function() {
	// Call Ajax Request for Core Navigation 2 Flyout
	if (this.type == Flyout.TYPE_CORENAV2) {
		var /*String[]*/ values = this.id.split("@");
		var /*String*/ elementId = values[0];
		var /*String*/ handle = values[1];
		
		//ms_corenav_loadFlyoutData(elementId, handle);
		ms_setIFrameHeight(this.flyout.id);
	} else {
		ms_setIFrameHeight(this.flyout.id);
	}
	
	// Activate Flyout
	this.active = true;
	Flyout.pushClass(this.flyout, Flyout.CSS_CLASS_HOVER);
	
	// Set openFlyout Reference
	Flyout.openFlyout[this.type] = this;
	
}

function getIEVersion() {
	try {
		if (navigator.appName=="Microsoft Internet Explorer" && navigator.appVersion.indexOf("MSIE")>0) {		
			var str = navigator.appVersion;
			var ind = parseInt(str.indexOf("MSIE"))+5;
			var ver = parseInt(str.substring(ind, ind+1));
			return ver;
		} else {
			return 0;
		}
	} catch(e) {}
}

Flyout.prototype.deactivate = function() {
	// Set Closing Timeout
	Flyout.closeTimeout[this.type] = setTimeout("Flyout.closeAll(\"" + this.type + "\")", Flyout.DEACTIVATION_TIMEOUT[this.type]);
}



getMenuHeight=function(menu) {

	var h = $('.flyWrap-' + menu).outerHeight();

	if(getIEVersion() == 6){
		$('.flyContent-' + menu).css({'height': h});
		
	}
	else{
		
	 	$('.flyContent-' + menu).css({'min-height' : h});
		
	}

}
function addOrRemoveCompareProductFromQuickView(checkBox){
	var variantCode = checkBox.id;	
	var compareCheckBox = document.getElementById('compareCheckbox-'+variantCode);
	if(checkBox.checked){
		compareCheckBox.checked = true;
	}else{
		compareCheckBox.checked = false;
	}	
	addOrRemoveCompareProduct(variantCode,compareCheckBox);
}

function addOrRemoveCompareProduct(variantCode, currentCheckbox, checkboxselectedSize) {

	$.ajaxSetup ({
		cache: false
	});

	var totalCount ;
	var loadUrl = "/app/ProductCompareController";
	var queryString = "";
	if ($(currentCheckbox).is(':checked')) {
		queryString = "function=addProduct";
	}
	else {
		queryString = "function=removeProduct";
		}
	
	queryString = queryString + "&productCode=" + variantCode;
		$.getJSON(loadUrl + "?" + queryString, function(jsonObject) {
		if(jsonObject.errorMessage != null) {
			alert(jsonObject.errorMessage);
		$(currentCheckbox).attr('checked', false);
		}		
		if(jsonObject.comparisonListSize != null) {
			
			countFunction(jsonObject.comparisonListSize);
			
		}		
	});
	
}

function countFunction(count)
{
	
	var totalCount = count;
	//alert('countFunction : ' + totalCount);
	if(totalCount=='1'){
		document.getElementById("comparebullet").innerHTML='<img src="/images/bullet_compare_selected.gif" /><img src="/images/bullet_compare.gif" hspace="10" /><img src="/images/bullet_compare.gif" />';
		document.getElementById("comparebulletTop").innerHTML='<img src="/images/bullet_compare_selected.gif" /><img src="/images/bullet_compare.gif" hspace="10" /><img src="/images/bullet_compare.gif" />';
		
	}
	else if(totalCount=='2'){
		document.getElementById("comparebullet").innerHTML='<img src="/images/bullet_compare_selected.gif" /><img src="/images/bullet_compare_selected.gif" hspace="10" /><img src="/images/bullet_compare.gif" />';
		document.getElementById("comparebulletTop").innerHTML='<img src="/images/bullet_compare_selected.gif" /><img src="/images/bullet_compare_selected.gif" hspace="10" /><img src="/images/bullet_compare.gif" />';
	}
	else if(totalCount=='3'){
	document.getElementById("comparebullet").innerHTML='<img src="/images/bullet_compare_selected.gif" /><img src="/images/bullet_compare_selected.gif" hspace="10" /><img src="/images/bullet_compare_selected.gif" />';
	document.getElementById("comparebulletTop").innerHTML='<img src="/images/bullet_compare_selected.gif" /><img src="/images/bullet_compare_selected.gif" hspace="10" /><img src="/images/bullet_compare_selected.gif" />';
	}
	else if(totalCount=='0'){
		document.getElementById("comparebullet").innerHTML='<img src="/images/bullet_compare.gif" /><img src="/images/bullet_compare.gif" hspace="10" /><img src="/images/bullet_compare.gif" />';
		document.getElementById("comparebulletTop").innerHTML='<img src="/images/bullet_compare.gif" /><img src="/images/bullet_compare.gif" hspace="10" /><img src="/images/bullet_compare.gif" />';
		}
}
function removeCompareProductAndReloadPage(variantCode) {
	$.ajaxSetup ({
		cache: false
	});
	var loadUrl = "/app/ProductCompareController";
	var queryString = "function=removeProduct&productCode=" + variantCode ;
	$.ajax({type: "GET", url: loadUrl + "?" + queryString, async: false });
	location.reload();
	return false;
}

function removeAllCompareProductAndReloadPage() {
	$.ajaxSetup ({
		cache: false
	});
	var loadUrl = "/app/ProductCompareController";
	var queryString = "function=removeAllProduct";
	$.ajax({type: "GET", url: loadUrl + "?" + queryString, async: false });
	//location.reload();
	
	return true;
}


function comparisonMeter() {

	
		var fireLink = false;
		$.ajaxSetup ({
			cache: false
		});
		var loadUrl = "/app/ProductCompareController";
		var queryString = "function=comparisonMeterValue";

		$.ajax({
			  url: loadUrl + "?" + queryString,
			  async: false,
			  dataType: 'json',
			  success: function(jsonObject) {
					if(jsonObject.comparisonListSize == null) {
					//	fireLink = true;
					}
					else {
					alert(jsonObject.comparisonListSize);
					//	fireLink = false;
					}
			  }
		});
		//only if firelink = true, than the link goes to the compare-page
	//	return fireLink;
	
	
	
	
	
	}
	
	
	
/*	$.ajax({
		type: "GET", url: loadUrl + "?" + queryString, 	async: false
		//success: function(data){alert(data);},
		//error:function(){alert('error');},
		
		});	*/
	//return false;
//}


/**
 * 	  GA Event tracking
 * 	  			Category - Slider Components
 *	  			Action - click
 *	  			Label - something like contentPageUid_sliderName_componentUid
 *	  			Value - omitted for now  
 *	  
 *    Requires jSonComments Plugin
 */
function initializeGoogleEventTrackingForSliders() {
	//bind to both click and keypress events, only for links which are in a slider and which do not link to external urls
	$('a.imageLinkComponentTracked:not(a[href^="http"]:not([href*="://' + document.domain + '"]))').click(function(jsEvent) {
		var $a = $(this);
		var targetUrl = $a.attr('href');
		     
		var gaCategory = 'Slider Components';
		var gaEvent = 'click'; 
		var gaLabel = $a.jSonComments().label;
		var openInNewWindow = isExternalLink($a);
		 
		recordEventAtAnalyticsAndOpenUrl(gaCategory, gaEvent, gaLabel, jsEvent, targetUrl, openInNewWindow);
	});  
}


function initializeGoogleEventTrackingForOutboundLinks() {
	//bind to both click and keypress events, only for external urls, which are not in a slider
	$('a[href^="http"]:not([href*="://' + document.domain + '"]):not(a.imageLinkComponentTracked)').click(function(jsEvent) {
        var $a = $(this);
        openOutboundLink($a, jsEvent);
	});
}

/**
 * this is needed, because the other 2 methods would open twice all urls, which are external urls and are in a slider
 */
function initializeGoogleEventTrackingForOutboundLinksInSliders() {
	//bind to both click and keypress events, only for external urls which are in a slider
	$('a.imageLinkComponentTracked[href^="http"]:not([href*="://' + document.domain + '"])').click(function(jsEvent) {
        var $a = $(this);
        openOutboundLink($a, jsEvent);
	});
}

/**
 *  GA Event tracking
 *		Category - Outbound Links
 *		Action - click
 * 		Label - the url of the external link. e.g. http://www.google.com
 * 		Value - omitted for now  
 * @param linkObject
 * @param jsEvent The event-object of the link which was clicked
 */
function openOutboundLink(linkObject, jsEvent) {
	var $a = linkObject;
    var href = $a.attr('href');

    var gaCategory = 'Outbound Links'; // set this to whatever you want
    var gaEvent = 'click'; // set this to whatever you want
    var gaLabel = href; // set this to whatever you want
    var targetUrl = href;
    var openInNewWindow = isExternalLink($a);
    
    recordEventAtAnalyticsAndOpenUrl(gaCategory, gaEvent, gaLabel, jsEvent, targetUrl, openInNewWindow);	
}

/**
 * @param linkObject a jQuery-link-object
 * @return boolean: returns true if the link has a target="_blank"
 */
function isExternalLink(linkObject) {
	var targetAttributeValue = linkObject.attr('target');
	if(targetAttributeValue == '_blank') {
		return true;
	}
	else {
		return false;
	}
}

/**
 * Sends an tracker-event to Google Analytics
 * @param gaCategory set this to whatever you want (e.g. outgoing-links, sliderItems, etc.)
 * @param gaEvent set this to whatever you want (normally 'click')
 * @param gaLabel set this to whatever you want (e.g. mySpecialLinkXY)
 * @param jsEvent The event-object of the link which was clicked
 * @param targetUrl the url which should be opened after the trackEvent has been sent to Google
 * @param openInNewWindow if this is true, the url will be opened in a new window
 */
function recordEventAtAnalyticsAndOpenUrl(gaCategory, gaEvent, gaLabel, jsEvent, targetUrl, openInNewWindow) {
	 try {
		 //alert('sending event to google. message: ' + gaLabel+' '+gaCategory+ ' '+gaEvent );
		 //pageTracker._trackEvent(gaCategory, gaEvent, gaLabel);
		 _gaq.push(['_trackEvent', gaLabel, gaCategory, gaEvent]);//New tracking method for asynchronous script.
		 setTimeout(function() {openUrl(targetUrl,openInNewWindow)}, 100);
		 jsEvent.preventDefault();
	 }catch(err){}
 } 
 

 /**
 * @param targetUrl
 * @param openInNewWindow boolean: if true, the targetUrl is opened in a new window
 */
function openUrl(targetUrl, openInNewWindow) {
	 if(openInNewWindow == false) {
		 document.location = targetUrl;
	 }
	 else {
		 window.open(targetUrl,'_blank');
	 }
 }

function showColor(colorText){	
		//var ColorSwatchPosLeft = $('#'+colorText).offset();
		//alert(ColorSwatchPosLeft);
		$(".FeaturesProductRight .SelectColor").css('position','relative');
		$('#Color_Finishes_Popup').css('display','block');
		$('#Color_Finishes_Popup').html('');
		$('#Color_Finishes_Popup').html(colorText);
	}
function hideColor(){
	$('#Color_Finishes_Popup').css('display','none');
	$(".FeaturesProductRight .SelectColor").removeAttr('style');
}
//Initialise QV POP Up
function resetAll(){
	
	$("#popupContact .PopupCont .PopUp_product_Info p#pSizeLabel").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info select#pSizeCombo").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info p#pColorLabel").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info p#pCapacityLabel").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info select#capacityCombo").css('display','none');
	
	$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgSwsTrkr img").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgTSAlock img").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgINTLBagTrack img").css('display','none');
	$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgUSCarryOn img").css('display','none');
}


function getQuickViewProduct(variantCode, cartMode, entryNumber, quantity, defaultImage, fromProductDetail) {
	
	if(fromProductDetail=='true'){
		//loadImageForZoom(defaultImage);
	}
	
	$.ajaxSetup ({
		cache: false
	});
	//disablePopup()
	resetAll(); //Initalize the Pop up
	var loadUrl = "/app/QuickViewController";
	var queryString = "productCode=" + variantCode;
	
	
	//get JSON object from controller
	$.getJSON(loadUrl + "?" + queryString, function(jsonObject) {
		renderQuickView(jsonObject, false, variantCode, cartMode, entryNumber, quantity, defaultImage, fromProductDetail)
	});
}

function renderQuickView(jsonObject, showSize, variantCode, cartMode, entryNumber, quantity, defaultImage, fromProductDetail)
{
	var name = jsonObject.quickProductData.name;
	var code = jsonObject.quickProductData.code;
	var completeProductUrl = jsonObject.quickProductData.completeProductUrl;
	var numOfReviews =jsonObject.quickProductData.noOfReviews;
	var avgRatings =jsonObject.quickProductData.ratings;
	var description = jsonObject.quickProductData.description;
	var size = jsonObject.quickProductData.size;
	var hexaColorCode = jsonObject.quickProductData.hexaColorCode;
	var currentVarColorCode = jsonObject.quickProductData.colorCode;
	var currentVarColorTransparent = jsonObject.quickProductData.colorTransparent;
	var pathAsString = jsonObject.quickProductData.pathAsString;		
	var reviewLabel= jsonObject.quickProductData.reviewLabel;
	var priceEnable= jsonObject.priceEnabled;
	var ecommersEnable= jsonObject.ecomm_enabled;
	var priceAvailable= jsonObject.quickProductData.priceAvailable;
	
	var readmoreLink = '';
	var hideTRG= false;
	
	if(hideTRG){
		$(".PopUp_product_Info p#rating").hide();
	}
	else
	{$(".PopUp_product_Info p#rating").show();}
	
	var availableQty = jsonObject.quickProductData.availableQuantity;
	if(jsonObject.quickProductData.descriptionLengthy){
		readmoreLink = '<a href="'+completeProductUrl+'">read more >></a>'
	}
	
	$("#popupContact .PopupCont .PopUp_product_Info span#numReviews").html(numOfReviews);
	$("#reviewLabel").html(reviewLabel);
	
	$("#popupContact .PopupCont .PopUp_product_Info #avgRatings").html('<img alt="" width ="85" src="/images/dummypictures/'+avgRatings+'.gif">');
	
	$("#popupContact .PopupCont .PopUp_product_Info h3#pName").html(name);
	$("#popupContact .PopupCont .PopUp_product_Info #ItemCode").html(code);
	$("#popupContact .PopupCont .PopUp_product_Info p#pDescription").html(description+readmoreLink);
	$("#popupContact .PopupCont .PopUp_product_Info p#pOverView").html('');<!-- Product Overview -->
	
	var attributeFeatureList  = jsonObject.quickProductData.featureList;
	var dimValuesForDisplay = '';
	for (var key in attributeFeatureList){
		if(attributeFeatureList[key].name.length>0){
			dimValuesForDisplay += '<b>'+ attributeFeatureList[key].name+ ':</b>&nbsp;' + attributeFeatureList[key].value+'<br>'	
		}else{
			dimValuesForDisplay += attributeFeatureList[key].value+'<br>'  <!-- In Case of Travel Gear -->
		}
		
	}		
	$("#popupContact .PopupCont .PopUp_product_Info span#pDimensions").html(dimValuesForDisplay);
	//$("#popupContact .PopupCont .PopUp_product_Info span#pDimensions").html(width +'&nbsp;W&nbsp;x&nbsp;'+height +'&nbsp;H&nbsp;x&nbsp;'+length +'&nbsp;L');
	
	//Modify size option values
	$("#popupContact .PopupCont .PopUp_product_Info select#pSizeCombo").children().remove();
	var vairantWithSameColorList = jsonObject.quickProductData.varientsWithSameColor;
	if(vairantWithSameColorList.length > 0 ){			
		$("#popupContact .PopupCont .PopUp_product_Info p#pSizeLabel").css('display','block');
		$("#popupContact .PopupCont .PopUp_product_Info select#pSizeCombo").css('display','block');
		$("#popupContact .PopupCont .PopUp_product_Info select#pSizeCombo").attr('options').add(new Option('select', ''));

	for (var key in vairantWithSameColorList){
		var sameColoredVariant = vairantWithSameColorList[key];
		var selected = false;
		$("#popupContact .PopupCont .PopUp_product_Info select#pSizeCombo").attr('options').add(new Option(sameColoredVariant.size, sameColoredVariant.code));
		if(size == sameColoredVariant.size && (showSize == true || cartMode == 'updateCart')){							
			$("#popupContact .PopupCont .PopUp_product_Info select#pSizeCombo option").attr('selected','selected')				
		}			
	}	
	}	
	//Capacity drop down starts
	if(null != jsonObject.quickProductData.capacityList)
	{
		 
		
		 
		$("#popupContact .PopupCont .PopUp_product_Info p#pCapacityLabel").css('display','block');
		$("#popupContact .PopupCont .PopUp_product_Info select#capacityCombo").css('display','block');		
		$("#popupContact .PopupCont .PopUp_product_Info select#capacityCombo").children().remove();
		
 
		
		var capacityList = jsonObject.quickProductData.capacityList;
		var orderedList = jsonObject.quickProductData.flashCapacityList;
		 
		for (var i in orderedList)
		{		
	 
			for (var key in capacityList)
			{	
			 
			 if(orderedList[i]==key)
			 {
				 
				$("#popupContact .PopupCont .PopUp_product_Info select#capacityCombo").attr('options').add(new Option(capacityList[key], key));

				if(code == key)
					{			
					 
					$("#popupContact .PopupCont .PopUp_product_Info select#capacityCombo option").attr('selected','selected');
				 	}
			 }
				
		  }
		}//ends
			
		
	 
	}
	if(jsonObject.quickProductData.showColorSwatch && jsonObject.quickProductData.flashCapacityList==0){
		$("#popupContact .PopupCont .PopUp_product_Info p#pColorLabel").css('visibility','visible');	
		$("#colorLabel").css('display','block');
		var otherColorsVariants = jsonObject.quickProductData.varientsWithSameSize;		
		$("#popupContact .PopupCont .PopUp_product_Info ul#pColorboxes").children().remove();
		var haxColorCode  = '';
		for (var key in otherColorsVariants){				
			var sameSizeVariant = otherColorsVariants[key];		              
			var temphaxColorCode  = sameSizeVariant.hexaColorCode;
			var colorCode = sameSizeVariant.colorCode;
			var colorTransparent = sameSizeVariant.colorTransparent;
			var selectedAct = "hidden";
			if(currentVarColorCode == colorCode  && colorTransparent == currentVarColorTransparent){					
				 selectedAct = "visisble";
			}
			var imageHTML = '';	
			if(sameSizeVariant.colorTransparent){		
				//imageHTML = "<img src=/images/popupImages/"+colorCode+"-Transparent.jpg width='30' height='15'/>"
				imageHTML = "/images/popupImages/"+colorCode+"-Transparent.jpg"
			}
			else if(temphaxColorCode == ''){						
				//imageHTML = "<img src=/images/popupImages/"+colorCode+".jpg width='30' height='15'/>"
				imageHTML = "/images/popupImages/"+colorCode+".jpg"
			}
			var li_Start = "<li style='cursor:pointer;cursor:hand;' onMouseover='showColor(this.id)' onMouseout='hideColor()' id='"+sameSizeVariant.colorText+" "+sameSizeVariant.colorTransparnetText+"'>";
			var li_Text1 = "<span><img src='/images/arrow-colorbox-top.gif' class='imgblock' style='visibility:"+selectedAct+"' /></span><span class='clr_block' title='"+cartMode+"' onClick='getFromColorBox(this," + entryNumber+","+ quantity+")' id='"+sameSizeVariant.code+"' style='background-color:"+temphaxColorCode+"; background-image:url("+imageHTML+");border:1px solid #ececec'></span>";
			var li_End = "</li>";

			var li =  li_Start + li_Text1 + li_End;
			
			$("#popupContact .PopupCont .PopUp_product_Info ul#pColorboxes").append(li);
		}
	}
	//End Modify color boxes
	
	//Starts: Create Variants Drop Down
	var siblingVariants = jsonObject.quickProductData.otherVarients;
	if(jsonObject.quickProductData.showVariantDropDown && siblingVariants.length > 1 && jsonObject.quickProductData.flashCapacityList==0 ){			
		$("#popupContact .PopupCont .PopUp_product_Info p#pStyleLabel").css('display','block');
		$("#popupContact .PopupCont .PopUp_product_Info select#pSiblingsCombo").css('display','block');
		
		$("#popupContact .PopupCont .PopUp_product_Info select#pSiblingsCombo").children().remove();
		var siblingVariant = null;
		var dropDownText = '';
		for (var key in siblingVariants){
			siblingVariant = siblingVariants[key];
			dropDownText = siblingVariant.name;
			if(siblingVariant.colorText != ""){
				dropDownText=dropDownText+', '+siblingVariant.colorText+' '+siblingVariant.colorTransparnetText;
			}	
			else if(siblingVariant.colorTransparnetText !=""){
				dropDownText=dropDownText+', '+siblingVariant.colorTransparnetText;
			}
			$("#popupContact .PopupCont .PopUp_product_Info select#pSiblingsCombo").attr('options').add(new Option(dropDownText, siblingVariant.code));
			if(siblingVariant.code == code){
				$("#popupContact .PopupCont .PopUp_product_Info select#pSiblingsCombo option").attr('selected','selected')
			}
	  }
	}else{
		$("#popupContact .PopupCont .PopUp_product_Info p#pStyleLabel").css('display','none');
		$("#popupContact .PopupCont .PopUp_product_Info select#pSiblingsCombo").css('display','none');
	}
	//End: Create Variants Drop Down
	
	//Set Default Image	
	var defaultImageURL  = '/images/dummypictures/awaitingimage.gif';
	if(jsonObject.quickProductData.defaultImage != ''){
		defaultImageURL = jsonObject.quickProductData.defaultImage;
	}
	$("#popupContact .PopupCont .PopUp_product .Show_Iamge img").attr('src',defaultImageURL);
	
	//Set Alternative Images
	var otherImages = '';		
	var alternameImagesUL = $("#popupContact .PopupCont .PopUp_product .Alt_views ul");		
	alternameImagesUL.children().remove();	
	for (var key in jsonObject.quickProductData.alternateImages){
		otherImages = "/images/dummypictures/awaitingimage.gif";
		if(jsonObject.quickProductData.alternateImages[key] != ''){
			otherImages = jsonObject.quickProductData.alternateImages[key];
			var additionalThumnailUrl = jsonObject.quickProductData.additionalThumnailUrlMap[key];
			if(additionalThumnailUrl == null ){
				additionalThumnailUrl=defaultImageURL;
			}
			var li = '<li onClick="changeImage(\''+additionalThumnailUrl+'\')"><img src='+otherImages+' /></li>';
			alternameImagesUL.append(li);
		}
	}
	
	//for (var i=0;i<3;i++){			
	//	otherImages = "/images/dummypictures/awaitingimage.gif";
	//	var li = '<li onClick="changeImage(this)"><img src='+otherImages+' /></li>';
//		alternameImagesUL.append(li);
//	}
	
	//Set Product Detail Link		
	//$("#popupContact .PopupCont .PopUp_product_Info span#pDetailPageLink a").attr('href','/content/product_details?code='+code);
	//alert(completeProductUrl)
	$("#popupContact .PopupCont .PopUp_product_Info span#pDetailPageLink a").attr('href',completeProductUrl);
	
	//Making Travel and gear Features visible		
	if(jsonObject.quickProductData.hasBagTrackProgram){
		$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgSwsTrkr img").css('display','block');
		
	}
	if(jsonObject.quickProductData.hasLock){
		$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgTSAlock img").css('display','block');		
	}
	if(jsonObject.quickProductData.internationalCarryOn){
		$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgINTLBagTrack img").css('display','block');		
	}
	if(jsonObject.quickProductData.usCarryOn){
		$("#popupContact .PopupCont .PopUp_product_Info p#pTravelGearFeatures span#tgUSCarryOn img").css('display','block');		
	}
	$("#showprice").html("");
	
	if((ecommersEnable && priceEnable && priceAvailable && (jsonObject.quickProductData.activeStatus =='ACTIVE' || jsonObject.quickProductData.activeStatus =='NONECOMMERCEWITHMSRP')) || (!ecommersEnable && priceEnable && priceAvailable)){
	
		if (jsonObject.quickProductData.formattedMSRPPrice != null && jsonObject.quickProductData.trgProduct)
		{
			$("#showprice").html('MSRP: ' + jsonObject.quickProductData.formattedMSRPPrice)
		}
		if (jsonObject.quickProductData.formattedYourPrice != null)
		{
			if (jsonObject.quickProductData.productSalePrice > 0)
			{
			$("#showprice").append('<br>Your Price: <span class="text_strike">' + jsonObject.quickProductData.formattedYourPrice +'</span>')
			} 
			else
			{
			$("#showprice").append('<br>Your Price: ' + jsonObject.quickProductData.formattedYourPrice)
			}
		}
		if (jsonObject.quickProductData.formattedSalePrice != null && jsonObject.quickProductData.productSalePrice > 0)
		{
			$("#showprice").append('<br><font color="red">Sale Price: ' + jsonObject.quickProductData.formattedSalePrice+'</font>')
		}
           	$("#showprice").css('display','block');
		if(ecommersEnable && jsonObject.quickProductData.activeStatus == 'ACTIVE'){
		$("#addToCartDiv").css('display','block');
		}
	}
	else
	{
		$("#addToCartDiv").css('display','none');		
		if(jsonObject.quickProductData.activeStatus != '' && jsonObject.quickProductData.activeStatus !='NOTACTIVEDISPLAYONWEB'){
		$("#showprice").html('Price is not available');
		}
	}
	
	
	//Check calling page Wall/Comparison
	var tileCompareBox = document.getElementById('compareCheckbox-'+variantCode);	
	if(tileCompareBox){
		var tileCompareBox = document.getElementById('compareCheckbox-'+variantCode);
		var isChecked = '';
		if(tileCompareBox.checked){			
			isChecked = "checked";
		}			
		var compareCheckBox = '<input id="'+code+'" type="checkbox" onclick="addOrRemoveCompareProductFromQuickView(this);" "'+isChecked+'"/>'			
		$("#popupContact .PopupCont .PopUp_product p#pcompareParagraph span#pCompareSpan").html(compareCheckBox);
		$("#popupContact .PopupCont .PopUp_product p#pcompareParagraph").find("a").css('display','block');
	}
	//End Check calling page Wall/Comparison
	
	var cartArea = null;
	var quantityArea = null;
	if (jsonObject.quickProductData.activeStatus == 'ACTIVE')
	{
	if (availableQty > 0 && jsonObject.quickProductData.activeStatus != 'NONECOMMERCEWITHMSRP' && jsonObject.quickProductData.activeStatus !='NOTACTIVEDISPLAYONWEB')
	{
		quantityArea = '<p>Qty.</p><p><select id="quantity" name="quantity">';
		for (var count=1; count<=availableQty; count++)
		{
			if (count == quantity || (count == availableQty && quantity > availableQty))
			{
				quantityArea = quantityArea + '<option selected="selected">'+count+'</option>';
			}
			else
			{
				quantityArea = quantityArea + '<option>'+count+'</option>';
			}
		}
		quantityArea = quantityArea + '</select></p>';
	
	var productBox = '<input type="hidden" name="productCode" value="' + code + '"/>';
	
	if (cartMode == 'updateCart')
	{
		var entryBox = 	'<input type="hidden" id="cartEntryNumber" name="cartEntryNumber" value="' + entryNumber + '"/>';
		var updateBox = '<input type="hidden" name="quickUpdate" value="true"/>';
		updateBox = updateBox + '<input type="hidden" id="cartMode" name="cartMode" value="updateCart"/>';
		updateBox = updateBox + '<input type="hidden" id="entryQty" name="entryQty" value=' + quantity + '/>';
		cartArea = productBox + entryBox + updateBox + '<input name="CartController" type="submit" value="Update Cart" class="BtnAddToCart" />';
	}
	else
	{
		if(ecommersEnable)
		{
		var addBox = '<input type="hidden" name="quickAdd" value="true"/>';
		addBox = addBox + '<input type="hidden" name="openPopUp" value="false"/>';
		addBox = addBox + '<div id="selectMessage" style="display: none"><font color="Red">To buy, Select size</font></div>';
		addBox = addBox + '<input type="hidden" id="cartMode" name="cartMode" value="addToCart"/>';
		cartArea = productBox + addBox + '<input name="CartController" type="button" value="Add to Cart" class="BtnAddToCart" onclick="checkSize();"/>';
		}
	}
	$("#qtyArea").html(quantityArea);
	$("#cartArea").html(cartArea);
	}
	else{
		$("#cartArea").html("");
		if(availableQty <= 0 && jsonObject.quickProductData.activeStatus != 'NONECOMMERCEWITHMSRP' && jsonObject.quickProductData.activeStatus !='NOTACTIVEDISPLAYONWEB') 
		{
			$("#qtyArea").html("We're sorry, this item is not available at this time. Please contact Customer Support for information on availability.");
			
		}
	}
	}
	else
	{
		$("#qtyArea").html("");
		$("#cartArea").html("");
	}
	if(!ecommersEnable){
		$("#qtyArea").html("");
		$("#cartArea").html("");
	}
}

function getQuickViewOnSizeChange(variantCode, showSize) {

	$.ajaxSetup ({
		cache: false
	});
	var cartMode = "addToCart";
	if (null != document.getElementById('cartMode') && document.getElementById('cartMode') != '')
	{
		cartMode = document.getElementById('cartMode').value;
	}	
	var cartEntryNumber = null;
	var cartQty = null;
	if (null != document.getElementById('cartEntryNumber') && document.getElementById('cartEntryNumber') != '')
	{
		cartEntryNumber = document.getElementById('cartEntryNumber').value;
	}
	
	var entryQty = null;
	if (null !== document.getElementById('entryQty') && document.getElementById('entryQty') != '')
	{
		entryQty = document.getElementById('entryQty').value;
	}

	//disablePopup()
	resetAll(); //Initalize the Pop up
	var loadUrl = "/app/QuickViewController";
	var queryString = "productCode=" + variantCode;
	
	
	//get JSON object from controller
	$.getJSON(loadUrl + "?" + queryString, function(jsonObject) {
		renderQuickView(jsonObject, showSize, variantCode, cartMode, cartEntryNumber, entryQty);
	});
}

function getFromColorBox(spanObj, entryNumber, quantity) {
	var variantCode = spanObj.id; 
	var cartMode = spanObj.title;
	getQuickViewProduct(variantCode, cartMode, entryNumber, quantity);
	$("#pdpImage").attr('height','240');
	$("#pdpImage").removeAttr('width');
}

//Function for change main image on click of alteranate Image
function changeImage(alternateImage){	
	document.getElementById('pdefaultImage').src =	alternateImage;
	//loadImageForZoom(alternateImage);
}

function requestForgotPassword() {
	$("#forgetPassword").validate();
	$("#loginMain .msgError").css('display','none');
	if($("#forgetPassword").valid()){
		var email = document.getElementById("emailAddress").value;
		 $.ajaxSetup ({
		cache: false
		 });
		var loadUrl = "/app/view/ForgotPasswordController";
		var queryString = "email=" + email;
		$("#userDoesNotExistDiv .msgError").css('display','none');

		//get JSON object from controller
		$.getJSON(loadUrl + "?" + queryString, function(jsonObject) {
			if(jsonObject.success){
			 document.getElementById("sucessboxDiv").style.display = "block";
			 document.getElementById("forgetPassDiv").style.display = "none";
			 document.getElementById("userDoesNotExistDiv").style.display = "none";
			 document.getElementById("instructionDiv").style.display = "none";
			}
			else{			
				document.getElementById("userDoesNotExistDiv").style.display = "block";
				document.getElementById("sucessboxDiv").style.display = "none";
				document.getElementById("instructionDiv").style.display = "none";			
			}

			
		});
	}
	else{return false}
}
/**
 * Only submit the search-query if the searchterm is not the default search term and is not empty
 * @return
 */
function initializeOnMainSearchFormSubmit() {
	$('#mainsearchform').submit(function() {
		  var searchForm = $(this);
		  var defaultSearchFieldValue = searchForm.jSonComments().defaultSearchFieldValue;
		  var searchTextfield = searchForm.find('[name=searchterm]');
		  var currentSearchFieldValue = searchTextfield.val();
		  //alert('defaultSearchFieldValue: ' + defaultSearchFieldValue + ', currentSearchFieldValue: ' + currentSearchFieldValue.length);
		  if(currentSearchFieldValue == defaultSearchFieldValue || currentSearchFieldValue.length < 1) {
			searchTextfield.focus();
			return false;  
		  }
		  else {
			return true;  
		  }
		  
	});
}


function resetForgotPassword(){
	document.getElementById("emailAddress").value = "";
	document.getElementById("sucessboxDiv").style.display = "none";
	 document.getElementById("userDoesNotExistDiv").style.display = "none";
	document.getElementById("forgetPassDiv").style.display = "block";
	document.getElementById("instructionDiv").style.display = "block";
}


function clearAllWarnings(formId){
	
	$("#"+formId).find("label.error").html("");
	$("#"+formId).find(".subhead").html("");
}
