// JavaScript Document
$(function(){
	$(".noLayer").click(function(){
		var selectedPlan = $(".protectionPlans  input[name|=protectionPlans]:checked").val();
		if(selectedPlan.length) $("#warranty").val(selectedPlan);
	});
	hoverImagesCount = $("#smallScroller .smImgLink").length;
	if(hoverImagesCount){
		if(hoverImagesCount <= 5)
			$("#smallScroller .scrollableArea").css("margin-left", ((325 - (hoverImagesCount * 65)) / 2) + "px");
		else{
			$("#smallScroller .scrollableArea").data("scrolled", 0).data("maxScroll", - hoverImagesCount * 65 + 320)
			.bind("slideDiv", function(e, delta){
				var proposedScroll = $(this).data("scrolled") + delta;
				if(proposedScroll > 0){
					proposedScroll = 0;
					$("#smallScroller .scrollingHotSpotLeft span").hide();
					$("#smallScroller .scrollingHotSpotRight span").css("display","block");
				}
				else if(proposedScroll < $(this).data("maxScroll")){
					proposedScroll = $(this).data("maxScroll");
					$("#smallScroller .scrollingHotSpotRight span").hide();
					$("#smallScroller .scrollingHotSpotLeft span").css("display","block");
				}else $("#smallScroller .scrollingHotSpot span").css("display","block");
				$(this).data("scrolled", proposedScroll).animate({marginLeft: proposedScroll + "px"}, Math.abs(delta * 2));
			});
			$("#smallScroller .scrollingHotSpot span").hover(function(){
			 	if($(this).is(".scrollingHotSpotRight span")) scrlDelta = -3;
				else scrlDelta = 3;
				scrMouseIn = setInterval("$('#smallScroller .scrollableArea').trigger('slideDiv', [" + scrlDelta + "])", 6);
			},function(){
				window.clearInterval(scrMouseIn);
			});
			$("#smallScroller .scrollingHotSpotRight span").css("display","block");
			
			
			
			/*$("#smallScroller .scrollableArea").trigger("slideDiv", [-30]);*/
		}
		$("#smallScroller .scrollableArea").delegate("a.smImgLink", "mouseover", function(){	
				$("#mainImage").attr("src", $(this).find("img").attr("src").replace("smallimages", $("div.mainImgContainer").hasClass("smallProductImage")? "images150x150" : "images345x345"));				
			if($("#fluid").length == 0) $("a#imagelink, a#enlargeLink").attr("href", this.href);
		}).delegate("a.smImgLink", "click", function(){
			return false;
		});
	}
	//MAP9
	$(".map9Msg").bhLayer({hover: {hide:250, clickToKeepOpen:false},posParentSelector:"body"});
	
	if($.trim($("#includesFree").text()).length  > 150)
		$("#includesFree").html("<li>" + $("#includesFree").text() + "</ li>");
	$(".seeMore").click(function(){
		$(this).siblings(".hiding").show().removeClass("hiding");
		$(this).remove();
	});
		
	$("#productInfo .findLast:last").addClass("last");	
	$(".findLast > *:last-child").addClass("last");
	if($("#logoReplacement").length){
		$("#productHeadingCC").width(930 - $("#mfrLogo").width() - $("#productHeadingTopRight").width());
	}
	var popupNumber = 0;
	$(".openInPopup").click(function(){
		 var popSize;
		if(this.target.indexOf("cust") == 0)
			popSize = this.target.split("X");
		else{
			if(this.target == "") this.target = "popUpNumber" + popupNumber++;
			popSize = [this.target,300,500,"yes"];
		}
		return widgets.popup(this, popSize[0], "width=" + popSize[2] + ",height=" + popSize[1] + ",scrollbars=" + popSize[3]);
	});	
	$("#fluid").bhLayer({
		openerSelector: "sibling #enlargeLink",
		posParentSelector: "#productTop",
		modal: true
	}).bind("onBeforeShow", function(){
		if($.browser.msie)	$(this).css("left", "12em");
		else $(this).find("embed").attr("wmode", "transparent");
	});
	$("#imagelink.linkForFluid").click(function(){$("#fluid").bhLayer("show");return false;});
	$("#onePopupLayer").bind("onAfterShow", function(){
		if($(this).data("currContent") == "warrantyLayer"){
			if($("#productCartOptions .inCartButton").is(":hidden")){
				var selectedPlan = $(".protectionPlans  input[name|=protectionPlans]:checked").val();
				if(typeof(selectedPlan) == "string" && selectedPlan.length){
					$(this).find(".popLayerMainContent .notInCartWarranty .addplan[rel|=" + selectedPlan + "]").addClass("removePlan");
				}
				$(this).find(".popLayerMainContent .notInCartWarranty .addplan").click(function(){
					if($(this).hasClass("removePlan")){
						$(".protectionPlans input[name|=protectionPlans]:last").click();
					}else{
						$(".protectionPlans input[value|=" + this.rel + "]").click();
					}
				});
			}else{
				$(".notInCartWarranty").hide();
				$(".inCartWarranty").show();
			}
		}
	});	
	/* nav */
	if( $("#nav2 li").length > 1 ) {
		
		$("#nav2").show();
	}
	
	$( "#tabs" ).tabs({
		"select" : function(event, ui) {
			$("#nav2 .botSelected").removeClass("botSelected");
			$("#nav2 li:eq(" + ui.index + ")").addClass("botSelected");
			return;
		},
		"show" : function(event, ui){
			removeDblNavs();
			var $tab = $(ui.tab)
			if($tab.attr("data-tabclass")){
				$(ui.panel).addClass($tab.attr("data-tabclass"));
			}
			return;
		},
		"load" : initAcc, 
		cache: true,
		spinner: "<em>Loading&#8230; &nbsp; &nbsp;<img src='/images/loading.gif'></em>"
	});
	

	$("#nav2").delegate("a", "click", function(){
		$( "#tabs" ).tabs("select", $("#nav2 li").index($(this).parent())).scrollTo(400,5);
		return false;
	});
	if($("#BottomRightBar").height()){
		$("#dady").css("min-height", $("#BottomRightBar").height() - 53 + "px");
	}
	/*opening the first tab
	if($("#nav").find("li.current").length){
		$("#nav > li.current").find("a").click();
	}else{
		$("#nav > li:first").find("a").click();		
	}*/
	/* end nav*/
	$(".featureNote").bhLayer();
	$("#readReviewsLink, #readReviewsLink2").click(function(e){
		e.preventDefault();
		$("#tabs").scrollTo(750, 0,function(){$( "#tabs" ).tabs("select", "#costumerReview")});
		return false;
	});
	$(".localScroller").live("click",function(e){
		var targetId = this.rel;
		var accTabSelector = $("#navAccessories a").attr("href");
		var $AccTab = $(accTabSelector);
		var miniParent = $(this).closest(".miniAcc");
		$AccTab.one("accReady", function(){
		var targetElem = $("#" + targetId);
			targetElem.closest(".accGroup").removeClass("collapsed");
		targetElem.scrollTo(750,75);
		if(! $("#more" + targetId+':visible').length){
			$("#show" + targetId).click()
		}
		miniParent.effect("transfer", { to: "#accGroup" + targetId, className: 'ui-effects-transfer' }, 750);
			return;
		});
		if($AccTab.html().length){
			$("#tabs").tabs("select", accTabSelector);
			$AccTab.trigger("accReady");
			return false;
		}
		var $clickedLink = $(this);
		$clickedLink.loading();
		$("#navAccessories a").data("href.tabs",this.href).data("load.tabs",this.href);
		$("#tabs").bind("tabsload.accLoaded", function(e, ui){
			if($(ui.panel).hasClass("bigAccessories")){
				$AccTab.trigger("accReady");
				$clickedLink.stopLoading();
				$(this).unbind("tabsload.accLoaded");
			}
			return;
		}).tabs("select", accTabSelector);
		return false;
	});
	$("#bottomRightBarHead").delegate("a", "click", function(e){
		if((! $(this).hasClass("active-tab")) && $("#bottomRightBarHead").hasClass("hasTabs")){
			$("#bottomRightBarHead").after($($(this).attr("href")));
			$(this).addClass("active-tab").siblings().removeClass("active-tab");
		}
		return false;	
	});
	$("#viewAllAccessories a").click(function(){
		$("#navAccessories a").click().scrollTo(750);
		return false;
	});
	
	$(".KitLink a").click(function(e){e.preventDefault()});
	$("#hdslrBtn").click(function(){
		var showHDSLR = function(){
		$("#divHDSLR_GROUP").children(".accGroup").removeClass("collapsed");
		goToAccessoryLabel("HDSLR_GROUP");
			return;
		}
		var accTabSelector = $("#navAccessories a").attr("href");
		if ($(accTabSelector).html().length){
			showHDSLR();
			return;
		}
		var $clickedLink = $(this);
		$clickedLink.loading();
		$("#tabs").bind("tabsload.accLoaded", function(e, ui){
			if($(ui.panel).hasClass("bigAccessories")){
				showHDSLR();
				$clickedLink.stopLoading();
				$(this).unbind("tabsload.accLoaded");
			}
			return;
		}).tabs("select", accTabSelector);
		return;
	});
	
	$('#InstantRebateList').bhLayer({
		openerSelector: false,
		closerSelector: "#cannon-layer-close",
		modal: {center: true, overlayStyle:{zIndex : 8000}, moveToBottom: true}
	}).css({zIndex:'9900'});
	
	if($.browser.msie){
		ajaxLoaderLayer.bind("onAfterShow", function(){
			$(".CCLPlogo").css("position", "static");
		}).bind("onBeforeHide", function(){
			$(".CCLPlogo").css("position", "relative");
		});
	}
	
	$('.cartLinkPrice').live('click', function() {
		document.getElementById( $(this).attr("data-href") ).click();
		return false;
	}); 
	/* Messaging for BKO */
	$("#CommentNote").bhLayer();
	
});/*End $(function())*/
jQuery.fn.removeIfEmpty = function(){
	if(! $.trim(this.html()).length) this.remove()
	return this;
}
function showAccessoriesTab() {
console.log("tell weisz to fix this");
	/*swapLayers('accessories');
	setSrc(document.getElementById('tab_accessories'));
	window.location.hash = "#accessories";*/
}
function goToAccessoryLabel(id) {
	$("#navAccessories a").click();
	$("#div" + id).scrollTo(1500,75);
	if(! $("#more" + id).length){
		$("#show" + id).click()
	}
}
//start Glossary 
function createGloss(targetDivID, defFile){
	targetCollection = $("#" + targetDivID + " *").not("a");  // cache jquery collection of items to add definitions to.
		$.get(defFile,  function(data){ // use ajax to get definitions file
			$(data).find("name").each(function(){ //run for all definition names
				 //case insensitive (i) and  global (g) regex (the parentheses give us a reference to the original string ($1).)
				var regex = new RegExp("\\b(" + $(this).text() + ")\\b", "ig");
				targetCollection.replaceText(regex , "<span class='dictDef undefinedDef'>$1</span>"); //jquery plugin does the replacing for us
			});
			
			$("#" + targetDivID + " span.dictDef").removeNested("span.dictDef"); // custom jquery plugin
			$("#" + targetDivID).delegate("span.undefinedDef", "mouseover", function(){
				var myText = $(data).find("name").textEquals($(this).text()); // custom plugin 
				var defText = myText.siblings("desc").text();
				$(this).removeClass("undefinedDef")
					.append("<div class='smallLayer'><h5>" + myText.text() + "</h5><p>" + defText + "</p><span class='close'>close</span></div>")
					.find(".smallLayer").bhLayer({modal:true, hover:{show:750,hide:1500}})
					.bind("onBeforeShow", function(){$(this).parent().addClass("active")})
					.bind("onAfterHide", function(){$(this).parent().removeClass("active")})
					.trigger("mouseenter");
			});
		},"xml");
	
	
}
//custom plugin to recursively remove extra tags of the same type
$.fn.removeNested = function(selector){
	this.find(selector).each(function(){ // stop the madness - when the collection returned is empty the recursion stops
		$(this).removeNested(selector); // recursive call
		$(this).replaceWith($(this).text()); // doin my thing
	}); 
	return this;
}
$.fn.textEquals = function(text){
	this.each(function(){
		if($(this).text().myStandard() == text.myStandard()) rv = $(this);
	});
	return rv;
}

