/**
* @author richardmerchant
*/

// set up global variables
var companyId = "";
var companyCategoryId = "";
var oldSearchString = ""
var addToBasket;
var totalQuantity = 0;
var totalsDelegates = 0;
// phone number validation variables
var digits;
var phoneNumberDelimiters;
var validWorldPhoneChars;
var minDigitsInIPhoneNumber;


$(function() {
	
//	if( -1 != navigator.userAgent.indexOf ("Mozilla") )
		//alert(navigator.userAgent);
	
	if($("#search_results").length == 0){
			$("#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;
		}
		
		// get value of category id
		var targetCatId = $("input#target").val();
		
		// 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;
		}
		
		// get the target site
		var targetSiteId = $("input#site").val();
		
		// more validation
		if(targetSiteId == "" || isNaN(targetSiteId) == 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;
		}
		
		var data = new Object();
		
		data.companyID 		= companyId;
		data.target			= targetCatId;
		data.site 			= targetSiteId;
		data.func 			= 'companyCatergorySearch';
		
		var dataString = $.toJSON(data);
		
		// send data to search function
//		var dataString = "?companyID=" + companyId + "&target=" + targetCatId + "&site=" + targetSiteId + "&function=companyCatergorySearch&";
		$.post('/ajax.php', {data: dataString}, function(data){
			if(data.length > 0)
			{
				$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
				eval("var userObj="+data);
				
				$("#search_results").html(userObj.result);
				$("#search_results").fadeIn(1000);
				
				$("#title").val(userObj.company_name);
				$("#share_heading").text(userObj.company_name);
				$('#share_submit').click(function(){
					share_email(userObj.company_link);
				});
				
			}
		});
    });
	
	$("#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();
		
//		console.log(companyCategoryId);
		
		// 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;
		}
		
		// get the target site
		var targetSiteId = $("input#site").val();
		
		// more validation
		if(targetSiteId == "" || isNaN(targetSiteId) == 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;
		}
		
		// get value of category id
		var targetCatId = $("input#target").val();
		
		// 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 + "&target=" + targetCatId + "&site=" + targetSiteId + "&function=companyCatergorySearch";
		
		var data = new Object();
		
		data.categoryID 	= companyCategoryId;
		data.target			= targetCatId;
		data.site 			= targetSiteId;
		data.func 			= 'companyCatergorySearch';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {data: dataString}, function(data){
			if( typeof data == 'object' )
			{
				$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
				$("#search_results").html(data.result);
				$("#search_results").fadeIn(1000);
				
				// set the values for the share form
			}
		}, "json");
    });
	
	
	if($("#delegate_details").length > 0 )
	{
		$("#addDelegate").click(function(){
			addDelegate();
		});
	}
	
	if ($('#booker_details').length > 0 )
	{
		$("#addBooker").click(function(){
			addBooker();
		});	
		
		$("#updateBooker").click(function(){
			updateBooker();
		});	
		
		$("#cancelUpdate").click(function(){
			cancelUpdate();
		});
	}
	
	
	
	// add fouus and blur to search form
	$('.search').focus(
	function()
	{
		if(this.value == this.defaultValue)
		{
			this.value = '';
		}
		
		if(this.value != this.defaultValue)
		{
			this.select();
		}
	});
	
	$('.search').blur(
	function()
	{
		if($.trim(this.value) == '')
		{
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
	
	// add fouus and blur to login form
	$('#username').focus(
	function()
	{
		if(this.value == this.defaultValue)
		{
			this.value = '';
		}
		
		if(this.value != this.defaultValue)
		{
			this.select();
		}
		
	});
	
	$('#username').blur(
	function()
	{
		if($.trim(this.value) == '')
		{
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
	
	
	
	// init tool tips
	// share form
//	$("#shareForm   :input").tooltip({ 
//	 
//	    // place tooltip on the right edge 
//	    position: "center right", 
//	 
//	    // a little tweaking of the position 
//	    offset: [-2, 10], 
//	 
//	    // use the built-in fadeIn/fadeOut effect 
//	    effect: "fade", 
//	 
//	    // custom opacity setting 
//	    opacity: 0.7, 
//	 
//	    // use this single tooltip element 
//	    tip: '.tooltip' 
//	 
//	});
});

function renewJob( contentId, currentTime )
{
	var appDeadline 	= $("input#application_deadline").val();
	var newDate = '<?php echo strtotime(application_deadline); ?>';
	
	if( application_deadline == '')
	{
		alert('The application deadline is empty. Resubmit with a valid date');
		return;
	}
	else if(currentDate > newDate)
	{
		alert('The new Application deadline seems to be before the current date. Please amend.');
		return;
	}
	else
	{
		//addToBasket(contentId);
	}
}
	
function jobsearch(page, string, option)
{
	var paging = false;
	// get value of search_string input box
	if(!string)
	{
		var searchString = $("input#search_string").val();
	}
	else
	{
		var searchString = string;
		paging = true;
	}
	
	
	// validation process here
	if(searchString == oldSearchString && paging == false)
	{
		return false;
	}
	else if(searchString == '' || searchString == 'Search Jobs')
	{
		$("input#search_string").focus();
		return false;
	}
	else
	{
		// store search string for later use
		oldSearchString = searchString;
	}
	
	// fade out current items
	$("#job_search_results").fadeOut(10, function(){
		$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
	});
	
	if(!page)
	{
		// 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()
{
	$("#reg_results").html("");
	// 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 organisation 	= $("input#organisation").val();
	var tel 			= $("input#tel").val();
//	var mobile			= $("input#mobile").val();
	var verification	= $("input#captcha_code").val();
	//console.info(verification);
	var errors = 0;
	
	// phone number validation variables
	digits = "0123456789"; // Declaring required variables
	phoneNumberDelimiters = "()- "; // non-digit characters which are allowed in phone numbers
	validWorldPhoneChars = phoneNumberDelimiters + "+"; // characters which are allowed in international phone numbers, (a leading + is OK)
	minDigitsInIPhoneNumber = 10; // Minimum no of digits in an international phone no.
	
	
//	if(title == 0 || title == "")
//	{
//		$('.title_errors').html("You must select a title").show(100);
//		errors++;
//	}
//	else
//	{
//		$('.title_errors').html("").hide(100);
//	}
	
	if(firstName == "")
	{
		$('.first_name_error').html("You must enter a first name").show(100);
		errors++;
	}
	else
	{
		$('.first_name_error').html("").hide(100);
	}
	
	if(surname == "")
	{
		$('.surname_error').html("You must enter a surname").show(100);
		errors++;
	}
	else
	{
		$('.surname_error').html("").hide(100);
	}
	
	if(workEmail == "")
	{
		$('.work_email_error').html("You must enter a work email").show(100);
		errors++;
	}
	else if(!validateEmail(workEmail))
	{
		$('.work_email_error').html("The email address does not seem to be valid. Please retype").show(100);
		errors++;
	}
	else
	{
		$('.work_email_error').html("").hide(100);
	}
	
	if(organisation == "")
	{
		$('.organisation_error').html("You must enter an organisation").show(100);
		errors++;
	}
	else
	{
		$('.organisation_error').html("").hide(100);
	}
	
	if( tel == "" )
	{
		
	}
	else
	{
		if( checkInternationalPhone( tel ) == false)
		{
			$('.tel_error').html("The phone number does not seem to be valid. Please retype").show(100);
			errors++;
		}
		else
		{
			$('.tel_error').html("").hide(100);
		}
	}
	
//	if( mobile == "" )
//	{
//		
//	}
//	else
//	{
//		if( checkInternationalPhone( mobile ) == false)
//		{
//			$('.mobile_error').html("The mobile number does not seem to be valid. Please retype").show(100);
//			errors++;
//		}
//		else
//		{
//			$('.mobile_error').html("")
//			.hide(100);
//		}
//	}
	
	if(verification == "")
	{
		$('.captcha_code_error').html('You must fill in the letters in the image above')
		.show(100);
		errors++;
	}
	else
	{
		$('.captcha_code_error').html('')
		.hide();
	}
	
	if(errors < 1)
	{
		$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
		
		sendRegRequestEmail(firstName, surname, workEmail, organisation, tel, verification);
	}
			
}

function nonMemberRegisterRequest()
{
	$("#reg_results").fadeOut();
	// 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 organisation 	= $("input#organisation").val();
	var tel 			= $("input#tel").val();
//	var mobile			= $("input#mobile").val();
	var verification	= $("input#captcha_code").val();
	var errors = 0;
	
	// phone number validation variables
	digits = "0123456789"; // Declaring required variables
	phoneNumberDelimiters = "()- "; // non-digit characters which are allowed in phone numbers
	validWorldPhoneChars = phoneNumberDelimiters + "+"; // characters which are allowed in international phone numbers, (a leading + is OK)
	minDigitsInIPhoneNumber = 10; // Minimum no of digits in an international phone no.
	
	
//	if(title == 0 || title == "")
//	{
//		$('.title_errors').html("You must select a title").show(100);
//		errors++;
//		
//	}
//	else
//	{
//		$('.title_errors').html("").hide(100);
//	}
	
	if(firstName == "")
	{
		$('.first_name_error').html("You must enter a first name").show(100);
		errors++;
	}
	else
	{
		$('.first_name_error').html("").hide(100);
	}
	
	if(surname == "")
	{
		$('.surname_error').html("You must enter a surname").show(100);
		errors++;
	}
	else
	{
		$('.surname_error').html("").hide(100);
	}
	
	if(workEmail == "")
	{
		$('.work_email_error').html("You must enter a work email").show(100);
		errors++;
	}
	else if(!validateEmail(workEmail))
	{
		$('.work_email_error').html("The email address does not seem to be valid. Please retype").show(100);
		errors++;
	}
	else
	{
		$('.work_email_error').html("").hide(100);
	}
	
//	if(organisation == "")
//	{
//		$('.organisation_error').html("You must enter an organisation").show(100);
//		errors++;
//	}
//	else
//	{
//		$('.organisation_error').html("").hide(100);
//	}
	
	if( tel == "" )
	{
		
	}
	else
	{
		if( checkInternationalPhone( tel ) == false)
		{
			$('.tel_error').html("The phone number does not seem to be valid. Please retype").show(100);
			errors++;
		}
		else
		{
			$('.tel_error').html("").hide(100);
		}
	}
	
//	if( mobile == "" )
//	{
//		
//	}
//	else
//	{
//		if( checkInternationalPhone( mobile ) == false)
//		{
//			$('.mobile_error').html("The mobile number does not seem to be valid. Please retype").show(100);
//			errors++;
//		}
//		else
//		{
//			$('.mobile_error').html("")
//			.hide(100);
//		}
//	}
	
	if(verification == "")
	{
		$('.captcha_code_error').html('You must fill in the letters in the image above')
		.show(100);
		errors++;
	}
	else
	{
		$('.captcha_code_error').html('')
		.hide();
	}
	
	if(errors < 1)
	{
		$("#ajax_loader").css({'visibility' : 'visible', 'display' : 'block'});
		sendNonMemberRegRequest(firstName, surname, workEmail, tel, verification);
	}
			
}

function sendRegRequestEmail(firstName, surname, workEmail, organisation, tel, verification)
{
	var data = {};
	
//	data.title 			= title;
	data.firstname 		= firstName;
	data.surname		= surname;
	data.workEmail		= workEmail;
	data.organisation	= organisation; 
	data.phone			= tel; 
//	data.mobile			= mobile; 
	data.verification	= verification;
	data.func			= 'registerRequest';
	
	var dataString = $.toJSON(data);
	
	$.post('/ajax.php', {data:dataString}, function(data){
		
		if (data.length > 0) {
			$("#ajax_loader").css({
				'visibility': 'hidden',
				'display': 'none'
			});
			
			eval("var userObj="+data);

			if(userObj.status.user == true)
			{
				$("#reg_results").html('<p class="strong">' + userObj.user + '</p>');
				
				var src = $('#captcha_image').attr('src');
					
				$('#captcha_image').attr('src', 'http://' + document.domain + '/securimage/securimage_show.php?sid=' + Math.random()); 
//					html = html + '<p>Organisation: ' + userObj.error.verification + '</p>';
				
				$("input#captcha_code").val("");
					
			}
			else if(userObj.status.error == true)
			{
				var html;
				
//				if(userObj.error.title.length > 0)			
//				{
////					html = html + '<p>Title: ' + userObj.error.title + '</p>';
//					$('.title_errors').html(userObj.error.title).show(100);
//				}
				
				if(userObj.error.firstname.length > 0)		
				{
//					html = html + '<p>First Name: ' + userObj.error.firstname + '</p>';
					$('.first_name_error').html(userObj.error.firstname).show(100);
				}
				
				if(userObj.error.surname.length > 0)		
				{
//					html = html + '<p>Surname: ' + userObj.error.surname + '</p>';
					$('.surname_error').html(userObj.error.surname).show(100);
				}
				
				if(userObj.error.organisation.length > 0)	
				{
//					html = html + '<p>Organisation: ' + userObj.error.organisation + '</p>';
					$('.organisation_error').html(userObj.error.organisation).show(100);
				}
				
				if(userObj.error.verification.length > 0)	
				{
//					html = html + '<p>Organisation: ' + userObj.error.verification + '</p>';
					
					$('.captcha_code_error').html(userObj.error.verification).show(100);	
					
								
				}
				
				var src = $('#captcha_image').attr('src');
				$('#captcha_image').attr('src', 'http://' + document.domain + '/securimage/securimage_show.php?sid=' + Math.random()); 
				$("input#captcha_code").val("");
				
				$("#reg_results").html(html);
			}
			else
			{
				var html;
				html = userObj.message;
				$("#reg_results").html(html);	
			}

//			$("#reg_results").show();
		}
	});
}

function sendNonMemberRegRequest( firstName, surname, workEmail, tel, verification)
{
	var data = {};
	
//	data.title 			= title;
	data.firstname 		= firstName;
	data.surname		= surname;
	data.workEmail		= workEmail;
	//data.organisation	= organisation; 
	data.phone			= tel; 
//	data.mobile			= mobile; 
	
	data.verification	= verification;
	data.func			= 'nonMemberRegisterRequest';
	
	var dataString = $.toJSON(data);
	
	$.post('/ajax.php', {data:dataString}, function(data){
		
		if (data.length > 0) {
			$("#ajax_loader").css({
				'visibility': 'hidden',
				'display': 'none'
			});
			
			eval("var userObj="+data);

			if(userObj.status.user == true)
			{
				$("#reg_results").html('<p class="strong">' + userObj.user + '</p>');
			}
			else if(userObj.status.error == true)
			{
				var html;
				
//				if(userObj.error.title.length > 0)			
//				{
////					html = html + '<p>Title: ' + userObj.error.title + '</p>';
//					$('.title_errors').html(userObj.error.title).show(100);
//				}
				
				if(userObj.error.firstname.length > 0)		
				{
//					html = html + '<p>First Name: ' + userObj.error.firstname + '</p>';
					$('.first_name_error').html(userObj.error.firstname).show(100);
				}
				
				if(userObj.error.surname.length > 0)		
				{
//					html = html + '<p>Surname: ' + userObj.error.surname + '</p>';
					$('.surname_error').html(userObj.error.surname).show(100);
				}
				
//				if(userObj.error.organisation.length > 0)	
//				{
////					html = html + '<p>Organisation: ' + userObj.error.organisation + '</p>';
//					$('.organisation_error').html(userObj.error.organisation).show(100);
//				}
				
				if(userObj.error.verification.length > 0)	
				{
					var src = $('#captcha_image').attr('src');
					
					$('#captcha_image').attr('src', 'http://' + document.domain + '/securimage/securimage_show.php?sid=' + Math.random()); 
//					html = html + '<p>Organisation: ' + userObj.error.verification + '</p>';
					//console.info(userObj.error.verification);
					
					$('.captcha_code_error').html(userObj.error.verification).show(100);				
				}
				
				$("#reg_results").html(html);
			}
			else
			{
				var html;
				html = userObj.message;
				$("#reg_results").html(html);	
			}
			
			$("#reg_results").fadeIn();
		}
	});
}

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);
}

// phone number functions
function checkInternationalPhone(strPhone){
	
	var bracket = 3;
	strPhone = trim(strPhone);
	
	
	if(strPhone.indexOf("+")>1) 
		return false;
	
	if(strPhone.indexOf("-")!=-1)
		bracket=bracket+1;
		
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)
		return false;
	
	var brchr=strPhone.indexOf("(");
	
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")
		return false;
		
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)
		return false; 
		
	var s = stripCharsInBag(strPhone, validWorldPhoneChars);
	
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function trim(s)
{   
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) 
			return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{     
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
 
// end phone number functions
 


function requestForgottenDetails()
{
	$("#forgot_results").hide();
	
	var username = $("input#username").val();
	
	var errors = 0;
	
	if(username == "")
	{
		$('.username_error').html("You must enter a username").show(500);
		errors++;
		
	}
	else if(!validateEmail(username))
	{
		$('.username_error').html("The email address enetered does not seem to be valid. Please check and re-enter.").show(500);
		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 data = {};
		data.username = username;
		data.func = 'forgottenPassword';
		
		var dataString = $.toJSON(data);
		
//		var dataString = "?username=" + username + "&function=forgottenPassword";
		$.post('/ajax.php', {data:dataString}, function(data){
			$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
			
			if(data['message'].length > 0)
				$("#forgot_results").html(data['message']);
			else if(data['userError'].length > 0)
				$("#forgot_results").html(data['userError']);
			else
				$("#forgot_results").html(data['emailError']);
				
			$("#forgot_results").fadeIn();
		},'json');
		
	}
	
}

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 = $("input#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("Sucsessfully updated");
				$(".edit_success").fadeIn(1500);
				//$("#updateForm").html(data);
				//$("#forgot_results").fadeIn();
			}
		});
	}
			
}

