//simple signin popup
function signIn(strRedirectURL, blnEmployer) {
	strEmployer ='';
	if(blnEmployer)
		strEmployer = '&blnEmployer=true';
	strScriptURL = strSiteURL+'ajax-scripts/signin.php?strRedirectURL='+strRedirectURL+strEmployer;
	showPopup('signin', 'Please Sign In to Access Your Account');
	$.get(strScriptURL, function(data){
		$("#generalPopupMain").html(data);
	});
}

//Use for signing in, then calling a function.
function signInAction(strFunctionName, arrFunctionParams) {
	strScriptURL = strSiteURL+'ajax-scripts/signin.php?strFunctionName='+strFunctionName+'&arrFunctionParams='+arrFunctionParams;
	showPopup('signin', 'Please Sign In to Access Your Account');
	$.get(strScriptURL, function(data){
		$("#generalPopupMain").html(data);
	});
}

function signOut() {
	window.location.href = strSiteURL+'process.php?strProcessType=logout';
}
function signOutEmployer() {
	window.location.href = strSiteURL+'processEmployer.php?strProcessType=logout';
}
function forgetMeEmployer() {
	window.location.href = strSiteURL+'processEmployer.php?strProcessType=logout&blnEraseName=true';
}

function forgetMe() {
	window.location.href = strSiteURL+'process.php?strProcessType=logout&blnEraseName=true';
}

function removeText(objThis, strText) {
	if(objThis.value == strText) {
		objThis.value = '';
		objThis.style.color = '#000';
	}
}
function addText(objThis, strText) {
	if(objThis.value == '') {
		objThis.value = strText;
		objThis.style.color = '#a6a6a6';
	}
}

function getScrollTop() {
	var intScrollTop = null;
	if(window.innerHeight) {
		intScrollTop = window.pageYOffset;
	} else if(document.documentElement.clientHeight) {
		intScrollTop = document.documentElement.scrollTop;
	} else {
		intScrollTop = document.body.scrollTop;
	}
	return intScrollTop;
}

function getScrollLeft() {
	var intScrollLeft = null;
	if(window.innerWidth) {
		intXOffset = window.pageXOffset;
	} else if(document.documentElement.clientWidth) {
		intXOffset = document.documentElement.scrollLeft;
	} else {
		intXOffset = document.body.scrollLeft;
	}
	return intScrollLeft;
}

function getWindowHeight() {
	var intHeight = null;
	if(window.innerHeight) {
		intHeight = window.innerHeight;
	} else if(document.documentElement.clientHeight) {
		intHeight = document.documentElement.clientHeight;
	} else {
		intHeight = document.body.clientHeight;
	}
	return intHeight;
}

function getWindowWidth() {
	var intWidth = null;
	if(window.innerWidth) {
		intWidth = window.innerWidth - 17;
	} else if(document.documentElement.clientWidth) {
		intWidth = document.documentElement.clientWidth;
	} else {
		intWidth = document.body.clientWidth;
	}
	return intWidth;
}

/*
*   Return: The page 'left' position of the element
*/
function getAbsoluteLeft(objElement) {
    var intXPos = objElement.offsetLeft;
    var objTemp = objElement.offsetParent;
    while (objTemp != null) {
        intXPos += objTemp.offsetLeft;
        objTemp = objTemp.offsetParent;
    }
    return intXPos;
}

/*
*   Return: The page 'left' position of the element
*/
function getAbsoluteTop(objElement) {
    var intYPos = objElement.offsetTop;
    var objTemp = objElement.offsetParent;
    while (objTemp != null) {
        intYPos += objTemp.offsetTop;
        objTemp = objTemp.offsetParent;
    }
    return intYPos;
}

//still need to test in all browsers
function getPageHeight() {
	return document.body.scrollHeight;
}

function showPopup(strLoad, strTitle) {

	objPopup = document.getElementById('generalPopup');
	objPopupMain = document.getElementById('generalPopupMain');
	objPopupHeader = document.getElementById('generalPopupHeader');


	objPopup.style.display = 'block';
	objPopup.style.top = getScrollTop()+ 25 + 'px';//(objTutorPopup.clientHeight / 2) + 'px';
	objPopup.style.left = (getWindowWidth() / 2) - (objPopup.clientWidth / 2) + 'px';

	objPopupHeader.innerHTML = strTitle;
	objPopupMain.innerHTML = '<img src="'+strSiteURL+'images/progbar.gif" alt="Loading ..." />';
/* 	var fncCallback = function(strResponse) {
		objPopupMain.innerHTML = strResponse;
	}
	strURL = window.location.href;
	AjaxRequest(strSiteURL+'ajax-scripts/'+strLoad+'.php?strURL='+Url.encode(strURL),null,fncCallback); */

	darkenBackground();
}

