var overlayID = "";

$(document).ready(function() {	

	//quick ff form
	var ffTaFocused = false;

	//listen for the make change event
	$("select#make").change(reloadModel);
	$("select#ffmake").change(reloadFeedbackModel);
	
	//add custom check for dropdown selection
	jQuery.validator.addMethod("selectRequired", function(val, elem) {
		if (elem.value == -1)
			return false;
		else
			return true;},
		" ");

	//add custom rule for minimum maximum length
	jQuery.validator.addMethod("checkMinAndMax", function(val, elem) {
		if (elem.value == -1)
			return false;
		else
			return true;},
		" ");

	//validator for Tell A Friend
	var validator1 = $("#tellForm").bind("invalid-form.validate", function() {
			$("#warn1").html("Your form contains " + validator1.numberOfInvalids() + " errors, see details below.");
		}).validate({ 
		onClick: true,
		onChange: true,
		errorContainer: $("#warn1"),
		rules: { 
			myname: {required: true, minlength:1},
			myemail: {minlength:5, email: true, required: true},
			cbTell1: {required: true, minlength:1},
			cbTell2: {required: false, minlength:1},
			cbTell3: {required: false, minlength:1},
			cbTellProdInfo: {required: true},
			txtTellEmail1: {minlength:5, email: true, required: function() {return $("input[id='cbTellEmail1']").is(':checked');}},
			txtTellPhArea1: {rangelength:[3,4], number: true, required: function() {return $("input[id='cbTellText1']").is(':checked');}},
			txtTellPhEx1: {minlength:3, maxlength:3, number: true, required: function() {return $("input[id='cbTellText1']").is(':checked');}},
			txtTellPhNm1: {minlength:4, maxlength:4, number: true, required: function() {return $("input[id='cbTellText1']").is(':checked');}},
			txtTellEmail2: {minlength:5, email: true, required: function() {return $("input[id='cbTellEmail2']").is(':checked');}},
			txtTellPhArea2: {rangelength:[3,4], number: true, required: function() {return $("input[id='cbTellText2']").is(':checked');}},
			txtTellPhEx2: {minlength:3, maxlength:3, number: true, required: function() {return $("input[id='cbTellText2']").is(':checked');}},
			txtTellPhNm2: {minlength:4, maxlength:4, number: true, required: function() {return $("input[id='cbTellText2']").is(':checked');}},
			txtTellEmail3: {minlength:5, email: true, required: function() {return $("input[id='cbTellEmail3']").is(':checked');}},
			txtTellPhArea3: {rangelength:[3,4], number: true, required: function() {return $("input[id='cbTellText3']").is(':checked');}},
			txtTellPhEx3: {minlength:3, maxlength:3, number: true, required: function() {return $("input[id='cbTellText3']").is(':checked');}},
			txtTellPhNm3: {minlength:4, maxlength:4, number: true, required: function() {return $("input[id='cbTellText3']").is(':checked');}} 
		}, 
		messages: { 
			myname: " ",
			myemail: " ",
			cbTell1: " ",
			cbTell2: " ",
			cbTell3: " ",
			txtTellEmail1: " ",
			txtTellPhArea1: " ",
			txtTellPhEx1: " ",
			txtTellPhNm1: " ", 
			txtTellEmail2: " ",
			txtTellPhArea2: " ",
			txtTellPhEx2: " ",
			txtTellPhNm2: " ", 
			txtTellEmail3: " ",
			txtTellPhArea3: " ",
			txtTellPhEx3: " ",
			txtTellPhNm3: " ", 
			cbTellProdInfo: " "}
	});


	//validator for Alert Me
	var validator2 = $("#alertForm").bind("invalid-form.validate", function() {
			$("#warn2").html("Your form contains " + validator2.numberOfInvalids() + " errors, see details below.");
		}).validate({ 
		onClick: true,
		onChange: true,
		errorContainer: $("#warn2"),
		rules: { 
			cbAlert1: {required: true, minlength:1},
			cbAlertProdInfo: {required: true},
			txtAlertEmail1: {minlength:5, email: true, required: function() {return $("input[id='cbAlertEmail1']").is(':checked');}},
			txtAlertPhArea1: {rangelength:[3,4], number: true, required: function() {return $("input[id='cbAlertText1']").is(':checked');}},
			txtAlertPhEx1: {minlength:3, maxlength:3, number: true, required: function() {return $("input[id='cbAlertText1']").is(':checked');}},
			txtAlertPhNm1: {minlength:4, maxlength:4, number: true, required: function() {return $("input[id='cbAlertText1']").is(':checked');}},
			make: {selectRequired: true},
			model: {selectRequired: true},
			carrier: {selectRequired: true},
			txtothermake: {minlength:1, required: function() {return ($("#make option:selected").val() == 0) ? true : false;}},
			txtothermodel: {minlength:1, required: function() {return ($("#model option:selected").val() == 0) ? true : false;}},
			txtothercarrier: {minlength:1, required: function() {return ($("#carrier option:selected").val() == 0) ? true : false;}}
		}, 
		messages: { 
			cbAlert1: " ",
			txtAlertEmail1: " ",
			txtAlertPhArea1: " ",
			txtAlertPhEx1: " ",
			txtAlertPhNm1: " ", 
			txtothermake: " ",
			txtothermodel: " ",
			txtothercarrier: " ",
			cbAlertProdInfo: " "}
	});

  //12/7/2009: Update for feedback form
  	//validator for Alert Me
	var validator3 = $("#feedbackForm").bind("invalid-form.validate", function() {
			$("#warn3").html("Your form contains " + validator3.numberOfInvalids() + " errors, see details below.");
		}).validate({ 
		onClick: true,
		onChange: true,
		errorContainer: $("#warn3"),
		rules: { 
			ffmake: {selectRequired: true},
			ffmodel: {selectRequired: true},
			ffcarrier: {selectRequired: true},
			fftxtothermake: {minlength:1, required: function() {return ($("#ffmake option:selected").val() == 0) ? true : false;}},
			fftxtothermodel: {minlength:1, required: function() {return ($("#ffmodel option:selected").val() == 0) ? true : false;}},
			fftxtothercarrier: {minlength:1, required: function() {return ($("#ffcarrier option:selected").val() == 0) ? true : false;}},
			fftxtfeedback: {minlength:1, required: true}
		}, 
		messages: { 
			fftxtothermake: " ",
			fftxtothermodel: " ",
			fftxtothercarrier: " ",
			fftxtfeedback: " "}
	});


	//if textbox with cb goes into focus
	$('.cbText').focus(function (e) {
		$('#cb'+this.id).attr('checked', true);
	});

	//if other dd is selected
	$('.ddAlertME').change(function (e) {
		var pre = '';
		if ($("#" + this.id).closest('form').attr('name') == "feedbackForm")
			pre = 'ff';
		if ($("#" + this.id + " option:selected").val() == 0) {
			$("#"+pre+"txtother" + this.id).removeAttr("disabled");
			$("#"+pre+"txtother" + this.id).css("visibility", "visible");
			$("#"+pre+"txtother" + this.id).focus();
		} else {
			$("#"+pre+"txtother" + this.id).val('');
			$("#"+pre+"txtother" + this.id).attr("disabled", true);
			$("#"+pre+"txtother" + this.id).css("visibility", "hidden");
		}
	});


	//if textarea class goes into focus
	$('.icontext').focus(function (e) {
		var val = jQuery.trim(this.value);
		if (!ffTaFocused) {
			this.value = "";
			ffTaFocused = true;
		}
	});	
	
	//if textarea class goes out of focus
	$('.icontext').blur(function (e) {
		var val = jQuery.trim(this.value);
		//var val = this.value.replace(/ /g,'');
		val = val.replace(/[^\w@\.\s]/g, '');
		this.value = val;
	});
	
	//if textbox class txtOtherBox goes out of focus
	$('.txtOtherBox').blur(function (e) {
		var val = jQuery.trim(this.value);
		//var val = this.value.replace(/ /g,'');
		val = val.replace(/[^\w@\.\s]/g, '');
		this.value = val;
	});

	//if textbox class meText goes out of focus
	$('.meText').blur(function (e) {
		var val = jQuery.trim(this.value);
		//var val = this.value.replace(/ /g,'');
		val = val.replace(/[^\w@\.\s]/g, '');
		this.value = val;
	});

	//if textbox with cb goes out of focus
	$('.cbText').blur(function (e) {
		//var val = jQuery.trim(this.value);
		var val = this.value.replace(/ /g,'');
		val = val.replace(/[^\w@\.]/g, '');
		this.value = val;
		if (val.length == 0)
			$('#cb'+this.id).attr('checked', false);
	});

	//if textbox with cb goes into focus
	$('.checkbox').click(function (e) {
		var id = this.id;
		$('#'+id.substring(2)).val('');
		if (id.indexOf("Text") >=0) { //its a phone number - two more value to clear
			$('#'+id.substring(2)+'Ex').val('');
			$('#'+id.substring(2)+'Nm').val('');
		}
		if ($('#'+id).is(':checked'))
			$('#'+id.substring(2)).focus();
		
	});

/***/
	//if submit button is clicked
	$('.submitForm').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		if ($(this).closest('form').attr('name') == "feedbackForm") {
			if (feedbackFormOK(ffTaFocused)) {
				//alert("Feedback Success.");
			}
		} else {
			if (prepFormattedSubmit()) {
				validator1.resetForm(); //Q&D
				validator2.resetForm();
				clearOverlayForms();
				$('#transMask').hide();
				$('.overlay').hide();
			}
		}
	});
