var ajaxObj = new ajaxClass();
var ajaxObjLocation = new ajaxClass();
var ajaxObjCategory = new ajaxClass();
var nameRegExp = /^[a-zA-Z\s]{1,50}$/i;
var userNameRegExp = /^[a-z][a-z0-9]{7,16}$/i;
var emailRegExp = /^[-a-z0-9._]+@([-a-z0-9]+\.)+[-a-z0-9]+$/i;
var userPasswordRegExp = /^[a-z0-9]{8,16}$/i;
var userCodeRegExp = /^[0-9]{1,20}$/i;

function getCountryParameters(countryId)
{
		j = countriesArray.length;
		for(var i=0 ; i < j ; i++)
		{
				if(countriesArray[i][0] == countryId) return countriesArray[i];		
		}
}

function getCategoryParameters(categoryId)
{
		j = categoryArray.length;
		for(var i=0 ; i < j ; i++)
		{
				if(categoryArray[i][0] == categoryId) return categoryArray[i];		
		}
}

function showCurrency()
{
		try // Some pages may not currency showing
		{
				countryComboRef = document.getElementById('countryCombo');
				if(countryComboRef.selectedIndex >0)
				{		
						tempArray = getCountryParameters(countryComboRef.value);
						document.getElementById('currencySymbol').innerText = '(' + tempArray[3] + ')';
						document.getElementById('currency').innerHTML = "Currency in <b>" + tempArray[2] + "</b>. ";				
				}
				else
				{
						document.getElementById('currencySymbol').innerText = "";
						document.getElementById('currency').innerHTML = "";
				}
		}
		catch(e) {}
}




/*
1) Looks for combos with higher groupindex, hides them and makes their selectedIndex = 0
2) Combos without groupIndex are ignored.
3) If the selectedIndex == 0 , do nothing else look for the next higher groupindex combo and load it
4) Special Case: if the next combo to load is State or Division and Country or Category do not support this or City and Title but states and division must come first, load next element whatever it is

The code below is optimized and may take shortcuts to implement the above
*/

function loadNextCombo(callerObj, ajaxObject)
{
		if(callerObj.selectedIndex == 0) document.getElementById('wait' + callerObj.getAttribute('group')).style.display = 'none';
		ajaxObject.abortRequest();
		
		var possibleRelatedElements = document.getElementsByTagName('select');
		var relatedElements = new Array();
		var callerIndex = callerObj.getAttribute('groupindex');
		var groupId = callerObj.getAttribute('group');
		var nextComboToLoad = null;
		
		for(var i= 0; i < possibleRelatedElements.length; i++)
		{
				if(possibleRelatedElements[i].getAttribute('group') == groupId && possibleRelatedElements[i].getAttribute('groupindex') > callerIndex)
				{
							possibleRelatedElements[i].selectedIndex = 0;
							
							///////////// May change from page to Page. The containg element might be different.
							document.getElementById(possibleRelatedElements[i].id + 'Table').style.display = 'none'; 
							
							relatedElements.push(possibleRelatedElements[i]);
				}
		}
		
		var numRelatedElements = relatedElements.length;	
		if(callerObj.selectedIndex > 0 && numRelatedElements > 0)
		{
				relatedElements.sort(comboSortFunction);
				if(relatedElements[0].id == 'stateCombo')
				{
						if(getCountryParameters(document.getElementById('countryCombo').value)[1] >0)
						{
								nextComboToLoad = relatedElements[0];															
						}
						else
						{
								nextComboToLoad = relatedElements[1];												
						}
				}
				else if(relatedElements[0].id == 'cityCombo')
				{
						if(getCountryParameters(document.getElementById('countryCombo').value)[1] == 0 || document.getElementById('stateCombo').selectedIndex > 0 )
						{
								nextComboToLoad = relatedElements[0];															
						}
						else
						{
								nextComboToLoad = relatedElements[1];
						}											
				}
				else if(relatedElements[0].id == 'divisionCombo')
				{
						if(getCategoryParameters(document.getElementById('categoryCombo').value)[1] >0)
						{
								nextComboToLoad = relatedElements[0];															
						}
						else
						{
								nextComboToLoad = relatedElements[1];
						}											
				}
				else if(relatedElements[0].id == 'titleCombo')
				{
						if(getCategoryParameters(document.getElementById('categoryCombo').value)[1] ==0 || document.getElementById('divisionCombo').selectedIndex > 0 )
						{
								nextComboToLoad = relatedElements[0];															
						}
						else
						{
								nextComboToLoad = relatedElements[1];
						}											
				}
				else
				{
								nextComboToLoad = relatedElements[0];
				}
		}
		
		if(nextComboToLoad) loadCombo(nextComboToLoad, ajaxObject);
}



