/**
 * @author richardmerchant
 */

// set up global variables
var companyId = "";
var companyCategoryId = "";
var oldSearchString = ""


$(function() {
	
   // submit sidebar search form 
	$("#sidebar_search_submit").click(function(){
		var filter_search = $("input#filter_search").val();
		var prev_filter_search;
		
		if(filter_search == prev_filter_search || filter_search == "" || filter_search == "Keywords")
		{
			$("input#filter_search").focus();
			return false;
		}
		else
		{
			$("#companySearch").submit();
			prev_filter_search = filter_search;
		}
		
	});
	
	// submit sidebar search form 
	$("#header_search_submit").click(function(){
		var q = $("input#q").val();
		var prev_q;
		
		if(q == prev_q || q == "" || q == "Search Site")
		{
			$("input#q").focus();
			return false;
		}
		else
		{
			$("#siteSearch").submit();
			prev_q = q;
		}
	});
		
	// add fouus an blur to search form
	$('input#q' ).focus(
	function()
	{
		if(this.value == this.defaultValue)
		{
			this.value = '';
		}
		
		if(this.value != this.defaultValue)
		{
			this.select();
		}
	});
	
	$('input#q').blur(
	function()
	{
		if($.trim(this.value) == '')
		{
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
		
		
		
		
		
		
		
		
		
		$("#search_results").fadeOut(500, function(){
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
		});
	
	$("#ajax_loader, .ajax_loader1, .ajax_loader2").css({'visibility' : 'hidden', 'display' : 'none'});
	
	$("#company_name").change(function() {
      	$("#search_results").hide();
		// show ajax loader
		$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
		
		// set category select box back to default setting
		$("select#company_category").val("");
		
		// get value of company_name select option
		companyId = $("select#company_name").val();
		
		// validation process here
		if(companyId == "" || isNaN(companyId) == true)
		{
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
			$("#search_results").html("<h3>No company was Selected</h3>")
			$("#search_results").show();
			$("select#company_name").focus();
			return false;
		}
		
		// send data to search function
		var dataString = "?companyID=" + companyId + "&function=companyCatergorySearch";
		
		$.post('/ajax.php' + dataString, function(data){
			if(data.length > 0)
			{
				$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
				$("#search_results").html(data);
				$("#search_results").fadeIn(1000);
			}
		});
    });
	
	$("#company_category").change(function() {
      	
		$("#search_results").hide();
		// show ajax loader
		$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
		
		// set the company select box back to default setting
		$("select#company_name").val("");
		
				
		// get value of company_category select option
		companyCategoryId = $("select#company_category").val();
		
		// get value of category id
		var targetCatId = $("input#targetCatId").val();
		
		
		// validation process here
		if(companyCategoryId == "" || isNaN(companyCategoryId) == true)
		{
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
			$("#search_results").html("<h3>No category was Selected</h3>")
			$("#search_results").fadeIn(1000);
			$("select#company_category").focus();
			return false;
		}
		
		// more validation
		if(targetCatId == "" || isNaN(targetCatId) == true)
		{
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
			$("#search_results").html("<h3>There seems to be an unexpected error searching for The company, Please refresh the page. Thank you</h3>")
			$("#search_results").fadeIn(1000);
			$("select#company_category").focus();
			return false;
		}
		
		// send data to search function
		var dataString = "?categoryID=" + companyCategoryId + "&targetCategoryID=" + targetCatId + "&function=companyCatergorySearch";
		
		$.post('/ajax.php' + dataString, function(data){
			if(data.length > 0)
			{
				$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
				$("#search_results").html(data);
				$("#search_results").fadeIn(1000);
			}
		});
    });
});


function jobsearch(page, string, paging)
{
	if(!paging)
	{
		// get value of search_string input box
		var searchString = $("input#search_string").val();
		
		// validation process here
		if(searchString == oldSearchString)
			return false;
		else if(searchString == '')
		{
			$("input#search_string").focus();
			return false;
		}
		else
		{
			// store search string for later use
			oldSearchString = searchString;
		}
	}
	else
	{
		var searchString = string;
	}
	
	// fade out current items
	$("#job_search_results").fadeOut(10, function(){
		$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
	});
	
	if(!paging)
	{
		// send data to search function
		var dataString = "?searchString=" + searchString + "&function=jobSearch";
	}
	else
	{
		// send data to search function
		var dataString = "?searchString=" + searchString + "&function=jobSearch&page=" + page;
	}
	
	
	$.post('/ajax.php' + dataString, function(data){
	if(data.length > 0)
		{
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
			$("#job_search_results").html(data);
			$("#job_search_results").fadeIn();
		}
	});
}

function registerRequest()
{
	// get value of search_string input box
	var title = $("select#title").val();
	var firstName = $("input#first_name").val();
	var surname = $("input#surname").val();
	var workEmail = $("input#work_email").val();
	var errors = 0;
	
	if(title == 0 || title == "")
	{
		$('.title_errors').html("You must select a title").show(1000);
		errors++;
		
	}
	else
	{
		$('.title_errors').html("").hide(500);
	}
	
	if(firstName == "")
	{
		$('.first_name_error').html("You must enter a first name").show(500);
		errors++;
	}
	else
	{
		$('.first_name_error').html("").hide(200);
	}
	
	if(surname == "")
	{
		$('.surnamename_error').html("You must enter a surname").show(500);
		errors++;
	}
	else
	{
		$('.surnamename_error').html("").hide(200);
	}
	
	if(workEmail == "")
	{
		$('.work_email_error').html("You must enter a work email").show(500);
		errors++;
	}
	else if(!validateEmail(workEmail))
	{
		$('.work_email_error').html("The email address does not seem to be valid. Please retype").show(500);
		errors++;
	}
	else
	{
		$('.work_email_error').html("").hide(200);
	}
	
	if(errors < 1)
	{
		// fade out request user form
		$("#regForm").fadeOut(10, function(){
			$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
		});
		
		
		sendRegRequestEmail(title, firstName, surname, workEmail);
	}
			
}


function validateEmail(elementValue){
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return emailPattern.test(elementValue);
}

function validateAlpha(elementValue){
   var alphaPattern = /^[a-zA-Z]$/;
   return alphaPattern.test(elementValue);
}

function validateAlphaNumeric(elementValue){
   var alphaNumericPattern = /^[a-zA-Z0-9]$/;
   return alphaNumericPattern.test(elementValue);
}


function sendRegRequestEmail(title, firstName, surname, workEmail)
{
	// send data to search function
	var dataString = "?title=" + title + "&firstname=" + firstName + "&surname=" + surname + "&email=" + workEmail + "&function=registerRequest";
	$.post('/ajax.php' + dataString, function(data){
		if(data.length > 0)
		{
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
			$("#reg_results").html(data);
			$("#reg_results").fadeIn();
		}
	});
}


function requestForgottenDetails()
{
	var username = $("input#username").val();
	
	var errors = 0;
	
	if(username == "")
	{
		$('.username_error').html("You must enter a username").show(1000);
		errors++;
		
	}
	else if(!validateEmail(username))
	{
		$('.username_error').html("The email address enetered does not seem to be valid. Please check and re-enter.").show(1000);
		errors++;
	}
	else
	{
		$('.username_error').html("").hide(500);
	}
	
	if(errors < 1)
	{
		// fade out forgot user form
		$('#forgottenForm').fadeOut(10, function(){
			$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
		});
		
		// send data to search function
		var dataString = "?username=" + username + "&function=forgottenPassword";
		$.post('/ajax.php' + dataString, function(data){
			if(data.length > 0)
			{
				$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
				$("#forgot_results").html(data);
				$("#forgot_results").fadeIn();
			}
		});
		
	}
	
}

function changeUserDetails()
{
	$(".edit_success").fadeOut(100);
	
	// get value of search_string input box
	var title = $("select#title").val();
	var firstName = $("input#first_name").val();
	var surname = $("input#surname").val();
	var email = $("input#email").val();
	var address1 = $("input#address1").val();
	var address2 = $("input#address2").val();
	var addressTown = $("input#addressTown").val();
	var county = $("input#county").val();
	var postcode = $("input#postcode").val();
	var country = $("input#country").val();
	var phone = $("input#phone").val();
	var fax = $("input#fax").val();
	var organisation = $("select#organisation").val();
	var jobtitle = $("input#jobtitle").val();
	var userid = $("input#userid1").val();
	var companyid = $("input#companyid").val();
	
	var errors = 0;
	
	if(title == 0 || title == "")
	{
		$('.title_errors').html("You must select a title").show(1000);
		errors++;
		
	}
	else
	{
		$('.title_errors').html("").hide(500);
	}
	
	if(firstName == "")
	{
		$('.first_name_error').html("You must enter a first name").show(500);
		errors++;
	}
	else
	{
		$('.first_name_error').html("").hide(200);
	}
	
	if(surname == "")
	{
		$('.surnamename_error').html("You must enter a surname").show(500);
		errors++;
	}
	else
	{
		$('.surnamename_error').html("").hide(200);
	}
	
	if(email == "")
	{
		$('.email_error').html("You must enter an email").show(500);
		errors++;
	}
	else if(!validateEmail(email))
	{
		$('.email_error').html("The email address does not seem to be valid. Please retype").show(500);
		errors++;
	}
	else
	{
		$('.email_error').html("").hide(200);
	}
	
	
	
	if (errors < 1) {
		// fade in ajax loader while processing update
		$("#edit_user_form").animate({
			opacity: 0.5
		}, 100);
		
		$(".ajax_loader1").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
	
	var data = new Object();
	
	data.title 			= title;
	data.firstname 		= firstName;
	data.surname		= surname;
	data.email			= email;
	data.address1		= address1; 
	data.address2		= address2; 
	data.addressTown	= addressTown; 
	data.county			= county;
	data.postcode		= postcode; 
	data.country		= country;
	data.phone			= phone;
	data.fax			= fax;
	data.organisation	= organisation;
	data.jobtitle		= jobtitle;
	data.userid			= userid;
	data.companyID		= companyid;    
	data.func			= 'updateUser';
	
	var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {data:dataString}, function(data){
			if (data.length > 0) {
				$(".ajax_loader1").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				$("#edit_user_form").animate({
					opacity: 1
				}, 1500);

				//var userObj = eval("(" + data + ")"); 
				eval("var userObj="+data);

				$("select#title option[value=userObj.userTITLE]").attr('selected','selected');
				$(".edit_success").html("Your details have sucsessfully been updated");
				$(".edit_success").fadeIn(1500);
				//$("#updateForm").html(data);
				//$("#forgot_results").fadeIn();
			}
		});
	}
			
}


function changePassword()
{
	var curPassword 	= $("#password").val();
	var newPassword 	= $("#new_password").val();
	var confNewPassword = $("#confirm_new_password").val();
	
	var errors = 0;
	
	if(curPassword == "")
	{
		$('.password_error').html("You must enter a password").show(500);
		errors++;
	}
	else
	{
		$('.password_error').html("").hide(200);
	}
	
	if(newPassword == "")
	{
		$('.new_password_error').html("You must enter a new password").show(500);
		errors++;
	}
	else if(newPassword.length < 4 || newPassword.length > 10)
	{
		$('.new_password_error').html("Your new password must be between 4 and 10 characters").show(500);
		errors++;
	}
	else
	{
		$('.new_password_error').html("").hide(200);
	}
	
	if(newPassword != confNewPassword)
	{
		$('.confirm_new_password_error').html("Password confirmation does not match your new password").show(500);
		errors++;
	}
	else
	{
		$('.confirm_new_password_error').html("").hide(200);
	}
	
	if (errors < 1) {
		// fade in ajax loader while processing update
		$("#change_password_form").animate({
			opacity: 0.5
		}, 100);
		
		$(".ajax_loader2").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		var data = new Object();
		
		data.curPassword = curPassword;
		data.newPassword = newPassword;
		data.func = 'updateUserPassword';
		
		var dataString = $.toJSON(data);
		
		// JUNK START
		
		
		data.alertCurPassword = function(){
			alert(this.curPassword);
		}
		
		data.alertPasswords = function(){
			alert(this.newPassword);
			this.alertCurPassword();
		}
		
		var lib = {
			
			init : function(){
				// do stuff
			} ,
			
			hey : function(){
				//alert('hey');
			}
			
		};
		
		
		var scrollBox = {
			
			init : function(){
				//do stuff
			}
			
		};
		
		
		scrollBox.init();
		lib.init();
		
		
		data.alertPasswords();
		
		
		
		function person(){
			
			this.setName = function( name ){
				this.name = name;
			}
			
			this.sayMyName = function(){
				alert(this.name);
			}
			
		}
		
		var mo = new myObj();
		mo.setName('rich');
		mo.sayMyName();
				
		mo2 =new myObj();
		mo2.setName('dave');
		mo2.sayMyName();
		
		// JUNK END
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajax_loader2").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj=" + data);
				$(".edit_pswd_success").html("Your details have sucsessfully been updated")
				
				$("#change_password_form").animate({
					opacity: 1
				}, 1500);
				
				$(".edit_pswd_success").show(500);
			}
		});
	}	
	
}


