var quoteFormValidation = null;
var hasIssues = false;

function makeCollapsable(){
	$("#quoteForm div.fieldgroup").each(function(){
		$(this).children("h3:first,a.editAnsw").unbind('click.collapse').bind('click.collapse', function(){
			if($(this).siblings(".collapsed").length > 1){
				// Expanding so collapse all others
				$("#quoteForm div.fieldgroup:visible").find("p,div,ul,a,span,table,button").addClass("collapsed").filter("a.editAnsw").removeClass("collapsed");
			}
			$(this).parent().find("p,div,ul,a,span,table,button").toggleClass("collapsed").filter("a.editAnsw").show();
		});
		$(this).find("p,div,ul,a,span,table,button").addClass("collapsed").filter("a.editAnsw").removeClass("collapsed").hide();
	});
	
	if($("#submitButton:visible").length > 0 && $("#boatStorageHolder input[name^='watercraftHasPolicyInfo_']:last").val() == 1){
		// All Watercraft Policy Info filled out, show last box
		$("#policyForm").next().find("p,div,ul,a,span,table,button").removeClass("collapsed").filter("a.editAnsw").addClass("collapsed").show();
	} else if($("#submitButton:visible").length > 0 && $("#boatStorageHolder input[name^='watercraftHasPolicyInfo_']").length == 1){
		// Only one watercraft, show it
		$("#policyForm div.fieldgroup").eq(0).find("p,div,ul,a,span,table,button").removeClass("collapsed").filter("a.editAnsw").addClass("collapsed").show();
	} else if($("#submitButton:visible").length > 0 && $("#boatStorageHolder input[name^='watercraftHasPolicyInfo_']:first").val() == 0){
		// Editing first of multiple watercraft so show Primary Residence Info
		$("#policyForm div.fieldgroup").eq(0).find("p,div,ul,a,span,table,button").removeClass("collapsed").filter("a.editAnsw").addClass("collapsed").show();
		// $("#quoteForm div.fieldgroup:visible").eq(0).find("p,div,ul,a,span,table,button").removeClass("collapsed").filter("a.editAnsw").addClass("collapsed").show();
	} else if($("#submitButton:visible").length > 0 && $("#boatStorageHolder input[name^='watercraftHasPolicyInfo_']:last").val() == 0){
		// Editing secondary watercraft so show it
		$("#policyForm div.fieldgroup").eq(0).find("p,div,ul,a,span,table,button").removeClass("collapsed").filter("a.editAnsw").addClass("collapsed").show();
	} else {
		// Unhide first visible fieldgroup
		$("#quoteForm div.fieldgroup:visible").eq(0).find("p,div,ul,a,span,table,button").removeClass("collapsed").filter("a.editAnsw").addClass("collapsed").show();
	}
	
	$("#quoteForm button.continueForm").unbind('click.continue').bind('click.continue', function(event){
		var hasErrors = false;
		var firstInvalid = null;
		if(event != null) event.preventDefault();
		$(this).parent().find(":input").each(function(){
			if(quoteFormValidation.element($(this)) == false) {
				if(!hasErrors) firstInvalid = $(this);
				hasErrors = true;
			}
		});
		if (hasErrors) {
			firstInvalid.select();
		} else {
			var visibleGroups = $("#quoteForm div.fieldgroup:visible");
			if(visibleGroups.index($(this).parent()) < visibleGroups.length-1) {
				$(this).parent().children("h3:first").trigger("click.collapse");
				var nextGroup = visibleGroups.eq(visibleGroups.index($(this).parent())+1);
				if(nextGroup.children(".collapsed").length > 1) nextGroup.children("h3:first").trigger("click.collapse");
			} else if($("#quoteForm a.next:visible").length == 1){
				$("#quoteForm a.next:visible").trigger("click");
			} else if($("#submitButton:visible").length == 1) {
				$("#submitButton:visible").trigger("click");
			}
		}
	});
	
	if($("#quoteForm select[name='quoBoatManufacturer']").val() == 'Other') {
		$("#quoteForm select[name='quoBoatManufacturer']").hide().next().show();
	}
	if($("#quoteForm select[name='quoBoatModel']").val() == 'Other') {
		$("#quoteForm select[name='quoBoatModel']").hide().next().show();
	}
}


function updateComplete(theTime){
	var currentTimeToComplete = $("#timeToComplete").html();
	// alert(currentTimeToComplete);
	var newTimeToComplete = currentTimeToComplete - theTime;
	if(newTimeToComplete <= 0) newTimeToComplete = 2;
	$("#timeToComplete").html(newTimeToComplete);
}