function createUser()
{
	$(".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 group = $("select#group").val();
	var jobtitle = $("input#jobtitle").val();
	var password = $("input#password").val();
	var conf_password = $("input#conf_password").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(password == "")
	{
		$('.password_error').html("You must enter a password").show(500);
		$('.conf_password_error').html("").hide(200);
		errors++;
	}
	else if(password.length < 4 || password.length > 10)
	{
		$('.password_error').html("The password must be between 4 and 10 characters").show(500);
		$('.conf_password_error').html("").hide(200);
		errors++;
	}
	else if(password != conf_password)
	{
		$('.password_error').html("").hide(200);
		$('.conf_password_error').html("Your passwords do not match").show(500);
		errors++;
	}
	else
	{
		$('.password_error').html("").hide(200);
		$('.conf_password_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'
		});
		
	return;
	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.group			= group;
	data.jobtitle		= jobtitle;
	data.password		= password;
	data.func			= 'createUser';
	
	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);
				var url = userObj.url;
				gotToLocation(url);
			}
		});
	}
			
}

function changePassword()
{
	var curPassword 	= $("#cur_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);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajax_loader2").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj=" + data);

				if( userObj.error == true )
				{
					$(".password_error").html( userObj.message ).show(500);
				}
				else
				{
					$(".password_error").html("").show(500);
					$(".edit_pswd_success").html( userObj.message ).show(500);
				}
				
				$("#change_password_form").animate({
					opacity: 1
				}, 1500);
			}
		});
	}	
	
}

