//*****************************************************************************************************************/
// Beyond.com jobsearch library
// Property of Beyond.com 5/26/2011
// job searching related code
//*****************************************************************************************************************/

//geocoder used to find locations of businesses
//geocoder used to find locations of businesses
var jObject = new mapObject();
var errorCount = 0;
var myCallBack;
var geocoder;

//wire up events and perform page load tasks
$(document).ready(function () {
	//ajaxifies html links for saving jobs
	$("*[savedText]").click(function () {
		return ajaxLink(this);
	});

	//event to handle showing/hiding of dynamic elements under each job
	$("*[showDiv]").click(function () {
		return toggleDynJobDivs(this);
	});

	/* handles toggling according under user account area on job search results, currently removed
	$("*[toggleBlind]").click(function () {
	controlToggle(this);
	});
	*/

	//event to save one job on job search results
	$(".save_job_link").click(function () {
		return saveJob(this);
	});

	//event to handle submission of quick search form
	$("#quickSearch").submit(function () {
		return quickSearchSubmit(this);
	});

	//event to handle submission of email form under a job in job details
	$(".email_form").submit(function () {
		var myValidator = new FormValidation();

		if (myValidator.ValidateAll(this))
			return postReferral(this);
		else
			return false;
	});

	//event to handle clearing out quick search forms default text in inputs
	$('#search-jobs-button').click(function () {
		if ($("input[name=fwhere]").val() == '(City, State or Zip)') {
			$("input[name=fwhere]").val('');
		}
	});
	//event to handle clearing out quick search forms default text in inputs
	$('#search-button').click(function () { if ($("input[name=fwhere]").val() == '(City, State or Zip)') { $("input[name=fwhere]").val(''); } });

	/*******************JOB DETAILS SPECIFIC*****************************/

	//wireup external apply lightbox on job details page
	$('[data-useextapplylbx="true"]').click(function () {
		//custom variables set in data of element with external apply
		var convURL = $(this).data("strconvurl");
		var pgid = $(this).data("pgid");
		var applySource = $(this).data("strapplysource");
		var jobId = $(this).data("jobid");
		var usefrm = $(this).data("usefrm");
		var applyurl = $(this).data("red");

		//track click on more info
		internalTracking(convURL);
		//setup lightbox functionality, with success/close/fail functions
		showLightbox('/common/content/lightbox/extJobRegister.asp?jobid=' + convURL, 381, 460, false, false,
				function () {
					internalTracking("/common/track/trackgeneral.asp?tcid=104&ttid=2&rtid=1");
					window.location.reload();
				},
				function () {
					window.open("/js/general/apprequest.asp?clk=N&ext=Y&pgid=" + pgid + "&src=" + applySource + "&id=" + jobId + "&usefrm=" + usefrm + "&red=" + applyurl, "_blank", "width=955,height=686,directories=0,location=1,menubar=1,resizable=1,scrollbars=1,status=0,titlebar=1,toolbar=1,fullscreen=0,channelmode=0,screenX=50,left=200,screenY=50,top=0");
				},
				null,
				function () {
					window.open("/js/general/apprequest.asp?clk=N&ext=Y&pgid=" + pgid + "&src=" + applySource + "&id=" + jobId + "&usefrm=" + usefrm + "&red=" + applyurl, "_blank", "width=955,height=686,directories=0,location=1,menubar=1,resizable=1,scrollbars=1,status=0,titlebar=1,toolbar=1,fullscreen=0,channelmode=0,screenX=50,left=200,screenY=50,top=0");
				}
			);
	});
});

//check for alert me checkbox checked if so, membership wall and then save job
function quickSearchSubmit(control) {
	clearDefault('(City, State or Zip)', control.FWhere);
	clearDefault('(Title, Keywords, Company)', control.FKeywords);
	if ($("#FAddAlert:checked").length == 1 && !isLoggedIn) {
		var lightBoxUrl;
		if (readCookie("CONTACTID") != undefined && readCookie("CONTACTID").length > 0) {
			lightBoxUrl = 'loginlbx.asp'
		}
		else {
			lightBoxUrl = 'registerlbx.asp'
		}
		//success method
		showLightbox('/common/content/lightbox/' + lightBoxUrl, 230, 461, false, false, function () {
			$("#quickSearch").submit();
		},
		//close method
		function () {
			$("#FAddAlert").attr("checked", false);
			$("#quickSearch").submit();
		});
		return false;
	}
	else
		return true;

	return false;
}