// Onload When Document Ready
$(document).ready(function() {
  $('a[rel=external]').attr('target', '_blank');
  $('.equalize').equalHeights('true');
  $("img[src$=png],.pngfix").pngfix();
	
	if($("#maplink").length > 0){
		$("#maplink").livequery( function(){	
			$(this).fancybox({ 
				'frameHeight' : 500,
				'hideOnContentClick': true
				});
		});
	}
	
  if($("#privacylink").length > 0){
		$("#privacylink").fancybox({
			'hideOnContentClick': true,
			'frameHeight': 500
	  });
	}
	
  if($("#completeLateButton").length > 0) {
		$("#completeLateButton").fancybox({
			'hideOnContentClick': false,
			callbackOnShow: function(){setPhoneMask();}
	  });
	}
	
  if($("#completeLateButton2").length > 0) {
		$("#completeLateButton2").fancybox({
			'hideOnContentClick': false,
			callbackOnShow: function(){setPhoneMask();}
	  });
	}
	
	if($("#callMeButton").length > 0) {
	  $("#callMeButton").fancybox({
			'hideOnContentClick': false,
			'frameHeight': 500,
			callbackOnShow: function(){setupQQRelatedSelects();}
	  });
	}
	
  $("#SignupForm").formToWizard({ submitButton: 'SaveAccount' });
	
	if($("#quoPhone").length > 0) {
		//$("#quoPhone").mask("(999) 999-9999",{placeholder:"_"});
		$("#quoPhone").setMask({mask:'(999) 999-9999',autoTab:false});
		//$("#quoTempTest").mask("(999) 999-9999",{placeholder:"_"});
		$("#quoTempTest").setMask({mask:'(999) 999-9999',autoTab:false});
		//$("#quoFax").mask("(999) 999-9999",{placeholder:"_"});
		$("#quoFax").setMask({mask:'(999) 999-9999',autoTab:false});

		//$("#quoYearsBoating").mask("9?9",{placeholder:""});
		$("#quoYearsBoating").setMask({mask:'99',autoTab:false});
		//$("#quoPreviousVesselYear").mask("9999",{placeholder:""});
		$("#quoPreviousVesselYear").setMask({mask:'9999',autoTab:false});
		//$("#quoViolationsYear").mask("9999",{placeholder:""});
		$("#quoViolationsYear").setMask({mask:'9999',autoTab:false});
	}

});

function addWatercraft(){
	var nocache = new Date().toString();
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'watercraftAdd.cfm?nocache=' + nocache,
		cache: false,
		data: $('#quoteForm').serialize(),
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to save watercraft, please verify the information is correct and try again.');
		return false;
	}
	
	$('#watercraftForm').load('watercraftForm.cfm', {'nocache': nocache}, function(){makeCollapsable();});
	$('#watercraftList').load('watercraftList.cfm', {'nocache': nocache});
	$('#watercraftPolicyList').load('watercraftPolicyInfo.cfm', {'nocache': nocache});
	
	$('#boatHolder').show();
	$('#addAnother').show();
	$('#saveAnother').hide();
	return true;
}

function removeWatercraft(row){
	var nocache = new Date().toString();
	var numCraft = getNumberOfWatercraft();
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'watercraftDelete.cfm?nocache=' + nocache,
		cache: false,
		data: { id: row },
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to remove watercraft, please try again shortly.');
		return false;
	}
	
	if (numCraft == 1){
		$('#boatHolder').hide();
	}
	$('#watercraftList').load('watercraftList.cfm', {'nocache': nocache});
	$('#watercraftPolicyList').load('watercraftPolicyInfo.cfm', {'nocache': nocache});
}