function loadCombo(comboObj, ajaxObject)
{
		document.getElementById('wait' + comboObj.getAttribute('group')).style.display = 'block';
		var possibleRelatedElements = document.getElementsByTagName('select');
		var index = comboObj.getAttribute('groupindex');
		var groupId = comboObj.getAttribute('group');
		var url = 'includes/getComboValues.php?get=' + comboObj.id ;
		
		for(var i= 0; i < possibleRelatedElements.length; i++)
		{
				if(possibleRelatedElements[i].getAttribute('group') == groupId && possibleRelatedElements[i].selectedIndex > 0)
				{
							url = url + '&' + possibleRelatedElements[i].name + '=' + possibleRelatedElements[i].value;
				}
		}

		ajaxObject.sendRequest('GET', url, true, null, function (){fetchComboResponse(comboObj, ajaxObject);}, 500);
}




function fetchComboResponse(comboObj, ajaxObject)
{
		if(ajaxObject.XMLHttpRequestObject.readyState == 4 && ajaxObject.XMLHttpRequestObject.status == 200	)
		{
				var xmlResponse = ajaxObject.XMLHttpRequestObject.responseXML;
				populateCombo(comboObj, xmlResponse, false, null);
				document.getElementById(comboObj.id + 'Table').style.display = 'block';
				document.getElementById('wait' + comboObj.getAttribute('group')).style.display = 'none';				
		}
}


function comboSortFunction(a, b)
{
		return a.getAttribute('groupindex') - b.getAttribute('groupindex');
}



function validateAddJob()
{
		var jobSalary = /^(([1-9][0-9]{0,7}))(\.[0-9]{1,4})?$/i;
		var jobCommision = /^(([1-9][0-9]{0,7})|(0))(\.[0-9]{1,4})?$/i;
		
		
		if(document.getElementById('countryCombo').selectedIndex == 0)
		{
				alert("Please select a country.");
				return false;							
		}

		if(document.getElementById('stateCombo').selectedIndex == 0 && getCountryParameters(document.getElementById('countryCombo').value)[1] > 0)
		{
				alert("Please select a state / province");
				return false;							
		}
		
		if(document.getElementById('cityCombo').selectedIndex == 0)
		{
				alert("Please select a city.");
				return false;							
		}
		
		if(document.getElementById('categoryCombo').selectedIndex == 0)
		{
				alert("Please select a job category.");
				return false;							
		}

		if(document.getElementById('divisionCombo').selectedIndex == 0 && getCategoryParameters(document.getElementById('categoryCombo').value)[1] > 0)
		{
				alert("Please select a sub category");
				return false;							
		}
		
		if(document.getElementById('titleCombo').selectedIndex == 0)
		{
				alert("Please select a job title.");
				return false;							
		}		
		
		if(document.getElementById('ageCombo').selectedIndex == 0)
		{
				alert("Please select your age");
				return false;				
		}	
		
		if(document.getElementById('genderCombo').selectedIndex == 0)
		{
				alert("Please select your gender");
				return false;							
		}	
		
		if(document.getElementById('nationalityCombo').selectedIndex == 0)
		{
				alert("Please select your nationality");
				return false;							
		}					
		
		
		if(document.getElementById('educationCombo').selectedIndex == 0)
		{
				alert("Please select your level of education.");
				return false;				
		}
		

		if(document.getElementById('experienceCombo').selectedIndex == 0)
		{
				alert("Please select the number of experience years.");
				return false;				
		}
		
		
		if(document.getElementById('industryCombo').selectedIndex == 0)
		{
				alert("Please select an industry.");
				return false;				
		}	
		
		if(document.getElementById('sizeCombo').selectedIndex == 0)
		{
				alert("Please select the size of the company.");
				return false;				
		}
		
		if(document.getElementById('sinceCombo').selectedIndex == 0)
		{
				alert("Please select the duration you have been working with your current employer.");
				return false;				
		}
		
		if(document.getElementById('jobTypeCombo').selectedIndex == 0)
		{
				alert("Please select a job type.");
				return false;				
		}
		
		if(document.getElementById('daysCombo').selectedIndex == 0)
		{
				alert("Please select the number of working days in a week.");
				return false;				
		}
		
		if(document.getElementById('hoursCombo').selectedIndex == 0)
		{
				alert("Please select the number of working hours in a day");
				return false;				
		}
		
		if(document.getElementById('vacationCombo').selectedIndex == 0)
		{
				alert("Please select the number of yearly paid vacation days");
				return false;				
		}
		
		if(document.getElementById('managingCombo').selectedIndex == 0)
		{
				alert("Please select the number of people you manage.");
				return false;				
		}
		
		if(document.getElementById('healthCombo').selectedIndex == 0)
		{
				alert("Please select a health insurance plan.");
				return false;				
		}
		
		
		if(!jobSalary.test(document.getElementById('salaryInput').value))
		{
				alert("Please type in a valid salary.");
				return false;
		}
		
		var monthlySalaryConfirm = window.confirm('The salary should be the monthly salary not the yearly. Are you sure you typed in your monthly salary?');
		if(monthlySalaryConfirm)
			return true;
		else
			return false;
}