function confirmation(strTitle, strName, strField, intId, strProcessType) {

	objPopup = document.getElementById('confirmationPopup');
	objPopupMain = document.getElementById('confirmationPopupMain');
	objPopupHeader = document.getElementById('confirmationPopupHeader');

	objId = document.getElementById('intIdConf');
	objProcessType = document.getElementById('strProcessTypeConf');

	objNameValue = document.getElementById('confNameValue');
	objNameField = document.getElementById('confNameField');


	objPopup.style.display = 'block';
	objPopup.style.top = getScrollTop()+ 200 + 'px';//(objPopup.clientHeight / 2) + 'px';
	objPopup.style.left = (getWindowWidth() / 2) - (objPopup.clientWidth / 2) + 'px';

	objPopupHeader.innerHTML = strTitle;
	objId.value = intId;
	objProcessType.value = strProcessType;
	
	objNameValue.innerHTML = strName;
	objNameField.innerHTML = strField;

	darkenBackground();
}

function hidePopup() {
	objShadowBox = document.getElementById('generalPopup');
	objShadowBox.style.display = 'none';

	normalBackground();
}
function hideConfirmationPopup() {
	objShadowBox = document.getElementById('confirmationPopup');
	objShadowBox.style.display = 'none';

	normalBackground();
}


function darkenBackground() {
     objDarkBG = document.getElementById('winDarkBackground');

	objDarkBG.style.top = '0px';
	objDarkBG.style.display = 'block';
	objDarkBG.style.height = getPageHeight() + 'px';
}
function normalBackground() {
    objDarkBG = document.getElementById('winDarkBackground');

	objDarkBG.style.display = 'none';
}

function pause(intDelayMilliseconds) {
	var dt = new Date();
	while(((new Date()) - dt) <= intDelayMilliseconds){}
}

function openLoading() {
	darkenBackground();
	
	objLoading = document.getElementById('pLoading');
	
	objLoading.style.display = 'block';
	objLoading.style.top = getScrollTop()+ (objLoading.clientHeight / 2) + 'px';
	objLoading.style.left = (getWindowWidth() / 2) - (objLoading.clientWidth / 2) + 'px';


}
function  closeSuccess() {
	$('#header_success').slideUp(700);
}

function pretendLoading(intDelay) {
	openLoading();
	//setTimeout("",4000);

}

function informationOver(strDiv) {
	objInformation = document.getElementById(strDiv);
	objInformation.style.display = '';
	//$('#'+strDiv).show();
}

function informationOut(strDiv) {
	objInformation = document.getElementById(strDiv);
	objInformation.style.display = 'none';
	//$('#'+strDiv).hide();
}

function showProfession() {
	objProfessionSelect = document.getElementById('professionSelect');
	objProfessionSelect.style.display = 'block';
}
function closeProfession() {
	objProfessionSelect = document.getElementById('professionSelect');
	objProfessionSelect.style.display = 'none';

}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	
	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1) {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return false;
}
function checkCookie()
{
	username=getCookie('username');
	if (username!=null && username!="")
	  {
	  alert('Welcome again '+username+'!');
	  }
	else
	  {
	  username=prompt('Please enter your name:',"");
	  if (username!=null && username!="")
	    {
	    setCookie('username',username,365);
	    }
	  }
}

function loadPage( intPage, strPageURL , strParams, blnAjax, strInto ) {
	var strURL = '';
 	if(strPageURL.indexOf('http://localhost')==-1) {
		//strSiteURL = 'http://localhost/';
	}

	//strPageURL = strPageURL.slice(1);

	if( getURLParamValue('intPage') == '' ) {
		if(strParams!='') strParams = strParams+'&';
		strURL += strSiteURL+strPageURL + '?' + strParams + 'intPage=' + intPage;
	}
	else {
		strURL += strSiteURL+strPageURL + '?' + strParams.replace(getURLParamValue('intPage').replace('?', ''), '&intPage=' + intPage);
	}

	//if( strURL != strVisitedURL ){
		if( blnAjax )
			//alert(strURL);
			AjaxRequest( strURL, strInto, default_handle );
		else
			location.href = strURL;
	//}

	strVisitedURL = strURL;
}


