/* UTILS ******************************************************/
function queryVal(name) {
  var v = (new RegExp("[\\?&]"+ (name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]")) +"=([^&#]*)")).exec(window.location.href);
  if (v == null) return "";
	else return v[1];
}

function hrefHash(hash) {
	var l = window.location.href;
	var h = l.indexOf('#');
	if (h > 0 && l.length >= h && hash == null) // if hash is null, then we are requesting the current hash
		return l.slice(h+1);
	else if (h > 0 && hash != null) // if h and hash exists, then we are requesting to replace it
		window.location = l.slice(0, h+1) + hash;
	else if (hash != null)
		window.location = window.location.href +'#'+ hash
	return '';
}

function _id(id) {
	return document.getElementById(id);
}

/* CAPTHCA ******************************************************/
function CheckCaptchas(thisStep, stepDirections, otherStepValidations) {
	thisStep = thisStep == null? 'Step3': thisStep;	
	var qrystr = queryVal("Captchas");
	if (qrystr == "false" || qrystr == "duplicate") {
		if (otherStepValidations && otherStepValidations != '')
			ValidateSteps(otherStepValidations, thisStep, '', '');

		DisplayDiv(thisStep);
		jQuery("#error"+ thisStep).css('visibility', 'visible');
		jQuery("#confirmationcode").addClass("invalid");
		hrefHash('confirmationcode');

		// enable All Step Buttons, since we've completed all previous steps
		jQuery('div.stepbutton').css('display', 'block');

		// if there are further directions for this step
//		if (stepDirections != null)
//			stepSetup(stepDirections)

		return false;
	} else
		return true;
}

// store previous id in a global variable between function calls
var PreviousDivId = "Step1";

function DisplayDiv(DivId, stepDirections){
	// hide previous Step
	_id(PreviousDivId).style.display = 'none';
	
	// update instructions
	//_id("Instructions").innerHTML = Instructions;
	
	// display selected Step
	_id(DivId).style.display = 'block';
	
	// remember Step to hide at next function call
	PreviousDivId = DivId;

	// change the Step navigation backgound image
	if (_id('StepsNav') != null)
		_id('StepsNav').style.backgroundImage = 'url(/images/' + PreviousDivId + '.gif)';

	if (stepDirections != null)
		stepSetup(stepDirections)
	
	// jump to top of the steps
	hrefHash('StepsTop');
}

function stepSetup(stepDirections) {
	switch (stepDirections) {
		case "setupHearabout":
			setupHearabout(); break;
	}
}

// store previous id in a global variable between function calls
var PreviousDropDownId = "";

function DisplayDropDown(DropDown) {
	DropDownId = DropDown.options[DropDown.selectedIndex].id;

	// hide previous div
	if (PreviousDropDownId != '')
		jQuery("#div"+ PreviousDropDownId).css('display', 'none');

	// display selected div
	jQuery("#div"+ DropDownId).css('display', 'block');
//jQuery("#div"+ DropDownId +' select')[0].selectedIndex = -1;
//alert(jQuery("#div"+ DropDownId +' select')[0].selectedIndex);

	// remember div to hide at next function call
	return PreviousDropDownId = DropDownId;
}

// Clears All previously selected dropdown values
function DropDownIndex(){
	jQuery("select.subdropdown").each(function() {
		$t = jQuery(this);
		if ($t[0].selectedIndex) { //// && $t[0].selectedIndex == 0)
			if ($t[0].selectedIndex >= 0 && $t[0].options[$t[0].selectedIndex].getAttribute('default') != null)
				return;
			$t[0].selectedIndex = -1;
		}
	});
}

PreviousOtherTextBoxId = null;
OtherTextBoxId = null;
function DisplayOtherTextBox(OtherDropDown) {
	// Hide all Other containers
	jQuery('.OtherTextDiv').css('display', 'none');

	OtherTextBoxId = OtherDropDown.options[OtherDropDown.selectedIndex].id;
	if (OtherTextBoxId != null && OtherTextBoxId != "")
		jQuery("#div"+ OtherTextBoxId).css('display', 'block');
/*
	if (PreviousOtherTextBoxId != null && PreviousOtherTextBoxId != "")
		jQuery("#div"+ PreviousOtherTextBoxId).css('display', 'none');
	return PreviousOtherTextBoxId = OtherTextBoxId; */
	return OtherTextBoxId;
}

var stepping = null;
function ValidateSteps(steps, thisStep, nextStep, nextStepDirections) {
	var steps = steps.split(',');
	var thisSteps = thisStep.indexOf(',') > 0? thisStep.split(','): null;
	var r = null;
	for (var i = 0, l = steps.length; i < l; i++) {
		eval('stepping = ValidateStep'+ steps[i] +'("'+ (thisSteps != null? thisSteps[i]: thisStep) +'","'+ nextStep +'","'+ nextStepDirections +'", '+ r +');');
		if (stepping != null && stepping == false)
			r = false;
//alert(r);
}
	r = r == null? true: false;

	if (!r)	jQuery("#error"+ thisStep).css('visibility', 'visible');

	$('#valid').value = r;
////alert(steps+':'+stepping+'%'+r);return false;
	return r;
}

function ValidateStepPersonal(thisStep, nextStep, nextStepDirections, carryOnErr){ 
	// Check Required Form Fields
	var err = false;
	carryOnErr = carryOnErr == null? true: false;
////alert(thisStep +' > '+ jQuery("div#"+ thisStep +" .required").length);
	jQuery("div#"+ thisStep +" .required").each(function() {
		var $t = jQuery(this);
		if (($t.attr("type") == "text" || $t.tagName == "textarea") && $t[0].value == "") {
			$t.addClass("invalid");
			$t.siblings("label[for="+ $t[0].id +"]").addClass("invalid");
			err = true;
		} else {
			$t.removeClass("invalid");
		}
	});

	/* LEAST ONE!!! */
	var radio = {}, radios = [], lastRadio = '', x = -1;
	jQuery("div#"+ thisStep +" .least").each(function() {
		var $t = jQuery(this);
		// check for the attribute radio, then
		var $radio = $t.attr("radio");
		if (lastRadio != $radio)
			radios[++x] = $radio;
		lastRadio = $radio;
		if (eval("radio."+ $radio) == null)
			eval("radio."+ $radio +" = false;")

		if (($t.attr("type") == "text" || $t.tagName == "textarea") && $t[0].value != "") {
			eval("radio."+ $radio +" = true");
		} else if (($t.attr("type") == "text" || $t.tagName == "textarea") && $t[0].value == "" && !eval("radio."+ $radio)) {
			eval("radio."+ $radio +" = false");
		}
	});

	for (var i = 0, l = radios.length; i < l; i++)
		if (!eval("radio."+ radios[i])) { err = true; jQuery('.least[radio='+ radios[i] +']').addClass("invalid"); }
			else jQuery('.least[radio='+ radios[i] +']').removeClass("invalid");
	
	if (!err) // clear this steps errors
		jQuery("div#"+ thisStep +" .invalid").removeClass("invalid");
	
//alert(err +':'+ !carryOnErr);
	if (err || !carryOnErr) {
		jQuery("#error"+ thisStep).css('visibility', 'visible');
		return false;
	} else {
		jQuery(".errorStep").css('visibility', 'hidden');
		jQuery(".errorspecific").css('display', 'none');
	}

	// enable Next Step
	if (nextStep != null && nextStep != '') {
		DisplayDiv(nextStep, nextStepDirections);
		jQuery('div#'+ nextStep +'Button').css('display', 'block');
	}
	
	return true;
}

function setupHearabout() {
	var $h = jQuery("#hear_hearabout");
	var h2Id = '', h3Id = '';
	var $n = jQuery("input#hidden_hearnetjets");
	var $n1 = jQuery("input#hidden_hearnetjetsPrimary");
	var $n2 = jQuery("input#hidden_hearnetjetsSecondary");

//alert('setup:'+ $n[0].value+':'+$n1[0].value+':'+$n2[0].value);

	// Select the Primary Option
	if ($n1[0].value != '' || $n[0].value != '') {
		v = $n1[0].value != ''? $n1[0].value: $n[0].value;
		for (var i = 0, l = $h[0].options.length; i < l; i++)
			if ($h[0].options[i].value == v) {
				$h[0].selectedIndex = i;
				l=-1;
				h2Id = DisplayDropDown($h[0]);
			}
	}

	// Select the Secondary Option or fill Secondary Text
	if (h2Id != '')
		if ($n2[0].value != '' || $n[0].value != '') {
			var $hDiv = jQuery("#div"+ h2Id);
			$h = $hDiv.children("select");
			v = $n2[0].value != ''? $n2[0].value: $n[0].value;

			// If SELECT
			if ($h.get() && $h.length > 0) {
				for (var i = 0, l = $h[0].options.length; i < l; i++)
					if ($h[0].options[i].value == v) {
						$h[0].selectedIndex = i;
						l=-1;
						h3Id = DisplayOtherTextBox($h[0]);
					}
			} else { // TEXT
				if (h2Id.indexOf('-') > 0)
					optid = h2Id.slice(0, h2Id.indexOf('-'));
				else
					optid = h2Id;
				var $h = jQuery("#hear"+ optid);
				if ($h.get() && $h.length > 0) {
					$h[0].value = v;
					$h.trigger('click'); // hide hover label
				}
			}
		}

	// Fill Tertiary Text
	if (h3Id != '')
		if ($n[0].value != '') {
			var $h = jQuery("#hear"+ h3Id);
			if ($h.get() && $h.length > 0 && $h[0].tagName && $h[0].tagName.toLowerCase() == "input") {
				$h[0].value = $n[0].value;
				$h.trigger('click'); // hide hover label
			}
		}
}

function ValidateStepHearAbout(thisStep, nextStep, nextStepDirections, carryOnErr){  
	var err = false;
	var $h = jQuery("#hear_hearabout");
	var $n = jQuery("input#hidden_hearnetjets");
	var $n1 = jQuery("input#hidden_hearnetjetsPrimary");
	var $n2 = jQuery("input#hidden_hearnetjetsSecondary");
	carryOnErr = carryOnErr == null? true: false;
//alert('validate:'+$n[0].value+':'+$n1[0].value+':'+$n2[0].value);

	// nullify the hiddens
	$n[0].value = $n1[0].value = $n2[0].value = '';

	// Check Drop Down
	if($h[0].selectedIndex < 0) {
		$h.addClass("invalid");
		$h.siblings("label[for="+ $h[0].id +"]").addClass("invalid");
////alert('0* '+ $h[0].id);
		err = true;
	} else {
		$n1[0].value = $n[0].value = $h[0][$h[0].selectedIndex].value; // set base select value
		// Check Secondary Drop Downs
		var optid = $h[0].options[$h[0].selectedIndex].id;
		var selid = '';
		if (optid.indexOf('-') > 0) {
			selid = optid.slice(optid.indexOf('-')+1);
			optid = optid.slice(0, optid.indexOf('-'));
		}
		var optval = $h[0].options[$h[0].selectedIndex].value;
		var $t = jQuery("#hear"+ optid);

		if ($t && $t[0] && $t[0].options) {
			if($t.parent('div').css('display') == 'block' && $t[0].selectedIndex == -1) {
				$t.addClass("invalid");
				$t.siblings("label[for="+ $t[0].id +"]").addClass("invalid");
//alert('1* '+ $t[0].id);
				err = true;
			} else if ($t[0].selectedIndex >= 0) {
				$n2[0].value = $n[0].value = $t[0][$t[0].selectedIndex].value; // set secondary select value
				var opt2id = jQuery("#hear"+ optid)[0].options[jQuery("#hear"+ optid)[0].selectedIndex].id;
				if (opt2id.toLowerCase().indexOf("please_specify") > 0) {
					var $o = jQuery("#hear"+ opt2id);
					if ($o.attr("type") == "text" && $o[0].value == "") {
						$o.addClass("invalid");
						$o.siblings("label[for=hear"+ opt2id +"]").addClass("invalid");
//alert('2* '+ $o[0].id);
						err = true;
					} else
						$n[0].value = $o[0].value; // set tertiary text value
				}
			}
//alert('3* '+ $t.parent('div').css('display') +':'+ $t[0].selectedIndex);
		} else {
			// Check Secondary Text Fields
			var whichopt = selid != ''? '_'+selid: optid;
			var opt2id = jQuery("#hear"+ whichopt)[0].options[jQuery("#hear"+ whichopt)[0].selectedIndex].id;
			if (opt2id.toLowerCase().indexOf("please_specify") > 0) {
				var $o = jQuery("#hear"+ opt2id);
				if ($o.attr("type") == "text" && $o[0].value == "") {
					$o.addClass("invalid");
					$o.siblings("label[for=hear"+ opt2id +"]").addClass("invalid");
////alert('3* '+ $o[0].id);
					err = true;
				} else
					$n[0].value = $o[0].value; // set secondary text value
			}
		}
	} // end if
	
	if (!err) // clear this steps errors
		jQuery("div#"+ thisStep +" .required.invalid").removeClass("invalid");

//alert(err +':'+ carryOnErr);

////alert(thisStep +' > '+ jQuery("div#"+ thisStep +" .required").length);
////alert(err +':'+ !carryOnErr +'='+ (err || !carryOnErr));
	if (err || !carryOnErr) {
		jQuery("#error"+ thisStep).css('visibility', 'visible');
		return false;
	} else {
////alert(thisStep +' > '+ jQuery("div#"+ thisStep +" .required.invalid").length);
		jQuery(".errorStep").css('visibility', 'hidden');
		jQuery(".errorspecific").css('display', 'none');	
	}

	// enable Next Step
	if (nextStep != null && nextStep != '') {
		DisplayDiv(nextStep, nextStepDirections);
		jQuery('div#'+ nextStep +'Button').css('display', 'block');
	}
	
	return true;
} //: ValidateStepHearAbout()

function ValidateStepBooks(thisStep, nextStep, nextStepDirections, carryOnErr, trackURL) {
	   if ( trackURL === undefined ) {
      trackURL = '';
   }

	// Check Required Form Fields
	var err = false;
	var totalCheckboxes = 0;
	var totalChecked = 0;
	carryOnErr = (carryOnErr == null || carryOnErr=="true") ? true: false;
	jQuery("div#"+ thisStep +" .setbooks").each(function() {
		var $t = jQuery(this);
		if ($t.attr("type") == "checkbox" && $t[0].checked == true)
			totalChecked++;
		totalCheckboxes++;		
	});

	if (totalChecked == 0)
		err = true;

	if (!err) // clear this steps errors
		jQuery("div#"+ thisStep +" .required.invalid").removeClass("invalid");

	if (err || !carryOnErr) {
		jQuery("div#"+ thisStep +" .checkSetBooks").addClass("invalid");
		jQuery("#error"+ thisStep).css('visibility', 'visible');
		return false;
	} else {
		jQuery(".errorStep").css('visibility', 'hidden');
	}
/*
	if (err) {
		jQuery("div#"+ thisStep +" .checkSetBooks").addClass("invalid");
		jQuery("div#errormsgs #errorStep1").css('display', 'inline');
		return;
	} else {
		jQuery("div#"+ thisStep +" .checkSetBooks").removeClass("invalid");
		jQuery("div#errormsgs .errorStep").css('display', 'none');
		jQuery(".invalid").removeClass("invalid");
	}
*/
	// enable Next Step
	if (nextStep != null && nextStep != '') {
		DisplayDiv(nextStep, nextStepDirections);
		if (trackURL != '' ){
			try {
				_id('tracking_pixel').src=trackURL;
				
			}catch (e) {
			//for testing	
			}
		}
		
		jQuery('div#'+ nextStep +'Button').css('display', 'block');
	}
	
	return true;
} //: ValidateStepBooks()

function ValidateStepCaptcha(thisStep, aNull, bNull, carryOnErr){
	thisStep = thisStep == null? 'Step3': thisStep;
	carryOnErr = carryOnErr == null? true: false;
//alert(carryOnErr+':'+ thisStep);

	// only check if filled in, server needs to validate correctness
	if (jQuery("#confirmationcode")[0].value.length < 1) {
		jQuery("#error"+ thisStep).css('visibility', 'visible');
		jQuery("#confirmationcode").addClass("invalid");
		jQuery("#error_confirmationcode").css('display', 'inline');
		$('#valid').value = 'false';
		return false;
	} else {
		if (!carryOnErr) {
			jQuery(".errorStep").css('visibility', 'hidden');
			jQuery(".errorspecific").css('display', 'none');
		}
		jQuery("#confirmationcode").removeClass("invalid");
	}

//alert(carryOnErr+':'+ thisStep);
	
	if (!carryOnErr) {
		$('#valid').value = 'false';
		return false;
	}

	$('#valid').value = 'true';
	// form is valid -> submit
	return true;	
}

function percentageOutput(p) {
return;
	var v = p.value;
	if (parseInt(v) == v && v > 100)
		v = v.slice(1);
	var val = parseInt((v).toString().replace(/[^0-9]/g, ''));
	p.value = (val == 'NaN' || val == null? 0: val) +'%';
}

/* HOVER ******************************************************/

function triggerSelects() {
$('select').each(function () {
	var $t = $(this);
	var triggered = $t.attr('triggered') == 'true'? true: false;
	if ($t[0].selectedIndex >= 0 && !triggered) { // only if not default
//alert($t[0].options[$t[0].selectedIndex].id);
		$t.trigger('change');
		$t.attr('triggered', 'true');
		triggerSelects();
	}
});
}

jQuery(function() { // ON LOAD
	// Find all input elements that are after labels that have a class of hover

// run through all selects and activate onchange if selection exists
	triggerSelects();
	
	jQuery("label.hover+input").add("label.hover+textarea")
	    // Wrap a div (with a class of hover-wrap) around the input element,
	    // resulting in HTML that looks like:
	    // <div class='hover-wrap'><input type="text" …/></div>
		.each(function() {
				var $t = jQuery(this);
				$t
				.wrap("<div class='hover-wrap hover-wrap-"+ this.tagName.toString().toLowerCase() +"'></div>")
		})
	    // Whenever the input element is focused upon (either through a click
	    // or by keyboard), hide the label 
	    .focus(function(){
			var $t = jQuery(this);
	        $t.prev().hide();
	    })
		.click(function(){ // acts like focus but useful when object can't be focused just yet
			var $t = jQuery(this);
	        $t.prev().hide();
		})

	    // Whenever the user has left the input element (and no text has been
	    //  entered into it) reveal the label again.
	    .blur(function(){
			var $t = jQuery(this);
	        if (!this.value) $t.prev().show()
	    })

	    // Go through each of the input elements individually
	    .each(function(){
			var $t = jQuery(this);
	        // Move the label to go inside of the <div class='hover-wrap'></div>
	        $t.before( $t.parent().prev() );

	        // Make sure that if a value is already in the form, that the label is
	        //  automatically hidden
	        if ( this.value ) $t.prev().hide();
	    });
	
	// JN: makes the label actually clickable and focus the input
	jQuery("label.hover").click(function() { 
		$t = jQuery(this);
		$t.hide();
		$t.next().focus();
	});
});