// _projectors.js
//
// Support code for feature search
// Requires JQuery

// Init form
$(document).ready(initApp);

function initApp() {
	$("#projectorsForm select").change(selChangeHandler);
	$("#projectorsForm .cust input").keydown(restrictCharEventHandler);
	$("#projectorsForm input:checkbox").click(function(){
		if($("#autoRefresh").attr("checked")) {
			$("#projectorsForm").submit();
		}
	});

	$("#expandLink1,#expandLink2").click(function() {
		$("#expandSec").toggle();
		$("#moreOpts").toggle();
	});
	$("#expandLink1").click(function() {
		$("#expHiddenInput").removeAttr("disabled");
	});
	$("#expandLink2").click(function() {
		$("#expHiddenInput").attr("disabled","disabled");
	})

	$("#projectorsForm .cust label").click(labelClickHandler).attr("title","Click to return to the option list");
	
	$(".addToFav a").mouseover(function() {
		$(this).toggleClass("active");
	})
	.mouseout(function() {
		$(this).toggleClass("active");
	});
	
	$("#autoRefresh").click(function(){
		if ($("#autoRefresh").attr("checked")) {
			var expireDate = new Date ("September 28, 1982");
		}
		else {
			var expireDate = new Date ("September 28, 2035");
		}	
		var gmt = expireDate.toGMTString();
		document.cookie="disable_auto_refresh=1;expires="+gmt+";domain=.projectorcentral.com";
	});
	
	$("<div>").attr("id","glossTip").css("position","absolute").click(hideGlossaryDef).appendTo(document.body).hide();
	
	$("a.gloss").click(showGlossaryDef).each(function() {
		$(this).data("glossDef",$(this).attr("title")).attr("title","Click to view an explanation for this item");
	});

	$(document.body).mousedown(hideGlossaryDef);
	$(document.body).mousedown(function() {
		$("#helpMessage").hide();
	});
	
	$("#projectorsForm").submit(projectorsFormSubmitHandler);
	
	$("#srchHelp").mousedown(function(e) {
		e.preventDefault();
		e.stopPropagation();
	});
	
	$("#srchHelp").bind("click", function(e) {
		$("#helpMessage").show(100);
		e.preventDefault();
		return false;
	});
	$("#closeHelp").bind("click", function(e) {
		$("#helpMessage").hide();
		e.preventDefault();
		return false;
	})
}

function showGlossaryDef(e) {
	var pos = $(e.target).offset();
	$("#glossTip").html($(e.target).data("glossDef")).show()
		.css("left", pos.left+"px").css("top",(pos.top-$(e.target).height()-$("#glossTip").height())+"px");
	e.preventDefault();
	return false;
}

function hideGlossaryDef() {
	$("#glossTip").hide();
}

function selChangeHandler(e) {
	// User selected show custom input option, which may no longer be in use
	if ($(e.target).val() == 0 && e.target.selectedIndex > 0) {
		showCustomInput(e.target);
	}
	else {
		if ($(e.target).hasClass("range")) {
			// The text field stores the actual value for ranged selects
			// since the selects themselves have no name
			// Also set labelVisible to false, since we gave it a value
			$("input."+e.target.id).val($(e.target).val()).data("labelVisible", false);
		}
		
		if ($(e.target).val().length > 0) {
			$(e.target).addClass("filterActive")
		}
		else {
			$(e.target).removeClass("filterActive");
		}
		
		if ($("#autoRefresh").attr("checked")) {
			$("#projectorsForm").submit();
		}
	}
}

function labelClickHandler(e) {
	var sel = $("#sel_"+$(e.target).attr("for"));
	sel.show().attr("selectedIndex",0);
	hideCustomInput(sel.get());
	
	$("#projectorsForm").submit();
	
	e.preventDefault();
	return false;
}

//
// Pre-processing before form is submitted
//
function projectorsFormSubmitHandler(e) {
	$("input[name=st]").val(1); // return user to first page
}

function restrictCharEventHandler(e) {
	if (e.which && e.which > 0) {
		code = e.which;
	}
	else {
		code = e.keyCode;
	}
	var legalCode = code <= 0x39                      // numbers and control keys
					|| (code >= 0x60 && code <= 0x69) // keypad numbers
					|| (code >= 0x70 && code <= 0x7b) // function keys F1 - F12
					|| (code == 0xbe)                 // period (decimal point)
					|| (code == 0x6e)                 // keypad decimal point
	// Only allow numbers, keypad numbers, control keys, and function keys
	// Also pass through anything with command/control pressed, since these do not generate characters
	if (code > 0 && !e.ctrlKey && !e.altKey && !e.metaKey && !legalCode) {
		 e.preventDefault();
	}
	else if (code > 0 && legalCode && e.shiftKey) {
		e.preventDefault(); // shift key not allowed for legal codes
	}
}