function deleteUserDetails(url)
{
	$(".edit_success").fadeOut(100);
	
	// get user conformation
	var confirmDelete = confirm("Are you sure you want to delete this user?");
	
	if(confirmDelete)
	{
		var userid = $("input#userid1").val();
		
		// 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.userid			= userid;
		data.func			= 'deleteUser';
		
		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);
	
				gotToLocation(url);
			}
		});
	}
	else
	{
		return;
	}
}

function jobUpload( bool )
{
	// validate mandatory fields
	var errors = 0;
	
	addToBasket = bool;
	
	//	check addToBasket is valid
	if(addToBasket == false){}
		
	else if(addToBasket == true){}
		
	else{
		$('.submitButtons')
		.html('<input name="submitJob" id="saveJob" value="Save Job" type="submit" onclick="jobUpload(false); return false;"  /><input name="submitJob" id="submitJob" value="Save and add to Basket" type="submit" onclick="jobUpload(true); return false;"  />');
		alert("There seems to be an error on the page. Please resubmit the form");
		errors++;
	}
		

	// get value from job uplaod form
	
	// gerneral tab
	var jobTitle 		= $("input#job_title").val();
	var jobRef 			= $("input#job_ref").val();
	
	// description tab
	var mceContent		= tinyMCE.getContent('job_description');
	var description 	= mceContent;
	var excerpt 		= $("textarea#job_excerpt").val();
	var mceContent2 	= tinyMCE.getContent('job_apply');
	var howToApply		= mceContent2;
	
	// skills tab
	var reguiredSkills 	= $("textarea#required_skills").val();
	var desiredSkills 	= $("textarea#desired_skills").val();
	
	// qulicication tab
	var qualifications 	= $("textarea#qualifications").val();
	var workExperience 	= $("textarea#work_experience").val();
	
	
	// salary/benefits tab
	var salary 			= $("input#salary").val();
	var freq 			= $("select#salary_freq").val();
	var benefits 		= $("textarea#benefits").val();
	
	var contactName 	= $("input#contact_name").val();
	var contactEmail 	= $("input#contact_email").val();
	var contactTel		= $("input#contact_tel").val();
	
	var companyName		= $("input#company_name").val();
	var address_line1 	= $("input#address_line1").val();
	var address_line2 	= $("input#address_line2").val();
	var town 			= $("input#town").val();
	var county 			= $("input#county").val();
	var postcode 		= $("input#postcode").val();
	var country 		= $("input#country").val();
	
	// advanced tab
	var jobCounty 		= $("select#job_location").val();
	var otherCounty 	= $("input#other_job_location").val();
	var area 			= $("input#job_area").val();
	var jobType 		= $("select#job_type").val();
	var appDeadline 	= $("input#application_deadline").val();
	var appStartDate	= $("input#start_date").val();
	
	/**
	 * Validate input
	 * return errors in each tab
	 * highlight the tabs with errors
	 */
	

	// GENERAL TAB
	
	// Job Title
	if(jobTitle == "")
	{
		$("#generalTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.job_title_error').html("You must enter a job title").show();
		++errors;
	}
	else
	{
		$("#generalTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.job_title_error').html("").hide();
	}
	
	// DESCRIPTION TAB
	// Job Description
	if(description == "")
	{
		$("#descriptionTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.job_description_error').html("You must enter a job description").show(500);
		++errors;
	}
	else
	{
		$("#descriptionTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.job_description_error').html("").hide(500);
	}

	// application deadline
	if(appDeadline == "")
	{
		$("#advancedTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.application_deadline_error').html("You must enter an application deadline").show();
		++errors;
	}
	else
	{
		$("#advancedTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.application_deadline_error').html("").hide(200);
	}
	
	// contact email
	if (contactEmail == "") {
		
		$("#contactTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.contact_email_error').html("You must supply a contact email address").show();
		++errors;
	}
	else {
	
		if( ! validateEmail( contactEmail ) )
		{
			$("#contactTab > a").css({
				borderLeft: '1px solid #ff1111',
				borderTop: '1px solid #ff1111',
				borderRight: '1px solid #ff1111'
			});
			
			$('.contact_name_error').html("You must enter a valid email").show();
			++errors;
		}
		else
		{
			$("#contactTab > a").css({
				borderLeft: '1px solid #666',
				borderTop: '1px solid #666',
				borderRight: '1px solid #666'
			});
			
			$('.contact_name_error').html("").hide(200);
		}
	}
	
	if(errors > 0)
	{
		$('.formError').text("There are errors on this form. Please select the tab with the red border. Thank you.").show(500);
		return false;
	}
	else
	{
		$('.formError').text("").hide(500);
		$("#jobForm").animate({
			opacity: 0.5
		}, 100);
		
		$("#ajax_loader").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		var data = new Object();
		
		data.jobtitle 		= jobTitle;
		data.jobref			= jobRef;
		data.description 	= description;
		data.excerpt		= excerpt;
		data.howToApply		= howToApply;
		data.reguiredSkills	= reguiredSkills;
		data.desiredSkills	= desiredSkills;
		data.qualifications	= qualifications;
		data.workExperience	= workExperience;
		data.salary			= salary;
		data.salaryFreq		= freq;
		data.benefits		= benefits;
		data.contactName	= contactName;
		data.contactEmail	= contactEmail;
		data.contactTel		= contactTel;
		data.companyName	= companyName;
		data.address1		= address_line1;
		data.address2		= address_line2;
		data.addressTown	= town;
		data.county			= county;
		data.postcode		= postcode;
		data.country		= country;
		data.jobCounty		= jobCounty;
		data.otherCounty	= otherCounty;
		data.area			= area;
		data.jobType		= jobType;
		data.appDeadline	= appDeadline;
		data.appStartDate	= appStartDate;
		data.addToBasket	= addToBasket;
		data.func 		= 'addJob';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$("#ajax_loader").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj="+data);

				if(userObj.status.user_error == true)
				{
					$(".upload_job_result").html('<p class="strong">' + userObj.user + '</p>');
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
				}
				else if(userObj.status.error == true)
				{
					var html;
					if(userObj.message.length > 0)						{html = html + '<p>Message: ' + userObj.message + '</p>';}
					if(userObj.error.job_title.length > 0)				{html = html + '<p>Job Title: ' + userObj.error.job_title + '</p>';}
					if(userObj.error.job_description.length > 0)		{html = html + '<p>Job Description: ' + userObj.error.job_description + '</p>';}
					if(userObj.error.application_deadline.length > 0)	{html = html + '<p>Application Deadline: ' + userObj.error.application_deadline + '</p>';}
					if(userObj.error.other_job_county.length > 0)		{html = html + '<p>Other Job County: ' + userObj.error.other_job_county + '</p>';}
					if(userObj.error.email.length > 0)					{html = html + '<p>Email: ' + userObj.error.email + '</p>';}
					
					$(".upload_job_result").html(html);
					
					$("#success")
						.html(html)
						.fadeIn(500);
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
				}
				else
				{
//					var html;
//					html = userObj.message;
//					
//					$(".formContainer").hide(1000, function(){
//						$("#success")
//						.html(html)
//						.fadeIn(500, function(){
//							getMiniBasket();
//						});
//					});

					var url;
					url = userObj.url;
					gotToLocation(url);
				}
			}
		});
		
	}

}

function jobEdit(param)
{
	$('.formError').text("").hide(500);
	$(".upload_job_result").text("").hide(500);
	
	$("#success")
		.html("")
		.fadeOut(500);
					
	if(isNaN(param))
	{
		alert('The content id seems to be invalid. Please refresh and try again');
		return;
	}
	var contentId = param;
	
	// get value from job uplaod form
	
	// gerneral tab
	var jobTitle 		= $("input#job_title").val();
	var jobRef 			= $("input#job_ref").val();
	
	// description tab
	var mceContent		= tinyMCE.getContent('job_description');
	//$("textarea#job_description").val(mceContent)
	var description 	= mceContent;
	var excerpt 		= $("textarea#job_excerpt").val();
	var mceContent2 	= tinyMCE.getContent('job_apply');
	var howToApply		= mceContent2;
	
	// skills tab
	var reguiredSkills 	= $("textarea#required_skills").val();
	var desiredSkills 	= $("textarea#desired_skills").val();
	
	// qulicication tab
	var qualifications 	= $("textarea#qualifications").val();
	var workExperience 	= $("textarea#work_experience").val();
	
	
	// salary/benefits tab
	var salary 			= $("input#salary").val();
//	var salTo 			= $("input#salary_to").val();
	var freq 			= $("select#salary_freq").val();
	var benefits 		= $("textarea#benefits").val();
	
	// contact tab
//	var companyInfo		= $("checkbox#company_info").val();
//	var contactInfo		= $("checkbox#contact_info").val();
	
	var contactName 	= $("input#contact_name").val();
	var contactEmail 	= $("input#contact_email").val();
	var contactTel		= $("input#contact_tel").val();
	
	var companyName		= $("input#company_name").val();
	var address_line1 	= $("input#address_line1").val();
	var address_line2 	= $("input#address_line2").val();
	var town 			= $("input#town").val();
	var county 			= $("input#county").val();
	var postcode 		= $("input#postcode").val();
	var country 		= $("input#country").val();
	
	// advanced tab
	var jobCounty 		= $("select#job_location").val();
	var otherCounty 	= $("input#other_job_location").val();
	var area 			= $("input#job_area").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 appStartDate	= $("input#start_date").val();
	
	/**
	 * Validate input
	 * return errors in each tab
	 * highlight the tabs with errors
	 */
	
	// validate mandatory fields
	var errors = 0;
	
	
	// GENERAL TAB
	
	// Job Title
	if(jobTitle == "")
	{
		$("#generalTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.job_title_error').html("You must enter a job title").show();
		++errors;
	}
	else
	{
		$("#generalTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.job_title_error').html("").hide();
	}
	
	
	// DESCRIPTION TAB
	// Job Description
	if(description == "")
	{
		$("#descriptionTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.job_description_error').html("You must enter a job description").show(500);
		++errors;
	}
	else
	{
		$("#descriptionTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.job_description_error').html("").hide(500);
	}
	
	// contact email address
	if (contactEmail == "") {
		
		$("#contactTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.contact_email_error').html("You must supply a contact email address").show();
		++errors;
	}
	else {
	
		if( ! validateEmail( contactEmail ) )
		{
			$("#contactTab > a").css({
				borderLeft: '1px solid #ff1111',
				borderTop: '1px solid #ff1111',
				borderRight: '1px solid #ff1111'
			});
			
			$('.contact_name_error').html("You must enter a valid email").show();
			++errors;
		}
		else
		{
			$("#contactTab > a").css({
				borderLeft: '1px solid #666',
				borderTop: '1px solid #666',
				borderRight: '1px solid #666'
			});
			
			$('.contact_name_error').html("").hide(200);
		}
	}
	
	if(errors > 0)
	{
		$('.formError').text("There is and error on the form. Please select the tab with the red border. Thank you.").show(500);
		return;
	}
	else
	{
		$('.formError').text("").hide(500);
		
		$("#jobForm").animate({
			opacity: 0.5
		}, 100);
		
		$("#ajax_loader").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		var data = new Object();
		
		data.jobtitle 		= jobTitle;
		data.jobref			= jobRef;
		data.description 	= description;
		data.excerpt		= excerpt;
		data.howToApply		= howToApply;
		data.reguiredSkills	= reguiredSkills;
		data.desiredSkills	= desiredSkills;
		data.qualifications	= qualifications;
		data.workExperience	= workExperience;
		data.salary			= salary
//		data.salaryTo		= salTo;
		data.salaryFreq		= freq;
		data.benefits		= benefits;
		data.contactName	= contactName;
		data.contactEmail	= contactEmail;
		data.contactTel		= contactTel;
		data.companyName	= companyName;
		data.address1		= address_line1;
		data.address2		= address_line2;
		data.addressTown	= town;
		data.county			= county;
		data.postcode		= postcode;
		data.country		= country;
		data.jobCounty		= jobCounty;
		data.otherCounty	= otherCounty;
		data.area			= area;
//		data.jobSector		= jobSector;
//		data.otherSector	= otherSector;
		data.jobType		= jobType;
		data.appDeadline	= appDeadline;
		data.appStartDate	= appStartDate;
		data.contentId		= contentId;
		data.func 		= 'editJob';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$("#ajax_loader").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj="+data);
				
				if(userObj.status.user == true)
				{
					$(".upload_job_result").html('<p class="strong">' + userObj.user + '</p>');
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
				}
				else if(userObj.status.error == true)
				{
					var html;
					if(userObj.error.job_title.length > 0)				{html = html + '<p>Job Title: ' + userObj.error.job_title + '</p>';}
					if(userObj.error.email.length > 0)					{html = html + '<p>Contact Email: ' + userObj.error.email + '</p>';}
					if(userObj.error.job_description.length > 0)		{html = html + '<p>Job Description: ' + userObj.error.job_description + '</p>';}
					if(userObj.error.application_deadline.length > 0)	{html = html + '<p>Organisation: ' + userObj.error.application_deadline + '</p>';}
					if(userObj.error.other_job_county.length > 0)		{html = html + '<p>Other Job County: ' + userObj.error.other_job_county + '</p>';}
					if(userObj.error.permissions.length > 0)			{html = html + '<p>Permissions: ' + userObj.error.permissions + '</p>';}
					
					$(".upload_job_result").html(html);
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
				}
				else{
					var html;
					html = userObj.message;
					//html = html + userObj.form;
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
					
					$("#success")
					.html(html)
					.fadeIn(500);
				}
			}
		});
		
	}
}

function createJob()
{
	var html;
	var url;
	
	$(".upload_job_result").html('');
	
	// validate mandatory fields
	var errors = 0;
	
	// get value from job uplaod form
	
	// gerneral tab
	var jobTitle 		= $("input#job_title").val();
	var jobRef 			= $("input#job_ref").val();
	
	// description tab
	var mceContent		= tinyMCE.getContent('job_description');
	var description 	= mceContent;
	var excerpt 		= $("textarea#job_excerpt").val();
	var mceContent2 	= tinyMCE.getContent('job_apply');
	var howToApply		= mceContent2;
	
	// skills tab
	var reguiredSkills 	= $("textarea#required_skills").val();
	var desiredSkills 	= $("textarea#desired_skills").val();
	
	// qulicication tab
	var qualifications 	= $("textarea#qualifications").val();
	var workExperience 	= $("textarea#work_experience").val();
	
	
	// salary/benefits tab
	var salary 			= $("input#salary").val();
	var freq 			= $("select#salary_freq").val();
	var benefits 		= $("textarea#benefits").val();
	
	var contactName 	= $("input#contact_name").val();
	var contactEmail 	= $("input#contact_email").val();
	var contactTel		= $("input#contact_tel").val();
	
	var companyName		= $("input#company_name").val();
	var address_line1 	= $("input#address_line1").val();
	var address_line2 	= $("input#address_line2").val();
	var town 			= $("input#town").val();
	var county 			= $("input#county").val();
	var postcode 		= $("input#postcode").val();
	var country 		= $("input#country").val();
	
	// advanced tab
	var jobCounty 		= $("select#job_location").val();
	var otherCounty 	= $("input#other_job_location").val();
	var area 			= $("input#job_area").val();
	var jobType 		= $("select#job_type").val();
	var appDeadline 	= $("input#application_deadline").val();
	var appStartDate	= $("input#start_date").val();
	
	/*
	 * Validate input
	 * return errors in each tab
	 * highlight the tabs with errors
	 */
	

	// GENERAL TAB
	
	// Job Title
	if(jobTitle == "")
	{
		$("#generalTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.job_title_error').html("You must enter a job title").show();
		++errors;
	}
	else
	{
		$("#generalTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.job_title_error').html("").hide();
	}
	
	// DESCRIPTION TAB
	// Job Description
	if(description == "")
	{
		$("#descriptionTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.job_description_error').html("You must enter a job description").show(500);
		++errors;
	}
	else
	{
		$("#descriptionTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.job_description_error').html("").hide(500);
	}

	
	// application deadline
	if(appDeadline == "")
	{
		$("#advancedTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.application_deadline_error').html("You must enter an application deadline").show();
		++errors;
	}
	else
	{
		$("#advancedTab > a").css({
			borderLeft: '1px solid #666',
			borderTop: '1px solid #666',
			borderRight: '1px solid #666'
		});
		
		$('.application_deadline_error').html("").hide(200);
	}
	
	
	// contact email address
	if (contactEmail == "") {
		
		$("#contactTab > a").css({
			borderLeft: '1px solid #ff1111',
			borderTop: '1px solid #ff1111',
			borderRight: '1px solid #ff1111'
		});
		
		$('.contact_email_error').html("You must supply a contact email address").show();
		++errors;
	}
	else {
	
		if( ! validateEmail( contactEmail ) )
		{
			$("#contactTab > a").css({
				borderLeft: '1px solid #ff1111',
				borderTop: '1px solid #ff1111',
				borderRight: '1px solid #ff1111'
			});
			
			$('.contact_name_error').html("You must enter a valid email").show();
			++errors;
		}
		else
		{
			$("#contactTab > a").css({
				borderLeft: '1px solid #666',
				borderTop: '1px solid #666',
				borderRight: '1px solid #666'
			});
			
			$('.contact_name_error').html("").hide(200);
		}
	}
	
	if(errors > 0)
	{
		$('.formError').text("There is an error on the form. Please select the tab with the red border to view the errors. Thank you.").show(500);
		return false;
	}
	else
	{
		$('.formError').text("").hide(500);
		$("#jobForm").animate({
			opacity: 0.5
		}, 100);
		
		$("#ajax_loader").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		var data = new Object();
		
		data.jobtitle 		= jobTitle;
		data.jobref			= jobRef;
		data.description 	= description;
		data.excerpt		= excerpt;
		data.howToApply		= howToApply;
		data.reguiredSkills	= reguiredSkills;
		data.desiredSkills	= desiredSkills;
		data.qualifications	= qualifications;
		data.workExperience	= workExperience;
		data.salary			= salary;
		data.salaryFreq		= freq;
		data.benefits		= benefits;
		data.contactName	= contactName;
		data.contactEmail	= contactEmail;
		data.contactTel		= contactTel;
		data.companyName	= companyName;
		data.address1		= address_line1;
		data.address2		= address_line2;
		data.addressTown	= town;
		data.county			= county;
		data.postcode		= postcode;
		data.country		= country;
		data.jobCounty		= jobCounty;
		data.otherCounty	= otherCounty;
		data.area			= area;
		data.jobType		= jobType;
		data.appDeadline	= appDeadline;
		data.appStartDate	= appStartDate;
		data.func 		= 'createJob';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$("#ajax_loader").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj="+data);
			
				if(userObj.status.user == true)
				{
					$(".upload_job_result").html('<p class="strong">' + userObj.user + '</p>');
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
				}
				else if(userObj.status.error == true)
				{
					if (html == undefined) {
					  alert('a is undefined');
					}

					if(userObj.error.job_title.length > 0)				{html = html + '<p>Job Title: ' + userObj.error.job_title + '</p>';}
					if(userObj.error.email.length > 0)					{html = html + '<p>Contact Email: ' + userObj.error.email + '</p>';}
					if(userObj.error.job_description.length > 0)		{html = html + '<p>Job Description: ' + userObj.error.job_description + '</p>';}
					if(userObj.error.application_deadline.length > 0)	{html = html + '<p>Organisation: ' + userObj.error.application_deadline + '</p>';}
					if(userObj.error.other_job_county.length > 0)		{html = html + '<p>Other Job County: ' + userObj.error.other_job_county + '</p>';}
					if(userObj.error.permissions.length > 0)			{html = html + '<p>Permissions: ' + userObj.error.permissions + '</p>';}
					
					$(".upload_job_result").html(html);
					
					$("#jobForm").animate({
						opacity: 1
					}, 1500);
				}
				else{
					// go to listing with sucsessfull upload message
					url = userObj.url;
					gotToLocation(url);
					
//					
//					$(".formContainer").hide(1000, function(){
//						$("#success")
//						.html(html);
//					});
				}
			}
		});
		
	}

}

function listContent( contentId, bool ) 
{
	$('#' + contentId + '_info').text('');
	
	var data = new Object();
	data.contentId	=	contentId;
	data.bool		=	bool;
	data.func		=	'listContent';
	
	var dataString	=	$.toJSON(data);
	$.post('/ajax.php', {data:dataString}, function(data){
		if ( data.length > 0 ) {
			
			eval("var userObj="+data);
			
			if(userObj.status.error == true)
			{
				$('#' + contentId + '_info').text(userObj.message);
			}
			else
			{
				if(userObj.button.length > 0)
					$('#' + contentId + '_job #list_job_button a button').text(userObj.button);
				else
					$('#' + contentId + '_job #list_job_button a button').remove();
				
				
				$('#' + contentId + '_info').text(userObj.message);
				
//				var t = setTimeout(function(){
//						$('#' + contentId + '_info').text('');
//					},5000);
			}
		}
	});
	
}

function getMiniBasket()
{
	
	var ajaxLoader = '<span class="db marginAuto" id="" style="margin:0 0 0 75px; z-index:1000; visibility:visible; display:block;"><img alt="ajax loader" src="/assets/images/shared/ajax-loader.gif" /></span>';
	
	$('#mini_basket > tbody').html(ajaxLoader);
	
	var data = new Object();
	data.func 		= 'getMiniBasket';
	var dataString = $.toJSON(data);
	
	// get the current basket
	$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajax_loader").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj=" + data);
				var html = userObj.basket;
				
				//if(userObj.z)
				$("#mini_basket > tbody").html(html);
				$("#mini_basket > tfoot #subtotal").append(userObj.total);
				//$("#mini_basket").fadeIn('fast');
			}
		});
	
}

function addToBasket( contentId, categoryId )
{
	if( ( contentId == "" || isNaN( contentId ) ) || ( categoryId == '' || isNaN( categoryId ) ) ) 
	{
		alert("There is a problem with this page. Please refresh to correct the problem");
		return;
	}
	else
	{
		$(".ajax_loader2").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		var data = new Object();
	
		data.contentId = contentId;
		data.categoryID = categoryId;
		data.func = 'addToBasket';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajax_loader2").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				eval("var userObj=" + data);
				
				if(userObj.status.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".upload_job_result").html(html);
					$('#' + contentId + '_info').text(html);
				}
				else
				{
					var html;
					html = userObj.message;
					
					$(".upload_job_result").html('');
					$('#' + contentId + '_info').text(html);
					$('#' + contentId + '_job .buttons #purchase_job_button').remove();
					
					$("#success")
					.html(html)
					.fadeIn(500);
					
					getMiniBasket();
				}
			}
		});
	}
}