function editWatercraft(row,autoedit){
	var nocache = new Date().toString();
	$.blockUI({ message: '<h1>Loading Watercraft Info, Please Wait...</h1>' });
	
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'watercraftForm.cfm?nocache=' + nocache,
		cache: false,
		data: { id: row },
		success: function(data){
			$('#watercraftForm').html(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to load watercraft info, please try again shortly.');
		return false;
	}
	
	makeCollapsable();
	if(autoedit != true) {
		$('#addAnother').hide();
		$('#saveAnother').show();
	}
	$.unblockUI();
}

function getNumberOfWatercraft(){
	var nocache = new Date().toString();
	var numberOfWatercraft = $.ajax({ type: "GET", url: "watercraftCheck.cfm?nocache=" + nocache, async: false, cache: false }).responseText;
	// alert('number watercraft:' + numberOfWatercraft);
	return numberOfWatercraft;
}

function setNewPurchase() {
	if($("[name='newPurchase']:checked").val() == 1){
		// $('#purchaseDate').show('fast');
		$('#quoPurchaseLabel').html('Purchase Price:');
		$("#purchasePrice > span.formInfo > a").attr("href", "tips/purchasePrice.html?width=275").attr("name", "Purchase Price");
	} else {
		// $('#purchaseDate').hide('fast');
		$('#quoPurchaseLabel').html('Estimated Hull Value:');
		$("#purchasePrice > span.formInfo > a").attr("href", "tips/hullValue.html?width=275").attr("name", "Estimated Hull Value");
	}
}

function setOtherOwners() {
	if($("[name='quoHasAdditionalOwners']:checked").val() == 1){
		$('#quoAdditionalOperator_option').show('fast');
	} else {
		$('#quoAdditionalOperator_option').hide();
	}
}

function setBoatsOwned() {
	if($("[name='quoPreviousOwned']:checked").val() == 1){
		$('#quoPreviousOwned_option').show('fast');
	} else {
		$('#quoPreviousOwned_option').hide();
	}
}

function setPriorClaims() {
	if($("[name='quoPriorClaims']:checked").val() == 1){
		$('#quoExplainClaims_option').show('fast');
	} else {
		$('#quoExplainClaims_option').hide();
	}
}

function setPriorViolations() {
	if($("[name='quoDrivingViolations']:checked").val() == 1){
		$('#quoDrivingViolations_option').show('fast');
	} else {
		$('#quoDrivingViolations_option').hide();
	}
}

function setCertifications() {
	if($("[name='quoHasCertifications']:checked").val() == 1){
		$('#quoCertifications_option').show('fast');
	} else {
		$('#quoCertifications_option').hide();
	}
}

function setPriResLayup() {
	if($("[name='quoPriResLayup']:checked").val() == 1){
		$('#quoPriResBoatLayup_option').show('fast');
	} else {
		$('#quoPriResBoatLayup_option').hide();
	}
}

function checkPriResFields() {
	var showFields = false;
	if($("[name='allSameAsPrimary']:checked").length > 0 || ($("[name^='watercraftIsPriRes_']").length > 1 && $("[name='sameAsPrimary']:checked").length > 0)) showFields = true;
	if(!showFields && $("[name^='watercraftIsPriRes_']").length > 1){
		$("[name^='watercraftIsPriRes_']").each(function(){if($(this).val() == 1) {showFields=true;return false;}});
	}
	return false;
	return showFields;
}

function setPriResFields() {
	if(checkPriResFields()){
		$('#primaryResidenceFields').show('fast');
		if($("#whereDoBoating [name='quoPriResBoatNavigationArea']").val() == '' && $('#primaryResidenceFields').children(".collapsed").length > 1) $('#primaryResidenceFields').children("h3:first").trigger("click.collapse");
	} else {
		$('#primaryResidenceFields').hide();
	}
}

function setAllPriRes() {
	var nocache = new Date().toString();
	if($("[name='allSameAsPrimary']:checked").length){
		hasIssues = false;
		$.ajax({
			async: false,
			type: 'POST',
			url: 'setAllPrimaryResidence.cfm?nocache=' + nocache,
			cache: false,
			data: { atResidence: 1 },
			success: function(data){
				if(data != 'Success') hasIssues = true;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				hasIssues = true;
			}
		});
		if (hasIssues) {
			hasIssues = false;
			$("[name='allSameAsPrimary']").attr("checked", null);
			alert('Unable to set Primary Residence preference, please try again.');
			return false;
		}
		
		$('#watercraftPolicyList').load(
			'watercraftPolicyInfo.cfm', 
			{'nocache': nocache}, 
			function(){
				$("[name='sameAsPrimary']").attr("checked", "checked").trigger('change');
				setPriResFields();
			}
		);
	}
}

function setPolicyPrimaryResidence() {
	if($("[name='sameAsPrimary']:checked").length > 0){
			$('#boatLoc,#boatCit').hide();
			$("#boatStat").parent().hide();
	} else {
			$('#boatLoc,#boatCit').show();
			$("#boatStat").parent().show();
	}
}

function setQuoLayup() {
	if($("[name='quoLayup']:checked").val() == 1){
		$('#quoBoatLayup_option').show('fast');
	} else {
		$('#quoBoatLayup_option').hide();
	}
}

function setCurrentInsured() {
	if($("[name='quoCurrentInsured']:checked").val() == 1){
		$('#quoCurrentInsured_option').show('fast');
	} else {
		$('#quoCurrentInsured_option').hide();
	}
}


function setChoosePolicyOptions() {
	if($("[name='quoChooseOptions']:checked").val() == 1){
		$('#quoChooseOptions_option').show('fast');
	} else {
		$('#quoChooseOptions_option').hide();
	}
}

function setLiabilityOnly() {
	if($("[name='quoLiabilityOnly']:checked").length > 0){
		// $('#setLiabilityOnlyFields_option').hide();
	} else {
		$('#setLiabilityOnlyFields_option').show('fast');
	}
}

function editWatercraftPolicy(row, revalidate){
	var nocache = new Date().toString();
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'policyForm.cfm?nocache=' + nocache,
		cache: false,
		data: { id: row },
		success: function(data){
			$('#policyForm').html(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to load Watercraft Policy Info, please try again.');
		$.unblockUI();
		return false;
	}
	if(revalidate){
		savePolicyDetails();
	}
	if(!setPolicyFormBindings()) {
		return false;
	}
	if(row == 0){
		$('#policyForm').hide();
	} else {
		$('#policyForm').show();
	}
	$.unblockUI();
	return true;
}

function setContactState() {
	if($("#quoState").val() == 'FL'){
		$('#quoCounty_container').show('fast');
	} else {
		$('#quoCounty_container').hide();
	}
}

function setPolicyState() {
	if($("#quoStorageState").val() == 'FL'){
		$('#policyStorageCounty').show('fast');
	} else {
		$('#policyStorageCounty').hide();
	}
}

function validatePreviousVessels() {
	var hasErrors = false;
	var RE = /^-{0,1}\d*\.{0,1}\d+$/;
	$("span.previousVesselFields").each(function(){
		var vessel = $(this).find("[name^='quoPreviousVessel_']").eq(0);
		var years = $(this).find("[name^='quoPreviousVesselYear_']").eq(0);
		if(vessel.val().length < 1) {
			vessel.select();
			hasErrors = true;
			return false;
		}
		if(years.val().length < 1 || !(RE.test(years.val()))){
			years.select();
			hasErrors = true;
			return false;
		}
	});
	if(hasErrors) {
		$("#previousVesselError").show();
		var container = $("#previousVesselError").closest("div.fieldgroup");
		if(container.children(".collapsed").length > 1) container.children("h3:first").trigger("click.collapse");
		return false;
	}
	$("#previousVesselError").hide();
	return true;
}

function updatePreviousVessels(){
	var nocache = new Date().toString();
	var theVessels = $("#previousVesselContainer input").serialize() + '&method=update';

	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'previousVesselProc.cfm?nocache=' + nocache,
		cache: false,
		data: theVessels,
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to update Previous Boats, please try again.');
		return false;
	}
	return true;
}

function addPreviousVessel() {
	if(!validatePreviousVessels()) return false;
	if(!updatePreviousVessels()) return false;
	var newFields = $("span.previousVesselFields:last").clone();
	var currMax = parseInt(newFields.find("[name^='quoPreviousVessel_']").attr("name").substring(18)) + 1;
	newFields.find("[name^='quoPreviousVessel_']").val("").attr("name", "quoPreviousVessel_" + currMax.toString());
	newFields.find("[name^='quoPreviousVesselYear_']").val("").attr("name", "quoPreviousVesselYear_" + currMax.toString());
	$("span.previousVesselFields:last").after(newFields);
	$("a.vesselRemovalLink").show();
}

function removePreviousVessel(theVessel) {
	var nocache = new Date().toString();
	var toRemove = $(theVessel).closest("span");
	var vessels = toRemove.parent().children("span");
	var arrayID = vessels.index(toRemove);

	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'previousVesselProc.cfm?nocache=' + nocache,
		cache: false,
		data: { method: "remove", id: arrayID },
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to remove Previous Boat, please try again.');
		return false;
	}

	toRemove.remove();
	if(vessels.length <= 2) $("a.vesselRemovalLink").hide();
	validatePreviousVessels();
}