function jobUpload()
{
	// get value of search_string input box
	var jobTitle 		= $("input#job_title").val();
	var jobSector 		= $("select#job_sector").val();
	var otherSector		= $("input#other_sector_name").val();
	var jobType 		= $("select#job_type").val();
	var appDeadline 	= $("input#application_deadline").val();
	
	var county 			= $("select#job_location").val();
	var otherCounty 	= $("input#other_job_location").val();
	var area 			= $("input#job_area").val();
	
	var salFrom 		= $("input#salary_from").val();
	var salTo 			= $("input#salary_to").val();
	var freq 			= $("select#salary_freq").val();
	
	var mceContent		= tinyMCE.getContent('job_description');
	$("textarea#job_description").val(mceContent)
	var description 	= $("textarea#job_description").val();
	
	var contantName 	= $("input#contact_name").val();
	var contactEmail 	= $("input#contact_email").val();
	var contactTel		= $("input#contact_tel").val();
	
	var companySelect	= $("select#company_select").val();
	var address1 		= $("input#address1").val();
	var address2 		= $("input#address2").val();
	var address3 		= $("input#address3").val();
	var address4 		= $("input#address4").val();
	var addressTown 	= $("input#town").val();
	var addressCounty 	= $("input#county").val();
	var addressPostcode = $("input#postcode").val();
	var addressCountry 	= $("input#country").val();
	var addressWebsite 	= $("input#companyweb").val();
	var showCompany 	= $("#show_company").val();
	
	
	// validate mandatory fields
	var errors = 0;
	
	// Job Title
	if(jobTitle == "")
	{
		$('.job_title_error').html("You must enter a job title").show(500);
		errors++;
	}
	else
	{
		$('.job_title_error').html("").hide(500);
	}
	
	
	// Job Sector
	if(jobSector == "")
	{
		$('.job_sector_error').html("You must select a job sector").show(500);
		errors++;
	}
	else if(jobSector == 0)
	{
		// other was selected, check that other field was filled in
		if(otherSector == "")
		{
			$(".other_sector_error").html("You must enter a sector for this job").show(500);
			errors++;
		}
	}
	else
	{
		$('.job_sector_error').html("").hide(200);
		$('.other_sector_error').html("").hide(200);
	}
	
	
	// Job Type
	if(jobType == 0)
	{
		$('.job_type_error').html("You must select a job type").show(500);
		errors++;
	}
	else
	{
		$('.job_type_error').html("").hide(200);
	}
	
	// County
	if(county == "")
	{
		$('.job_location_error').html("You must select a county").show(500);
		errors++;
	}
	else if(county == 0)
	{
		// other was selected, check that other field was filled in
		if(otherCounty == "")
		{
			$(".other_job_location_error").html("You must enter a location for this job").show(500);
			errors++;
		}
	}
	else
	{
		$('.job_location_error').html("").hide(200);
		$('.other_job_location_error').html("").hide(200);
	}
	
	
	// Job Area
	if(area == "")
	{
		$('.job_area_error').html("You must enter a job area").show(500);
		errors++;
	}
	else
	{
		$('.job_area_error').html("").hide(500);
	}
	
	// Job Salary from
	if(salFrom == "")
	{
		$('.salary_from_error').html("You must enter a start from salary").show(500);
		errors++;
	}
	else
	{
		$('.salary_from_error').html("").hide(500);
	}
	
	// Job Salary to
	if(salTo == "")
	{
		$('.salary_to_error').html("You must enter a start from salary").show(500);
		errors++;
	}
	else
	{
		$('.salary_to_error').html("").hide(500);
	}
	
	// Job Description
	if(description == "")
	{
		$('.job_description_error').html("You must enter a job description").show(500);
		errors++;
	}
	else
	{
		$('.job_description_error').html("").hide(500);
	}
	
	// Contact Name
	if(contantName == "")
	{
		$('.contact_name_error').html("You must enter a contact name").show(500);
		errors++;
	}
	else
	{
		$('.contact_name_error').html("").hide(500);
	}
	
	// Contact Email
	if(contactEmail != '')
	{
		if (!validateEmail(contactEmail)) {
			$('.contact_email_error').html("The contacts email address does not seem to be valid. Please retype").show(500);
			errors++;
		}
		else {
			$('.contact_email_error').html("").hide(200);
		}
	}
	
	// Company Details
	if(companySelect == "")
	{
		$('.company_select_error').html("You must enter assign this job to a company").show(500);
		errors++;
	}
	else
	{
		$('.company_select_error').html("").hide(500);
	}
	
	if(showCompany == '')
	{
		showCompany = 0;
	}
	
	//alert(errors);
	
	if (errors < 1) 
	{
		// fade in ajax loader while processing update
		$("#jobForm").animate({
			opacity: 0.5
		}, 100);
		
		$("#ajax_loader").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		//alert(county);
		// send data to search function
		var dataString = 	"?jobTitle=" + jobTitle + 
							"&jobSector=" + jobSector + 
							"&jobType="	+ jobType +
							"&otherSector=" + otherSector + 
							"&appDeadline=" + appDeadline + 
							"&location=" + county + 
							"&otherCounty=" + otherCounty + 
							"&area=" + area + 
							"&salFrom=" + salFrom + 
							"&salTo=" + salTo + 
							"&freq=" + freq + 
							"&description=" + description + 
							"&contantName=" + contantName + 
							"&contactEmail=" + contactEmail + 
							"&contactTel=" + contactTel +  
							"&address1=" + address1 + 
							"&address2=" + address2 +  
							"&address3=" + address3 +  
							"&address4=" + address4 +  
							"&town=" + addressTown +   
							"&county=" + addressCounty +  
							"&postcode=" + addressPostcode +  
							"&country=" + addressCountry +  
							"&companyWebsite=" + addressWebsite +  
							"&showCompany=" + showCompany +  
							"&companySelect=" + companySelect +  
							"&function=addJob";
							
		
		$.post('/ajax.php' + dataString, function(data){
			if(data.length > 0)
			{
				$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
				$(".upload_job_result").html(data);
				$(".upload_job_result").fadeIn();
			}
		});
	}

}