function addEventOrder( contentId )
{
	var ProductOpt = new Array();
	
	$(".ajaxLoader").css({
			'visibility': 'visible'
		});
		
	var contentId 	= parseFloat($("input#basketcontent").val()); 
	var productId 	= parseFloat($("input#basketproduct").val());
//	var productOpt 	= parseFloat($("select.productOptions").val());
	var quantity 	= parseFloat($("select#quantity").val());
	
//	$('.product_option select.productOptions').each(function(index, i){
$('.product_option select.productOptions, .product_option input.productOptions').each(function(index, i){
//		if($(this).val() != 0)
		ProductOpt[index] = parseInt($(this).val());
	});
	
	var productOpt 	= ProductOpt[0];
	
	if(ProductOpt.length > 1 )
		var productLocation = ProductOpt[1];
	else
		var productLocation = 0;
	
//	if( ProductOpt[1].length > 0 )
//		alert(ProductOpt[1]);
	

	// check if the selected order is the same as the current order// check if the selected order is the same as the current order
	var newOrder = true;
	$('.productDetails .product_optid').each(function(){
		var curOptId = parseInt($(this).val());
		
		if( productOpt == curOptId )
			newOrder = false;
	});
	
	
	if(newOrder)
	{
		// do minimal check to ensure server load is not to heavy
		var eventQuantity = 0;
		$('.productDetails .product_quantity').each(function(){
			eventQuantity = eventQuantity + parseInt($(this).val());
		});	
		
		var delegates = $('#delegate_list_table tbody tr .delegateDetails').length;
		
		if( delegates < eventQuantity )
		{
			$('.message').html('Please supply delegates for the current event order before add another event booking. Thanks you').addClass('red').show(500);
			// reset form
			$('#productForm')[0].reset(); 
			// show add delegate form
			$('#addEvent').attr('disabled','disabled');
			
			$(".ajaxLoader").css({
				'visibility': 'hidden'
			});
		
			setTimeout(function(){
					$('.message').fadeOut('slow',function(){
						$('.message').text('');
						$('.message').removeClass('red');
					});
				},5000);
			return;
		}
		else
			$('.message').html('').hide(500);
	}
	
//	var contentId 	= parseFloat($("input#basketcontent").val()); 
//	var productId 	= parseFloat($("input#basketproduct").val());
//	var productOpt 	= parseFloat($("select.productOptions").val());
//	var quantity 	= parseFloat($("select#quantity").val());
	
	var origVat 		= parseFloat($('input#vat').val());
	var origTotal 		= parseFloat($('input#tot').val());
	var origTotalIncldVat 	= parseFloat($('input#totIncldVat').val());
	
	var errors = 0;
	
	if( contentId == "" || isNaN( contentId ) )
	{
		alert("There is a problem with this page. Please refresh to correct the problem");
		 errors++
	}
	
	if( quantity == "" || quantity == "0" || isNaN( quantity ) )
	{
		alert("The quantity must be 1 or more");
		errors++
	}
	
	if(errors > 0)
	{
		$(".ajaxLoader").css({
			'visibility': 'hidden'
		});
		
		return;
	}
	else
	{
		var data = new Object();
	
		data.contentId 			= contentId;
		data.quantity  			= quantity;
		data.productId 			= productId;
		data.productOpt 		= productOpt;
		data.productLocation 	= productLocation
		data.origVat			= origVat;
		data.origTotal			= origTotal;
		data.origTotalIncldVat	= origTotalIncldVat;
		data.func 				= 'addEventOrder';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajaxLoader").css({
					'visibility': 'hidden'
				});
				
				eval("var userObj=" + data);
				
