// JavaScript Document

// Universal var to grab the current URL + directory structure
var jsPrepend = unescape(window.location.href.substring(0, (window.location.href.lastIndexOf('/')) + 1));
// Universal var to grab just the current URL with trailing whack
var jsURL = window.location.href.substring(0, (window.location.href.indexOf('/', 9) + 1));
var jsURLFolderArray = window.location.pathname.split('/');
var jsURLDir = jsURLFolderArray[1] + '/';
if (jsURLDir.indexOf('bet', 0) < 0) { jsURLDir = '' };
var jsURL = jsURL + jsURLDir;
//alert('jsPrepend: ' + jsPrepend + '\njsURL: ' + jsURL + '\njsURLDir: ' + jsURLDir);// + '\nN/V: ' + jsURLNameValueArray[0]);

// Universal logout function.  Can be used by Job Seekers or Recruiters
// Only used by Job seekers at this time due to YUI vs. jQuery conflicts
// Older version for Recruiters is in functionsadmin near line 100 and is called: LogoutJRD
jQuery('.doLogout').bind('click', function() {
	if (confirm('Are you sure you want to log out?')) {
		if (window.location.toString().indexOf('admin') > -1) {
			window.location = 'logout.asp';
		}
		else {
			window.location = 'resume_main.asp?logout=1';
		}
	}
});

//Print
//goPrint send user to target page to print
jQuery('.goPrint').bind('click', function() {
	//alert('print: ' + jQuery(this).attr('id'));
	jQuery.post(jsPrepend + 'includes/sync/print_session.asp',
		{ "PrintAction": "1", "PrintTarget": jQuery(this).attr('id') }
	);
	window.open('http://www.jobing.com/' + jQuery(this).attr('id'), 'JResume');
	//window.open(jsPrepend + jQuery(this).attr('id'), 'JResume');
	//window.print();
	return false;
});

//doPrint invokes the print job
jQuery('.doPrint').bind('click', function() {
	window.print();
	return false;
});

//Share
jQuery('.doShare').click(function() {
	//id = Service(twitter,etc.)_JobSeekerID_ResumeID
	var thisIDArray = jQuery(this).attr('id').split('_');
	var EventData = thisIDArray[0];
	var FK1 = thisIDArray[1];
	//jQuery('#resume_list_' + thisID).hide();
	jQuery.get(jsPrepend + 'clicktrack.asp', { "FK1": FK1, "EventID": '43', "EventData": EventData });

});

//Change from full site to mobile site
jQuery('#goMobile').click(function() {
	jQuery.post(jsPrepend + 'ajax/mobile/web/switch', { "mbt": 'MobileSmart', "target": window.location.href },
		function(data) {
			if (data = 'success') {
				window.location = window.location.href;
			};
		}
	);
	return false;
});

//Change from mobile site to full site
jQuery('#goWeb').click(function() {
	jQuery.post(jsPrepend + 'ajax/mobile/web/switch', { "mbt": 'Web' },
		function(data) {
			if (data = 'success') {
				window.location = window.location.href;
			};
		}
	);
	return false;
});

//Email JobSeeker/Resume

jQuery('.goShareEmail').bind('click', function() {
	var idArray = jQuery(this).attr('id').split('_');
	shareEmailType = idArray[0];
	//P1 = ResumeID
	//P2 = ResumeRev
	shareEmailP1 = idArray[1];
	shareEmailP2 = idArray[2];
	jQuery('#Dialog_Send_Email').removeClass('hideElement').addClass('showElement');
	jQuery('#Dialog_Send_Email').dialog({
		title: 'Send Email',
		height: 400,
		width: 400,
		bgiframe: true,
		resizable: false,
		draggable: false,
		modal: true,
		autoOpen: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Send Email': function() {

				var Sender = jQuery('#ShareSender').val();
				var Recipient = jQuery('#ShareRecipient').val();
				var Message = jQuery('#ShareMessage').val();
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

				//If we pass recipient info in, error check it
				if (Recipient != 'FixedRecipient') {
					if (!emailReg.test(Recipient) || Recipient == '') {
						DisplayError(jQuery('#ShareRecipient'), 'Invalid Recipient Address');
					}
					else {
						RemoveError(jQuery('#ShareRecipient'), 1);
					};
				};

				//If we pass sender info, error check it
				if (Sender != 'FixedSender') {
					if (!emailReg.test(Sender) || Sender == '') {
						DisplayError(jQuery('#ShareSender'), 'Invalid Sender Address');
					}
					else {
						RemoveError(jQuery('#ShareSender'), 1);
					};
				};

				formOnError = jQuery('.errorbg').length;

				if (formOnError == 0) {
					//If everything is kosher, call function to send email
					doShareEmail(shareEmailType, Recipient, Sender, Message, shareEmailP1, shareEmailP2);
				};
			},
			'Cancel': function() {
				jQuery(this).dialog('close');
			}
		}
	});
});