//save search and alert
function ajaxLink(control) {
	if (!isLoggedIn) {
		var lightBoxUrl;
		if (readCookie("CONTACTID") != undefined && readCookie("CONTACTID").length > 0) {
			lightBoxUrl = 'loginlbx.asp'
		}
		else {
			lightBoxUrl = 'registerlbx.asp'
		}
		showLightbox('/common/content/lightbox/' + lightBoxUrl, 230, 461, false, false,
			function () {
				//stop infinite recursion, buy setting success method to just close box
				curBox.successMethod = curBox.close;

				ajaxPost($(control).attr('href'), null, null, 'Y');
				$(control).removeAttr("href").text($(control).attr("savedText")).unbind().css({ "cursor": "default", "font-weight": "bold" });
				window.location.reload();
			});
	}
	else {
		ajaxPost($(control).attr('href'), null, null, 'N');
		$(control).removeAttr("href").text($(control).attr("savedText")).unbind().css({ "cursor": "auto", "font-weight": "bold" });
	}
	return false;
}

//save individual job on job search results
function saveJob(jobs) {
	var jobDiv, strJobID;
	jobDiv = $(jobs).parents("[id^=jobDiv]");

	strJobID = $(jobDiv).attr("jid");

	if (!isLoggedIn) {
		var lightBoxUrl;
		if (readCookie("CONTACTID") != undefined && readCookie("CONTACTID").length > 0) {
			lightBoxUrl = 'loginlbx.asp'
		}
		else {
			lightBoxUrl = 'registerlbx.asp?alert=y'
		}
		showLightbox('/common/content/lightbox/' + lightBoxUrl, 230, 461, false, false,
			function () {
				ajaxSaveJob(strJobID, readCookie("SESSIONID"), readCookie("CONTACTID"), 'Y');
				$(jobDiv).find(".save_job_link").removeAttr("href").text("Saved").unbind().css({ "cursor": "auto", "font-weight": "bold" });
				curBox.close();
			});
	}
	else {

		ajaxSaveJob(strJobID, readCookie("SESSIONID"), readCookie("CONTACTID"), 'N');
		$(jobDiv).find(".save_job_link").removeAttr("href").text("Saved").unbind().css({ "cursor": "auto", "font-weight": "bold" });
	}
	return false;
}

