//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Home Page JS
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//Document Ready +++++
$(function() {			
	globalInitiateJavascript("");
});
function globalInitiateJavascript(scope){
	//convert submit buttons to links
	globalConvertSubmitToLinks(scope);
	
	//Preload Images
	//var img1 = $("<img />").attr("src", "../ui/images/radio-on.jpg");
	
	//Click Action for the Buttons
	$("a.go,a.subscribe").mousedown(function() {
		$(this).css({ backgroundPosition: 'right top'})
		}).mouseout(function() { $(this).css({ backgroundPosition: 'left top'})
		}).mouseup(function() { $(this).css({ backgroundPosition: 'left top'})
	});
	//Search text style toggle
	$("#search").focus(function(){
		if($(this).val() == "Search..." || $(this).val() == ""){ $(this).val(""); $(this).addClass("focus");	 }
	});	
	$("#search").blur(function(){
		if($(this).val() == ""){ $(this).val("Search..."); $(this).removeClass("focus"); }
	});
	//Newsletter text style toggle
	$("#newsletter,#comingsoon").val("Enter your email address...");
	$("#newsletter,#comingsoon").focus(function(){
		if($(this).val() == "Enter your email address..." || $(this).val() == ""){ $(this).val(""); $(this).addClass("focus");	}
	});	
	$("#newsletter,#comingsoon").blur(function(){
		if($(this).val() == ""){ $(this).val("Enter your email address..."); $(this).removeClass("focus"); }
	});
	//Drop Menus +++++++++++++++++++
	$("#parts").mouseenter(function() {		
		//Hide the other menu in case it's open
		$("#accessories-menu").hide(); 
		//Show the Parts Menu
		$("#parts-menu").fadeIn("fast");	
				
		$("#parts").mouseleave(function() {	
				//Hide the Parts Menu
				$("#parts-menu").fadeOut("fast");	
				$("input#search").mouseenter(function(){
					$("#parts-menu").fadeOut("fast");	
				});
		});		
	});	
	$("#accessories").mouseenter(function() {	
		//Hide the other menu in case it's open
		$("#parts-menu").hide(); 
		//Show the Accessories Menu
		$("#accessories-menu").fadeIn("fast");
		
		$("#accessories").mouseleave(function() {
			//Hide the Accessories Menu
			$("#accessories-menu").fadeOut("fast");	
			$("input#search").mouseenter(function(){
				$("#accessories-menu").fadeOut("fast");	
			});				
		});		
	});	
	//Clicking a "View Our Price" link on a Product Listing Page
	$(".view-price").click(function(){
		$(this).hide();
		$(this).prev().show();
		$("#product-discount-code-tweak").hide();
		return false;
	});
	//Don't need this for the "Get Sales Price" example
	$(".product-view-price").click(function(){
		$(this).hide();
		$(this).next().show();
		//$("#product-discount-code").hide();
		return false;
	});	
	//Discount Code Entry on Product Page
	$("#discount-code").keyup(function(){		
    	if($(this).val().toLowerCase() == "low"){
	    	setAlertMessage("error","",1);	
    		$(".product-view-price-code").hide();
    		$(".tag-our-price").show();
			$(".tag-msrp").wrapInner("<del></del>");
    		$("#product-discount-code").hide(); 
			var hidden=$("<input>").attr({"type":"hidden", "name":"RespMAP", "value":1, "className":"hide"});
			$("input[name=PNum]").after(hidden);			
			$.ajax({url: "/markRespMap.php", datatype: 'html', type:'GET'});									
    	}else if($(this).val().length>=3){
			setAlertMessage("error","That is an incorrect code",1);
		}
    });
    //Discount Code Entry on Part Replacement Page
	$(".discount-code-tweak").keyup(function(){
    	if($(this).val().toLowerCase() == "low"){ 	    	
    		$(".view-price-resp").hide();
    		$(".our-price").show();
    		$(".parts-msrp").wrapInner("<del></del>");
    		$(".product-discount-code-tweak").hide(); 
			var hidden=$("<input>").attr({"type":"hidden", "name":"RespMAP", "value":1, "className":"hide"});
			$("#submitButton").after(hidden);
			$.ajax({url: "/markRespMap.php", datatype: 'html', type:'GET'});
    	}
    });
    //Discount Code Style Toggle
	$("#discount-code,.discount-code-tweak").val("Discount Code..."); //Reset
	$("#discount-code,.discount-code-tweak").focus(function(){
		if($(this).val() == "Discount Code..." || $(this).val() == ""){ $(this).val(""); $(this).addClass("focus");	 }
	});	
	$("#discount-code,.discount-code-tweak").blur(function(){
		if($(this).val() == ""){ $(this).val("Discount Code..."); $(this).removeClass("focus"); }
	});


	//Product Page "Product Images" Changer
	$("#tiny-product-images li a").mouseenter(function(){
		$("#product-"+$(this).attr("id")).parent().siblings().children("img").hide(); //Hide the other images
		$("#product-"+$(this).attr("id")).show(); //Show the product # that got moused over
	});
	//Extra Info Selection Changer
	$("#extra-info li a,.learning-center-details li a").click(function(){
		if($(this).text() == $("#extra-info li:first a").text()){ $("#extra-info li:first a").parent().removeClass("fix-left-border"); } else{ $("#extra-info li:first a").parent().addClass("fix-left-border"); } //This fixes a missing left border on the first <li>
		$(this).parent().siblings().removeClass("selected");
		$(this).parent().addClass("selected");
		$("#"+$(this).attr("id").substring(10)).siblings().hide();
		$("#"+$(this).attr("id").substring(10)).show()
		return false;
	});
	
	$("#stars-link-review").click(function() {		
		$("#extra-info li a,.learning-center-details li a").parent().siblings().removeClass("selected");	
		$("#click-for-reviews-tab").parent().addClass("selected");
		$("#reviews-tab").siblings().hide();
		$("#reviews-tab").show();				
	});
	
	globalMakeModals();
	//My Replacement Parts Section Toggle
	$(".my-masks").click(function(){ 
		$(".my-parts-masks").show(); $(".my-parts-machines").hide(); $(".my-parts-humidifiers").hide();
	});
	$(".my-machines").click(function(){ 
		$(".my-parts-masks").hide(); $(".my-parts-machines").show(); $(".my-parts-humidifiers").hide();
	});
	$(".my-humidifiers").click(function(){ 
		$(".my-parts-masks").hide(); $(".my-parts-machines").hide(); $(".my-parts-humidifiers").show();
	});
	//Replacement Parts +++++++++++++++++++++++++++++++++++++++
	$(".part-swap").mouseenter(function(){
		$("#main-swap").attr("src",$(this).attr("mouseoverimage"));
	});
	$(".part-swap").mouseleave(function(){
		$("#main-swap").attr("src",$("input[type=hidden][name=mainimagesrc]").val());
	});
	
	//Shop by Brand +++++++++++++++++++++++++++++++++++++++
	$("#brand-select ul li a").click(function(){
		$("ul.popular-brands li").removeClass("selected");
		$(this).parent().addClass("selected");
		$("#brand-select-brand").text($(this).text());
		$("#categories li").hide();
		var allcats=$(this).attr("forcats").split(",");
		for(eachCat in allcats){
			$("#cat-"+allcats[eachCat]).show();
			var tempurl=$("#cat-"+allcats[eachCat]+" a").attr("href");
			var pos=tempurl.indexOf("brands=");
			$("#cat-"+allcats[eachCat]+" a").attr("href",tempurl.substr(0,pos+7).concat($(this).attr("mnid")));
		}
		$("#brand-select-category").show();
		return false;
	});
	//Clear Form Error +++++++++++++++++++++++++++++++++++++++
	$(".close").click(function(){
		$(this).parent().slideUp("fast");
		setAlertMessage($(this).parents("div").attr("id"),"",1);
		return false;
	});
	$(".print,.print-on-gray").show();
	//Print Button
	$(".print,.print-on-gray").click(function(){
		if($(this).attr("target")!="_blank"){
			window.print();
			return false;
		}
	});
	//compare window open
	$(".popupCompare").click(function(e){
		e.preventDefault(e);
		comparecharts = window.open ($(this).attr("href"),"comparecharts","location=no,status=no,scrollbars=yes");
		  comparecharts.moveTo(0,0);
		  comparecharts.resizeTo(screen.width,screen.height);
	});
	//compare chart definitions
	$(".description").mouseenter(function(){
		$(this).next().children(".description-popup").show();
		$(this).next().children(".description-popup").removeClass("hide");
	});
	$(".description").mouseleave(function(){
		$(this).next().children(".description-popup").hide();
	});
	//google tracking ++++++++++++++++++++++++++++++++++++++++
	$("a[type=track]").click(function(){
		if($(this).attr("trackUrl")!=undefined){
			pageTracker._trackPageview($(this).attr("trackUrl"));
		}
	});
}
//Format the total number
function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
	var x = Math.round(num * Math.pow(10,dec));
	if (x >= 0) n1=n2='';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - dec; if (z<0) z--;
	for(var i = z; i < 0; i++) y.unshift('0');
	if (z<0) z = 1; y.splice(z, 0, pnt); if(y[0] == pnt) y.unshift('0');
	while (z > 3) {z-=3; y.splice(z,0,thou);}var r = curr1+n1+y.join('')+n2+curr2;return r;
}
//generate a random string len chars long
function globalRandomString(len){
	var charset = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY";
	var pass = "";
	for (var i=0;i<len;i++){
		pass += charset.charAt(Math.floor(Math.random()*charset.length));
	}
	return pass;
}
function in_array(obj, arr) {
  for(var i=0; i<arr.length; i++) {
    if (arr[i] == obj) return i;
  }
  return -1
}
function globalMakeModals(){
	//Modals +++++++++++++++++++++++++++++++++++++++
	$(".modal-open").click(function(e) {
		e.preventDefault(e);
		var getchar='?';
		if(this.href.indexOf("?")!=-1){
			getchar="&";
		}

		$.modal('<iframe name="modaliframe" id="modaliframe" frameborder="0" src="' + this.href + getchar + 'lightframe=1" />',{ onShow: function() { $(".simplemodal-container").append('<div class="modal-top-left"></div><div class="modal-top-right"></div><div class="modal-bottom-left"></div><div class="modal-bottom-right"></div><div class="modal-background-right"></div><div class="modal-background-left"></div>'); }, overlayClose:true });
		//$("#modaliframe").load(resizeModal2);
		//resizeModal();
	});
	//Close Modal
	$(".modal-close").click(function() {
		parent.$.modal.close();
	});
	//Links inside a modal that point the parent to another page ++++++++++
	$(".go-to").click(function() {
		parent.location.href = $(this).attr("href");
		parent.$.modal.close();
		return false;
	});
	$(".modal-small-open").click(function(e) {
		e.preventDefault(e);
		var getchar='?';
		if(this.href.indexOf("?")!=-1){
			getchar="&";
		}
		$.modal('<iframe id="modaliframe-small" frameborder="0" src="' + this.href + getchar + 'lightframe=1" />',{ onShow: function() { $(".simplemodal-container").append('<div class="modal-top-left"></div><div class="modal-top-right"></div><div class="modal-bottom-left"></div><div class="modal-bottom-right"></div><div class="modal-background-right"></div><div class="modal-background-left"></div>'); }, overlayClose:true, containerId:'simplemodal-container-small' });
	});
}
function globalConvertSubmitToLinks(scope){
	if(scope!=""){
		scope+=" ";
	}
	$(scope+"input[type=submit]").each(function(){
		while($(this).parents("form").attr("name")==""){
			var newname=globalRandomString(10);
			if($("form[name="+newname+"]").attr("name")==undefined){
				$(this).parents("form").attr("name",newname);
			}
		}
		if($(this).val()==""){
			$(this).val("submit");
		}
		if(!$(this).attr("className")){
			$(this).attr("className","buy");
		}
		var anchor = $('<a>').attr({href: '#', name: $(this).attr("name"), className: $(this).attr("className"), submitval: $(this).val()});
		if($(this).attr("tabIndex")!=0){
			anchor.attr("tabIndex", $(this).attr("tabIndex"));
		}
		anchor.click(function(){
			if ($(this).parents("form").find("input[name=submitVal]").length == 1) {
				$(this).parents("form").find("input[name=submitVal]").val(($(this).attr("submitval")));	
			}
			$(this).parents("form").submit(); 
			return false;
		});
		anchor.html('<span>'+$(this).val()+'</span>');
		$(this).after(anchor);
		$(this).hide();
	})
}
//Dynamic Modal Resizing
function resizeModal() {
		//Get the modal's height after it has rendered
		window.parent.$("#modaliframe").height(10); 
		var h = $(document).height();
		//Get the parent window's viewport height
		var parentHeight = typeof window.parent.innerHeight != 'undefined' ? window.parent.innerHeight : window.parent.document.body.offsetHeight;
		//Set a new modal container height and iframe height according to the modal's contents
		window.parent.$("#simplemodal-container").height(h+80); 
		window.parent.$("#modaliframe").height(h+50); 
		//Reposition the modal on the screen according to its new height
		modalHeight = h + 80;
		var fromTop = ((parentHeight - modalHeight) / 2);
		window.parent.$("#simplemodal-container").css("top", fromTop + "px");
}
//Dynamic Modal Resizing
function resizeModal2() {
		//Get the modal's height after it has rendered
		var h = $(document).height();
		//Get the parent window's viewport height
		var parentHeight = typeof window.parent.innerHeight != 'undefined' ? window.parent.innerHeight : window.parent.document.body.offsetHeight;
		//Set a new modal container height and iframe height according to the modal's contents
		window.parent.$("#simplemodal-container").height(h + 80); 
		window.parent.$("#modaliframe").height(h + 50); 
		//Reposition the modal on the screen according to its new height
		modalHeight = h + 80;
		var fromTop = ((parentHeight - modalHeight) / 2);
		window.parent.$("#simplemodal-container").css("top", fromTop + "px");
}
function setAlertMessage(alerttype,message,overwrite){
	if(window.parent.$("#"+alerttype+"-text").length>0){
		var alerttext=window.parent.$("#"+alerttype+"-text");
		var alertdiv=window.parent.$("#"+alerttype);
	}else{
		var alerttext=$("#"+alerttype+"-text");
		var alertdiv=$("#"+alerttype);
	}
	if(message!="" && message.substr(-4).toUpperCase!="<BR>"){		
		message+=($.browser.msie?"<BR>":"<br>");
	}
	if(overwrite!=1){
		var currenttext=alerttext.html();
		if(currenttext.indexOf(message)==-1){
			message=currenttext+message;
		}else{
			message=currenttext;
		}
	}	
	alerttext.html(message);	
	if(message==""){				
		alertdiv.hide();
				
	}else{
		alertdiv.slideDown();
	}
}
function removeAlertMessage(alerttype,message){
	if(window.parent.$("#"+alerttype+"-text").length>0){
		var alerttext=window.parent.$("#"+alerttype+"-text");
		var alertdiv=window.parent.$("#"+alerttype);
	}else{
		var alerttext=$("#"+alerttype+"-text");
		var alertdiv=$("#"+alerttype);
	}
	if(message!="" && message.substr(-4).toUpperCase!="<BR>"){
		message+=($.browser.msie?"<BR>":"<br>");
	}
	message=alerttext.html().replace(message,"");
	alerttext.html(message);
	if(message==""){
		alertdiv.hide();
	}else{
		alertdiv.slideDown();
	}
}
function markErrorField(field){
	$(field).addClass("input-error");
}

// ajax the subscribe button at the bottom of the page..
$(function() {		
	$("form[id=newsletter-form]").submit(function()
	{ 
		$.post("newsletter_in.php", { "email": $("#newsletter").val(), "ajax": 1 }, 
			function(data) {				
				setAlertMessage("success","",1);	
				setAlertMessage("error","",1);	
				var data_arr = data.split("|");
				var result = parseInt(data_arr[0]);
				var message = data_arr[1];		
				var pathname = window.location.pathname;				
				pageTracker._trackPageview("Newsletter/Footer/"+pathname);
				if (result == 1) {
					$("#newsletter-modal-open").attr("href","/newsletter_in_confirm.php?email="+$("#newsletter").val());
					$("#newsletter-modal-open").click();
				}
								
				if (message!="")
				{			
					setAlertMessage(result==1?"success":"error",message,1);	
					if (result==1) $("#email_newsletter").val("");
				}
			}
		);	
		return false 
 	});
});
