var disabledButtonHandler = function () { return false; };

function enableSubmitButtons(sFormName) {

	$("#" + sFormName + " .changeRequired img").each(function () {
		this.src = String(this.src).replace("-gray", "");
	});

	$("#" + sFormName + " .changeRequired").removeClass("disabledButton").each(function () { document.body.className += ''; });
	$("#" + sFormName + " button.changeRequired").attr("disabled", "");
	$("#" + sFormName + " a.changeRequired").unbind('click', disabledButtonHandler);
}

function disableSubmitButtons(sFormName) {
	$("#" + sFormName + " .changeRequired img").each(function () {
		if (String(this.src).indexOf("-gray") == -1)
			this.src = String(this.src).substr(0, String(this.src).lastIndexOf(".")) + "-gray" + String(this.src).substr(String(this.src).lastIndexOf("."));
	});

	$("#" + sFormName + " .changeRequired").addClass("disabledButton").each(function () { document.body.className += ''; });
	$("#" + sFormName + " button.changeRequired").attr("disabled", "disabled");
	$("#" + sFormName + " a.changeRequired").bind('click', disabledButtonHandler);
}

var oCheckFormTimer;

function checkFormChanges(sFormName) {
	clearTimeout(oCheckFormTimer);
	oCheckFormTimer = setTimeout("doCheckFormChanges('" +sFormName+ "');",120);
}

function doCheckFormChanges(sFormName)	{
	bChanged = false;

	$("#" + sFormName + " input[type=text],#" + sFormName + " textarea").each(function () {

		if ($.md5(this.value) != $("#" + this.name + "Original").val()) {
			bChanged = true;
			return false;
		}
	});

	if (!bChanged) {

		$("#" + sFormName + " input[type=radio]:checked").each(function () {
			
			if (this.value != $("#" + this.name + "Original").val()) {
				bChanged = true;
				return false;
			}
		});
	}

	if (!bChanged) {
		
		$("#" + sFormName + " select option:selected").each(function () {

			if (this.value != $("#" + this.parentNode.name + "Original").val()) {
				bChanged = true;
				return false;
			}
		});
	}

	bChanged ? enableSubmitButtons(sFormName) : disableSubmitButtons(sFormName);

	$("#"+sFormName+"Edited").val(bChanged);
}

function requireFormEdit(sFormName) {
	disableSubmitButtons(sFormName);

	oInput = document.createElement("input");
	oInput.type = "hidden";
	oInput.name = oInput.id = sFormName + "Edited";
	oInput.value = "false";

	$("#" + sFormName).append(oInput);

	$("#" + sFormName + " input[type=text],#" + sFormName + " textarea").each(function () {
		if ($("#" + this.name + "Original").length == 0) {

			oInput = document.createElement("input");
			oInput.type = "hidden";
			oInput.name = oInput.id = this.name + "Original";
			oInput.value = $.md5(this.value);

			$("#" + sFormName).append(oInput);
		}

		$(this).mouseup(function () { checkFormChanges(sFormName); }).keyup(function () { checkFormChanges(sFormName); }).change(function () { checkFormChanges(sFormName); });
	});

	$("#" + sFormName + " input[type=radio]:checked,#" + sFormName + " input[type=checkbox]:checked").each(function () {
		if ($("#" + this.name + "Original").length == 0) {

			oInput = document.createElement("input");
			oInput.type = "hidden";
			oInput.name = oInput.id = this.name + "Original";
			oInput.value = this.value;

			$("#" + sFormName).append(oInput);
		}
	});

	$("#" + sFormName + " input[type=radio]").click(function () { checkFormChanges(sFormName); });

	$("#" + sFormName + " select option:selected").each(function () {
		
		if ($("#" + this.parentNode.name + "Original").length == 0) {
			
			oInput = document.createElement("input");
			oInput.type = "hidden";
			oInput.name = oInput.id = this.parentNode.name + "Original";
			oInput.value = this.value;

			$("#" + sFormName).append(oInput);
		}
	});

	$("#" + sFormName + " select").change(function () { checkFormChanges(sFormName); }).keyup(function () { checkFormChanges(sFormName); });

}

function toggleInfoBox(sInfoBoxName)	{
	$(".inputInfoBox").not("#" + sInfoBoxName).hide();
	$("#" + sInfoBoxName).toggle(100);
}

function stripeRows() {
	$(".stripedRows td").removeClass("stripedRow")
	$(".visible:odd td").addClass("stripedRow");
}