function notify()
{
		document.getElementById('notifyQuestion').style.display = 'none';
		document.getElementById('notifyAccept').style.display = 'block';							
}

function confirmNotify(x)
{
		if(!emailRegExp.test(document.getElementById('email').value))
		{
				alert("Email is not valid");
				return false;
		}		
		document.getElementById('notifyAccept').style.display = 'none';
		document.getElementById('notifyProcess').style.display = 'block';
		if(document.getElementById('location').selectedIndex == 1 && document.getElementById('location').length == 2)
		{
				locationName = locationsArr[2]; 
				data = 'jobid=' + x + '&email=' + encodeURIComponent(document.getElementById('email').value) + '&locationid=' + document.getElementById('location').value + '&freq=1&locationtype=3'; 
		}
		else
		{
				locationName = locationsArr[document.getElementById('location').selectedIndex];
				data = 'jobid=' + x + '&email=' + encodeURIComponent(document.getElementById('email').value) + '&locationid=' + document.getElementById('location').value + '&freq=1&locationtype=' + (document.getElementById('location').selectedIndex + 1); 
		}
		ajaxObj.sendRequest('POST', 'includes/notification.php', true, data , notifyResult, 0);
}

function notifyResult()
{
		if(ajaxObj.XMLHttpRequestObject.readyState == 4 && ajaxObj.XMLHttpRequestObject.status == 200	)
		{
				if(ajaxObj.XMLHttpRequestObject.responseText == "00")
				{
						document.getElementById('locationNameHolder').innerText = locationName;
						document.getElementById('notifyProcess').style.display = 'none';
						document.getElementById('notifySuccess').style.display = 'block';
						document.getElementById('notifyFail').style.display = 'none';
				}
				else
				{
						document.getElementById('notifySuccess').style.display = 'none';
						document.getElementById('notifyAccept').style.display = 'block';
						document.getElementById('notifyProcess').style.display = 'none';
						document.getElementById('notifyFail').innerHTML = "<span style='color:red;'>" + ajaxObj.XMLHttpRequestObject.responseText + "</span>";
						document.getElementById('notifyFail').style.display = 'block';						
				}
		}		
}




function validateSubscibe()
{
		if(!emailRegExp.test(document.getElementById('subEmail').value))
		{
				alert("Email is not valid");
				return false;
		}				
		
		if(document.getElementById('countryCombo').selectedIndex == 0)
		{
				alert("Please select a country.");
				return false;							
		}
		
		if(document.getElementById('categoryCombo').selectedIndex == 0)
		{
				alert("Please select a job category.");
				return false;							
		}

		if(document.getElementById('divisionCombo').selectedIndex == 0 && getCategoryParameters(document.getElementById('categoryCombo').value)[1] > 0)
		{
				alert("Please select a sub category");
				return false;							
		}
		
		if(document.getElementById('titleCombo').selectedIndex == 0)
		{
				alert("Please select a job title.");
				return false;							
		}
		
		return true;
}


