// csi.js
// Copyright (C) 2010, CloverLeaf Solutions, Inc.

var titleUpdated;
var contentUpdated;
var footerUpdated;

var sliderWaitInterval = 6000; // Milliseconds between each photo

var currentSliderNdx = 1;
var sliderFirstID;
var sliderFirstNdx;
var sliderLastID;
var sliderLastNdx;
var timer;

var okToSlide = true;

$(document).ready(function() {
	init();
	setTimeout("matchContentHeights();",500);
});

function matchContentHeights() {
	
	var div1;
	var div2;
	var leftAdjustment = 0;
	var rightAdjustment = 0;
	
	var adjustment = 0;
	
	if ( $('div.solutionContentLeft').length ) {
		div1 = "solutionContentLeft";
		div2 = "rightContentContainer";
	}

	if ( $('div.solutionContentLeft50').length ) {
		div1 = "solutionContentLeft50";
		div2 = "rightContentContainer50";
	}
	
	var leftHeight = $('div.' + div1).outerHeight() + leftAdjustment;
	var rightHeight = $('div.' + div2).outerHeight() + rightAdjustment;

	if($.browser.msie){
		//leftHeight = leftHeight + 15;
		if (leftHeight > rightHeight) {
			adjustment = leftHeight - rightHeight + 13;
			$('div.' + div2 + ' p:last').append("<br/><img src='/img/1x1.gif' border='0' alt='spacer' width='1' height='" + adjustment + "' border='0' />");
			$('div.' + div1).css("margin-bottom","-13px");
			$('div.' + div2).css("margin-bottom","-13px");
		} else {
			$('div.' + div1).height(rightHeight-47);
			$('div.' + div1).css("margin-bottom","-13px");
			$('div.' + div2).css("margin-bottom","-13px");
		}
	} else {

		if (leftHeight > rightHeight) {
			$('div.' + div2).height(leftHeight-1);
		} else {
			$('div.' + div1).height(rightHeight-32);
		}
	}

	return;
}

function attachNavEvents(parent, myClass) {
	$(parent + " ." + myClass).mouseover(function() {
		$(this).append('<div class="nav-' + myClass + '"></div>');
		$("div.nav-" + myClass).css({display:"none"}).fadeIn(100);
	}).mouseout(function() {
		$("div.nav-" + myClass).fadeOut(100, function() {
			$(this).remove();
		});
	}).mousedown(function() {
		$("div.nav-" + myClass).attr("class", "nav-" + myClass + "-click");
	}).mouseup(function() {
		$("div.nav-" + myClass + "-click").attr("class", "nav-" + myClass);
	});
}

function init() {
	
	// Remove dotted line around nav-link elements on focus
	$(".nav-link").focus(function() { 
		$(".nav-link").blur();
	});
	
	if (section == "/" || (section == "solutions" && page == "index")) {
		setTimeout("setupSlider();",sliderWaitInterval);
	}
	preloadImages(section);
	
	if (page == "submit-resume") {
		
		if ($.browser.msie && $.browser.version.substr(0,1) == "6") {
			alert('really? you are submitting a resume to a technology company and you are still using IE6?');
		} else {
			$('#resumeFileDisplay').change(function() {
				valid("resumeFileDisplay","select your resume file","","RESUME");
			});
			$('#contact-phone').change(function() {
				valid("contact-phone","enter a valid phone number","","PHONE");
			});
			$('#contact-email').change(function() {
				valid("contact-email","enter a valid email address","","EMAIL");
			});
			$('#position').change(function() {
				valid("position","select a position","-Select-","");
			});
			$('#own-resume').change(function() {
				valid("own-resume","confirm you are sending your own resume","checkbox","");
			});
	
			$('#resume').change(function() {
				setFile('resume', this.value);
				return true;
			});
			 
			$('#resume-name').change(function() {
				valid("resume-name","enter your name","","NAME");
			});
			
			// hack to make the .change fire after setting focus on an input in IE
			if( $.browser.msie ){ $('#resume-name').focusout(); }
			
			var defaultJob = $("#position").val();
			if (defaultJob != "-Select-") {
				valid("position","select a position","-Select-","");
	//			alert('defaultJob[' + defaultJob + ']');
			}
	
			$('#resume-name').focus();
		}
	}
	
	if (page == "submit-rfp") {
		$('#company-name').change(function() {
			valid("company-name","enter your company name","","");
		});
		$('#rfp-name').change(function() {
			valid("rfp-name","enter your name","","NAME");
		});
		$('#rfpFileDisplay').change(function() {
			valid("rfpFileDisplay","select your rfp document","","RFP");
		});
		$('#contact-phone').change(function() {
			valid("contact-phone","enter a valid phone number","","PHONE");
		});
		$('#contact-email').change(function() {
			valid("contact-email","enter a valid email address","","EMAIL");
		});

		$('#rfp').change(function() {
			setFile('rfp', this.value);
			return true;
		});

		// hack to make the .change fire after setting focus on an input in IE
		if( $.browser.msie ){ $('#company-name').focusout(); }

		$('#company-name').focus();
	}
	
	return;
}