/*********************Generic Useful Functions *****************************************/
//function gets url parameters for js
//Example on url http://www.volge.com/example.php?strArtistName=BenGibbard&flag=true
//eg getURLParamValue( 'strArtistName', true ) will return BenGibbard
//eg getURLParamValue( 'strArtistName', false ) will return strArtistName=BenGibbard
function getURLParamValue( strParamName, blnValueOnly ) {
	if(blnValueOnly)
    	intReturnType = 1; //setting this to 1 returns only the value of the param
	else
		intReturnType = 0; //setting this to 0 returns the param and value

	var strRegex = "[\\?&]"+strParamName+"=([^&#]*)";
	var objRegex = new RegExp( strRegex );
	var results = objRegex.exec( location.href );
	if( results == null )
		return '';
	else
	    return results[intReturnType];
}

//will take a url and replace the current value of a param, or it will just add the param if new
function replaceURLParamValue(strURL, strParamName, strParamValue) {
	strURLParam = getURLParamValue(strParamName, false);
	strSeperator = '';

	if(strURLParam == '') {
		if(strURL.indexOf('&') < 0)
			strSeperator = '?';
		else
			strSeperator = '&';

		strNewURL = strURL + strSeperator + strParamName + '=' + strParamValue;
		
	}
	else {
		if(strURLParam.charAt(0)=='?') {
			strSeperator = '?';
		}
		strURLParam = strURLParam.replace('&', '');
		strNewURL = strURL.replace(strURLParam, strSeperator+strParamName + '=' + strParamValue)
	}
	return strNewURL;
}

/*
*   Desc: Function fills all the specified selection fields with specified values on the page
*   Return: none
*/
function fillSelections( strForm, objSelects ) {
    var objForm = document.getElementById( strForm );
	
    for (var i in objSelects) {
		if(objSelects[i] != '') { //&& parseInt(objSelects[i], 10) != 0
			objForm.elements[i].value = objSelects[i];
		}
    }
}
function fillRadio(strForm, strRadio, strValue) {
	var objForm = document.getElementById( strForm );

	for(a=0; a < objForm.elements[strRadio].length; a++) {
		if( objForm.elements[strRadio][a].value == strValue) {
			 objForm.elements[strRadio][a].checked= true;

		}
	}
}

/*
*   Desc: Function fills all the specified check fields with specified values on the page
*   Return: none
*/
function fillChecks( strForm, objChecks ) {
    var objForm = document.getElementById( strForm );

    for (var i in objChecks) {
		
		if( objChecks[i] == '1' )
			objForm.elements[i].checked = true;
		else
			objForm.elements[i].checked = false;
    }
}

function getRadioCheckedValue(strFormName, strRadioName) {
	objForm = document.getElementById(strFormName);
	var objRadio = objForm.elements[strRadioName];
	
	for(var i = 0; i < objRadio.length; i++) {
		if(objRadio[i].checked) {
			return objRadio[i].value;
		}
	}
	return '';
}

function ucwords(str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // *     example 1: ucwords('kevin van zonneveld');    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();    });
}