function doShareEmail(EmailType, T, F, M, P1, P2) {
	// We have made it here because we had no errors on our form
	// PARAMETERS:
	// EmailType: What kind of email are we sending out
	//		Resume: PublicURL or JS Admin Resume send
	//		Contact: PublicURL contact JS
	// T: Recipient
	// F: Sender
	// M: Message
	// P1: Resume: ResumeID; Contact: ResumeID
	// P2: Resume: ResumeRev; Contact: 
	// Now we want to send an email out, which will vary based on
	// which form was submitted.
	if (EmailType == 'Resume') {
		//jQuery.post(jsPrepend + 'ajax/resume/share/email', { "Rev": Rev, "Recipient": Recipient, "Message": Message, "AccountID": AccountID, "JobSeekerID": JobSeekerID, "ResumeID": ResumeID, "ProfileID": ProfileID, "SessionID": SessionID, "NavigationID": NavigationID },
		jQuery.post(jsPrepend + 'ajax/resume/share/email', { "T": T, "F": F, "M": M, "P1": P1, "P2": P2 },
			function(data) {
				if (data == 'success') {
					alert('Your email has been sent.');
					//jQuery('#Dialog_Send_Email').addClass('hideElement');
				}
				else {
					alert('Error. Recipient email address not found.');
				};
				jQuery('#Dialog_Send_Email').dialog('close');
			}
		);
	}
	else if (EmailType == 'Contact') {
		
	}
};


/*	WE MAY USE THE FOLLOWING FUNCTION AS A DIALOG WRAPPER TO BE POPPED UP AS AN OVERLAY ON ANY PAGE 
	RIGHT NOW IT IS JUST FOR THE CONTACT BUTTON ON THE PUBLIC RESUME PAGE
*/
//This email dialog goes with the sub sb_EmailSendDIV on _functions.asp
jQuery('.doSendEmail').bind('click', function() {
	//alert('here i am');
	jQuery('#SendEmail').removeClass('hideElement');
	jQuery('#SendEmail').dialog({
		bgiframe: true,
		resizable: false,
		draggable: false,
		modal: true,
		height: 375,
		width: 475,
		closeText: 'Email Sent',
		autoOpen: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Send': function() {
				//Check for valid email address
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

				if (!emailReg.test(jQuery('#eSender').val()) || jQuery('#eSender').val() =='') {
					DisplayError(jQuery('#eSender'), 'Invalid Email Address');
				}
				else {
					RemoveError(jQuery('#eSender'), 1);
				};

				//Check for non-empty message
				if (jQuery('#msg').val() == '') {
					DisplayError(jQuery('#msg'), 'Enter a Message');
				}
				else {
					RemoveError(jQuery('#msg'), 1);
				};

				formOnError = jQuery('.errorbg').length;

				if (formOnError == 0) {
					jQuery('#SendEmailFeedback').removeClass('hideElement').html(' <img src="http://imgsg.jobing.com/ajax-loader.gif" width="16" height="16" alt="Loading..." id="loading" />');

					jQuery.post(jsPrepend + 'ajax/email/send/simple', { "f": jQuery('#eSender').val(), "m": jQuery('#msg').val(), "t": jQuery('#t').val(), "i": jQuery('#i').val() },
						function(data) {
							if (data == 'success') {
								alert('Your email has been sent.');
								jQuery('#SendEmail').dialog('close');
								jQuery('#SendEmail').addClass('hideElement');
							}
							else {
								jQuery('#SendEmailFeedback').removeClass('hideElement').addClass('error errorbg').html(' Error: The email was not sent.');
							};
						}
					);
				};

			},
			Cancel: function() {
				jQuery(this).dialog('close');
			}
		}
	});
});