function submitForm(formId) {
	
	if (formId == "rfp") {
		
		var postData = "clover=leaf";
		var errors = false;
		
		/* Validate in reverse order -- last field with error will have focus set
		*/
		
		// validate company-name
		if (!valid("company-name","enter your company name","","")) {
			errors = true;
			$("#company-name").focus();
		}
		
		// validate file
		if (!valid("rfpFileDisplay","select your rfp document","","RFP")) {
			errors = true;
			//$("#rfp").focus();
		}
		
		// validate email
		if (!valid("contact-email","enter a valid email address","","EMAIL")) {
			errors = true;
			$("#contact-email").focus();
		}

		// validate phone
		if (!valid("contact-phone","enter a valid phone","","PHONE")) {
			errors = true;
			$("#contact-phone").focus();
		}
		
		// validate name
		if (!valid("rfp-name","enter your name","","NAME")) {
			errors = true;
			$("#rfp-name").focus();
		}

		if (errors != true) {
			$("#browse_button").hide();
			$("#submit_button").hide();
			$("#busyIndicator").show();
			document.rfpForm.submit();
			return true;
		} else {
			return false;
		}
	}

	if (formId == "resume") {
		
		var postData = "clover=leaf";
		var errors = false;
		
		/* Validate in reverse order -- last field with error will have focus set
		*/
		
		// validate own-resume
		if (!valid("own-resume","confirm you are sending your own resume","checkbox","")) {
			errors = true;
			$("#own-resume").focus();
		}
		
		// validate file
		if (!valid("resumeFileDisplay","select your resume file","","RESUME")) {
			errors = true;
			//$("#resume").focus();
		}
		
		// validate position
		if (!valid("position","select a position","-Select-","")) {
			errors = true;
			$("#position").focus();
		}
		// validate email
		if (!valid("contact-email","enter a valid email address","","EMAIL")) {
			errors = true;
			$("#contact-email").focus();
		}

		// validate phone
		if (!valid("contact-phone","enter a valid phone","","PHONE")) {
			errors = true;
			$("#contact-phone").focus();
		}
		
		// validate name
		if (!valid("resume-name","enter your name","","NAME")) {
			errors = true;
			$("#resume-name").focus();
		}

		if (errors != true) {
			$("#browse_button").hide();
			$("#submit_button").hide();
			$("#busyIndicator").show();
			document.resumeForm.submit();
			return true;
		} else {
			return false;
		}
	}
}
function valid(id, desc, compare, validationType) {
	
	var comparisonErrorValue = "";
	var comparisonTarget = $("#" + id).val();
	var validValue = true;
	
	if (compare == "checkbox") {
		comparisonTarget = $("#" + id + ":checked").val();
		comparisonErrorValue = undefined;
	} else {
		if (compare != "") {
			comparisonErrorValue = compare;
		}
	}
	// These validations return a description so we can help the user with their issues
	// "OK"=valid; else invalid
	if (validationType == "NAME") {
		desc = validName(comparisonTarget);
		if (desc == "OK") {
			validValue = true;
		} else {
			validValue = false;
		}
	} else {
		if (validationType =="EMAIL") {
			desc = validEmail(comparisonTarget);
			if (desc == "OK") {
				validValue = true;
			} else {
				validValue = false;
			}
		} else {
			if (validationType == "PHONE") {
				desc = validPhone(comparisonTarget);
				if (desc == "OK") {
					validValue = true;
				} else {
					validValue = false;
				}
			} else {
				if (validationType == "RESUME") {
					var fileNameOnly = comparisonTarget;
					var tmp = comparisonTarget;
					var ndx = tmp.lastIndexOf("\\");
					if (ndx > 0) {
						fileNameOnly = tmp.substr(ndx + 1);
					}
					comparisonTarget = fileNameOnly;
					desc = validResume(comparisonTarget);
					if (desc == "OK") {
						validValue = true;
					} else {
						validValue = false;
					}
				} else {
					if (validationType == "RFP") {
						var fileNameOnly = comparisonTarget;
						var tmp = comparisonTarget;
						var ndx = tmp.lastIndexOf("\\");
						if (ndx > 0) {
							fileNameOnly = tmp.substr(ndx + 1);
						}
						comparisonTarget = fileNameOnly;
						desc = validRFP(comparisonTarget);
						if (desc == "OK") {
							validValue = true;
						} else {
							validValue = false;
						}
					}
				}
			}
		}
	}
	
	// remove the notSet class once validated... 
	$("#" + id).removeClass('notSet');
	
	if (comparisonTarget != comparisonErrorValue && validValue) { 
		$("#" + id).removeClass('inputError');
		$("#" + id + "Status").hide().html('<img src="/img/check-mark.png" alt="ready" />').fadeIn("slow");
		$("#" + id + "Msg").html('');
		
		// see if we can enable the submit button by checking all other fields' error status (look for inputError class)
		setSubmitButtonState();
		
		return true;
	} else {
		$("#" + id).addClass('inputError');
		$("#" + id + "Status").hide().html('<img src="/img/exclaim-red.png" alt="Error" />').fadeIn("slow");
		$("#" + id + "Msg").html('Please ' + desc);
		
		// see if we can enable the submit button by checking all other fields' error status (look for inputError class)
		setSubmitButtonState();
		
		return false;
	}
}

