﻿//*****************************************************************************************************************/
// Beyond.com JS library
// Property of Beyond.com 1/13/2009
// 
// Central location for all reuseable javascript code, requires jquery library 1.2.6 or later
//*****************************************************************************************************************/
var isValid = true;
var shareObject = new myShareObj();

var emailJobForm = '<div id="Email" class="email_form"><div class="heading"><div class="close"></div><p>Send this job to a friend</p></div><div id="forms"><div id="form"><div id="left_col" class="float_left"><p>Your first name</p><p>Your last name</p><p>Your email</p><p>To email</p><p class="one_row">Personal message</p><p class="one_row">(optional)</p></div><div id="right_col" class="float_left"><div class="one_row"><input id="fName" class="name fName"/><div class="errDiv"><label for="fName" class="error">*required</label></div></div><div class="one_row"><input id="lName" class="name lName"/><div class="errDiv"><label for="lName" class="error">*required</label></div></div><div class="one_row"><input id="fromEmail" class="email fromEmail"/><div class="errDiv"><label for="fromEmail" class="error">*must be a valid email</label></div></div><div class="one_row"><input id="toEmail" class="email"/><div class="errDiv"><label for="toEmail" class="error">*must be a valid email</label></div></div><div><textarea id="emailMessage" class="message" rows="4"></textarea><div class="errDiv"><label for="message" class="error">*must be less then 1000 characters</label></div></div></div><div class="clear">&nbsp;</div><div><input type="submit" class="submit" value="send" /></div></div><div id="result"><p>The job has been sent, <a href="/JS/General/Job.asp?a=save&id=##SourceInformationID##">send another</a>?</p></div></div></div>';
var saveJobForm = '<div id="Save" class="save_form"><div class="heading"><div class="close"></div><p>Job has been saved!</p></div></div>';

/*********************************    BEGIN validation utilities   ***********************************************************/

function toggleMe(div) {
	$(div).toggle();
}

function toggleChildren(parent) {
	$(parent).children().not(".close").toggle();
}

function disableLink(link) {
	$(link).attr("href", "");
}

function toggleChildrenIgnore(parent, ignore) {
	$(parent).children().not(ignore).hide();        //hide all divs under parent but selected one
	var ignore_selection = parent + " > " + ignore; //selection builder
	$(ignore_selection).toggle();                   //show selected div under parent
}


function validateMaxLength(text, length) {
	return text.length <= length;
}

function validateAlpha(alpha) {
	var filter = /^[a-zA-Z]+$/;
	if (filter.test(alpha))
		return true;
	else
		return false;
}

function validateNoHTML(email) {
	var filter = /<\/?[^>]*>/;
	if (filter.test(email))
		return true;
	else
		return false;
}

function validatePhoneNumeric(phone) {
	var filter = /^(\d{10})$/;
	if (filter.test(phone) | phone.length == 0)
		return true;
	else
		return false;
}

function validate() {
	isValid = true;
	$("input").submit();
	$("textarea").submit();
	return (isValid);
}

function displayForm(formName, jobID, link) {
	var form, formToDisplay
	var placeholder = "#ajax_job_forms" + jobID;
	formName = "#" + formName;
	var formSel = "#ajax_job_forms" + jobID + " > " + formName;

	if ($(formSel).html())//true if div already exists, hide any other form elements and toggle it
	{
		$(placeholder).children().not(formName).hide();
		$(placeholder).find(formName).toggle();
	}
	else {
		switch (formName) {
			case "#Email":
				formToDisplay = emailJobForm;
				break;
			case "#Save":
				formToDisplay = saveJobForm;
				break;
			default:
				return true;
		}

		$(placeholder).children().not(formName).hide();

		//put form on page
		$(placeholder).append(formToDisplay);

		//wire up events
		$(placeholder).find(".close").click(function () { toggleMe(formSel) }); 													//Close
		$(placeholder).find(".submit").click(function () { submitTellAFriend(formSel, placeholder, "") }); 					//Submit
		$(placeholder).find("#result a").click(function () { toggleChildren($(formSel).find("#forms")); return false; }); //Email Toggle forms
		$(placeholder).append('<input type="hidden" id="linkHidden" value="' + link + '"/>');
		//setup validation for all controls under formSel
		setValidation(formSel);

		//prepopulate form
		prepopulateTellAFriendFields();
	}
}