//				if(userObj.status.user == true)
//				{
//					$(".upload_job_result").html('<p class="strong">' + userObj.user + '</p>');
//				}
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html).show(500);
				}
				else
				{
					$(".message").hide(500).html("");
					
					$(".totIncldVat").html(userObj.totalPriceIncldVat);
					$(".vat").html(userObj.totalVat);
					$(".tot").html(userObj.totalPrice);
					
					
//					var tableRow = '<tr>';
//					tableRow = tableRow + '<td class="productDetails hide">';
//					tableRow = tableRow + '<input type="hidden" class="product_quantity" value="'+ userObj.quantity +'"/>';
//					tableRow = tableRow + '<input type="hidden" class="product_optid" value="'+ userObj.productOpt +'"/>';
//					tableRow = tableRow + '</td>';
//					tableRow = tableRow + '<td>' + userObj.quantity + '</td>';
//					tableRow = tableRow + '<td>' + userObj.productOptionName +'</td>';
//					tableRow = tableRow + '<td align="right">' + userObj.productPriceExldVat + '</td>';
//					tableRow = tableRow + '<td><a href="javascript: void(0);" onclick="removeEventOrder(this, ' + userObj.productOptionTotalPrice + ', ' + userObj.quantity + ')" >Remove</a></td>';
//					tableRow = tableRow + '</tr>';
					$("#event_basket tbody").html(userObj.table);
					
					// insert values to hidden fields
					$("#event_basket tbody").append('<input type="hidden" id="totIncldVat" name="totIncldVat" value="' + userObj.figures.totalPriceIncldVat + '" />');
					$("#event_basket tbody").append('<input type="hidden" id="vat" name="vat" value="' + userObj.figures.totalVat + '" />');
					$("#event_basket tbody").append('<input type="hidden" id="tot" name="tot" value="'+ userObj.figures.totalPrice +'" />');
					// check if delegate form is hidden, if true show
					
					if($("#delegate_details").hasClass('hide'))
					{
						$("#delegate_details").removeClass('hide');
					}
					
					// reset form
					$('#productForm')[0].reset();
//					$.uniform.update(); 
					// show add delegate form
					$('#addEvent').attr('disabled','disabled');
					$('#delegate_form').show();
					$('#delegate_list').show();
					
					// add delegate span to delegate table
//					$('#delegate_list_table tbody').append('<span id="delegate_event_'+userObj.eventId+'"></span>');
				}
			}
		});
	}
}