// see if we can enable the submit button by checking all other fields' error status (look for inputError class)
function setSubmitButtonState() {
	var notSetCount = $('.notSet').length;
	var errorCount = $('.inputError').length;
	if (errorCount == 0 && notSetCount ==0) {
		$("#submit_button").removeClass('disabled_button');
	} else {
		$("#submit_button").addClass('disabled_button');
	}
}

function setFile(fileType, val) {
	var fileNameOnly = val;
	var tmp = val;
	var ndx = tmp.lastIndexOf("\\");
	if (ndx > 0) {
		fileNameOnly = tmp.substr(ndx + 1);
	}
	$("#" + fileType + "FileDisplay").val(fileNameOnly);
	$("#" + fileType + "FileDisplay").trigger('change');
}

/* Form Validations
*/
function validName(name) {
	if (name == "") {
		return "enter your name";
	}
	// name must have first and last separated by space - each part must be at least 2 characters
	if (name.indexOf(" ")== -1) {
		return "enter your first and last name, separated by a space";
	} else {
		var name_parts = name.split(" ");
		if (name_parts[0].length < 2 || name_parts[1].length < 2) {
			return "enter your first and last name (each at least 2 characters)";
		}
	}
	return "OK";
}

function validResume(filename) {
	if (filename == "") {
		return "select your resume file (Accepted formats: .doc, .docx, or .pdf)";
	}
	
	var validExtensions = "DOC;DOCX;PDF"
	// parse out extension
	var file_parts = filename.split(".");
	
	var num_parts = file_parts.length;
	
	if (num_parts > 0) {
		num_parts--;
		var ext = file_parts[num_parts].toUpperCase();
		var foundIndex = validExtensions.indexOf(ext);
		if (foundIndex < 0) {
			return "select your resume file (Accepted formats: .doc, .docx, or .pdf)";
		}
	} else {
		return "select your resume file (Accepted formats: .doc, .docx, or .pdf)";
	}

	return "OK";
}