function validatePreviousClaims() {
	var hasErrors = false;
//	var RE = /^-{0,1}\d*\.{0,1}\d+$/;
	var RE = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d{1,2})?$/;

	$("span.quoExplainClaimsFields").each(function(){
		var year = $(this).find("[name^='quoPriorClaimsYear_']").eq(0);
		var reason = $(this).find("[name^='quoExplainClaims_']").eq(0);
		var reasonOther = $(this).find("[name^='quoExplainClaimsOther_']").eq(0);
		var fault = $(this).find("[name^='quoPriorClaimsFault_']:checked");
		var amount = $(this).find("[name^='quoPriorClaimsAmount_']").eq(0);
		if(year.val().length < 1) {
			year.focus();
			hasErrors = true;
			return false;
		}
		if(reason.val().length < 1) {
			reason.focus();
			hasErrors = true;
			return false;
		}
		if(reason.val() == 'Other' && reasonOther.val().length < 1){
			reasonOther.select();
			hasErrors = true;
			return false;
		}
		if(fault.length != 1){
			$(this).find("[name^='quoPriorClaimsFault_']:first").focus();
			hasErrors = true;
			return false;
		}
		if(amount.val().length < 1 || !(RE.test(amount.val()))){
			amount.select();
			hasErrors = true;
			return false;
		}
	});
	if(hasErrors) {
		$("#priorClaimsError").show();
		var container = $("#priorClaimsError").closest("div.fieldgroup");
		if(container.children(".collapsed").length > 1) container.children("h3:first").trigger("click.collapse");
		return false;
	}
	$("#priorClaimsError").hide();
	return true;
}

function updatePreviousClaims(){
	var nocache = new Date().toString();
	var theClaims = $("#priorClaimsContainer :input").serialize() + '&method=update';
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'previousClaimProc.cfm?nocache=' + nocache,
		cache: false,
		data: theClaims,
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to update Previous Claims, please try again.');
		return false;
	}
	return true;
}

function addPreviousClaim() {
	if(!validatePreviousClaims()) return false;
	if(!updatePreviousClaims()) return false;
	var newFields = $("span.quoExplainClaimsFields:last").clone(true);
	var currMax = parseInt(newFields.find("[name^='quoPriorClaimsYear_']").attr("name").substring(19)) + 1;
	newFields.find("[name^='quoPriorClaimsYear_']").attr("name", "quoPriorClaimsYear_" + currMax.toString()).children("option:first").attr("selected", "selected");
	newFields.find("[name^='quoExplainClaims_']").val("").attr("name", "quoExplainClaims_" + currMax.toString()).show().next().hide();
	newFields.find("[name^='quoExplainClaimsOther_']").val("").attr("name", "quoExplainClaimsOther_" + currMax.toString());
	newFields.find("[name^='quoPriorClaimsFault_']").attr("name", "quoPriorClaimsFault_" + currMax.toString()).filter(":last").attr("checked", "checked");
	newFields.find("[name^='quoPriorClaimsAmount_']").val("").attr("name", "quoPriorClaimsAmount_" + currMax.toString());
	$("span.quoExplainClaimsFields:last").after(newFields);
	$("input[name='quoPriorClaimsAmount_" + currMax.toString() + "']").setMask({mask: "cccccccccc",type:'reverse', fixedChars : '[():/ -]', autoTab:false});
	
	$("a.claimRemovalLink").show();
}

function removePreviousClaim(theClaim) {
	var nocache = new Date().toString();
	var toRemove = $(theClaim).closest("span");
	var claims = toRemove.parent().children("span");
	var arrayID = claims.index(toRemove);
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'previousClaimProc.cfm?nocache=' + nocache,
		cache: false,
		data: { method: "remove", id: arrayID },
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to remove Previous Claim, please try again.');
		return false;
	}

	toRemove.remove();
	if(claims.length <= 2) $("a.claimRemovalLink").hide();
	validatePreviousClaims();
}

function validatePreviousViolations() {
	var hasErrors = false;
	var RE = /^-{0,1}\d*\.{0,1}\d+$/;
	$("span.priorViolationFields").each(function(){
		var year = $(this).find("[name^='quoViolationsYear_']").eq(0);
		var reason = $(this).find("[name^='quoExplainViolations_']").eq(0);
		var reasonOther = $(this).find("[name^='quoExplainViolationsOther_']").eq(0);
		var fault = $(this).find("[name^='quoExplainViolationsFault_']:checked");
		if(year.val().length < 1) {
			year.focus();
			hasErrors = true;
			return false;
		}
		if(reason.val().length < 1) {
			reason.focus();
			hasErrors = true;
			return false;
		}
		if(reason.val() == 'Other' && reasonOther.val().length < 1){
			reasonOther.select();
			hasErrors = true;
			return false;
		}
		if(fault.length != 1){
			$(this).find("[name^='quoExplainViolationsFault_']:first").focus();
			hasErrors = true;
			return false;
		}
	});
	if(hasErrors) {
		$("#priorViolationsError").show();
		var container = $("#priorViolationsError").closest("div.fieldgroup");
		if(container.children(".collapsed").length > 1) container.children("h3:first").trigger("click.collapse");
		return false;
	}
	$("#priorViolationsError").hide();
	return true;
}