/****/

	//if close button is clicked
	$('.exitOverlay').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		//clear the error messages/validate
		validator1.resetForm(); //Q&D
		validator2.resetForm();
		clearOverlayForms();
	});		
	
	//if mask is clicked
	$('#transMask').click(function () {
		//clear the error messages/validate
		validator1.resetForm(); //Q&D
		validator2.resetForm();
		clearOverlayForms();
	});			
	
});

function clearOverlayForms() {
	//hide the overlay, put the movie back
	$('#transMask').hide();
	$('.overlay').hide();
	if ( $("#flash_mov").length > 0 ) {
		$('#hideMovie').hide();
		$('#flash_mov').show();
	}

	//clear the visible form
	$(':input', overlayID).each(function() {
	    var type = this.type;
	    var tag = this.tagName.toLowerCase(); // normalize case

	    if (type == 'text' || type == 'password' || tag == 'textarea')
	      this.value = "";
	    else if (type == 'checkbox' || type == 'radio')
	      this.checked = false;
	    else if (tag == 'select')
	      this.selectedIndex = 0;
	  });
	overlayID = "";

	//new - activate the dropdowns, deactivate the other textboxes
	$("select").removeAttr("disabled");
	$(".txtOtherBox").attr("disabled", true);
	$(".txtOtherBox").css("visibility", "hidden");


	//new - clear the submit form
	$(':input', '#formattedSubmit').each(function() {
	    var type = this.type;
	    if (type == 'hidden')
	      this.value = "";
	  });
}