//Give download resume function time to convert resume
function doWait(millis) {
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while (curDate - date < millis);
}

function cursorWait() {
	document.body.style.cursor = 'wait';
}

function cursorClear() {
	document.body.style.cursor = 'default';
}

//Download Resume
jQuery('.doDownloadResume').bind('click', function() {
	cursorWait();
	ResumeURL = jQuery(this).attr('id').toLowerCase();
	ResumeDir = jsURLDir.toLowerCase(); //jsURLFolderArray[1].toLowerCase();
	if (ResumeURL == ResumeDir) { ResumeDir = 'www' };
	//alert('ResumeURL: ' + ResumeURL + '\njsURLDirArray: ' + ResumeDir + '\njsURL: ' + jsURL);
	jQuery.post(jsPrepend + 'ajax/resume/download/pdf/create', { "p": ResumeDir, "n": ResumeURL },
	//	jQuery.post(jsPrepend + 'ajax/resume/download/pdf/create', { "p": jsURLDir, "n": jQuery('#filename').val() },
		function(data) {
			if (data == 'success') {
				//alert('Your email has been sent.');
				//LOOP OVER THIS UNTIL FILE IS READY???
				doWait(5000)
				jQuery.post(jsPrepend + 'ajax/resume/download/pdf/exists', { "p": ResumeDir, "n": ResumeURL },
				//jQuery.post(jsPrepend + 'ajax/resume/download/pdf/exists', { "p": jsURLDir, "n": jQuery('#filename').val() },
					function(data) {
						if (data == 'success') {
							cursorClear();
							//window.location = jsURL + 'download.asp?n=' + ResumeURL + '&p=' + ResumeDir;
							//window.open(jsURL + 'download/OutputPDF/' + ResumeURL + '-resume.pdf', '', 'resizable=1,scrollbars=1')
							window.location.href = jsURL + 'download/OutputPDF/' + ResumeURL + '-resume.pdf';
							//window.location = jsURL + 'download/OutputPDF/' + jQuery('#filename').val() + '-resume.pdf';
						}
						else {
							doWait(5000)
							jQuery.post(jsPrepend + 'ajax/resume/download/pdf/exists', { "p": ResumeDir, "n": ResumeURL },
								function(data) {
									if (data == 'success') {
										cursorClear();
										//window.location = jsURL + 'download.asp?n=' + ResumeURL + '&p=' + ResumeDir;
										//window.open(jsURL + 'download/OutputPDF/' + ResumeURL + '-resume.pdf', '', 'resizable=1,scrollbars=1')
										window.location.href = jsURL + 'download/OutputPDF/' + ResumeURL + '-resume.pdf';
										//window.location = jsURL + 'download/OutputPDF/' + jQuery('#filename').val() + '-resume.pdf';
									}
									else {
										alert(' Error: There was a problem downloading the resume..');
									};
								}
							);
						};
					}
				);
			}
			else {
				alert(' Error: There was a problem downloading the resume.');
			};
		}
	);
});