function validateURL(strURL) {
	var objRegex = new RegExp();
	objRegex.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
	if (!objRegex.test(strURL)) {
		return false;
	}
	return true;
}
function validateYouTubeEmbeddedVideo(strCode) {
	var objRegex = new RegExp();
	objRegex.compile("^<object .+www\.youtube\.com.+</embed></object>");
	if (!objRegex.test(strCode)) {
		return false;
	}
	return true;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function strip_tags(strString) {
	return strString.replace(/(<([^>]+)>)/ig,"");
}

function IsNumeric(intNumber) {
	intNumber = intNumber.replace(',', '');
	intNumber = intNumber.replace(' ', '');
	return (parseInt(intNumber) - 0) == intNumber;
}


function bookmarkUs() {
	if (window.sidebar) { // Firefox
		window.sidebar.addPanel('CareerVitals.', 'http://www.CareerVitals.com', "");
	} else if(window.opera && window.print) { // Opera
		var strAnchor = document.createElement('a');
		strAnchor.setAttribute('href','http://www.CareerVitals.com');
		strAnchor.setAttribute('title','CareerVitals.');
		strAnchor.setAttribute('rel','sidebar');
		strAnchor.click();
	} else if(document.all) { // IE
		window.external.AddFavorite('http://www.CareerVitals.com}', 'CareerVitals.com.');
	}
}
//UNFINISHED.. WIP
//returns true is error, false otherwise
function validateForm(arrFields) {
	for(var arrField in arrFields) { alert('#'+arrFields);
		if(arrField.strFieldType == 'text') {
			if(!$('#'+arrField['strFieldName']).val()) {
				$('#errors').append(arrField['strErrorCaption']+' must be entered <br />');
				$('#'+arrField['strFieldName']).val().addClass('error_field');
				blnError = true;
			}
		}
	}
}

function showVideo(intLinkId) {
	showPopup('', '');
	strScriptURL = strSiteURL + 'processAjax.php?strProcessType=show_video&intLinkId='+intLinkId;
	$.get(strScriptURL, function(data){
		$('#generalPopupMain').html(data);
	});
}

function validateEmail(blnPopup, blnEmployer) {
	strErrorDiv = (blnPopup ? 'error': 'errors');
	strEmployerParam = (blnEmployer ? '&blnIsEmployer=true' : '');

	if($("#strEmail").val()) {
		$.ajax({
			url: strSiteURL + 'ajax-scripts/ajaxCheckEmail.php',
			type: 'POST',
			data: 'strEmail='+$("#strEmail").val() + strEmployerParam,
			success: function(strVal) {
				arrMessage = strVal.split('|');
				if(arrMessage[0] == 'error') {
					$("#"+strErrorDiv).append(arrMessage[1]+' <br />');
					$("#strEmail").addClass('error_field');
					$("#blnValidForm").val('false');

				}
				else {
					//alert('Good! : '+arrMessage[0]+' b '+arrMessage[1]);
					$("#"+strErrorDiv).html($("#errors").html().replace(/Invalid email format./g, ''));
					$("#"+strErrorDiv).html($("#errors").html().replace(/Email already exists./g, ''));
					$("#strEmail").removeClass('error_field');
					$("#blnValidForm").val('true');
				}
			}
		});
	}
}

//returns true if error, false others
function validateEmailFormat(strEmailDiv) {
	objEmail = document.getElementById(strEmailDiv);
	if(objEmail.value != '') {
		regExp = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
		if (!regExp.test(objEmail.value)) {
			$("#errors").append('Please ensure all emails are in proper format <br />');
			$('#'+strEmailDiv).addClass('error_field');
			return true;
		}
	}
}

//returns true if error, false others
function validateEmailFormatFromString(strEmail) {
	if(strEmail != '') {
		regExp = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
		if (!regExp.test(strEmail)) {
			return true;
		}
	}
}

function validatePassword() {
	if($("#strPassword").val() && $("#strPasswordConfirm").val()) {
		$.ajax({
			url: strSiteURL + 'ajax-scripts/ajaxCheckPassword.php',
			type: 'POST',
			data: 'strPassword='+$("#strPassword").val()+'&strPasswordConfirm='+$("#strPasswordConfirm").val(),
			success: function(strVal) {
				arrMessage = strVal.split('|');
				if(arrMessage[0] == 'error') {
					$("#errors").html($("#errors").html().replace(/Passwords did not match./g, ''));
					$("#errors").html($("#errors").html().replace(/Password must be between 6 and 20 characters with no spaces./g, ''));
					$("#errors").append(arrMessage[1]);
					$("#strPassword").addClass('error_field');
					$("#strPasswordConfirm").addClass('error_field');
					$("#blnValidForm").val('false');
				}
				else {
					//alert('Good! : '+arrMessage[0]+' b '+arrMessage[1]);
					$("#errors").html($("#errors").html().replace(/Passwords did not match./g, ''));
					$("#errors").html($("#errors").html().replace(/Password must be between 6 and 20 characters with no spaces./g, ''));
					$("#strPassword").removeClass('error_field');
					$("#strPasswordConfirm").removeClass('error_field');
					$("#blnValidForm").val('true');
				}
			}
		});
	}
}

function selectCountry(ojbThis, strCountry, strState) {
	strCountry = (ojbThis.value != undefined ? ojbThis.value : strCountry);

	strScriptURL = strSiteURL + 'ajax-scripts/ajaxReturnStatesFromCountry.php?strCountry='+strCountry;
	$.get(strScriptURL, function(data){
		data=trim(data);
		if(data == '') {
			$('#statesrow').hide();
		}
		else {
			$('#statesrow').show();
			$('#states').html(data);
			if(strState)
				$('#strState').val(strState); //select the proper state
		}
	});
}


function countTextarea(strTextareaDiv, strCounterDiv, intLimit) {
	if($('#'+strTextareaDiv).val().length > intLimit) {
		$('#'+strTextareaDiv).val($('#'+strTextareaDiv).val().substr(0, intLimit));
	}
	else {
		$('#'+strCounterDiv).html(intLimit - $('#'+strTextareaDiv).val().length);
	}

}

//Display another image with a button is hovered over
function showButtonHover(objThis, strImage) {
	objThis.src = strSiteURL + 'images/'+strImage;
}

function showSubmitButtonHover(objThis, strImage) {
	objThis.style.backgroundImage = strSiteURL + 'images/'+strImage;
}

function showSubNavHover(strImageId, intShow) {
	strShow = 'hidden';
	if(intShow == 1)
		strShow = 'visible';
	document.getElementById(strImageId).style.visibility = strShow;
}