function validRFP(filename) {
	if (filename == "") {
		return "select your rfp document file";
	}
	
	var validExtensions = "DOC;DOCX;PDF;TXT;ZIP"
	// parse out extension
	var file_parts = filename.split(".");
	
	var num_parts = file_parts.length;
	
	if (num_parts > 0) {
		num_parts--;
		var ext = file_parts[num_parts].toUpperCase();
		var foundIndex = validExtensions.indexOf(ext);
		if (foundIndex < 0) {
			return "select your rfp document<br/>(Accepted formats: .doc, .docx, .pdf, .txt, or .zip)";
		}
	} else {
		return "select your rfp document<br/> (Accepted formats: .doc, .docx, .pdf, .txt, or .zip)";
	}

	return "OK";
}


function validPhone(phone_input) {
		
	// First trim any leading or trailing whitespace...
	
	var phone_string = phone_input.replace(/\s/g, "");
	phone_string = phone_string.replace(/\-/g, "");
	phone_string = phone_string.replace(/\./g, "");
	phone_string = phone_string.replace(/\)/g, "");
	phone_string = phone_string.replace(/\(/g, "");
	
	if (phone_string.substr(0,1) == "1") {
		phone_string = phone_string.substr(1);
	}

	if (phone_string.length < 10) {
		return "enter a valid 10-digit phone number";
	}
	
	var phone_ext = "";
	
	if (phone_string.length > 10) {
		phone_ext = phone_string.substr(10);
		phone_string = phone_string.substr(0,10);
	}
	// now split into parts and check with validations below...
	splittable_phone = phone_string.replace(/\(?\b([0-9]{3})\)?[\-. ]?([0-9]{3})[\-. ]?([0-9]{4})\b/g, "$1-$2-$3");
	var phone_parts = splittable_phone.split("-");
	
	var phone_area = phone_parts[0];
	var phone_prefix = phone_parts[1];
	var phone_number = phone_parts[2];
	
	if (phone_area == undefined || phone_area == undefined || phone_number == undefined) {
		return "enter a valid 10-digit phone number";
	}
	
	// Phone Validations (Error Conditions):
	// - All must be numeric and completely filled
	
	// - Area Code:
	//   - Allowed range of [2-9] for the first digit, [0-8] for the second, and [0-9] for the third digit.
	//   - Can't be 911 or 000
	
	// - Prefix:
	//	 - Allowed ranges [2-9] for the first digit, and [0-9] for both the second and third digits.
	//   - Can't be 555
	
	if (!isNumeric(phone_number) || phone_number.length != 4) {
		return "enter a valid phone number (numbers must be numbers)";
	}
	if (!isNumeric(phone_prefix) || phone_prefix.length != 3 || phone_prefix == "555") { 
		return "enter a valid phone number (Prefix " + phone_prefix + " is invalid)";
	} else {
		if (parseInt(phone_prefix.substring(0,1)) < 2 ) {
			return "enter a valid phone number (Prefix " + phone_prefix + " is invalid)";
		}
	}
	if (!isNumeric(phone_area) || phone_area.length != 3 || phone_area == "000" || phone_area == "911") {
		return "enter a valid phone number (Area code " + phone_area + " is invalid)";
	} else {
		if (parseInt(phone_area.substring(0,1)) < 2 ) {
			return "enter a valid phone number (Area code " + phone_area + " is invalid)";
		}
		if (parseInt(phone_area.substring(1,2)) > 8 ) {
			return "enter a valid phone number (Area code " + phone_area + " is invalid)";
		}
	}

	// Phone is OK, display with formatting
	var newNum =  "(" + phone_area + ") " + phone_prefix + "-" + phone_number;
	if (phone_ext != "") {
		newNum = newNum + " " + phone_ext;
	}
	$("#contact-phone").val(newNum);
	
	return "OK";
}

function isNumeric(sText) {
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}
	