/*String.prototype.myStandard = function(){
	alert(this);
	return this.toLowerCase().replace( /[^a-z0-9]/g, "");
}*/
$.extend(String.prototype, {myStandard :function(){
	return this.toLowerCase().replace( /[^a-z0-9]/g, "");
}});
/*
 * jQuery replaceText - v1.1 - 11/21/2009
 * http://benalman.com/projects/jquery-replacetext-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){$.fn.replaceText=function(a,b,c){return this.each(function(){var e=this.firstChild,g,d,f=[];if(e){do{if(e.nodeType===3){g=e.nodeValue;d=g.replace(a,b);if(d!==g){if(!c&&/</.test(d)){$(e).before(d);f.push(e)}else{e.nodeValue=d}}}}while(e=e.nextSibling)}f.length&&$(f).remove()})}})(jQuery);






var currentIncludesObj = null;
var testIfContentInPage = "";
function expandClose(id,sku,itemSource, sync) 
{
	var jqueryId = $("#"+id);
	var clickedElem = jqueryId.prev("li");
	var objid;
	var tab;
	var kitDetails = document.getElementById(id).className;
	
	var patt1=/kitFeatures|kitSpecs/i;
	var property = kitDetails.match(patt1).toString();
	switch(property){
		case 'kitFeatures':
			tab = $("#Overview");
			objid = "getFeatures";
			break;
		case 'kitSpecs':
			tab = $("#Specification");
			objid = "getSpecifications";
			break;
		default:
			alert("error");
			return false;
		}
	
	
	if(jqueryId.is(":visible")){
		jqueryId.hide();
		clickedElem.removeClass("KitLinkHover").addClass("KitLink");
		removeDblNavs();
		return false;
	}
	tab.find(".KitLinkHover").removeClass("KitLinkHover").addClass("KitLink");
	tab.find(".Kdetail").hide();
	jqueryId.fadeIn();
	clickedElem.addClass("KitLinkHover");
	clickedElem.removeClass("KitLink");
	   
	if(testIfContentInPage.indexOf(id) == -1)
	{
		dwr.util.setEscapeHtml(false);
		if(sync)
			dwr.engine.setAsync(false);
		
		clickedElem.loading();
		eval("DWRHelper." + objid)( sku, itemSource,
			function(value){
				dwr.util.setValue(id, value);
				activateJumpLinks(jqueryId);
				jqueryId.find(".specNote .smallLayer").bhLayer({modal:true,openerReturnFalse:true});
				removeDblNavs();
				clickedElem.stopLoading();
			}
		);
		testIfContentInPage += id + ",";
	}else removeDblNavs();
}

$(function(){
	$("div.similarItem a").hover(function(){
		$(".similarItem a span.description").css("text-decoration", "underline");									
	}, function(){
		$(".similarItem a span.description").css("text-decoration", "none");	
	});
});

$(function(){
	var one = $(".similarItem a span.brand").text();
	var two = $(".similarItem a span.description").text();
	var three = $(".similarItem a span.red").text();
	
	one = one.replace(/\s\s+/g, '');
	$(".similarItem a span.brand").html(one);
	two = two.replace(/\s\s+/g, '');
	$(".similarItem a span.description").html(two);
	three = three.replace(/\s\s+/g, '');
	$(".similarItem a span.red").html(three);
		   
	var oneText = $(".similarItem a span.brand").text().length;
	var twoText = $(".similarItem a span.description").text().length;
	var threeText = $(".similarItem a span.red").text().length;
	
	var total = oneText + twoText + threeText;
	
	if (total > 45)
	{
	var calTotal = total - 45;
	var twoAllowed = twoText - calTotal - 3;
	var visibleText = $(".similarItem a span.description").text().substring(0, twoAllowed);
	var hiddenText = $(".similarItem a span.description").text().substring(twoAllowed);
	$(".similarItem a span.description").html(visibleText + '<span style="display:none;">' + hiddenText + '</span>');
	
	$(".similarItem a span.description").append("...");
	};
});

function removeDblNavs(){
	if ($("#dady >div:visible").height() < $(window).height()){
		$("#nav2").hide();
	}else{
		$("#nav2").show();
	}
}