function getCompany()
{
 	var companyid = $('#company').val();
	prevCompId = '';
	
	if(companyid == '' || companyid == prevCompId)
		return;
	else
	{
		location = '../edit_company/'+companyid;
	}
		
	prevCompId = companyid;
}

function getUser()
{
 	var userid = $('#user').val();
	prevUserId = '';
	
	if(userid == '' || userid == prevUserId)
		return;
	else
	{
		location = 'http://dev.sbgi.org.uk/edit_user/benchmark_user/'+userid;
	}
		
	prevUserId = userid;
}

function clearPasswordForm()
{
	$('#password').val("");
	$('#new_password').val("");
	$('#confirm_new_password').val("");
}

function showJobForm()
{
	$("#jobForm").fadeIn(500,function(){
		$('.showForm').css({'display' : 'none'});
			$('.hideForm'). css({'display' : 'block'});
	});
	
}
function hideJobForm()
{
	$("#jobForm").fadeOut(500,function(){
		$('.hideForm').css({'display' : 'none'});
			$('.showForm'). css({'display' : 'block'});
	});
}

function checkSector(dom,hidden_div)
{
	var value = $("#"+dom).val();
	
	if(value == "")
	{
		if($("." +hidden_div).hasClass('visible'))
		{
			$('.visible').hide('fast').removeClass('visible');
			return;
		}
	}
	
	
	if(value == 0)
	{
		$("." +hidden_div).show('fast').addClass('visible');
	}
	else
	{
		
		if($("." +hidden_div).hasClass('visible'))
		{
			$('.visible').hide('fast').removeClass('visible');
		}
	}
}

function pageNum(page, string)
{
	alert(page + ' and search string was ' + string);
}