function validEmail(emailAddress) {

	var at="@";
	var dot=".";
	var lat=emailAddress.indexOf(at);
	var lstr=emailAddress.length - 1;
	var ldot=emailAddress.indexOf(dot);
	
	if (emailAddress.indexOf(at) == -1 || emailAddress.indexOf(at) == 0 || emailAddress.indexOf(at) == lstr) {
		return "enter a valid email address (must include a @)";
	}

	if (emailAddress.indexOf(dot) == -1 || emailAddress.indexOf(dot) == 0 || emailAddress.indexOf(dot) == lstr) {
		return "enter a valid email address (must include a .)";
	}

	 if (emailAddress.indexOf(at,(lat+1)) != -1) {
		return "enter a valid email address (can only have one @)";
	 }

	 if (emailAddress.substring(lat-1,lat) == dot || emailAddress.substring(lat+1,lat+2) == dot) {
		return "enter a valid email address (must include charactes between the . and @)";
	 }

	 if (emailAddress.indexOf(dot,(lat+2)) == -1) {
		return "enter a valid email address (must include a . after the @)";
	 }
	
	 if (emailAddress.indexOf(" ") != -1) {
		return "enter a valid email address (no spaces are allowed)";
	 }

	 return "OK";					
}
	
function preloadImages(section) {
	
/* TO DO: call PHP via AJAX to get list of images in the current section and then preload them */	
	
	if (section == "/") {
		preload(section,[
			'/img/about/index.jpg',
			'/img/solutions/index.jpg',
			'/img/methods/index.jpg',
			'/img/careers/index.jpg',
			'/img/sales/index.jpg',
			'/img/terms/index.jpg',
			'/img/privacy/index.jpg',
			'/img/download/index.jpg',
			'/img/contact/index.jpg'
		]);
	} else {
		if (section == "about") {
			preload(section,[
				'/img/about/mission-statement.jpg',
				'/img/about/philosophy.jpg',
				'/img/about/value-proposition.jpg',
				'/img/about/consulting-services.jpg',
				'/img/about/history.jpg'
			]);
		} else {
			if (section == "solutions") {
				preload(section,[
					'/img/solutions/software-development.jpg',
					'/img/solutions/systems-integration.jpg',
					'/img/solutions/project-management.jpg',
					'/img/solutions/data-management.jpg',
					'/img/solutions/user-experience.jpg',
					'/img/solutions/all.jpg',

					'/img/solutions/background-checks.jpg',
					'/img/solutions/criminal-processing.jpg',
					'/img/solutions/sex-arson-registration.jpg',
					'/img/solutions/data-exchange.jpg',
					'/img/solutions/dynamic-user-interface.jpg',
					'/img/solutions/background-checks.jpg',
					'/img/solutions/gambling-registration.jpg',
					'/img/solutions/dispositions.jpg',
					'/img/solutions/clets-gateway.jpg',
					'/img/solutions/subsequent-arrest-notifications.jpg',
					'/img/solutions/requirements-analysis.jpg',
					'/img/solutions/datamart.jpg',
					'/img/solutions/performance-testing.jpg',
					'/img/solutions/dna-processing.jpg',
					'/img/solutions/business-intelligence.jpg',
					'/img/solutions/user-acceptance-testing.jpg',
					'/img/solutions/data-validation.jpg',
					'/img/solutions/record-consolidation.jpg',
					'/img/solutions/class-registration.jpg',
					'/img/solutions/knowledge-management.jpg',
					'/img/solutions/child-abuse-notifications.jpg',
					'/img/solutions/fingerprint-card-scanning.jpg',
					'/img/solutions/data-mining.jpg'
				]);
			} else {
				if (section == "methods") {
					preload(section,[
						'/img/methods/software-development-lifecycle.jpg',
						'/img/methods/standards.jpg',
						'/img/methods/our-approach.jpg'
					]);
				} else {
					if (section == "careers") {
						preload(section,[
							'/img/careers/benefits.jpg',
							'/img/careers/culture.jpg',
							'/img/careers/current-openings.jpg',
							'/img/careers/submit-resume.jpg'
						]);
					} else {
						if (section == "sales") {
							preload(section,[
								'/img/sales/california-small-business.jpg',
								'/img/sales/cmas.jpg',
								'/img/sales/msa.jpg',
								'/img/sales/submit-rfp.jpg'
							]);
						}
					}
				}
			}
		}
	}
}


function preload(section,arrayOfImages) {
    $(arrayOfImages).each(function(){
        (new Image()).src = this;
    });
}


