var aValue;
var nI = 0;
var aURLArguments = location.search.substring(1).split('&');
for (nI = 0; nI < aURLArguments.length; nI++) {
	aValue = aURLArguments[nI].split('=');
	if (aValue[0].toLowerCase() == 'srccode') {
		document.cookie = 'srccode=' + escape(aValue[1]) + ';domain=.bhphotovideo.com;expires=';
   	}
   	if (aValue[0].toLowerCase() == 'cpncode') {
		document.cookie = 'cpncode=' + escape(aValue[1]) + ';domain=.bhphotovideo.com;expires=';
    }
}

// Drop Down Navigation
function change(){
selected=document.dropdownnav.drop.selectedIndex;
loc=document.dropdownnav.drop[selected].value;
document.location=loc;
}

var compareSize = 0
var reloadCompareSize = true; // if user presses the back button to listing page, we dont have the comparison size

function setOnloadCompareSize() 

{
	DWRHelper.getUsersItemCompareSize( function( value ){ 
		compareSize = value; 
	} );
}

function setCompareSize( size ) {
	compareSize = size; 
}

function compareSubmit ()
{
    if  ( compareSize < 2 )
    {
        alert ( "Please check 2 or more items before clicking compare!" );
		return false;
    }
    else {
	   document.comparisonForm.submit();
	}
}

function addToCompare( categoryId, theElement )
{
	var array = theElement.name.split("_");
	sku = array[1];
	itemSource = array[2];

	if( theElement.checked )
	{
		if( reloadCompareSize )
		{
			DWRHelper.addToComparisonChart( categoryId, sku, itemSource, {
				callback: function( value ){
							 compareSize = value;
							 reloadCompareSize = false;
							 if( compareSize == 5 )
							 {
								compareSize = 4;
								rejectCompare( theElement );
							 }
							 else {
								 $(".comparisonForm input[name='items']").val( $(".comparisonForm input[name='items']").val() + ";" + sku + "-" + itemSource  );
							 }
						  },
				async:true
			});
		}
		else if( compareSize < 4 )
		{
			DWRHelper.addToComparisonChart( categoryId, sku, itemSource );
		    compareSize++;
			$(".comparisonForm input[name='items']").val( $(".comparisonForm input[name='items']").val() + ";" + sku + "-" + itemSource  );
		}
		else {
		    rejectCompare( theElement );
		}
	}
	else
	{
		 DWRHelper.removeFromComparisonChart( categoryId, sku, itemSource );
	     compareSize--;
		 $(".comparisonForm input[name='items']").val( $(".comparisonForm input[name='items']").val().replace(sku + "-" + itemSource,"")  );
	}
}

function rejectCompare( element )
{
	element.checked = false;
	alert ( "Sorry you can only compare up to 4 items " );
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

//Function called when clicking on close window in holiday closing popup. Hides the layer that the page is being called into.

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}


var origWidth, origHeight;
if (document.layers) {
	origWidth = window.innerWidth; origHeight = window.innerHeight;
	window.onresize = function() { if (window.innerWidth != origWidth || window.innerHeight != origHeight) history.go(0); }
}

var cur_lyr;
function swapLayers(id) {
  if (cur_lyr) hideLayer(cur_lyr);
  showLayer(id);
  cur_lyr = id;
}

function showLayer(id) {
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.display = "block";
}

function hideLayer(id) {
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.display = "none";
}

function getElemRefs(id) {
	var el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? document.layers[id]: null;
	if (el) el.css = (el.style)? el.style: el;
	return el;
}


/*var cur_lyrPromotion;
function PromotionLayers(id) {
  if (cur_lyrPromotion) hidePromotionLayer(cur_lyrPromotion);
  showPromotionLayer(id);
  cur_lyrPromotion = id;
}

function showPromotionLayer(id) {
  var lyrPromotion = getElemRefsPromotion(id);
  if (lyrPromotion && lyrPromotion.css) lyrPromotion.css.display = "block";
}

function hidePromotionLayer(id) {
  var lyrPromotion = getElemRefsPromotion(id);
  if (lyrPromotion && lyrPromotion.css) lyrPromotion.css.display = "none";
}

function getElemRefsPromotion(id) {
	var el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? document.layers[id]: null;
	if (el) el.css = (el.style)? el.style: el;
	return el;
}
*/



