var singleMatch = false;
var processingVar = "";
var poiJsError = "";
var skipOffer = "";

function doProcessing(){
	if($("#processing").length > 0){
		$("form #submit").hide();
		$("#processing").show();
	}else
		$("form #submit").hide().after("<span id='processing' " +
				"class='button processing'>" + processingVar + "...</span>");
	//Ajax-submit for the thankyou page
	if($("#container").hasClass("Thankyou") || $("#container").hasClass("Sorry")){
		var dataString = "", vK = [];
		$("li:visible [name^='ProgramOfInterest']:visible").each(function(){
			if(this.selectedIndex > 0){
				var n = $(this).attr('name');
				dataString += "&"+n+"="+$(this).val();
				vK.push(n.replace(/\D/g,''));
			}
		});
		dataString += "&TQVendorKeys=" + vK.join(',');
		//alert (dataString);return false;
		$.ajax({
			type: "POST",
			url: "submit.jsp",
			data: dataString,
			cache: false,
			success: function(data) {
				//if no lead submitted
				if(data.indexOf("<div>") < 0){
					//if this is a single match, show next vendor in chain, if any
					if(singleMatch){
						var cli = $("#right form ul li:visible");
						//check if there are any more vendors in the chain
						if(cli.next().length > 0){
							cli.fadeOut(function(){
								cli.next().fadeIn();
								$('#processing').hide();
								$("form #submit").show();
							});
							return false;
						}
					}
					$("#right").hide();
					$("#lsv h5").fadeIn('slow');
					$("[id^='lCnh_']:eq(0)").show();
					return false;
				}
				data = data.substring(data.indexOf("<div>") + 5, data.length - 6);
				// This is to stop any data modifications enroute ;-)
				try{
					data = eval("({"+data+"})");
				}catch(e){$("#right").hide(); return;}
				var ul = $("#lsv");
				for(var x in data){
					var dx = data[x];
					var li = $("<li />").append("<img src='"+dx.l+"' /> <strong>"
							+dx.n+"</strong><br/><h5 style='display: none;'>"
							+dx.b+"</h5><ul><li>"
							+dx.p+"</li></ul>");
					ul.append(li);
				}
				//Change the 'sorry' message into 'congratulations' ;-)
				if($("#container").hasClass("Sorry"))
					$("#left > h1").replaceWith("<h3 class='blue'>Congratulations</h3><p>The " +
							"schools you've chosen are listed below. A representative from each of " +
							"these schools will contact you shortly with further information.</p>");
				if(singleMatch){
					var cli = $("#right form ul li:visible");
					if(cli.next().length > 0){
						cli.fadeOut(function(){
							cli.next().fadeIn();
							$('#processing').hide();
							$("form #submit").show();
						});
						return false;
					}
				}
				$("#right").hide();
				$("#lsv h5").fadeIn('slow');
				$("[id^='lCnh_']:eq(0)").show();
			}
		});
		return false;
	}
}
$(function(){
	
	singleMatch = $("[name='matchType']").val() === 'single';

	//Set widths on the phone fields
	$("[name^=HP_],[name^=WP_]").css('width','62px');

	var cnFld = $("[name='CN']");
	var spFld = $("[name='SP']");

	// On_change method for State field
	spFld.change(function(){
		var cn = $(this).val().substring(0,2);
		if(cn != "US" && cn != "CA" && cn != "UM")
			cn = cnFld.options[0].value;
		cnFld.val(cn);
	});

	// On_change method for Country field
	cnFld.change(function(){
		var cn  = $(this).val();
		if(cn != "US" && cn != "CA" && cn != "UM")
			// can we use selectedIndex on the drop-down?
			spFld.val(spFld.get(0).options[0].value);
	});

	// on submit - do processing...
	$("form").submit(doProcessing);

	// submit & redirect if 'Age' is selected '17 and younger'
	$("[name='Age']").change(function(){
		if($(this).val() == '17')
			$("#submit").trigger('click');
	});

	// submit & redirect if 'EducationLevel' is selected 'None'
	$("[name='EducationLevel']").change(function(){
		if($(this).val() == 'None')
			$("#submit").trigger('click');
	});

	// Disable 'Undecided' when any valid subject is chosen
	$("[name='ProgramsOfInterestType']").click(function(){
		var c = $("[name='ProgramsOfInterestType']:checked").not("[value='Undecided']").length;
		var un = $("[name='ProgramsOfInterestType'][value='Undecided']");
		if(c > 0)
			un.removeAttr('checked').attr('disabled','disabled');
		else
			un.removeAttr('disabled');
	}).trigger('click').trigger('click');

	if($("#container").hasClass("Thankyou") || $("#container").hasClass("Sorry"))
		$("#submit").before($("<a class='button skip' href='#'>" + skipOffer + "</a>").click(function(){
			if(singleMatch){
				var cli = $("#right form ul li:visible");
				if(cli.next().length > 0){
					cli.fadeOut(function(){
						cli.next().fadeIn();
					});
					return false;
				}
			}
			$("#right").hide();
			$("#lsv h5").fadeIn('slow');
			$("[id^='lCnh_']:eq(0)").show();
			return false;
		}));

	//Don't worry. Only one of this happens
	//The ajax call that makes the request to pull additional matches
	$("[id='lCnh']:eq(0)").each(function(){
		$("#lsv h5").fadeIn('slow');
	});
	$("[id^='lCnh_']:eq(0)").each(function(){
		var loadImg = $("<div><img src='styles/i/loading.gif' title='loading more schools...' /></div>");
		loadImg.css('padding','10px');
		loadImg.css('text-align','center');
		$(this).after(loadImg);
		$(this).hide();
		// TQLC.jsp?n=4
		var n=this.id.replace(/\D/g,'');
		$.get("TQLC.jsp", "n="+n, function(data){
			loadImg.hide();
			if(data.indexOf("<div>") < 0){
				$("#lsv h5").fadeIn('slow');
				$("[id^='lCnh_']:eq(0)").show();
				$("#right").hide();
				return false;
			}
			data = data.substring(data.indexOf("<div>")+5, data.length-6);
			// This is to stop any data modifications enroute ;-)
			try{
				data = eval("({"+data+"})");
			}catch(e){return;}
			var ul = $("<ul />");
			var newV = [];
			for(var x in data){
				var dx = data[x];
				ul.append("<li><label><img src='" + dx.l + "' /></label><span>" + dx.n
						+ "</span><br/><h5 "+(singleMatch?"":"style='display: none;'")+">"
							+dx.b+"</h5>" + dx.p + "</li>");
				newV.push(x);
			}
			// Finally, keep track of the new vendors
			$("form").prepend("<input type='hidden' id='TQVendorKeys' value="+newV.join(',')+" />");
			// Do the UI magic
			$("form h2.top + div").after(ul);
			if(singleMatch)
				ul.find('li:gt(0)').hide();
			cleansePOI();
			$("#right").show();
		});
	});

	cleansePOI();

	// Forcing to select at least a program on the 'poi' and 'tq/sry' page
	if($("#container").hasClass("POI") 
			|| $("#container").hasClass("Thankyou") 
			|| $("#container").hasClass("Sorry"))
		$('form').unbind('submit').submit(function(){
			var canSubmit = false;
			$("li:visible [name^='ProgramOfInterest']").each(function(){
				canSubmit = (this.selectedIndex > 0);
				if(canSubmit) return false;
			});
			if(!canSubmit)
				alert(poiJsError);
			else
				doProcessing();
			if($("#container").hasClass("POI"))
				return canSubmit;
			return false;
		});

	function cleansePOI(){
		//Enable POI to be self-sustainable if grouped
		$("select[name^='ProgramOfInterest']").each(function(){
			var newPOI = $(this).clone(true).empty(), optGroup = undefined;
			$(this).find("option").each(function(){
				if(this.value.indexOf('::LABEL::') > -1 ){
					if(optGroup != undefined)
						newPOI.append(optGroup);
					optGroup = $("<optgroup />").attr('label', this.text);
				}else if(optGroup != undefined){
					optGroup.append(this);
				}else
					newPOI.append(this);
			});
			newPOI.append(optGroup);
			newPOI[0].selectedIndex = 0;
			$(this).replaceWith(newPOI);
		});
	}
});