function ajaxSaveJob(strJobID, mySessionID, myContactID, FirstTime) {
	$.ajax({ type: "GET",
		url: "/js/action/saveJob.asp",
		dataType: "html",
		data: { "strJobID": strJobID, "SessionID": mySessionID, "ContactID": myContactID, "UM": FirstTime },
		processData: true,
		error: function (XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
		success: function (xml) { ajaxFinish(xml); if (FirstTime == 'Y') { window.location.reload(); } }
	});

}

//post email job referal form, under job details
function postReferral(curControl) {
	var control;

	//serialize data begin
	var inputs = $(curControl).find("input:input, select");
	var data = {};

	for (var i = 0; i < inputs.length; i++) {
		var control = inputs[i];
		data[$(control).attr('id')] = $(control).val();
	}
	data["link"] = $(curControl).parents("[id^=jobDiv]").find(".job_title").attr("href");
	data["title"] = $(curControl).parents("[id^=jobDiv]").find(".job_title").text();
	data["ftype"] = "JOB";
	//serialize data end

	ajaxPost($(curControl).attr("action"), data, true, 'N');
	$(curControl).parent().children().toggle();

	return false;
}


//this function takes the name of a parent div and controls toggling of content and image on/off state
function controlToggle(curControl) {
	var fastToggle = $(curControl).attr("fastToggle");
	//toggles toggle image off/on
	var imageSrc = $(curControl).find("img").attr('src');
	if (imageSrc.indexOf("_on.") > -1)
		imageSrc = imageSrc.replace("_on.", "_off.");
	else
		imageSrc = imageSrc.replace("_off.", "_on.");

	$(curControl).find("img").attr('src', imageSrc);
	//toggles toggle image off/on

	//toggle element given by toggleBlind
	var rawDivSelectorList = $(curControl).attr('toggleBlind');
	var selectorArray = rawDivSelectorList.split("|");
	//foreach loop
	for (var selector in selectorArray) {
		var toggleBlindSelector = "#" + selectorArray[selector];
		if (fastToggle == "true")
			$(curControl).parent().find(toggleBlindSelector).toggle();
		else
			$(curControl).parent().find(toggleBlindSelector).fadeToggle();
	}
	return false;
}

//handles toggling the divs under each job
function toggleDynJobDivs(curControl, toggleDivOverride) {
	//get job container
	jObject.jobDiv = $(curControl).parents("[id^=jobDiv]");
	//get classname for dynamic widget to be shown
	var divClass = (toggleDivOverride == undefined) ? ("." + $(curControl).attr("showDiv") + "_div_j") : ("." + toggleDivOverride + "_div_j");

	//is dynamic div currently displayed
	if ($(jObject.jobDiv).find(divClass).css('display') == "none") {
		$(jObject.jobDiv).find(".dynamic_divs_j").children("div").hide();
		$(jObject.jobDiv).find(divClass).fadeToggle();

		/*uncomment to reenable google maps
		//if showing more div, display google map
		if ($(curControl).attr("showDiv") == "more") {
		//setup map object properties
		var lat = $(jObject.jobDiv).attr("jlat");
		var lon = $(jObject.jobDiv).attr("jlon");
		jObject.markerDirectionsLocation = $(jObject.jobDiv).find(".job_location").text();
		//if "Confidential Company" or no name then use "" for label
		if ($(jObject.jobDiv).find(".job_company").text().toUpperCase() == "CONFIDENTIAL COMPANY" || $(jObject.jobDiv).find(".job_company").text().toUpperCase() == "")
		jObject.markerLabel = "";
		else
		jObject.markerLabel = $(jObject.jobDiv).find(".job_company").text();


		if ((typeof lon == "undefinded") | (lon == "0") | (typeof lat == "undefined") | (lat == "0")) {
		geocoder = new google.maps.Geocoder();
		var address = $(jObject.jobDiv).find(".job_location").text();
		geocoder.geocode({ 'address': address }, function (results, status) {
		//decode lat/lon into array with lat then lon elements
		var locationString = results[0].geometry.location.toString().replace(/\(|\)|\s/g, "");
		locationString = locationString.split(",");
		if (status == google.maps.GeocoderStatus.OK) {
		jObject.initMap(locationString[0], locationString[1]);
		} else {
		alert("Geocode was not successful for the following reason: " + status);
		}
		});

		}
		else {
		jObject.initMap(lat, lon);
		}
		}
		*/



		//if showing share widget, build links and display widget
		if ($(curControl).attr("showDiv") == "share") {
			shareObject.url = window.location.protocol + "//" + window.location.host + $(jObject.jobDiv).find(".job_title").attr("href");
			shareObject.titlesummary = shareObject.title = $(jObject.jobDiv).find(".job_title").text();
			shareObject.twitterTag = "Great #Job Opportunity: ";
			$(jObject.jobDiv).find(".social_list").html(shareObject.getLinks());
		}
	}
	else
		$(jObject.jobDiv).find(divClass).fadeToggle();

	return false;
}

//Javascript Map Class============================================================================================================================================
function mapObject() {
	//Private methods

	//marker click behavior
	var markerClickedPrivate = function (label, location) {
		var locationString = location.toString().replace(/\(|\)|\s/g, "");

		//if company name not given don't use it for location
		if (label == "") {
			newwindow = window.open('http://maps.google.com/maps?q=' + locationString, 'Directions', 'height=600,width=800');
		}
		else {

			newwindow = window.open('http://maps.google.com/maps?q=' + encodeURIComponent(label) + " near " + locationString, 'Directions', 'height=600,width=800');
		}

		setTimeout('$(newwindow).focus()', 1000);
		return false;
	};

	//public methods
	return {
		jobDiv: '',
		latlng: '',
		markerLabel: '',
		markerDirectionsLocation: '',
		//build google map
		initMap: function (lat, lon) {
			this.latlng = new google.maps.LatLng(lat, lon);
			//if map has not already been built, build it
			if ($(this.jobDiv).find(".map_canvas").children().length == 0) {
				var map = new google.maps.Map($(this.jobDiv).find(".map_canvas")[0], { 'zoom': 10, 'center': this.latlng, 'mapTypeId': google.maps.MapTypeId.ROADMAP, 'mapTypeControl': false, 'navigationControl': true, 'streetViewControl': false });

				//use this if you can fix the visual/layout bug with the infowindow
				/*var infowindow = new google.maps.InfoWindow({
				content: "hey there", maxWidth: "200px"
				});
				*/

				var marker = new google.maps.Marker({
					position: this.latlng,
					map: map,
					title: this.markerLabel
				});

				google.maps.event.addListener(marker, 'click', function () {
					markerClickedPrivate(marker.title, marker.position);
					//use this if you can fix the visual/layout bug with the infowindow
				});
			}
		}
	};
}

//END Javascript Map Class============================================================================================================================================


//if the apply url is set to direct link (not go through job details) the click must first fire some javascript so that bots can not disturb the tracking data
function byd_click(atag, val)
{
	var href = atag.href;
	var index = href.indexOf('/');
	if(index>0){return};		
}	