function changeOtherQuantityBox(q)
{
	if( q.id.indexOf('layer') != -1 )
		getElementRefs(q.id.substring( 'layer'.length ) ).value = q.value;
	else
	    getElementRefs('layer' + q.id).value = q.value;
}

var notesArray = [];
function isNotTheFirstTime(id) {
    for( i=0; i <= notesArray.length; i++ ) {
		if( notesArray[i] == id )
		    return true;
	}
	return false;
}

var mouseX = ""
var mouseY = ""
var iReturnValue =""

function popLayersSalesComment(id,type)
{
	if( type == 'addtocart' && isNotTheFirstTime(id) )
		 return true;
	else if ( !isNotTheFirstTime(id) )
		notesArray[notesArray.length]=id;

    showLayerSalesComment(id);
	return false;
}

/*function movelayer(event) {
		//alert(document.body.scrollTop)
		mouseX = event.screenY
		mouseY = event.screenX
		
	}*/

function getY( oElement )
{
iReturnValue = 0;
while( oElement != null ) {
iReturnValue += oElement.offsetTop;
oElement = oElement.offsetParent;

}
return iReturnValue;
}



function showLayerSalesComment(id) {
	var lyrSalesComment = getElemRefs(id);
		if(id=="map7"){
			 // document.getElementById(id).style.left = 79 + "%"
			 document.getElementById(id).style.left = 50 + "%";
			 document.getElementById(id).style.marginLeft = 298 + "px"
		}else{
            document.getElementById(id).style.left = 50 + "%"
		}
			//document.getElementById(id).style.top = (iReturnValue-25) + "px"
			if (lyrSalesComment && lyrSalesComment.css)  lyrSalesComment.css.display = "block";
  
}


function hideLayerSalesComment(id) {
  var lyrSalesComment = getElemRefs(id);
  if (lyrSalesComment && lyrSalesComment.css) lyrSalesComment.css.display = "none";
}


function submitAddToCart(id) {
    document.getElementById(id).submit();
}


$(document).ready(function(){
	
	$(".map9").hover(function () {
		$(this).parent("span").siblings("div.map7n9").show();
    },function(){
		$(this).parent("span").siblings("div.map7n9").hide();
	});
	
	$('#InstantRebateList').bhLayer({
		openerSelector: false,
		closerSelector: "#cannon-layer-close",
		modal: {center: true, overlayStyle:{zIndex : 8000}, moveToBottom: true}
	}).css({zIndex:'9900'});

	if($.browser.msie){
		$("#atcAtwLayer").bind("onAfterShow", function(){
			var layerBottom = $(this).offset().top + $(this).height() + 20;
		  $(this).parents(".productBlock").nextAll(".productBlock").each(function(){ 
			  if($(this).offset().top < layerBottom)
				  $(this).addClass("negativeZ");
			});
		}).bind("onBeforeHide", function(){
			$(".productBlock.negativeZ").removeClass("negativeZ");
		});
		
	}
	
	$('.cartLinkPrice').live('click', function() {
		$("#atcButton" + $(this).attr("data-href")).click();
		return false;
	});
	
	//removing a message that is set in PageBuilder to be placed only at bottom of listing page
	$('#messagingTopContainer .PBMessageBOTTOM').parent('#messagingTopContainer').remove();
	
	//sort by
	$('.selected').click(function(){$(this).nextAll('.options').show().end().addClass('active')})
	$('.sortMain,.displayMain').bind('mouseleave',function(){$(this).children('.options').hide().end().find('.active').removeClass('active')})
	
	//usedCondition Email
	$("#onePopupLayer").bhLayer().bind("onAfterShow",function(){
	    $("form.emailCond").validate({ 
	        	rules: {
	                retypeEmail: { 
	                    required: true,
	                    equalTo: "#emailAddress"
	                }
	        	},
	            errorPlacement: function(error,element){
	                    $(".error").show();
	              }
	        })
	});
});