function updatePreviousViolations(){
	var nocache = new Date().toString();
	var theViolations = $("#priorViolationsContainer :input").serialize() + '&method=update';
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'previousViolationProc.cfm?nocache=' + nocache,
		cache: false,
		data: theViolations,
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to update Previous Violations, please try again.');
		return false;
	}
	return true;
}

function addPreviousViolation() {
	if(!validatePreviousViolations()) return false;
	if(!updatePreviousViolations()) return false;
	var newFields = $("span.priorViolationFields:last").clone(true);
	var currMax = parseInt(newFields.find("[name^='quoViolationsYear_']").attr("name").substring(18)) + 1;
	newFields.find("[name^='quoViolationsYear_']").attr("name", "quoViolationsYear_" + currMax.toString()).children("option:first").attr("selected", "selected");
	newFields.find("[name^='quoExplainViolations_']").val("").attr("name", "quoExplainViolations_" + currMax.toString()).show().next().hide();
	newFields.find("[name^='quoExplainViolationsOther_']").val("").attr("name", "quoExplainViolationsOther_" + currMax.toString());
	newFields.find("[name^='quoExplainViolationsFault_']").attr("name", "quoExplainViolationsFault_" + currMax.toString()).filter(":last").attr("checked", "checked");
	$("span.priorViolationFields:last").after(newFields);
	
	$("a.violationRemovalLink").show();
}

function removePreviousViolation(theClaim) {
	var nocache = new Date().toString();
	var toRemove = $(theClaim).closest("span");
	var claims = toRemove.parent().children("span");
	var arrayID = claims.index(toRemove);
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'previousViolationProc.cfm?nocache=' + nocache,
		cache: false,
		data: { method: "remove", id: arrayID },
		success: function(data){
			if(data != 'Success') hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to remove Previous Violation, please try again.');
		return false;
	}
	toRemove.remove();
	if(claims.length <= 2) $("a.violationRemovalLink").hide();
	validatePreviousViolations();
}

function editNextWatercraftPolicy(){
	var next = 0;
	var counter = 0;
	$("#boatStorageHolder [name^='watercraftHasPolicyInfo_']").each(function(){
		counter++;
		// alert('Watercraft ' + counter + ' has policy: ' + $(this).val());
		if(next == 0 && $(this).val() == 0) {
			next = counter;
		}
	});
	// alert('Next: ' + next);
	return editWatercraftPolicy(next);
}

function savePolicyDetails(){
	var nocache = new Date().toString();
	if(!validatePolicyDetails()) {
		// alert('Policy Validation failed');
		showFirstInvalid();
		return false;
	}
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'policyInfoAdd.cfm?nocache=' + nocache,
		cache: false,
		data: $('#quoteForm').serialize(),
		success: function(data){
			if(data == 'Success') {
				// Set as completed
				$("#boatStorageHolder [name='watercraftHasPolicyInfo_" + $("#policyForm input[name='policyID']").val() + "']").val("1");
			} else hasIssues = true;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to save Watercraft Policy details, please verify the information and try again.');
		return false;
	}

	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'watercraftPolicyInfo.cfm?nocache=' + nocache,
		cache: false,
		data: null,
		success: function(data){
			// alert(data);
			// alert('Policy Details save completed');
			$('#watercraftPolicyList').html(data);
			// alert('Policy Details reload completed');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		alert('Unable to save Watercraft Policy details, please verify the information and try again.');
		return false;
	}
	
	if(!editNextWatercraftPolicy()) return false;
	
	/*
	$.post('policyInfoAdd.cfm', $('#quoteForm').serialize(), function(){
		$('#watercraftPolicyList').load('watercraftPolicyInfo.cfm', function(){
			editNextWatercraftPolicy();
		});
	});
	*/
	return true;
}

function validatePolicyDetails(){
	var hasErrors = '';
	var counter = 0;
	// If not editing a policy short circuit
	if($("[name='policyID']").val() == 0) return true;
	
	if(!quoteFormValidation.element("[name='quoStorageZipcode']")) hasErrors = hasErrors + 'quoStorageZipcode required\n';
	if(!quoteFormValidation.element("[name='quoMarina']")) hasErrors = hasErrors + 'quoMarina required\n';
	if(!quoteFormValidation.element("[name='quoStorageCity']")) hasErrors = hasErrors + 'quoStorageCity required\n';
	if(!quoteFormValidation.element("[name='quoStorageState']")) hasErrors = hasErrors + 'quoStorageState required\n';
	if(!quoteFormValidation.element("[name='quoLayup']")) hasErrors = hasErrors + 'quoLayup required\n';
	if(!quoteFormValidation.element("[name='quoBoatNavigationArea']")) hasErrors = hasErrors + 'quoBoatNavigationArea required\n';
	if(!quoteFormValidation.element("[name='quoCurrentInsured']")) hasErrors = hasErrors + 'quoCurrentInsured required\n';
	if(!quoteFormValidation.element("[name='quoChooseOptions']")) hasErrors = hasErrors + 'quoChooseOptions required\n';
	if(!quoteFormValidation.element("[name='quoLiability']")) hasErrors = hasErrors + 'quoLiability required\n';
	if(!quoteFormValidation.element("[name='quoLiabilityOther']")) hasErrors = hasErrors + 'quoLiabilityOther required\n';
	if(!quoteFormValidation.element("[name='quoMedicalPayments']")) hasErrors = hasErrors + 'quoMedicalPayments required\n';
	if(!quoteFormValidation.element("[name='quoMedicalPaymentsOther']")) hasErrors = hasErrors + 'quoMedicalPaymentsOther required\n';
	if(!quoteFormValidation.element("[name='quoDeductible']")) hasErrors = hasErrors + 'quoDeductible required\n';
	if(!quoteFormValidation.element("[name='quoDeductibleOther']")) hasErrors = hasErrors + 'quoDeductibleOther required\n';
	if(!quoteFormValidation.element("[name='quoPersonalEffects']")) hasErrors = hasErrors + 'quoPersonalEffects required\n';
	if(!quoteFormValidation.element("[name='quoTowing']")) hasErrors = hasErrors + 'quoTowing required\n';
	if(!quoteFormValidation.element("[name='quoFishing']")) hasErrors = hasErrors + 'quoFishing required\n';
	if(hasErrors.length > 0) {
		// alert(hasErrors);
		return false;
	} return true;
}