function validateLogin()
{
		if(!emailRegExp.test(document.getElementById('loginEmail').value))
		{
				alert("Email is not valid");
				return false;
		}				
		
		if(!userPasswordRegExp.test(document.getElementById('loginPassword').value))
		{
				alert("Password is not valid");
				return false;
		}		
		
		return true;		
}



function validateVerify()
{
		if(!emailRegExp.test(document.getElementById('signUpEmail').value))
		{
				alert("Email is not valid");
				return false;
		}				
		
		if(!userPasswordRegExp.test(document.getElementById('signUpPassword').value))
		{
				alert("Password is not valid");
				return false;
		}	
		
		if(!userCodeRegExp.test(document.getElementById('signUpCode').value))
		{
				alert("Verification code is not valid");
				return false;
		}		
		
		return true;		
}


function sendCode()
{
		if(!emailRegExp.test(document.getElementById('signUpEmail').value))
		{
				alert("Email is not valid");
		}
		else
		{		
				document.getElementById('processing').style.display = 'inline';
				document.getElementById('sendLink').style.display = 'none';
		
				ajaxObj.sendRequest('POST', 'includes/sendcode.php', true, "email=" + encodeURIComponent(document.getElementById('signUpEmail').value) , codeSendResult, 0);
		}
}

function codeSendResult()
{
		if(ajaxObj.XMLHttpRequestObject.readyState == 4 && ajaxObj.XMLHttpRequestObject.status == 200	)
		{
				if(ajaxObj.XMLHttpRequestObject.responseText == "00")
				{
						document.getElementById('result').innerHTML = "<span style='color:green;'>Activation code was sent to your email.</span>";
						document.getElementById('result').style.display = 'inline';
						document.getElementById('processing').style.display = 'none';
				}
				else
				{
						document.getElementById('result').innerHTML = "<span style='color:red;'>Some problems has occured. Try again later.</span>";
						document.getElementById('result').style.display = 'inline';
						document.getElementById('processing').style.display = 'none';					
				}
		}			
}



function sendSuggestion()
{
		if(document.getElementById('textAreaSuggestion').value == '')
		{
				alert('Suggestion is empty. Please type something.');	
		}
		else
		{
				document.getElementById('divSendSuggestion').style.display = 'none';
				document.getElementById('divSendingSuggestion').style.display = 'block';
				
				var myFunc = function() { 
												if(ajaxObj.XMLHttpRequestObject.readyState == 4 && ajaxObj.XMLHttpRequestObject.status == 200)
												{
														document.getElementById('divSendingSuggestion').style.display = 'none';
														document.getElementById('divSuccessSuggestion').style.display = 'block';
												}	
										}
				ajaxObj.sendRequest('POST', 'includes/sendsuggestion.php', true, "suggestion=" + encodeURIComponent(document.getElementById('textAreaSuggestion').value) , myFunc, 0);				
		}
}




function sendInvitation()
{
		if(!emailRegExp.test(document.getElementById('textEmailInvitation').value))
		{
				alert("Email is not valid");
		}
		else if(!nameRegExp.test(document.getElementById('textNameInvitation').value))
		{
				alert("Name is not valid. Only letters and spaces are allowed.");
		}		
		else
		{		
				document.getElementById('divSendInvitation').style.display = 'none';
				document.getElementById('divSendingInvitation').style.display = 'block';
				
				var myFunc = function() { 
												if(ajaxObj.XMLHttpRequestObject.readyState == 4 && ajaxObj.XMLHttpRequestObject.status == 200)
												{
														document.getElementById('divSendingInvitation').style.display = 'none';
														document.getElementById('divSuccessInvitation').style.display = 'block';
												}	
										}
				ajaxObj.sendRequest('POST', 'includes/sendinvitation.php', true, "email=" + encodeURIComponent(document.getElementById('textEmailInvitation').value) + "&name=" + encodeURIComponent(document.getElementById('textNameInvitation').value)  , myFunc, 0);	
		}
}