function removeEventOrder(eventId, contentId, order_quantity)
{
	$(".ajaxLoader").css({
			'visibility': 'visible'
		});
	
	// if order_quantity is less than delegates, instruct them to remove delegates before removing order
	var remaining_order_quantity = 0;
	var total_order_quantity = 0;
	var amount = 0;
	$(".productDetails .product_quantity").each(function(){
			amount = parseInt($(this).val());
			total_order_quantity = total_order_quantity + amount;
		});
	
	// get the remaining order quantity
	remaining_order_quantity = total_order_quantity - order_quantity;
	
	// get the total amount of delegates
	// check the amount of delegates added
	var totalsDelegates = $("#delegate_list_table tbody tr .delegateDetails").length;
	
	if(totalsDelegates > remaining_order_quantity)
	{
		var remove_amount = totalsDelegates - remaining_order_quantity;
		$('.message').html("Please remove ("+ remove_amount +") delegates before removing this order. Thank you").addClass('red').show(500);
		
		setTimeout(function(){
				$('.message').fadeOut('slow',function(){
					$('.message').text('');
					$('.message').removeClass('red');
				});
			},5000);
//		alert("Please remove ("+ remove_amount +") delegates before removing this order. Thank you"); 
		$(".ajaxLoader").css({
					'visibility': 'hidden'
				});
		return;
	}
	
	
	// get total exld vat
	var totalPrice = $("input#tot").val();

	// recalculate the form
	var productOptionPrice = parseFloat(amount);
	
	if( productOptionPrice == "" )
	{
		$(".ajaxLoader").css({
					'visibility': 'hidden'
				});
		alert("There's a problem removing this item, please refresh and add the products you need again. Thanks you");
		return;
	}
	else
	{
		var data = new Object();
		
//		data.productPrice = productOptionPrice;
//		data.origTotal = totalPrice;
		data.eventId = eventId;
		data.contentId = contentId;
		data.func = 'removeEventOrder';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajaxLoader").css({
					'visibility': 'hidden'
				});
				
				eval("var userObj=" + data);
				
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html).show(500);
				}
				else
				{
					$(".message").hide(500).html("");
					
					$(".totIncldVat").html(userObj.totalPriceIncldVat);
					$(".vat").html(userObj.totalVat);
					$(".tot").html(userObj.totalPrice);
					
					$("#event_basket tbody").html(userObj.table);
					
					// insert values to hidden fields
					$("#event_basket tbody").append('<input type="hidden" id="totIncldVat" name="totIncldVat" value="' + userObj.figures.totalPriceIncldVat + '" />');
					$("#event_basket tbody").append('<input type="hidden" id="vat" name="vat" value="' + userObj.figures.totalVat + '" />');
					$("#event_basket tbody").append('<input type="hidden" id="tot" name="tot" value="'+ userObj.figures.totalPrice +'" />');
					
//					$(".totExVat").html(userObj.totalPriceExldVat);
//					$(".vat").html(userObj.totalVat);
//					$(".tot").html(userObj.totalPrice);
//					
//					// insert values to hidden fields
//					$("#totExVat").val(userObj.figures.totalPriceExldVat);
//					$("#vat").val(userObj.figures.totalVat);
//					$("#tot").val(userObj.figures.totalPrice);
//					
//					// remove table row
//					var parent = $(ele).parent().parent();
//					parent.remove();
					
					// check the value of the order
					var orderValue = parseFloat(userObj.figures.totalPrice);
					if(orderValue < 1 || isNaN(orderValue))
					{
						$("#delegate_details").addClass('hide');
					}
					
					// reset form
					$("#productForm")[0].reset();
//					$.uniform.update();
				}
			}
		});
	}
}

function addDelegate()
{
	$(".ajaxLoader2").css({
			'visibility': 'visible'
		});
	
	var errors = 0;
	
	// get form fields
	var name = $("input#name").val();
	var busEmail = $("input#busEmail").val();
	var posInComp = $("input#posInComp").val();
	var contentId = $("input#contentId").val();
	
	if( name == "" || busEmail == "" || posInComp == "" )
	{
		$(".ajaxLoader2").css({
					'visibility': 'hidden'
				});
		$("#delegate_form_error").text("All delegate details must be supplied").show(500);
		errors++;
	}
	else
	{
		$("#delegate_form_error").text("").hide(500);
	}
	
	if( !validateEmail(busEmail) )
	{
		$('#del_busEmail_error').text('Your email address is not Valid. Please check and retype').show(500);
		errors++;
	}
	else
	{
		$("#del_busEmail_error").text("").hide(500);
	}
	
	if( errors < 1 )
	{
		// get the amount quantity of each order
		totalQuantity = 0;
		$(".productDetails .product_quantity").each(function(){
			var amount = parseInt($(this).val());
			totalQuantity = totalQuantity + amount;
		});
		
		var data = new Object();
		
		data.name = name;
		data.email = busEmail;
		data.position = posInComp;
		data.quantity = totalQuantity;
		data.contentId = contentId;
		data.func = 'addDelegate';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajaxLoader2").css({
					'visibility': 'hidden'
				});
				
				eval("var userObj=" + data);
				
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html);
					$(".message").show(500);
				}
				else
				{
					$(".message").hide(500).html("");
					
//					var tableRow = '<tr>';
//					tableRow = tableRow + '<td class="delegateDetails hide">';
//					tableRow = tableRow + '<input type="hidden" class="delegateId" value="'+ userObj.delegateId +'"/>';
//					tableRow = tableRow + '</td>';
//					tableRow = tableRow + '<td>' + userObj.name + '</td>';
//					tableRow = tableRow + '<td>' + userObj.email +'</td>';
//					tableRow = tableRow + '<td>' + userObj.position + '</td>';
//					tableRow = tableRow + '<td><a href="javascript: void(0);" onclick="removeDelegate(this, ' + userObj.delegateId + ')" >Remove</a></td>';
//					tableRow = tableRow + '</tr>';
					
					$("#delegate_list_table tbody").html(userObj.table);
					$('#delegate_form form')[0].reset();
					
					// check the amount of delegates added
					totalsDelegates = userObj.totalDelegates;
					totalQuantity = userObj.numberofTickets;
//					console.log("number of delegate " + totalsDelegates);
//					console.log("number of tickets " + totalQuantity);
					// if amount of delegates is equal to quantity hide delegate form
					if( totalsDelegates == totalQuantity )
					{
						$('#delegate_form').hide();
						
						// show continue button
						$('.continue').show();
					}
					else if( totalsDelegates > totalQuantity )
					{
						var extraTickets = totalsDelegates - totalQuantity;
						$(".message").html("There are more delegates than ticket quantity. Please purchase ("+ extraTickets +") more tickets").show(500);
					}
						
				}
			}
		});
	}
	else
	{
		$(".ajaxLoader2").css({
					'visibility': 'hidden'
				});
		return;
	}
}

function removeDelegate(delegateId)
{
	var contentId = $("input#contentId").val();
	
	$(".ajaxLoader2").css({
			'visibility': 'visible'
		});
		
	var data = new Object();
		
	data.delegateId = delegateId;
	data.contentId = contentId;
	data.func = 'removeDelegate';
	
	var dataString = $.toJSON(data);
	
	$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$(".ajaxLoader2").css({
					'visibility': 'hidden'
				});
				
				eval("var userObj=" + data);
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html).addClass('red').show(500);
				}
				else
				{
					$(".message").hide(500).removeClass('red').html("");
					
					// remove table row
//					var parent = $(ele).parent().parent();
//					parent.remove();

					$("#delegate_list_table tbody").html(userObj.table);
					
					// check check the amount of delegates to the amount of tickets
					totalsDelegates = userObj.totalDelegates;
					totalQuantity = userObj.numberofTickets;
//					console.log(totalQuantity);
					
//					var delegates = $('#delegate_list_table tbody tr').length;
//					var ticketQuantity = 0;
//					$('.productDetails .product_quantity').each(function(){
//						ticketQuantity = ticketQuantity + parseInt($(this).val());
//					});
					
					if(totalsDelegates < totalQuantity)
					{
						// hide continue button
						$('.continue').hide();
						$('#booker_details').hide();
						
						// show add delegate form
						$('#delegate_form').show();
					}
				}
			}
		});
}