function processForm(){
	//setTimeout('alert(\'Problem processing form, please try again.\');$.unblockUI();', 20000);
	var nocache = new Date().toString();
	var formdata = $('#quoteForm').serialize();
	$.ajax({
		async: false,
	  type: 'POST',
	  url: 'processForm.cfm?nocache=' + nocache,
		cache: false,
	  data: formdata,
	  success: function() {
			// alert('successful!');
			document.location.href='thankYou.cfm?fromQuote=1';
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			// alert('Problem processing form, please try again.');
			$.unblockUI();
		}
	});
	/*
	$.post('processForm.cfm', $('#quoteForm').serialize(), function(data){
		document.location.href='thankYou.cfm';
	});
	*/
}

function setPolicyFormBindings(){
	var nocache = new Date().toString();
	hasIssues = false;
	$.ajax({
		async: false,
		type: 'POST',
		url: 'watercraftPolicyInfo.cfm?nocache=' + nocache,
		cache: false,
		data: null,
		success: function(data){
			$('#watercraftPolicyList').html(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			hasIssues = true;
		}
	});
	if (hasIssues) {
		hasIssues = false;
		// alert('Unable to setup Watercraft Policy Form, please try again.');
		return false;
	}
	
	// Only one watercraft?
	if($("input[name^='watercraftHasPolicyInfo_']").length == 1){
		//$("#primaryResidenceFields").prev().hide();
		// $("[name='sameAsPrimary']").attr("checked", "").trigger("change").parent().hide();
		$("#configBoatReminder").hide().prev().children(".continueForm").show();
 	} else {
		//$("#primaryResidenceFields").prev().hide();
		$("#configBoatReminder").show().prev().children(".continueForm").hide();
	}
	
	$("[name='quoCurrentPremium']").setMask({mask:'cccccccccc', fixedChars : '[():/ -]',type:'reverse', autoTab:false});
	
	$("[name='sameAsPrimary']").unbind("change.reveal").bind("change.reveal", function(){setPolicyPrimaryResidence();setPriResFields();}).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).unbind("click.reveal").bind("click.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
	
	$("#quoStorageState").unbind("change.county").bind("change.county", setPolicyState).unbind("blur.county").bind("blur.county", function(){$(this).trigger("change.county");}).trigger('change.county');
	
	$("[name='quoLayup']").unbind("change.reveal").bind("change.reveal", setQuoLayup).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");

	$("[name='quoCurrentInsured']").unbind("change.reveal").bind("change.reveal", setCurrentInsured).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
	
	$("[name='quoChooseOptions']").unbind("change.reveal").bind("change.reveal", setChoosePolicyOptions).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
	
	$("[name='quoLiabilityOnly']").unbind("change.reveal").bind("change.reveal", setLiabilityOnly).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
	
	$("select.selectWithOther").change(function(){
		if($(this).val() == 'Other') {
			$(this).hide().next().show();
		}
	}).trigger('change');
	$("a.selectWithOtherToggle").click(function(){
		$(this).siblings('input').val('').parent().hide().siblings('select:first').val('').show();
		return false;
	});
	
	JT_init();
	makeCollapsable();
	return true;
}

function setFormBindings(){
	//$.mask.definitions['c']='[0-9,]';

	//$("#quoPurchasePrice").mask("?ccccccccccc",{placeholder:""});
	$("#quoPurchasePrice").setMask({mask:'cccccccccc', fixedChars : '[():/ -]',type:'reverse', autoTab:false});
	$("#quoBoatLength").setMask({mask:'ccccccc', fixedChars : '[():/ -]',type:'reverse', autoTab:false});
	//$("#quoTrailerValue").mask("?ccccccc",{placeholder:""});
	$("#quoTrailerValue").setMask({mask:'cccccccccc', fixedChars : '[():/ -]',type:'reverse', autoTab:false});
	//$("#quoEngineHorsepower").mask("?9999",{placeholder:""});
	$("#quoEngineHorsepower").setMask({mask:'ccccc', fixedChars : '[():/ -]', type:'reverse', autoTab:false});
	
	$("[name='newPurchase']").unbind("change.reveal").bind("change.reveal", setNewPurchase).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
	
	$("#quoteForm").relatedSelects({
			onChangeLoad: 'getSelectData.cfm',
			dataType: 'html',
			defaultOptionText: '- Select -',
			selects: {
				'modYear':		{ loadingMessage:'Loading Manufacturers...' },
				'quoBoatManufacturer':		{ loadingMessage:'Loading Models...' },
				'quoBoatModel':	{}
			}
		});

	$("#quoteForm").relatedSelects({
			onChangeLoad: 'getTrailerData.cfm',
			dataType: 'html',
			defaultOptionText: '- Select -',
			selects: {
				'quoTrailerYear':		{ loadingMessage:'Loading Manufacturers...' },
				'quoTrailerMake':	{}
			}
		});

	$("#quoteForm").relatedSelects({
			onChangeLoad: 'getOutboardData.cfm',
			dataType: 'html',
			defaultOptionText: '- Select -',
			selects: {
				'quoEngineType':		{ loadingMessage:'Loading ...' },
				'quoEngineYear':		{ loadingMessage:'Loading Manufacturers...' },
				'quoEngineManufacturer':	{}
			}
		});

		$("[name='quoHasAdditionalOwners']").change(setOtherOwners);
		setOtherOwners();
		$("#quoState").unbind("change.county").bind("change.county", setContactState).unbind("blur.county").bind("blur.county", function(){$(this).trigger("change.county");}).trigger('change.county');
		$("[name='quoPreviousOwned']").unbind("change.reveal").bind("change.reveal", setBoatsOwned).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
		$("[name='quoPriorClaims']").unbind("change.reveal").bind("change.reveal", setPriorClaims).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
		$("input[name^='quoPriorClaimsAmount_']").setMask({mask: "cccccccccc",type:'reverse', fixedChars : '[():/ -]', autoTab:false});
		$("[name='quoDrivingViolations']").unbind("change.reveal").bind("change.reveal", setPriorViolations).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
		$("[name='quoHasCertifications']").unbind("change.reveal").bind("change.reveal", setCertifications).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
		$("[name='allSameAsPrimary']").unbind("change.reveal").bind("change.reveal", setAllPriRes).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
		$("[name='quoPriResLayup']").unbind("change.reveal").bind("change.reveal", setPriResLayup).unbind("blur.reveal").bind("blur.reveal", function(){$(this).trigger("change.reveal");}).trigger("change.reveal");
		
		setPolicyFormBindings();
		

/* form validation */
	$.validator.addMethod("currency", function(value, element) { 
	  return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d{1,2})?$/.test(value);
	}, "Please specify a valid dollar amount (ie $9,999.95)");
	
	quoteFormValidation = $('#quoteForm').validate({
		errorClass: "validateMsg",
			groups: {
    		quoDOB: "quoDOBMonth quoDOBDay quoDOBYear"
  		},

		rules: {

			/* begin validation for the watercraft info page */
			quoPurchasePrice: "required currency", /*{
				required: {
        	depends: function(element) {
          	return ($("#newPurchase:checked").val()==1);
         	}
       	}
			}, */
			
			modYear: "required",
			quoBoatManufacturer: "required",
			quoBoatManufacturerOtherText: "required",
			quoBoatModel: "required",
			quoBoatModelOtherText: "required", 
			quoBoatLength: "required number", 
			quoTrailerYear: "required", 
			quoTrailerMake: "required", 
			quoTrailerValue: "required currency", 
			quoTrailerMakeOtherText: "required", 
			quoEngineType: "required",
			quoEngineTypeOtherText: "required", 
			quoEngineYear: "required",

			quoEngineManufacturer: {required: {depends: function(){return ($("#quoEngineManufacturer").is(':visible'))? true:false;}}},
//			quoEngineManufacturer: "required", 			
//			quoEngineManufacturerOther: "required", 	
			quoEngineManufacturerOther: {required: {depends: function(){return ($("#quoEngineManufacturerOther").is(':visible'))? true:false;}}},

			quoEngineQuantity: "required",
			quoEngineHorsepower: "required",
			quoEngineFuel: "required",

		/* end validation for the watercraft info page */

		/* begin validation for the contact info page */
				quoFName: "required",
				quoLName: "required",
				quoDOBMonth: "required",
				quoDOBDay: "required",
				quoDOBYear: "required",
				quoAddress1: "required",
				quoCity: "required",
				quoState: "required",
				quoZip: "required",
				quoPhone: "required",
				quoReturnEmail: {
					required: true,
					email: true
				},
				
				/* Need to validate manually
				quoPreviousVessel: {
					required: {
						depends: function(element) {
	          	return ($("#quoPreviousOwned:checked").val()==1);
						}
					}
				}, 
				*/
				
				/* No longer using per Eric
				quoPreviousVessels: {
					required: {
						depends: function(element) {
	          	return ( ($("#quoYearsBoating").val().length > 0) && ($("#quoYearsBoating").val() > 0) );
						}
					}
				},
				*/
				quoCounty: {
					required: {
						depends: function(element) {
	          	return ( $('#quoState:selected').val() == 'FL' );
						}
					}
				},
				quoYearsBoating: "required", 
		/* end validation for the contact info page */
		
		/* begin validation for the policy info page */
			quoPriResLayup: {required: {depends: function(){return checkPriResFields();}}},
			quoPriResBoatNavigationArea: {required: {depends: function(){return checkPriResFields();}}},
			quoMarina: {required: {depends: function(){return ($("[name='sameAsPrimary']:checked").length == 0)? true:false;}}},
			quoStorageCity: {required: {depends: function(){return ($("[name='sameAsPrimary']:checked").length == 0)? true:false;}}},
			quoStorageState: {required: {depends: function(){return ($("[name='sameAsPrimary']:checked").length == 0)? true:false;}}},
			quoStorageZipcode: {required: {depends: function(){return ($("[name='sameAsPrimary']:checked").length == 0)? true:false;}}},
			
			quoLayup: {required: {depends: function(){return ($("[name^='watercraftIsPriRes_']").length == 1 || $("[name='sameAsPrimary']:checked").length == 0)? true:false;}}},
			quoBoatNavigationArea: {required: {depends: function(){return ($("[name^='watercraftIsPriRes_']").length == 1 || $("[name='sameAsPrimary']:checked").length == 0)? true:false;}}},
			
			quoCurrentInsured: "required",
			quoChooseOptions: "required",
			quoLiability: {required: {depends: function(){return ($("[name='quoChooseOptions']:checked").val() == 1)? true:false;}}},
			quoLiabilityOther: {required: {depends: function(){return ($("[name='quoLiability']").val() == 'Other')? true:false;}}},
			quoMedicalPayments: {required: {depends: function(){return ($("[name='quoChooseOptions']:checked").val() == 1)? true:false;}}},
			quoMedicalPaymentsOther: {required: {depends: function(){return ($("[name='quoMedicalPayments']").val() == 'Other')? true:false;}}},
			quoDeductible: {required: {depends: function(){return ($("[name='quoChooseOptions']:checked").val() == 1)? true:false;}}},
			quoDeductibleOther: {required: {depends: function(){return ($("[name='quoDeductible']").val() == 'Other')? true:false;}}},
			quoPersonalEffects: {required: {depends: function(){return ($("[name='quoChooseOptions']:checked").val() == 1)? true:false;}}},
			quoTowing: {required: {depends: function(){return ($("[name='quoChooseOptions']:checked").val() == 1)? true:false;}}},
			quoFishing: {required: {depends: function(){return ($("[name='quoChooseOptions']:checked").val() == 1)? true:false;}}},
			quoHowFound: "required"
		/* end validation for the policy info page */
		
		}
	});   

}