//Process recommends
function ProcessRecommend(itemID, sessionID) {

	jQuery.ajax({
		url: jsURL + "includes/_processvotes.asp",
		type: "GET",
		dataType: "text",
		cache: false,
		data: "getvotecount=1&sessionid=" + sessionID + "&blogpostid=" + itemID + "&votetypeid=3",
		success: function(responsetext) {
			document.getElementById("VoteCount" + itemID).innerHTML = responsetext;
			//			document.getElementById("VoteStar"+itemID).src="<%=imgServer%>2007/vote-staron.gif";
			document.getElementById("CheckMark" + itemID).className = "IconCheckSmlOff";
			//			document.getElementById("CheckMark"+itemID).src="<%=imgServer%>2007/vote-check-GM.gif";
			document.getElementById("VoteLink" + itemID).style.display = "none";
			document.getElementById("HasVoted" + itemID).style.display = "block";
			document.getElementById("HasVoted" + itemID).style.color = "#999";
		},
		error: function(Request, ErrorString) {
			alert(Request.responsetext);
		}
	});
}

//Form functions
function DisplayError(thisField, customError) {
	//alert('we will error check here!\n' + thisField + '\n' + customError);
	if (thisField.attr('name') == 'CategoryID0') {
		//alert('here i am');
		thisField.siblings('.feedback').html(customError);
		thisField.siblings('.feedback').removeClass('hideElement success').addClass('showElement error');
	}
	else {
		if (customError != 'stdError') {
			thisField.siblings('.right').children('.feedback').html(customError);
		}
		thisField.siblings('.right').children('.feedback').removeClass('hideElement success').addClass('showElement error');
	}
	thisField.parent('li').removeClass('successbg').addClass('errorbg'); //formOnError += 1;
	//alert('DisplayError Called for ' + thisField + ': ' + formOnError);
	//alert('DisplayError Called for ' + thisField);
};

function RemoveError(thisField, emptyFeedback) {
	//alert('RemoveError called for + thisField');
	if (thisField.attr('name') == 'CategoryID0') {
		//alert('here i am');
		thisField.siblings('.feedback').removeClass('showElement error').addClass('hideElement');
		if (emptyFeedback == 1) { thisField.siblings('.feedback').empty() }
		thisField.parent('li').removeClass('errorbg'); //formOnError += 0
	}
	else {
		thisField.siblings('.right').children('.feedback').removeClass('showElement error').addClass('hideElement');
		if (emptyFeedback == 1) { thisField.siblings('.right').children('.feedback').empty() }
		thisField.parent('li').removeClass('errorbg'); //formOnError += 0
		//alert('RemoveError Called for ' + thisField + ': ' + formOnError);
	}
};

function DisplaySuccess(thisField, customSuccess) {
	thisField.siblings('.right').children('.feedback').empty().removeClass('error'); //.parent().removeClass("errorbg").addClass("successbg");
	thisField.parent('li').removeClass('errorbg'); //checkEmpty += 1;
	//If we are displaying success messages, use below
	//thisField.siblings('.feedback').empty().removeClass('error').addClass('showElement success').html(customSuccess);//.parent().removeClass("errorbg").addClass("successbg");
	//thisField.parent('li').removeClass('errorbg').addClass('successbg'); //checkEmpty += 1;
};

// Show or Hide Search Options in Site Header
function ShowHide(WhichAction, WhichElement) {
	var i=1;
	if (WhichAction == "Show") {
		while(true) {
			if(document.getElementById("SearchItem"+i)) {
				document.getElementById("SearchItem"+i).style.display="block";
				i++;
			}
			else {
				break;
			}
		}
		document.getElementById("SearchItemsCtr").className="SearchItemsCtr";
		document.getElementById("SearchItemsCtr").style.borderLeft = "2px solid #cccccc";
		document.getElementById("SearchItemsCtr").style.borderRight = "2px solid #cccccc";
		document.getElementById("SearchItemsCtr").style.borderTop = "2px solid #cccccc";
		document.getElementById("SearchItemsCtr").style.backgroundColor = "white";
		document.getElementById("SearchWhat").style.borderLeft = "2px solid #cccccc";
		document.getElementById("SearchWhat").style.borderRight = "2px solid #cccccc";
	}
	else if (WhichAction == "Hide") {
		while(true) {
			if(document.getElementById("SearchItem"+i)) {
				document.getElementById("SearchItem"+i).style.display="none";
				i++;
			}
			else {
				break;
			}
		}
		document.getElementById("SearchItemsCtr").className="";
		document.getElementById("SearchItemsCtr").className="SearchItemsCtr";
		document.getElementById("SearchItemsCtr").style.borderLeft = "2px solid transparent";
		document.getElementById("SearchItemsCtr").style.borderRight = "2px solid transparent";
		document.getElementById("SearchItemsCtr").style.borderTop = "2px solid transparent";
		document.getElementById("SearchItemsCtr").style.backgroundColor = "transparent";
		document.getElementById("SearchWhat").style.borderLeft = "2px solid transparent";
		document.getElementById("SearchWhat").style.borderRight = "2px solid transparent";
	}
}