/********************
function clearForm(f) {

    $(f).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

************/

function loadOverlay(id) {
	var maskHeight = $(document).height();
	var maskWidth = $(document).width(); //$(window).width();
	$('#transMask').css({'width':maskWidth,'height':maskHeight});
		
	$('#transMask').fadeIn().fadeTo("def",0.75);	
	//$('#transMask').fadeTo("def",0.5);	

	//IE needs the movie hidden - swap with background image
	if ( $("#flash_mov").length > 0 ) {
		$('#flash_mov').hide();
		$('#hideMovie').show();
	}

	var top = 0;
	var left = 0;
	var yMargin = 20;
	var xMargin = 20;

	//height consideration - are we too close to the bottom? If so, use the bottom as a base - otherwise offset from the scroll top
	var winH = $(window).height();
	var docH = $(document).height();
	var scrollTop = $(document).scrollTop();
	var overlayH = $(id).height();

	if ((scrollTop + yMargin + overlayH) > docH) {
		//we are too far down, base overlay from the bottom
		top = (docH - yMargin) - overlayH;
	} else {
		if (((2*yMargin) + overlayH) < winH)
			top = scrollTop + (winH/2 - $(id).height()/2);
		else
			top = scrollTop + yMargin;
	}

	//width consideration - are we too close to the left? If so, base form the left - otherwise center
	var winW = $(window).width();
	var docW = $(document).width();
	var scrollLeft = $(document).scrollLeft();
	var overlayW = $(id).width();

	//here we want don't want to use an else - we may be ok in multiple cases - last best case wins
	if ((scrollLeft + (2*xMargin) + overlayW) > docW) { 
		//we are too far to the right
		left = (docW - xMargin) - overlayW;
	} 
	if (((2*xMargin) + overlayW) < winW) { 
		//we can center in the window or the document. Choosing window.
		left = scrollLeft + winW/2 - $(id).width()/2;
	}
	if (left == 0) { 
		//we didn't meet either case - base it on the left
		if (xMargin + scrollLeft < docW)
			left = xMargin + scrollLeft;
		else
			left = xMargin;
	}

	$(id).css('top',  top);
	$(id).css('left', left);
	//$(id).css('position', 'fixed');

	$(id).fadeIn(1000);
	overlayID = id;
}