/* Created by jankoatwarpspeed.com */

(function($) {
    $.fn.formToWizard = function(options) {
        options = $.extend({  
            submitButton: "" 
        }, options); 
        
        var element = this;
        var steps = $(element).find("fieldset");
        var count = steps.size();
        var submmitButtonName = "#" + options.submitButton;
        $(submmitButtonName).hide();

        // 2
        $(element).before("<ul id='steps'></ul>");

        steps.each(function(i) {
            $(this).wrap("<div id='step" + i + "'></div>");
            $(this).append("<p id='step" + i + "commands'></p>");

            // 2
            var name = $(this).find("legend").html();
            $("#steps").append("<li id='stepDesc" + i + "'>Step " + (i + 1) + "<span>" + name + "</span></li>");

            if (i == 0) {
                createNextButton(i);
                selectStep(i);
            }
            else if (i == count - 1) {
                $("#step" + i).hide();
                createPrevButton(i);
            }
            else {
                $("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
        });

        function createPrevButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Prev' class='prev'>< Back</a>");

            $("#" + stepName + "Prev").bind("click", function(e) {
                $("#" + stepName).hide();
                $("#step" + (i - 1)).show();
                $(submmitButtonName).hide();
                selectStep(i - 1);
								makeCollapsable();
            });
        }

        function createNextButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next'>Next ></a>");

            $("#" + stepName + "Next").bind("click", function(e) {
						
							if(validateForm(i)){
								if(i == 0){
									if(addWatercraft()) {
										updateComplete(10);
									} else {
										showFirstInvalid();
										return false;
									}
								} else if(i == 1) {
									
									hasIssues = false;
									$.ajax({
										async: false,
										type: 'POST',
										url: 'contactInfoAdd.cfm',
										cache: false,
										data: $('#quoteForm').serialize(),
										success: function(data){
											if(data != 'Success') hasIssues = true;
										},
										error: function(XMLHttpRequest, textStatus, errorThrown){
											hasIssues = true;
										}
									});
									if (hasIssues) {
										hasIssues = false;
										alert('Unable to save Contact Info, please verify your information and try again.');
										return false;
									}
									
									$.blockUI({ message: '<h1>Loading Watercraft Info, Please Wait...</h1>' });
									if (!editNextWatercraftPolicy()) {
										$.unblockUI();
										return false;
									}
									updateComplete(5);
									
								} else if(i == 2) {
									
									hasIssues = false;
									$.ajax({
										async: false,
										type: 'POST',
										url: 'policyInfoAdd.cfm',
										cache: false,
										data: $('#quoteForm').serialize(),
										success: function(data){
											if(data != 'Success') hasIssues = true;
										},
										error: function(XMLHttpRequest, textStatus, errorThrown){
											hasIssues = true;
										}
									});
									if (hasIssues) {
										hasIssues = false;
										alert('Unable to save Policy Info, please verify your information and try again.');
										return false;
									}
									updateComplete(5);
									
								}

		            $("#" + stepName).hide();
		            $("#step" + (i + 1)).show();
		            if (i + 2 == count)
		                $(submmitButtonName).show();
		            selectStep(i + 1);
								makeCollapsable();
							} 
							showFirstInvalid();
            });
        }

        function selectStep(i) {
            $("#steps li").removeClass("current");
            $("#stepDesc" + i).addClass("current");
        }

    }
})(jQuery);


/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */

// $(document).ready(JT_init);

function JT_init(){
	$("a.jTip").unbind('hover').unbind('click').hover(function(){JT_show(this.href,this.id,this.name);}, function(){$('#JT').remove()}).click(function(){return false;});
}

function JT_show(url,linkId,title){
	if(title == false)title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) - 3; //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 250};
	if(params['link'] !== undefined){
	$('#' + linkId).bind('click',function(){window.location = params['link']});
	$('#' + linkId).css('cursor','pointer');
	}
	
	$("#JT").remove();
	if(hasArea>((params['width']*1)+75)){
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		var arrowOffset = getElementWidth(linkId) + 11;
		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
	}else{
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position
	}
	
	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$('#JT').show();
	$('#JT_copy').load(url);
}

function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}

function addBookmark(title,url) {
  if (window.sidebar) {
    window.sidebar.addPanel(title, url,"");
  } else if( document.all ) {
    window.external.AddFavorite( url, title);
  } else if( window.opera && window.print ) {
    return true;
  }
}