function setupSlider() {
	
	var sliderContentUrl = "/inc/";
	
	if (section == "/") {
		sliderContentUrl += "homeSlider.inc";
	} else {
		if (section == "solutions") {
			sliderContentUrl += section + "Slider.inc";
		} else {
			return false;
		}
	}
	
	var quote = '"';
	var sliderControls = "<div id='sliderControls'>";
	sliderControls += "<a href=" + quote + "javascript:slideFeature('PREV');" + quote + "><img src='/img/prev-button.png' alt='previous' border='0'/></a> ";
	sliderControls += "<a id='pause-link' href=" + quote + "javascript:pauseSlider();" + quote + "><img src='/img/pause-button.png' alt='pause' border='0'/></a>";
	sliderControls += "<a id='play-link' href=" + quote + "javascript:playSlider();" + quote + "><img src='/img/play-button.png' alt='play' border='0'/></a>";
	sliderControls += " <a href=" + quote + "javascript:slideFeature('NEXT');" + quote + "><img src='/img/next-button.png' alt='next' border='0'/></a>";
	sliderControls += "</div>";
	
	$.ajax({
	  url: sliderContentUrl,
	  async:true,
	  cache: false,
	  success: function(html){
		$("#sliderContainer").html(html).append(sliderControls);

		$("#sliderControls a").focus(function() { 
			$("#sliderControls a").blur();
		});

		timer = setTimeout("startSlider();",100);
	  }
	});
}

function startSlider() {
	
	// determine first and last items
	sliderFirstID = $('#cloverSlider .staging li').first().attr("id");
	sliderLastID  = $('#cloverSlider .staging li').last().attr("id");
	
	if (sliderFirstID == "" || sliderFirstID == "undefined" || sliderLastID == "" || sliderLastID == "undefined") {
		alert('problem loading features');
		return false;		
	}

	sliderFirstNdx = sliderFirstID.substr(sliderFirstID.indexOf("-")+1);
	sliderLastNdx = sliderLastID.substr(sliderLastID.indexOf("-")+1);
	
	//load first item
	$('#cloverSlider .viewport').fadeOut('slow',function() {
		$('#cloverSlider .viewport').html($('#cloverFeature-1').html()).fadeIn('slow');
	});
	
	// start first slide
	timer = setTimeout("slideFeature();",sliderWaitInterval);
}

function slideFeature(ctrl) {
	
	var waitIntervalExtension = 0;
	
	if (ctrl != "" && okToSlide == false) {
		// PREV or NEXT pressed while paused, hide play link and show pause link
		$("#play-link").hide();$("#pause-link").show();
		okToSlide = true;
	}
	
	clearTimeout(timer);
	
	if (ctrl=="PREV") {
		// add 5 seconds to waitInterval if user clicks Prev (they missed something and want to read it - let them read it)
		waitIntervalExtension = 7000;
		okToSlide = true;
	}
	
	if (okToSlide == true) {
		if (ctrl=="PREV") {
			// Go to previous feature
			currentSliderNdx = currentSliderNdx - 1;	
			// If past first feature, go to last
			if (currentSliderNdx < 1) {
				currentSliderNdx = sliderLastNdx;
			}

		} else {
			// Just go to next feature
			currentSliderNdx = currentSliderNdx + 1;	
			// If last feature, go to first
			if (currentSliderNdx > sliderLastNdx) {
				currentSliderNdx = 1;
			}
		}
	
		$('#cloverSlider .viewport').fadeOut('slow',function() {
			$('#cloverSlider .viewport').html($('#cloverFeature-' + currentSliderNdx).html()).fadeIn('slow');
		});
		// and now for a bit of recursion...
		timer = setTimeout("slideFeature();",sliderWaitInterval + waitIntervalExtension);
	} else {
		return false;
	}
}

function pauseSlider() {
	$("#pause-link").hide();$("#play-link").show();
	clearTimeout(timer);
	okToSlide = false;
}
function playSlider() {
	$("#play-link").hide();$("#pause-link").show();
	clearTimeout(timer);
	okToSlide = true;
	timer = setTimeout("slideFeature();",sliderWaitInterval);
}