function addBooker()
{
	$(".ajaxLoader3").css({
			'visibility': 'visible'
		});
		
	// get form fields
	var name = $("input#booker_name").val();
	var posInComp = $("input#booker_posInComp").val();
	var comp = $("input#booker_comp").val();
	var busAdd = $("textarea#booker_busAdd").val();
	var busEmail = $("input#booker_busEmail").val();
	var busTel = $("input#booker_busTel").val();
	var busFax = $("input#booker_busFax").val();
	var errors = 0;
	var contentId = $("input#contentId").val();
	
	if( name == "" )
	{
		$(".name_error").text("Please enter your full name").show();
		errors++;
	}
	else
	{
		$(".name_error").text("").hide();
	}
	
	if( busEmail == "" )
	{
		$(".email_error").text("Please enter your business email").show();
		errors++;
	}
	else
	{
		if( ! validateEmail(busEmail) )
		{
			$(".email_error").text("Your email address is not Valid. Please check and retype").show();
			errors++;
		}
		else
		{
			$(".email_error").text("").hide();
		}
	}
	
	if( comp == "" )
	{
		$(".company_error").text("Please enter your company name").show();
		errors++;
	}
	else
	{
		$(".company_error").text("").hide();
	}
	
	if( busAdd == "" )
	{
		$(".address_error").text("Please enter your business address").show();
		errors++;
	}
	else
	{
		$(".address_error").text("").hide();
	}
	
	if( busTel == "" )
	{
		$(".tel_error").text("Please enter your business telephone number").show();
		errors++;
	}
	else
	{
		var telParts = busTel.split(" ");
		var telError = false;
		
		for(x = 0; x < telParts.length; x++)
		{
			if(isNaN(telParts[x]))
			{
				telError = true;
			}
		}
		
		if(telError)
		{
			$(".tel_error").text("Your phone number is not valid. Please check and retype").show();
			errors++;
		}
		else
		{
			$(".tel_error").text("").hide();
		}
		
	}
	
	if( errors > 0 )
	{
		$(".ajaxLoader3").css({
					'visibility': 'hidden'
				});
		
		return;
	}
	else
	{
		var data = new Object();
		
		data.name = name;
		data.email = busEmail;
		data.position = posInComp;
		data.address = busAdd;
		data.phone = busTel;
		data.fax = busFax;
		data.companyName = comp;
		data.contentId = contentId;
		data.func = 'addBooker';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		},function(data){
			
			if (data.length > 0) {
				$(".ajaxLoader3").css({
					'visibility': 'hidden'
				});
				
				eval("var userObj=" + data);
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html);
					$(".message").addClass('red');
					$(".message").show(500);
					//$(".message").show(500);
				}
				else
				{
					// hide message
					$(".message").html("");
					$(".message").removeClass('red');
					$(".message").hide(500);
					
					// hide and reset the add booker form
					$("#booker_details").hide(100);
					$("#booker_form").removeAttr('style');
					$("#booker_form form")[0].reset();
					
					// add booker details then show
					var html = userObj.details;
					$("#booker").html(html);
					$("#booker").show(100);
					
					// make booking button live	
					$('.bookNow').each(function(){
						$(this).html('<span class="blueButtonLeft"></span><span class="blueButtonMiddle"><a class=""  href="javascript: void(0)" onclick="addEventToBasket(); return false;">Book Online</a></span><span class="blueButtonRight"></span>');
					});
				}
			}
				
				
		});
	}
	
}

function editBooker()
{
	$(".ajaxLoader3").css({
			'visibility': 'visible'
		});
		
	// hide current details
	$("#booker").hide();
	
	
		
	// show loader
//	$("#booker")
//	.html('<span style="margin: 0pt 0pt 0pt 255px; z-index: 1000; visibility: visible; display: block;" class="db ajaxLoader3"><img src="/assets/images/shared/ajax-loader.gif" alt="ajax loader"></span>')
//	.show(500);
	
	// get the booker for the orders and populate form.
	
	var contentId = $("input#contentId").val();
	
	var data = new Object();
		
	data.contentId = contentId;
	data.func = 'getBooker';
	var dataString = $.toJSON(data);
	$.post('/ajax.php', {
			data: dataString
		},function(data){
			
			if (data.length > 0) {
//				$(".ajaxLoader3").css({
//					'visibility': 'hidden'
//				});
				
				// remove the booker details
//				$("#booker").html("");
					
				eval("var userObj=" + data);
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html);
					$(".message").show(500);
					
					// show current details
					$("#booker").hide();
					//$(".message").show(500);
				}
				else
				{
					// hide message
					$(".message").hide(500);
					$(".message").html("");
					
					// reset the booker form
					$("#booker_form form")[0].reset();
					
					
					// add booker details then show
					
					$("input#booker_name").val(userObj.name);
					$("input#booker_posInComp").val(userObj.position);
					$("input#booker_comp").val(userObj.company);
					$("textarea#booker_busAdd").val(userObj.address);
					$("input#booker_busEmail").val(userObj.email);
					$("input#booker_busTel").val(userObj.telephone);
					$("input#booker_busFax").val(userObj.fax);
	
					// hide and disable add booker buttion
					$('#addBooker').attr('disables', 'disabled').addClass('hide');
					
					// show and enable update/cancel booker button
					$('#updateBooker').removeAttr("disabled").removeClass('hide');
					$('#cancelUpdate').removeAttr("disabled").removeClass('hide');
					
					setTimeout(function(){
						$(".ajaxLoader3").css({
							'visibility': 'hidden'
						});
						
						$("#booker_details").show(100);
					},2000);
					
					// make booking button inactive	
					$('.bookNow').each(function(){
						$(this).html('<img alt="Complete order to book" title="Complete order to book" src="/assets/images/shared/blueButton50opacity.jpg"/>');		
					});
				}
			}
				
				
		});
}

function updateBooker()
{
	$(".ajaxLoader3").css({
			'visibility': 'visible'
		});
		
	// get form fields
	var name = $("input#booker_name").val();
	var posInComp = $("input#booker_posInComp").val();
	var comp = $("input#booker_comp").val();
	var busAdd = $("textarea#booker_busAdd").val();
	var busEmail = $("input#booker_busEmail").val();
	var busTel = $("input#booker_busTel").val();
	var busFax = $("input#booker_busFax").val();
	var errors = 0;
	var contentId = $("input#contentId").val();
	
	if( name == "" )
	{
		$(".name_error").text("Please enter your full name").show();
		errors++;
	}
	else
	{
		$(".name_error").text("").hide();
	}
	
	if( busEmail == "" )
	{
		$(".email_error").text("Please enter your business email").show();
		errors++;
	}
	else
	{
		$(".email_error").text("").hide();
	}
	
	if( comp == "" )
	{
		$(".company_error").text("Please enter your company name").show();
		errors++;
	}
	else
	{
		$(".company_error").text("").hide();
	}
	
	if( busAdd == "" )
	{
		$(".address_error").text("Please enter your business address").show();
		errors++;
	}
	else
	{
		$(".address_error").text("").hide();
	}
	
	if( busTel == "" )
	{
		$(".tel_error").text("Please enter your business telephone number").show();
		errors++;
	}
	else
	{
		$(".tel_error").text("").hide();
	}
	
	if( errors > 0 )
	{
		$(".ajaxLoader3").css({
					'visibility': 'hidden'
				});
		
		return;
	}
	else
	{
		var data = new Object();
		
		data.name = name;
		data.email = busEmail;
		data.position = posInComp;
		data.address = busAdd;
		data.phone = busTel;
		data.fax = busFax;
		data.companyName = comp;
		data.contentId = contentId;
		data.func = 'updateBooker';
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		},function(data){
			
			if (data.length > 0) {
				$(".ajaxLoader3").css({
					'visibility': 'hidden'
				});
				
				eval("var userObj=" + data);
				
				if(userObj.error == true)
				{
					var html; 
					html = userObj.message;
					
					$(".message").html(html);
					$(".message").addClass('red');
					$(".message").show(500);
					//$(".message").show(500);
				}
				else
				{
					// hide message
					$(".message").hide(500);
					$(".message").html("");
					$(".message").removeClass('red');
					
					// remove the booker details
					$("#booker").html("");
					
					// hide and reset the add booker form
					$("#booker_details").hide();
					$("#booker_form form")[0].reset();
					
					// update/cancel button and disable
					$('#updateBooker').attr("disabled", "disabled").addClass('hide');
					$('#cancelUpdate').attr("disabled", "disabled").addClass('hide');
					
					// add booker details then show
					var html = userObj.details;
					$("#booker").html(html);
					$("#booker").show('fast');
					
					// make booking button live	
					$('.bookNow').each(function(){
						$(this).html('<span class="blueButtonLeft"></span><span class="blueButtonMiddle"><a class=""  href="javascript: void(0)" onclick="addEventToBasket(); return false;">Book Online</a></span><span class="blueButtonRight"></span>');		
					});
				}
			}
				
				
		});
	}
	
}