//nType - 1=quote; 2=sales, 3=leasing
function checkQuickQuote(nForm,nType) {
	sError = "";

	if(nType == null)
		nType = 1;

	if ($("[id^='fldRequest" + nForm + "']:checked").length == 0 && $("#fldOther" + nForm + ":checked").length == 0) {
		sError += "Select your equipment<br />";
	}
	else if ($("#fldOther" + nForm + ":checked").length == 1 && $("#fldRequest" + nForm + "Other").val() == "") {
		sError += "Enter your equipment<br />";
	}

	if(nType == 1)	{
		if ($("[id^='fldRentalType" + nForm + "']:checked").length == 0) {
			sError += "Select the type of rental<br />";
		}

		if ($("[id^='fldPeriod" + nForm + "']:checked").length == 0) {
			sError += "Select the rental period<br />";
		}

		if ($.trim($("#fldDeliveryDate" + nForm).val()) == "")	{
			sError += "Enter a delivery date<br />";
		}
		else{
			if(!realDate($.trim($("#fldDeliveryDate" + nForm).val())))	{
				sError += "Delivery date is invalid<br />";
			}
		}

		if ($.trim($("#fldPickupDate" + nForm).val()) == "")	{
			sError += "Enter a pickup date<br />";
		}
		else{
			if(!realDate($.trim($("#fldPickupDate" + nForm).val())))	{
				sError += "Pickup date is invalid<br />";
			}
		}
	}

	if ($.trim($("#fldQuantity" + nForm).val()) == "") {
		sError += "Enter a quantity<br />";
	}

	if ($.trim($("#fldName" + nForm).val()) == "") {
		sError += "Enter a name<br />";
	}

	if ($.trim($("#fldCompany" + nForm).val()) == "") {
	//	sError += "Enter a company<br />";
	}

	if ($.trim($("#fldLocation" + nForm).val()) == "") {
		sError += "Enter a location<br />";
	}

	if ($.trim($("#fldEmail" + nForm).val()) == "") {
		sError += "Enter an email<br />";
	}
	else{
		if(!realEmail($.trim($("#fldEmail" + nForm).val())) && !realPhone($.trim($("#fldEmail" + nForm).val())))	{
			sError += "Email or phone is invalid<br />";
		}
	}

	if (sError == "")
		return true;
	else {
		$("#quickQuoteError" + nForm).html(sError);
		$("#quickQuoteError" + nForm).slideDown(200);
	}		

	return false;

}

function setField(sField, sValue) {
	document.getElementById(sField).value = sValue;
}

function realDate(sDateToCheck)	{
	//minimum date must be M/D/YY
	if(sDateToCheck.length < 6)
		return false;
	
	nFirstSlash = sDateToCheck.indexOf("/");
	
	//the first / must be at least the second char of string
	if(nFirstSlash > 0)	{
		
		nSecondSlash = sDateToCheck.indexOf("/",sDateToCheck.indexOf("/")+1);		
		//there must be a second / after the first
		if(nSecondSlash > nFirstSlash)	{
			
			sMonth = sDateToCheck.substr(0,nFirstSlash);
			sDay = sDateToCheck.substr(nFirstSlash+1,nSecondSlash-nFirstSlash-1);
			sYear = sDateToCheck.substr(nSecondSlash+1);
			
			if(isNaN(sMonth))
				return false;
			else if(sMonth.length > 2)
				return false;

			sMonth -= 1; //javascript months start from 0
				
			if(isNaN(sDay))
				return false;
			else if(sDay.length > 2)
				return false;
				
			if(isNaN(sYear))
				return false;
			else if(sYear.length > 4)
				return false;
			else if(sYear.length == 2)
				sYear = "20" + sYear;
			else if(sYear.length !== 4)
				return false;		
			
			nMilliseconds = (new Date(sYear,sMonth,sDay)).getTime();

			oDate = new Date();
			oDate.setTime(nMilliseconds);

			if(oDate.getFullYear() != sYear || oDate.getMonth() != sMonth || oDate.getDate() != sDay)	{
				return false;
			}

		}
		else
			return false;
	}
	else
		return false;

	return true;
}

function realEmail(sEmailToCheck) {
	var oRegExp = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/gi;

	return oRegExp.test(sEmailToCheck);
}

function realPhone(sPhoneToCheck) {
	var oRegExp = /[^0-9]/gi;

	sPhone = String(sPhoneToCheck).replace(oRegExp,"")

	if(sPhone.length < 10)
		return false;
	
	oRegExp = /[0-9.\(\)\-+x\s]/gi;

	sPhone = sPhoneToCheck.replace(oRegExp,"");
	
	if(sPhone != "")
		return false;

	return true;
}

function openMiniCal(sFieldName,dMinDate,dMaxDate)	{
	grayOutScreen(function(){hideMiniCal();});

	oMiniCal = document.createElement("div");
	oMiniCal.id = "miniCalDiv";
	
	$(oMiniCal).html("<iframe frameborder='0' src='/includes/mini-calendar.asp?dMinDate="+dMinDate+"&dMaxDate="+dMaxDate+"&dtDate="+$(sFieldName).val()+"&sField=" + sFieldName + "' style='width: 185px; height: 191px;'></iframe>");

	$("body").append(oMiniCal);
}

function hideMiniCal(sFieldName)	{
	unGrayOutScreen();

	$("#miniCalDiv").remove();
}

function grayOutScreen(oAfter)	{
	
	oGrayDiv = document.createElement("div");
	oGrayDiv.id = "grayOutDiv";
	$(oGrayDiv).css({"width":$(document).width(),"height":$(document).height()});

	if(oAfter != null) $(oGrayDiv).click(oAfter);

	$("body").append(oGrayDiv);

}

function unGrayOutScreen(sFieldName)	{
	$("#grayOutDiv").remove();
}

function loadGoogleMapsAPI()	{
	var oScript = document.createElement("script");
	oScript.type = "text/javascript";
	oScript.src = "http://maps.google.com/maps/api/js?sensor=false"
	$("body").append(oScript);
}

function showGoogleMap(sMapSearchString,sMapDivName,nZoomLevel) {

	var oGeocoder = new google.maps.Geocoder();

	oGeocoder.geocode({'address':sMapSearchString}, function(results,status)	{
		
		var oMapOptions =	{
			zoom: nZoomLevel,
			center: results[0].geometry.location,
			mapTypeId: google.maps.MapTypeId.HYBRID,
			mapTypeControl: false,
			streetViewControl: false,
			scrollwheel: false,
			navigationControl: false,
			draggable: false,
			disableDoubleClickZoom: true
		}

		var map = new google.maps.Map(document.getElementById(sMapDivName),oMapOptions);

	});

}

function htmlEncode(sStringToEncode){ 
    if(sStringToEncode)
        return $("<div/>").text(sStringToEncode).html(); 
	else
        return "";
}