//
// Emulates a combo box by displaying a text field on top of the SELECT
// with a label
//
// The label is to the right of the text field, with text field border used to
// pad the input and keep width computations sane
//
// text field and label are provided in markup, with a class name corresponding to the
// SELECT's id
//
// if arg editFocus is true, then the text field gains focus, otherwise, focus() is not called
//
function showCustomInput(sel) {
	var custHt = $(sel).outerHeight();
	$(sel).attr("disabled","disabled").hide();
	$("#cust_"+sel.id).show().height(custHt).find("input").removeAttr("disabled").eq(0).focus();
}

function hideCustomInput(sel) {
	$(sel).removeAttr("disabled").show().focus();
	$("#cust_"+$(sel).attr("id")).hide().find("input").attr("disabled","disabled");
}

function metricToggleHandler() {
	// the class of the button stores what units we're currently using
	// if it currently has english, then we're switching to metric mode
	if ($("#toggleMetric").hasClass("english")) {
		// Become metric
		$(".inCmLabel").html("cm");
		$(".ftMLabel").html("m");
		$(".throwFilter input").each(function() {
			$(this).attr("name", $(this).attr("id")+"_m");
		});
		
		// Update weight select; append _m to name and id, also
		$("#sel_w").attr("id", "sel_w_m").attr("name", "w_m");
		$("#cust_sel_w").attr("id","cust_sel_w_m");
		$("#cust_sel_w_m label").text("kgs");
		$("#cust_sel_w_m input").attr("name", "w_m");

		// change label to read kgs instead of lbs
		$("#sel_w_m option[value!='']").each(function() {
			var h = $(this).html();
			$(this).html(h.substr(0,h.length-3)+"kgs");
		});
		
		$("#toggleMetric").html("Switch to English");
		
		// Update specs
		$("table.partList .spec_wt").each(function() {
			var wtNum = Number($(this).html().match(/[0-9.]+/)[0]);
			$(this).html(Math.round((wtNum/2.2046226) * 10)/10 + " kgs");
		});
		$("table.partList .spec_ft").each(function() {
			var ftNum = Number($(this).html().match(/[0-9.]+/)[0]);
			$(this).html(Math.round((ftNum*0.3048) * 10)/10 + " m");
		});
		$("table.partList .spec_in").each(function() {
			var inNum = Number($(this).html().match(/[0-9.]+/)[0]);
			$(this).html(Math.round(inNum*2.54) + " cm");
		});
	}
	else {
		// Become English
		$(".inCmLabel").html("inches");
		$(".ftMLabel").html("feet");
		$(".throwFilter input").each(function() {
			$(this).attr("name", $(this).attr("id"));
		});
		
		// Update weight select; remove _m from name and id, also
		$("#sel_w_m").attr("id", "sel_w").attr("name", "w");
		$("#cust_sel_w_m").attr("id","cust_sel_w");
		$("#cust_sel_w input").attr("name","w");
		$("#cust_sel_w label").text("lbs");
		
		// change label to read lbs instead of kgs
		$("#sel_w option[value!='']").each(function() {
			var h = $(this).html();
			$(this).html(h.substr(0,h.length-3)+"lbs");
		});
		
		$("#toggleMetric").html("Switch to Metric");
		
		$("table.partList .spec_wt").each(function() {
			var wtNum = Number($(this).html().match(/[0-9.]+/)[0]);
			$(this).html(Math.round((wtNum*2.2046226)*10)/10 + " lbs");
		});
		$("table.partList .spec_ft").each(function() {
			var ftNum = Number($(this).html().match(/[0-9.]+/)[0]);
			$(this).html(Math.round((ftNum/0.3048) * 10)/10 + "'");
		});
		$("table.partList .spec_in").each(function() {
			var inNum = Number($(this).html().match(/[0-9.]+/)[0]);
			$(this).html(Math.round(inNum/2.54) + "\"");
		});
		
	}
	$("#toggleMetric").toggleClass("english");

	// Update metric cookie -- note that "#toggleMetric" is after current unit display has been updated
	var expireDate = new Date ("September 28, 2037");
	var gmt = expireDate.toGMTString();
	document.cookie="METRIC="+(!$("#toggleMetric").hasClass("english")?1:0)+";expires="+gmt+";domain=.projectorcentral.com";
}