function cancelUpdate()
{
	// show loader
	$(".ajaxLoader3").css({
			'visibility': 'visible'
		});
	
	
	// hide and reset the add booker form
	$("#booker_details").hide();
	$("#booker_form form")[0].reset();
	
	
	// show details
	setTimeout(function(){
		$("#booker").show('fast');
		
		// hide loader
		$(".ajaxLoader3").css({
			'visibility': 'hidden'
		});
		
		// make booking button live	
		$('.bookNow').each(function(){
			$(this).html('<span class="blueButtonLeft"></span><span class="blueButtonMiddle"><a class=""  href="javascript: void(0)" onclick="addEventToBasket(); return false;">Book Online</a></span><span class="blueButtonRight"></span>');		
		});	
	
	},2000);
	
	
	
}

function addEventToBasket()
{
	$(".ajaxLoader3").css({
			'visibility': 'visible'
		});
		
	var contentId = $("input#contentId").val();
	var basketproduct = $("input#basketproduct").val();
	var data = new Object();
		
	data.basketproduct = basketproduct;
	data.contentId = contentId;
	data.func = 'addEventToBasket';
	
	var dataString = $.toJSON(data);
	
	$.post('/ajax.php', {
		data: dataString
	},function(data){
		
		if (data.length > 0) {
			$(".ajaxLoader3").css({
				'visibility': 'hidden'
			});
		}
		
		eval("var userObj=" + data);
		
		if(userObj.error == true)
		{
			var html; 
			html = userObj.message;
			
			$(".message").html(html);
			$(".message").show(500);
		}
		else
		{
			var html; 
			html = userObj.message;
			
			// hide message
			$(".message").html("");
			$(".message").hide(500);
			
//			$(".message").html(html);
//			$(".message").show(500);
			
//			setTimeout('$(".message").hide(500);', 7000);
			// update basket
			getMiniBasket();
			
			gotToLocation(userObj.url);
			
		}
	});
}

function gotToLocation(url)
{
	window.location = url;
}

function viewCompany(id)
{
	if(id =="" || isNaN(id) == true)
	{
		return false;
	}
	
	// get value of category id
	var targetCatId = $("input#target").val();
	
	// 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;
	}
		
	$("#search_results").fadeOut(500, function(){
		$("#ajax_loader").css({'visibility' : 'hidden', 'display' : 'none'});
	});
	
	// send data to search function
	var dataString = "?companyID=" + id + "&target=" + targetCatId + "&function=viewCompany";
	
	$.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 getCompany()
{
 	var companyid = $('#company').val();
	prevCompId = '';
	
	if(companyid == '' || companyid == prevCompId)
		return;
	else
	{
		location = '../edit_company/'+companyid;
	}
		
	prevCompId = companyid;
}

function getUser(url)
{
 	var userid = $('#user').val();
	prevUserId = '';
	
	if(userid == '' || userid == prevUserId)
		return;
	else
	{
		location = url + 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(value == 'Other')
	{
		$("." +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);
}

function share_email(url)
{
	// regex
	var textOnly = /^[a-zA-Z\s]+$/;
	
	// error count
	var errors = 0;
	
	// form values
	var name 		= $('input#share_name').val();
	var from 		= $('input#share_from_email').val();
	var to 			= $('input#share_to_email').val();
	var message 	= $('textarea#share_message').val();
	var title		= $('input#title').val();
	var share_type	= $('input#share_type').val();
	
	// Validation
	/** 
	 * validate the name form field
	 * check if empty
	 * check if not alpha inc white space
	 */
	if(name == "")
	{
		$('.share_name_error').text('The name field can not be empty. Please try again. Thanks').show();
		errors++;
	}
	else
	{
		$('.share_name_error').text('').hide();
	}
	
	/** 
	 * validate the from form field
	 * check if empty
	 * check if not valid emails address
	 */
	if(from == "")
	{
		$('.share_from_email_error').text('The from field can not be empty. Please try again. Thanks');
		$('.share_from_email_error').show();
		errors++;
	}
	else if(!validateEmail(from))
	{
		$('.share_from_email_error').text('The from field must be a valid email address. Please try again. Thanks');
		$('.share_from_email_error').show();
		errors++;
	}
	else
	{
		$('.share_from_email_error').text('');
		$('.share_from_email_error').hide();
	}
	
	/** 
	 * validate the to form field
	 * check if empty
	 * check if not valid emails address
	 */
	if(to == "")
	{
		$('.share_to_email_error').text('The to field can not be empty. Please try again. Thanks');
		$('.share_to_email_error').show();
		errors++;
	}
	else if(!validateEmail(to))
	{
		$('.share_to_email_error').text('The to field must be a valid email address. Please try again. Thanks');
		$('.share_to_email_error').show();
		errors++;
	}
	else
	{
		$('.share_to_email_error').text('');
		$('.share_to_email_error').hide();
	}
	
	/** 
	 * validate the message form field
	 * check if empty
	 */
	if(message == "")
	{
		$('.share_message_error').text('The message can not be empty. Please try again. Thanks');
		$('.share_message_error').show();
		errors++;
	}
	else
	{
		$('.share_message_error').text('');
		$('.share_message_error').hide();
	}
	
	if(errors > 0)
	{
		return;
	}
	else
	{
		// fade in ajax loader while processing update
		$("#shareForm").animate({
			opacity: 0.5
		}, 100);
		
		$(".result").hide();
		
		$("#ajax_loader").css({
			'visibility': 'visible',
			'display': 'block'
		});
		
		var data = new Object();
		
		data.name 		= name;
		data.from 		= from;
		data.to 		= to;
		data.message	= message;
		data.url 		= url;
		data.jobtitle 	= title;
//		data.func 		= 'shareJob';
		
		if (share_type == 'event') {
			data.func = 'shareEvent';
		}
		else if( share_type == 'company' ){
			data.func = 'shareCompany';
		}
		else {
			data.func = 'shareJob';
		}
		
		var dataString = $.toJSON(data);
		
		$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				$("#ajax_loader").css({
					'visibility': 'hidden',
					'display': 'none'
				});
				
				$(".result")
				.html(data)
				.fadeIn();
				
				$('input#share_to_email').val("");
				$('textarea#share_message').val("");
				
				
				$("#shareForm").animate({
					opacity: 1
				}, 1500);
			}
		});
	}
}

function clearForm(formId)
{
	$(formId + ' input').each(function(index){
		alert(index);
	});
}


function getFullContactInfo(index)
{
	var checked = $(index).attr('checked');
	
	if(checked)
	{
		var data = new Object();
		data.func 		= 'getFullUserContactDetails';
		var dataString = $.toJSON(data);
	
		// get the user contact details
		$.post('/ajax.php', {
				data: dataString
			}, function(data){
				if (data.length > 0) {
					eval("var userObj=" + data);
					
					if(userObj.status.error == true)
					{
						$('.contact_name_error').text(userObj.error);
						$('.contact_name_error').fadeIn('1000', function(){
							setTimeout('$(".contact_name_error").fadeOut("slow")', 3000);
						});
					}
					else
					{
						$("#title").val();
						$("#contactfirstname").val(userObj.firstname);
						$("#contactsurname").val(userObj.surname);
						$("#contactposition").val(userObj.position);
						$("#companyemail").val(userObj.email);
						$("#companytel").val(userObj.tel);
						$("#companyfax").val(userObj.fax);
					}
				}
			});
	}
	else
	{
						$("#title").val();
						$("#contactfirstname").val("");
						$("#contactsurname").val("");
						$("#contactposition").val("");
						$("#companyemail").val("");
						$("#companytel").val("");
						$("#companyfax").val("");
	}
	
} 

function deleteContent(jobTitle, url)
{
	var check = confirm("Are your sure you wand to delete this job?\nJob Title: " + jobTitle);
	
	if(check)
	{
		document.location = url;
	}
	else
	{
		return;
	}
}

function getUserDelegateDetails()
{
	var data = new Object();
	data.func 		= 'getLoggedInUser';
	var dataString = $.toJSON(data);
	
	// get the user contact details
	$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				eval("var userObj=" + data);
				
				if(userObj.error == true)
				{
					alert(userObj.message);
				}
				else
				{
					var name = userObj.firstname + ' ' + userObj.lastname;
					$("#name").val(name);
					$("#posInComp").val(userObj.position);
					$("#busEmail").val(userObj.email);
				}
			}
		});
}
function getUserBookerDetails()
{
	var data = new Object();
	data.func 		= 'getLoggedInUser';
	var dataString = $.toJSON(data);
	
	// get the user contact details
	$.post('/ajax.php', {
			data: dataString
		}, function(data){
			if (data.length > 0) {
				eval("var userObj=" + data);
				
				if(userObj.error == true)
				{
					alert(userObj.message);
				}
				else
				{
					var name = userObj.firstname + ' ' + userObj.lastname;
					$("#booker_name").val(name);
					$("#booker_posInComp").val(userObj.position);
					$("#booker_comp").val(userObj.company);
					$("#booker_busTel").val(userObj.tel);
					$("#booker_busFax").val(userObj.fax);
					$("#booker_busEmail").val(userObj.email);
					
					var address;
					if(userObj.address1.length > 0)		{ address = userObj.address1 };	
					if(userObj.address1.length > 0)		{ address = address + '\n' + userObj.address2 };
					if(userObj.town.length > 0)			{ address = address + '\n' + userObj.town };
					if(userObj.county.length > 0)		{ address = address + '\n' + userObj.county };
					if(userObj.postcode.length > 0)		{ address = address + '\n' + userObj.postcode };
					if(userObj.country.length > 0)		{ address = address + '\n' + userObj.country };
					
					$("#booker_busAdd").text(address);
				}
			}
		});
}