//Clear keywords, job types, locations on quick search forms
function ClearSearch(WhichPage) {
	//document.forms["GoogleSearch"].elements["q"].value="";
	document.forms["QuickSearch"].elements["keywords"].value="";
	document.forms["QuickSearch"].elements["field"].selectedIndex=0;
	document.forms["QuickSearch"].elements["location"].selectedIndex=0;
	//document.forms["blog_form"].elements["blog_keywords"].value="";
	//document.forms["video_form"].elements["video_keywords"].value="";

	//if clearing form on search results, we need to clear top and bottom
	if (WhichPage == "SearchResults") {
		document.forms["YouSearchedFor"].elements["keywords"].value="";
		document.forms["YouSearchedFor"].elements["field"].selectedIndex=0;
		document.forms["YouSearchedFor"].elements["location"].selectedIndex=0;
	}
	
	//clear session vars for search
	ClearSearchSessionVars()
}

function ClearSearchSessionVars() {

	/* ASYNC REQUEST
	 * call type: POST
	 * action page: async_clearsearchsession.asp
	 * what to do w/response: callback
	 * arguments (querystring) to send to action page: "t="+escape(textColor)+"&b="+escape(bgColor)+"&c="+escape(compID)+"&m="+escape(modbyID)
	 */
	//YAHOO.util.Connect.asyncRequest('GET','async_clearsearchsession.asp');
	jQuery.get('async_clearsearchsession.asp')
	//For testing we use callback
	//YAHOO.util.Connect.asyncRequest('GET','async_clearsearchsession.asp',callback);

	/* WHAT HAPPENS WHEN REQUEST IS COMPLETE
	 * success returns the value that would be printed to the page
	 * failure returns nothing, so we display an alert
	 * only called if we uncomment the call with "callback" above
	 */ 
	var callback = 
	{ 
		success: function(o) {
			//location.href="company_profile_settings.asp?task=<%=task%>"
			alert("success: "+o.responseText);
		}, 
		failure: function(o) {
			alert(o.responseText+"\nAn error ocurred when trying to clear this form.");
		}
	} 

}

//MakeChoice used by _quickSsearch.asp + default.asp in use - 080104 (really 080327) -GB
// Search type highlighting
var selected = "jobs";

function MakeChoice(WhichChoice) {
	selected = WhichChoice;
	var choiceList = ["jobs","blogs","videos","web"];
	//var choiceList = ["jobs","blogs","videos","companies","events","web"];
	for(var i=0;i<choiceList.length;i++) {
		if(choiceList[i]==WhichChoice) {
			document.getElementById(choiceList[i]).style.fontWeight = "bold";
			if(choiceList[i]=="jobs"){
				document.getElementById("JobingSearch").style.display = "block";
				document.getElementById("BlogSearch").style.display = "none";
				document.getElementById("VideoSearch").style.display = "none";
				document.getElementById("WebSearch").style.display = "none";
			}
			else if (choiceList[i]=="videos"){
				document.getElementById("JobingSearch").style.display = "none";
				document.getElementById("BlogSearch").style.display = "none";
				document.getElementById("VideoSearch").style.display = "block";
				document.getElementById("WebSearch").style.display = "none";
				document.getElementById("SearchWhat").style.borderLeft = "2px solid transparent";
				document.getElementById("SearchWhat").style.borderRight = "2px solid transparent";
			}
			else if (choiceList[i]=="blogs"){
				document.getElementById("JobingSearch").style.display = "none";
				document.getElementById("BlogSearch").style.display = "block";
				document.getElementById("VideoSearch").style.display = "none";
				document.getElementById("WebSearch").style.display = "none";
				document.getElementById("SearchWhat").style.borderLeft = "2px solid transparent";
				document.getElementById("SearchWhat").style.borderRight = "2px solid transparent";
			}
			else{
				document.getElementById("JobingSearch").style.display = "none";
				document.getElementById("BlogSearch").style.display = "none";
				document.getElementById("VideoSearch").style.display = "none";
				document.getElementById("WebSearch").style.display = "block";
				document.getElementById("SearchWhat").style.borderLeft = "2px solid transparent";
				document.getElementById("SearchWhat").style.borderRight = "2px solid transparent";
			}
			//if(choiceList[i]=="jobs"){document.getElementById("Search_jobTypeCatTable").style.display = "block";}
			//else{document.getElementById("Search_jobTypeCatTable").style.display = "none";}
		}
		else{
			document.getElementById(choiceList[i]).style.fontWeight = "lighter";
		}
	}
}