function setValidation(parentDiv)   //set required name validation, email regex validation, and required message validation
{
	$(parentDiv).find(".phone").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if (validatePhoneNumeric($(this).val())) {
				$(this).css("background-color", "white");
				$(this).parent().find(".errDiv").children().hide();
			}
			else {
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
	$(parentDiv).find(".name, .email, .required").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if ($(this).val().length > 0) {
				$(this).parent().find(".errDiv").children().hide();
				$(this).css("background-color", "white");
			}
			else {
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
	$(parentDiv).find(".email").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if (validateEmailRegex($(this).val()) & validateEmailBlacklist($(this).val()) & validationEmailTypos($(this).val())) {
				$(this).css("background-color", "white");
				$(this).parent().find(".errDiv").children().hide();
			}
			else {
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
	$(parentDiv).find(".multiEmail").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if (validateMultiEmail($(this).val())) {
				$(this).val($(this).val().replace(/[\s]|[ ]/g, "")); //take out spaces/tabs/breaks
				$(this).css("background-color", "white");
				$(this).parent().find(".errDiv").children().hide();
			}
			else {
				$(this).val($(this).val().replace(/[\s]|[ ]/g, "")); //take out spaces/tabs/breaks
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
	$(parentDiv).find("textarea").not(".email, .multiEmail").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if (validateMaxLength($(this).val(), 1000)) {
				$(this).css("background-color", "white");
				$(this).parent().find(".errDiv").children().hide();
			}
			else {
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
	$(parentDiv).find(".alpha").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if (validateAlpha($(this).val(), 1000)) {
				$(this).css("background-color", "white");
				$(this).parent().find(".errDiv").children().hide();
			}
			else {
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
	$(parentDiv).find(".noHTML").submit(function () {
		if ($(this).parent().attr('style') != "display: none;" & $(this).parent().attr('style') != "DISPLAY: none") {
			if (validateNoHTML($(this).val()) == false) {
				$(this).css("background-color", "white");
				$(this).parent().find(".errDiv").children().hide();
			}
			else {
				isValid = false;
				$(this).css("background-color", "#EFC0C0");
				$(this).parent().find(".errDiv").children().show();
			}
		}
	});
}

/*********************************     END validation utilities  **************************************************************/

/*********************************    BEGIN AJAX callbacks  ********************************************************/

//called when ajax call completed
function ajaxFinish(xml) {
	//alert(xml);
	//TODO add code to be executed on successful ajax call
}

//called when ajax call errors, attempts to show error message
function ajaxError(xmlObj, textStatus, errorThrown) {
	//TODO  add code here for errror handling of ajax calls
	/*
	alert("(Ajax error: "+errorThrown+")");
	alert(textStatus);
	*/
}

/*********************************     END AJAX callbacks  **********************************************************/

/*********************************    BEGIN HTML decode  ********************************************************/
//called when ajax call errors, attempts to show error message
function htmlDecode(sourceString) {
	if (sourceString != undefined) {
		var regexSpaces = /(%20)|(\+)/g;
		var regexAmp = /(%40)/g;
		var regexPeriod = /(%2E)/g;
		var regexDash = /(%2D)/g;

		sourceString = sourceString.replace(regexSpaces, " ");
		sourceString = sourceString.replace(regexAmp, "@");
		sourceString = sourceString.replace(regexPeriod, ".");
		sourceString = sourceString.replace(regexDash, "-");

		return sourceString;
	}
	else
		return "";
}
/*********************************     END HTML decode  **********************************************************/

/*********************************     BEGIN beyond box  **********************************************************/
function alignBeyondBox(id) {
	var boxSelection = "#" + id;

	var screenSize, beyondBoxSize, leftPad, rightPad, left;
	screenSize = $(window).width();
	leftPad = $(boxSelection).css("padding-left");
	if (leftPad) {
		leftPad = parseInt(leftPad.replace("px", ""));
		rightPad = $(boxSelection).css("padding-right");
		rightPad = parseInt(rightPad.replace("px", ""));
		beyondBoxSize = $(boxSelection).css("width");
		beyondBoxSize = parseInt(beyondBoxSize.replace("px", ""));
		beyondBoxSize = beyondBoxSize + leftPad + rightPad;

		left = (screenSize / 2) - (beyondBoxSize / 2);
		$(boxSelection).css("position", "absolute");
		$(boxSelection).css("left", left);
		$(boxSelection).css("position", "absolute");
	}
}
/********************************* END beyond box  **********************************************************/

/********************************* BEGIN cookie reader  *****************************************************/
//reads in the specified item from the cookie
function readCookie(key) {
	var keyEQ = key + "=";

	var ca = document.cookie.split(';');

	for (var i = 0; i < ca.length; i++) {

		var c = ca[i];
		if (c.indexOf(keyEQ) > 0) {
			var cb = c.split('&');
			for (var j = 0; j < cb.length; j++) {

				var b = cb[j];
				while (b.charAt(0) == ' ') b = b.substring(1, b.length);

				if (b.indexOf(keyEQ) == 0) return htmlDecode(b.substring(keyEQ.length, b.length));
			}
		}
	}
	return null;
}
/********************************* END cookie reader  *******************************************************/

/********************************* BEGIN quicksearch form action change *************************************/

//determine where quick search form should post
function CheckAction(f) {
	if (f.alert.checked && readCookie("CONTACTID") == undefined) {
		f.action = '/js/form/searchalertform.asp';
		f.submit();
		return false;
	}
	return true;
}
/********************************* END quicksearch form action change ***************************************/

//clears out text in the input if it matches defaultText
function clearDefaultText(defaultText, fieldName) {
	var enteredText = $("input[name=" + fieldName + "]").val();
	if (enteredText == defaultText) {
		$("input[name=" + fieldName + "]").val('');
	}
	$("input[name=" + fieldName + "]").css('color', 'black');
}



/********************************* sharing widget ***************************************/
function myShareObj() {
	//Public methods
	return {
		linkTemplate: '<a target="_blank" class="twitter ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-Twitter\']);" href="http://twitter.com/share?url=##URL##&text=##SHORTTITLE##">Twitter</a><a target="_blank" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-Facebook\']);" class="facebook ##CLASS##" href="http://www.facebook.com/sharer.php?u=##URL##&t=##TITLE##">Facebook</a><a target="_blank" class="buzz ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-GoogleBuzz\']);" href="http://www.google.com/buzz/post?message=##TITLE##&url=##URL##">Google Buzz</a><a target="_blank" class="yahoo ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-Yahoo\']);" href="http://buzz.yahoo.com/buzz?targetUrl=##URL##">Yahoo</a><a target="_blank" class="messenger ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-MSNMessenger\']);" href="http://profile.live.com/badge?url=##URL##">Messenger</a><a target="_blank" class="linkedin ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-LinkedIn\']);" href="http://www.linkedin.com/shareArticle?mini=true&url=##URL##&title=##TITLE##&summary=##TITLESUMMARY##&source=##DOMAIN##">LinkedIn</a><a target="_blank" class="digg ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-Digg\']);" href="http://digg.com/submit?url=##URL##">Digg</a><a target="_blank" class="stumble ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-StumbleUpon\']);" href="http://www.stumbleupon.com/submit/?url=##URL##">Stumble</a><a target="_blank" class="delicious ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-Delicious\']);" href="http://delicious.com/save?v=5&noui&jump=close&url=##URL##&title=##TITLE##">Delicious</a><a target="_blank" class="reddit ##CLASS##" rel="nofollow" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'Share-Reddit\']);" href="http://reddit.com/submit?url=##URL##&title=##TITLE##">Reddit</a>',
		url: location.href,
		baseurl: location.host,
		title: document.title,
		titlesummary: document.title,
		domainname: location.hostname,
		anchorClass: '',
		twitterTag: '',
		twitterTitle: function () {
			var maxLength = 90;
			if (this.title.length > maxLength)
				return this.twitterTag + " " + this.title.substring(0, maxLength);
			else
				return this.twitterTag + " " + this.title.substring(0, this.title.length);
		},
		getLinks: function () {
			var displayHTML;

			this.displayHTML = this.linkTemplate;
			this.displayHTML = this.displayHTML.replace(/##URL##/g, encodeURIComponent(this.url));
			this.displayHTML = this.displayHTML.replace(/##BASEURL##/g, encodeURIComponent(this.baseurl));
			this.displayHTML = this.displayHTML.replace(/##TITLE##/g, encodeURIComponent(this.title));
			this.displayHTML = this.displayHTML.replace(/##SHORTTITLE##/g, encodeURIComponent(this.twitterTitle()));
			this.displayHTML = this.displayHTML.replace(/##TITLESUMMARY##/g, encodeURIComponent(this.titlesummary));
			this.displayHTML = this.displayHTML.replace(/##DOMAIN##/g, encodeURIComponent(this.domainname));
			this.displayHTML = this.displayHTML.replace(/##CLASS##/g, this.anchorClass);

			return this.displayHTML;
		}
	}
}
/********************************* END sharing widget ***************************************/

/********************************* BEGIN XHR post function ***************************************/
function ajaxPost(url, data, aSyncCall, um, ignoreResponse) {
	//set syncronisity of ajax call
	var async;
	if (aSyncCall == undefined || async == false)
		async = false;
	else
		async = true;

	//add ajax parameter
	if (data == null)
		data = {};
	if (um == 'Y')
		data["UM"] = "Y";
	data["AJAXREQUEST"] = "Y";
	$.ajax({ type: "Post",
		url: url,
		dataType: "html",
		data: data,
		async: async,
		processData: true,
		error: function (XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
		success: function (xml) {
			if (!ignoreResponse) {
				var temp = xml.toString();
				if (temp.toUpperCase().indexOf("AJAX_POST_SUCCESS") > -1) {
					curBox.success = true;
					return curBox.successActivity();
				}
				else {
				    if (temp.toUpperCase().indexOf("AJAX_POST_FAILED:") > -1) {
				        alert(temp.substr(17));
				    } else {
				        alert("request failed, please try again.");
				    }
					return curBox.failureMethod();
				}
			}
			else
				return true;
			return false;
		}
	});
}
/********************************* END XHR post function ***************************************/

//tracking function
function internalTracking(url) {
	ajaxPost(url, {}, true, "", true);
}