function reloadModel() {
	var sel = document.getElementById("model");
	if ($(this).val() == -1) {
		var options = '<option value="-1">Phone Model</option>';
		$('select#model options').remove();
 		$("select#model").html(options);
		sel.disabled = "disabled";
		$("#txtothermodel").val("");
		$("#txtothermodel").attr("disabled", true);
		$("#txtothermodel").css("visibility", "hidden");
	} else {
		$.getJSON("scripts/getModel.php",{makeID: $(this).val(), ajax: 'true'}, function(j){
      			var options = '<option value="-1">Phone Model</option>';
			if (j.length > 0) {	
      				for (var i = 0; i < j.length; i++) 
        				options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
				$('select#model options').remove();
      				$("select#model").html(options);
				if (j.length > 1) {
					sel.disabled = "";
					$("#txtothermodel").val("");
					$("#txtothermodel").attr("disabled", true);
					$("#txtothermodel").css("visibility", "hidden");
				}
			}
			if (j.length == 1) {
				sel.selectedIndex = 1;
				sel.disabled = "disabled";
				$("#txtothermodel").val("");
				$("#txtothermodel").removeAttr("disabled");
				$("#txtothermodel").css("visibility", "visible");
			}
		});
	}
}

function reloadFeedbackModel() {
	var sel = document.getElementById("ffmodel");
	if ($(this).val() == -1) {
		var options = '<option value="-1">Phone Model</option>';
		$('select#ffmodel options').remove();
 		$("select#ffmodel").html(options);
		sel.disabled = "disabled";
		$("#fftxtotherffmodel").val("");
		$("#fftxtotherffmodel").attr("disabled", true);
		$("#fftxtotherffmodel").css("visibility", "hidden");
	} else {
		$.getJSON("scripts/getModel.php",{makeID: $(this).val(), ajax: 'true'}, function(j){
      			var options = '<option value="-1">Phone Model</option>';
			if (j.length > 0) {	
      				for (var i = 0; i < j.length; i++) 
        				options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
				$('select#ffmodel options').remove();
      				$("select#ffmodel").html(options);
				if (j.length > 1) {
					sel.disabled = "";
					$("#fftxtotherffmodel").val("");
					$("#fftxtotherffmodel").attr("disabled", true);
					$("#fftxtotherffmodel").css("visibility", "hidden");
				}
			}
			if (j.length == 1) {
				sel.selectedIndex = 1;
				sel.disabled = "disabled";
				$("#fftxtotherffmodel").val("");
				$("#fftxtotherffmodel").removeAttr("disabled");
				$("#fftxtotherffmodel").css("visibility", "visible");
			}
		});
	}
}