function submitFormWithEnter(SearchType,URL,e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
		execSearch(SearchType,URL);
//		myfield.form.submit();
		return false;
	}
	else
		return true;
}

function execSearch(SearchType,URL){
	var searchText = new String(document.getElementById(SearchType + "_keywords").value).substring(0,50); 
	if (SearchType=="tag"){
		document.location = URL + SearchType + "/" + new String(escape(searchText)).replace(/\+/g,"%2B").replace(/\%20/g,"+").replace(/\//g,"");
	}
	else {
		document.location = URL + SearchType + "/search/" + new String(escape(searchText)).replace(/\%20/g,"+").replace(/\//g,"");
	}
	document.forms[SearchType + "_form"].submitSearch.value="Processing";
	document.forms[SearchType + "_form"].submitSearch.disabled=true;
}

//until sb_GetButton_v2 is smarter, we need this for video/blog search submit
function dummy(){
}

// Grey or Ungrey Form Fields
function DisableFields(FormName,SectionID) {
	var i=1;
	
	while(true) {
		if(document.getElementById(SectionID+i)) {	
	
			if (document.all || document.getElementById){
			if (document.getElementById(SectionID+i).disabled==true)
			document.getElementById(SectionID+i).disabled=false
			else
			document.getElementById(SectionID+i).disabled=true
			}
			i++;
		}
		else {
			break;
		}
	}
}

// Video Tracking System v9
VideoTrack = {

	Log: function(VideoActionID,VideoID,VideoData) {
		jQuery.get(jsBetaVar+'/ClickTrack.asp?FK1=' + VideoID + '&EventData=' + escape(VideoData) + '&EventID=' + VideoActionID);
	}
}

var curVideoID; 

function thisMovie(movieName) 
{
	if (navigator.appName.indexOf("Microsoft") != -1) 
	{
		return window[movieName];
	} 
	else 
	{
		return document[movieName];
	}
}

function handleVideoUnload() 
{ 
    VideoTrack.Log(42,curVideoID,thisMovie('FlashVideo').getTimeTotal());
    //  thisMovie('FlashVideo').trackFlashUnload();
} 
 
function VideoUnload(videoID) 
{ 
    curVideoID 				= videoID;
    window.onbeforeunload 	= handleVideoUnload; 
}

// Show or Hide Divs
function ShowHideDiv(WhichAction, WhichElement) {
	if (WhichElement == "commvid") {
		if (WhichAction == "Show") {
			document.getElementById("commvidlist").style.display="none";
			document.getElementById("commvidplayer").style.display="block";
		}
		else if (WhichAction == "Hide") {
			document.getElementById("commvidlist").style.display="block";
			document.getElementById("commvidplayer").style.display="none";
		}
	} else {
		if (document.getElementById(WhichElement).style.display == "block") {
			document.getElementById(WhichElement).style.display="none";
		} else {
			document.getElementById(WhichElement).style.display="block";
		}
	}
}