// START Megillah
var openBub = false;
$(function(){
	$("#megillah").bhLayer({
		openerSelector: $("#megillahChupchick"),
		posParentSelector: ".tBlock",
		openerReturnFalse:true,
		showAnimation: function(){
			$(this).show();
			$("#megillahChupchick").effect("transfer", { to: "#megillah", className: 'megillah-transfer' }, 750, function(){
				$("#megillah").css("visibility", "visible");
			});
		},
		hideAnimation: function(){
			$(this).css("visibility", "hidden").effect("transfer", { to: "#megillahChupchick", className: 'megillah-transfer' }, 750, function(){
				$("#megillah").hide();
			});
		}
	}).one("onBeforeShow", function(){
		$("#megScrollable").scrollBox({
			cellWidth: 273,
			marginWidth: 10,
			scrolee: "#megScrollableInner"
		});   
		$(".megillaScrollButton").sliderButtons($("#megScrollable")).click(function(){
			myDelta = ($(this).data("arrow").arrowType == "left")? 849 : -849;
			$(this).data("arrow").slider.scrollBox("slide", myDelta, 425,  true);
		});
	});
	
	megillahBubble = $("#megillahBubble");
	var bubbleCount = 0;
	$("#megScrollableInner .megCatSection").each(function(index){
		if($(this).find("ul li").length > 1){
			bubbleCount++;
			$("#" + this.id.split("-")[0] + "-link").addClass("hasCatChildren");
		}
	});
	
	megillahBubble.bhLayer({
		openerSelector: false,
		posParentSelector: "body",
		moveToBottom: true,
		autoHide:false
	}).trackHover();
	$("#categories").delegate("li.hasCatChildren", "mouseenter", function(){
		if(bubbleClose)clearTimeout(bubbleClose);
		$("#catBlueNote").bhLayer("hide");
		var bubContent = $("#" + this.id.split("-")[0] + "-megCatSection");
		megillahBubble.find("h3 b").html(bubContent.find("h3").text());
		megillahBubble.find("#megillahBubbleMain").html(bubContent.find("ul").clone());
		megillahBubble.bhLayer("show");
		megillahBubble.position({
			of: $(this),
			my: "left top",
			at: "left top",
			offset: "150 -30",
			collision: "none none"
		});
	openBub = true;
	}).delegate("li", "mouseleave", function(){
		bubbleClose = setTimeout(closeBubble, 200);
	});
	if($.browser.msie){
		megillahBubble.bind("onAfterShow", function(){
			$("#megillahBubbleHead, #megillahBubbleMain ul").css("width", "auto");
			var biggestLi = 302;
			$("#megillahBubbleHead").each(function(){
				biggestLi = Math.max(biggestLi, $(this).outerWidth()+15);
				})
			$("#megillahBubbleMain li").each(function(){
				biggestLi = Math.max(biggestLi, $(this).outerWidth());
			});
			$("#megillahBubbleHead").width(Math.max(biggestLi + 4, $("#megillahBubbleHead").width() + 20));
			$("#megillahBubbleMain ul").width(biggestLi);
		});
	}
	$("#catBlueNote").bhLayer({openerSelector:false,modal:true}).delegate("#catBlueNoteNoShow", "click", function(e){
		$("#catBlueNote").bhLayer("hide");
		$.cookie('blueNoteNoShow', true, { path: '/',domain: 'bhphotovideo.com', expires: 30 });
		return false;
	});
	$("#backToTopLink").click(function(){
		$($.browser.webkit? "body" : "html").animate({scrollTop: 0});
		return false;
	});
	setTimeout('$("#catBlueNote").bhLayer("show")', 2000);
	
});
function closeBubble(){
	if(! megillahBubble.hasClass("hover-active")){
		if(openBub){
			megillahBubble.bhLayer("hide");
			openBub = false;
		}
		
	}else{
		megillahBubble.one("mouseleave", function(){
			bubbleClose = setTimeout(closeBubble, 200);
		});
	}
}
$.fn.trackHover = function(){
	this.hover(function(){$(this).addClass("hover-active");},function(){$(this).removeClass("hover-active")});
}
bubbleClose = 0;
var megillahBubble;

// END Megillah

//start "Offer Similar Items"
$(function(){
	$("div.similarItem a").hover(function(){
		$("div.similarItem a span").css("color","#0462be");
	}, function(){
		$("div.similarItem a span").css("color","#595959");
	});
	
	$("div.similarItem").addClass("si_map");
	var si = $("div.similarItem a span");
	for(ss = 0; ss < si.length; ss++) {
		$(si[ss]).closest('div.similarItem').removeClass("si_map");
	}
});
//end "Offer Similar Items"

