var is_authenticated;
var authinfo;
var currenturl = window.location.href;
var accordionLastActive = 0;
var accordionLength = 0;
var accordionNextActive = 0;
var accordionvars = {
		autoHeight: false,
		change: function(event, ui) {
			accordionLastActive = ui.options['active'];
			save_profile_form();
		}
	}

$(document).ready(function () {
			
	$.get(
		'/wp-content/themes/acg/inc/app/session.php',
				function(data)
				{
					if(data.user_id)
					{
						is_authenticated = true;
						authinfo = data;
						if(currenturl.indexOf('/log-in/') >= 0 || currenturl.indexOf('/register/') >= 0)
							window.location = '/profile/';
						
						if(currenturl.indexOf('/profile') >= 0)
						{

							if(currenturl.indexOf('complete') >= 0)
							{
								//This is where you should start
								var incompletefields = 0;
								for(var i in data.profile)
								{
									for(var j in data.profile[i])
									{
										if($.isArray(data.profile[i][j]) && j!='multi')
										{
											var implodearray;
												if(j == 'categoryID' || j == 'secondaryCategories')
												{
													var catpopulate = j;
													$.get(
														'/wp-content/themes/acg/inc/app/categories.php?catid='+data.profile[i][j].join(','),
														function(cdata)
														{
															var catarray = new Array();
															for(var c in cdata)
																catarray[c] = cdata[c]['category'];
															$('#'+catpopulate).text(catarray.join(', '));
														},
														'json'
													);
												}
												else
												{	
													$('#'+j).text(data.profile[i][j].join(', '));
												}
										}
										else if(j == 'multi')
										{

											if(data.profile[i][j].length > 0)
											{
												for(k=0;k<data.profile[i][j].length;k++)
												{
													if(k > 0) addProfileTab(i,k);
													for(var l in data.profile[i][j][k])
													{
														//console.log("#"+l+"_"+k);
														$("#"+l+"_"+k).text(data.profile[i][j][k][l]);
													}
												}
											}
											
											
										}
										else
										{
											if(j == 'categoryID' || j == 'secondaryCategories')
											{
												var catpopulates = j;
												$.get(
													'/wp-content/themes/acg/inc/app/categories.php?catid='+data.profile[i][j],
													function(cdata)
													{
														for(var c in cdata)
														{
															$('#'+catpopulates).text(cdata[c]['category']);
														}
													},
													'json'
												);
											}
											else if(j == 'country_1')
											{
												var crpopulates = j;
												$.get(
													'/wp-content/themes/acg/inc/app/countries.php?countryid='+data.profile[i][j],
													function(crdata)
													{
														for(var cr in crdata)
														{
															$('#'+crpopulates).text(crdata[cr]['name']);
														}
													},
													'json'
												);
											}
											else if(j == 'country_2')
											{
												if(data.profile[i][j])
												{
													var cr2populates = j;
													$.get(
														'/wp-content/themes/acg/inc/app/countries.php?countryid='+data.profile[i][j],
														function(cr2data)
														{
															for(var cr2 in cr2data)
															{
																$('#'+cr2populates).text(cr2data[cr2]['name']);
															}
														},
														'json'
													);
												}
											}
											else
											{									
												$('#'+j).text(data.profile[i][j]);
											}
										}
									}
								}
								console.log("beforegetcalled"); 
								$.get(
									'/wp-content/themes/acg/inc/app/required.php',

									function(data)
									{
										for(var i in data)
										{
											for(var j in data[i])
											{
					
												if($.isArray(data[i][j]) && j=='multi')
												{
													for(var k in data[i][j])
													{
														for(var l in data[i][j][k])
														{
															if(data[i][j][k][l] == 1)
															{
																incompletefields++;
																$("#"+l+"_"+k).html('<i style="color:#aaa">required</i>');
															}
														}
													}
												}
												else
												{
													if(data[i][j] == 1)
													{
														incompletefields++;
														$('#'+j).html('<i style="color:#aaa">required</i>');
													}
												}
												
											}
										}
										if(incompletefields > 0)
											alert('There are fields still requiring data. You must complete these fields before you can submit your profile');
									},
									'json'
								);
							}
							else
							{
								
								var formid = $("form.profileform").attr('rel');
								console.log(formid); 
								for(var i in data.profile[formid])
								{
									if(i == 'multi')
									{
										if(data.profile[formid][i].length > 0)
										{
											
											for(j=0;j<data.profile[formid][i].length;j++)
											{
												if(j > 0) {
													addDeleteButton();
													addAccordionTab(j);
												}
												for(var k in data.profile[formid][i][j])
													$(":input#"+k+"_"+j).val(data.profile[formid][i][j][k])
													

											}
										}
									}
									else
									{
										$(":input#"+i).val(data.profile[formid][i]);
									}
								}
								
								if(currenturl.indexOf('/profile/') >= 0)
								{
									$.get(
										'/wp-content/themes/acg/inc/app/countries.php',
										function(crdata)
										{
											for(var cr in crdata)
												$('#country_1, #country_2').append('<option value="' + crdata[cr]['countryID'] + '">' + crdata[cr]['name'] + '</option>');
											$(":input#country_1").val(data.profile[formid]['country_1']);
											$(":input#country_2").val(data.profile[formid]['country_2']);
										},
										'json'
									);
									$.get(
										'/wp-content/themes/acg/inc/app/categories.php',
										function(cdata)
										{
											for(var c in cdata)
												$('#categoryID, #secondaryCategories').append('<option value="' + cdata[c]['catid'] + '">' + cdata[c]['category'] + '</option>');
											$(":input#categoryID").val(data.profile[formid]['categoryID']);
											$(":input#secondaryCategories").val(data.profile[formid]['secondaryCategories']);
										},
										'json'
									);
								}
							}
						}
						$("#accordion").accordion(accordionvars);
					}
					else
					{
						if(currenturl.indexOf('/profile') >= 0)
							window.location = '/log-in/';
					}
				},
				'json'
		);
		
	$(".breadcrumb a").click(
		function (){
			save_profile_form($(this).attr('href'));
			return false;
		}
	);
	
	$(".addanother").click(function(){
		save_profile_form();
		addAccordionTab();
		$("#accordion").accordion('destroy').accordion(accordionvars).accordion('activate',accordionLength);
		
		$("#accordion").children("div:last").find("input:first").focus(); //Change this to scrollTo
		return false;
	});
	
	$('.profileform .save').click(
		function (){
			save_profile_form('','Your data has been saved','Failed to save. Try again');
			return false;
		}
	);
	
	$('.profileform .next').click(
		function (){
			var requiredempty = 0;
			$(':input.required').each(
				function(){
					if($(this).val() == '')
					{
						$(this).prev().addClass('error');
						requiredempty++;
					}
				}
			);
			if(requiredempty){
				if(confirm('There are required fields on this page that must be completed. You will not be able to submit this profile information for a job application until all required fields have been completed.\n\nProceed anyway?'))
					save_profile_form($(this).attr('href'));
				else
					save_profile_form();
			}else{
				save_profile_form($(this).attr('href'));
			}
			return false;
		}
	);
	
	$('.profileform .logout').click(
		function(){
			$.post(
				'/wp-content/themes/acg/inc/app/update_profile.php',
				$('.profileform').serialize(),
				function(data)
				{			
					if(data.status == 401)
					{
						alert('Your changes have not been saved because your session has expired. To save your changes, please log in again');
						window.location = '/log-in/';
					}
					else
					{
						
						$.get(
							'/wp-content/themes/acg/inc/app/logout.php',
							function(){
								//window.location = '/log-in/';
							}
						);
						
					}
				},
				'json'
			);
			return false;
		}
	);

/* VALIDATOR DEFAULTS */
	$.validator.setDefaults({
		debug: true,
		errorElement: "li", // Something has to be defined here, or JQuery overwrites existing label classes with the error class instead of appending. 
		errorContainer: '#errormsg',
		errorLabelContainer: '#errormsg ul',
		onfocusout: false,
		highlight: function (element, errorClass, validClass) {
			$(element).addClass(errorClass).removeClass(validClass);
			$(element.form).find("label[for=" + element.id + "]")
			.addClass(errorClass);
		},
		unhighlight: function (element, errorClass, validClass) {
			$(element).removeClass(errorClass).addClass(validClass);
			$(element.form).find("label[for=" + element.id + "]")
			.removeClass(errorClass);
		},
		invalidHandler: function (form, validator) {
			$('html,body').animate(
				{scrollTop: (360)}
			);
		},
		submitHandler: function (form) {
			$(form).hide();
			$('<p class="successmsg">Your changes have been recorded.  Thank you.</p>')
				.insertBefore(form);
			$('html,body').animate(
				{scrollTop: (360)}
			);
		}
	});
	
/* PROFILE-BASIC */
	$("#tmp-profile-basic").validate({
		rules: {
			address_1: "required",
			categoryID: "required",
			city_1: "required",
			companyURL: {
				url: true
			},
			basic_confirm_password: {
				equalTo: "#basic_password"
			},
			country_1: "required",
			dateAvailable: {
				required: true,
				date: true
			},
			description: {
				required: true,
				accept: "pdf|doc|docx|rtf|xml|vcf"
			},
			desiredLocations: "required",
			email: {
				required: true,
				email: true
			},
			email2: {
				email: true
			},
			firstName: "required",
			lastName: "required",
			persComments: "required",
			phone: "required",
			preferredContact: "required",
			source: "required",
			state_1: "required",
			willRelocate: "required",
			zip_1: "required",
			select:{ 
				required: function (element) {
					if( $("#select").val() ==''){
						return false;
					}else{
						return true;
					}
				}
			}
		},
		messages: {
			address1_1: "Please enter your address.",
			categoryID: "Please choose a primary category.",
			city_1: "Please enter your city.",
			companyURL: {
				url: "Enter a valid web site address, for example http://www.mysite.com."
			},
			basic_confirm_password: {
				equalTo: "Your passwords must match."
			},			
			country_1: "Please enter your country.",
			dateAvailable: {
				required: "Please enter the date you are available.",
				date: "The date you are available is not formatted as a date (mm/dd/yyy)."
			},
			description: {
				required: "You must upload your resume.",
				accept: "Your resume must be in one of the following file formats: pdf, doc, docx, rtf, xml, or Vcard(vcf)."
			},
			desiredLocations: "You must enter at least one location that you would like to work in.",
			email: {
				required: "Please enter your email address.",
				email: "Enter a valid email address, for example user@example.com."
			},
			firstName: "Please enter your first name.",
			lastName: "Please enter your last name.",
			persComments: "Please enter some comments about yourself.",
			phone: "Please enter your phone number.",
			preferredContact: "Please specify your preferred method of contact.",
			source: "Please tell us how you heard about us.",
			state_1: "Please enter your state.",
			willRelocate: "Please indicate whether or not you are willing to relocate.",
			zip_1: "Please enter your zip code."
		}
	});

/* PROFILE-ED */
	$("#tmp-profile-ed").validate({
		rules: {
			educationDegree: "required",
			graduationDate_1: {
				date: true
			},
			school_1: "required",
			schoolCity_1: "required",
			schoolEndDate_1: {
				required: true,
				date: true
			},
			schoolStartDate_1: {
				required: true,
				date: true
			},
			schoolState_1: "required"
		},
		messages: {
			educationDegree: "Please enter your highest level of education.",
			graduationDate_1: {
				date: "Your graduation date for School 1 is not formatted as a date (mm/dd/yyy)."
			},
			school_1: "Please enter the name of School 1.",
			schoolCity_1: "Please enter the city in which School 1 is located.",
			schoolEndDate_1: {
				required: "Please enter the date that you ended your education at School 1.",
				date: "The date you ended your education at School 1 is not formatted as a date (mm/dd/yyy)."
			},
			schoolStartDate_1: {
				required: "Please enter the date that you started your education at School 1.",
				date: "The date you started your education at School 1 is not formatted as a date (mm/dd/yyy)."
			},
			schoolState_1: "Please enter the state in which School 1 is located."
		}
	});

/* PROFILE-REF */
	$("#tmp-profile-ref").validate({
		rules: {
			candidateTitle_1: "required",
			candidateTitle_2: "required",
			candidateTitle_3: "required",
			employmentEndDate_1: {
				date: true
			},
			employmentEndDate_2: {
				date: true
			},
			employmentEndDate_3: {
				date: true
			},
			employmentStartDate_1: {
				date: true
			},
			employmentStartDate_2: {
				date: true
			},
			employmentStartDate_3: {
				date: true
			},
			refEmail_1: {
				required: true,
				email: true
			},
			refEmail_2: {
				required: true,
				email: true
			},
			refEmail_3: {
				required: true,
				email: true
			},
			refFirstName_1: "required",
			refFirstName_2: "required",
			refFirstName_3: "required",
			refLastName_1: "required",
			refLastName_2: "required",
			refLastName_3: "required",
			refPhone_1: "required",
			refPhone_2: "required",
			refPhone_3: "required",
			refTitle_1: "required",
			refTitle_2: "required",
			refTitle_3: "required",
			yearsKnown_1: "required",
			yearsKnown_2: "required",
			yearsKnown_3: "required"
		},
		messages: {
			candidateTitle_1: "Please enter your title when you knew Reference 1.",
			candidateTitle_2: "Please enter your title when you knew Reference 2.",
			candidateTitle_3: "Please enter your title when you knew Reference 3.",
			employmentEndDate_1: {
				date: "The date you ended employment with Reference 1 is not formatted as a date (mm/dd/yyy)."
			},
			employmentEndDate_2: {
				date: "The date you ended employment with Reference 2 is not formatted as a date (mm/dd/yyy)."
			},
			employmentEndDate_3: {
				date: "The date you ended employment with Reference 3 is not formatted as a date (mm/dd/yyy)."
			},
			employmentStartDate_1: {
				date: "The date you started employment with Reference 1 is not formatted as a date (mm/dd/yyy)."
			},
			employmentStartDate_2: {
				date: "The date you started employment with Reference 2 is not formatted as a date (mm/dd/yyy)."
			},
			employmentStartDate_3: {
				date: "The date you started employment with Reference 3 is not formatted as a date (mm/dd/yyy)."
			},
			refEmail_1: {
				required: "Please enter an email address for Reference 1.",
				email: "Enter a valid email address for Reference 1, for example user@example.com."
			},
			refEmail_2: {
				required: "Please enter an email address for Reference 2.",
				email: "Enter a valid email address for Reference 2, for example user@example.com."
			},
			refEmail_3: {
				required: "Please enter an email address for Reference 3.",
				email: "Enter a valid email address for Reference 3, for example user@example.com."
			},
			refFirstName_1: "Please enter the first name of Reference 1.",
			refFirstName_2: "Please enter the first name of Reference 2.",
			refFirstName_3: "Please enter the first name of Reference 3.",
			refLastName_1: "Please enter the last name of Reference 1.",
			refLastName_2: "Please enter the last name of Reference 2.",
			refLastName_3: "Please enter the last name of Reference 3.",
			refPhone_1: "Please enter a phone number for Reference 1.",
			refPhone_2: "Please enter a phone number for Reference 2.",
			refPhone_3: "Please enter a phone number for Reference 3.",
			refTitle_1: "Please enter the job title for Reference 1.",
			refTitle_2: "Please enter the job title for Reference 2.",
			refTitle_3: "Please enter the job title for Reference 3.",
			yearsKnown_1: "Please indicate how many years you have known Reference 1.",
			yearsKnown_2: "Please indicate how many years you have known Reference 2.",
			yearsKnown_3: "Please indicate how many years you have known Reference 3."
		}
	});

/* PROFILE-WORK */
	$("#tmp-profile-work").validate({
		rules: {
			companyName_1: "required",
			jobEndDate_1: {
				required: true,
				date: true
			},
			jobStartDate_1: {
				required: true,
				date: true
			},
			occupation: "required",
			salaryType_1: "required",
			salary1_1: "required",
			salary2_1: "required",
			terminationReason_1: "required",
			title_1: "required",
			workAuthorized: "required"
		},
		messages: {
			companyName_1: "Please enter the company name at Position 1.",
			jobEndDate_1: {
				required: "Please enter the end date of Position 1.",
				date: "The end date of Position 1 is not formatted as a date (mm/dd/yyyy)."
			},
			jobStartDate_1: {
				required: "Please enter the start date of Position 1.",
				date: "The start date of Position 1 is not formatted as a date (mm/dd/yyyy)."
			},
			occupation: "Please indicate your current occupation.",
			salaryType_1: "Please select what type of salary you received at Position 1.",
			salary1_1: "Please enter your starting salary at Position 1.",
			salary2_1: "Please enter your ending salary at Position 1.",
			terminationReason_1: "Please tell why your position at Position 1 ended.",
			title_1: "Please enter your title at Position 1.",
			workAuthorized: "Please indicate whether or not you are authorized to work in the US."
		}
	});

/* REGISTER */
	var register_validator = $("#register").validate({
		rules: {
			confirm_password: {
				required: true,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
			},
			password: "required",
			username: "required"
		},
		messages: {
			confirm_password: {
				required: "Please enter your password again.",
				equalTo: "Your passwords must match."
			},
			email: {
				required: "Please enter your email address.",
				email: "Enter a valid email address, for example user@example.com."
			},
			password: "Please enter your password.",
			username: "Please enter your username."
		},
		submitHandler: function (form) {
			$.post(
				'/wp-content/themes/acg/inc/app/register.php',
				$(form).serialize(),
				function(data)
				{
					if(data.status == '202')
					{
						window.location = "/profile/";
					}
					else
					{
						if(data.errors)
							register_validator.showErrors(data.errors);
						else
							alert('There was a problem submitting your registration');
					}
				},
				'json'
			);
		}
	});

/* LOGIN */
	var login_validator = $("#login").validate({
		rules: {
			login_password: "required",
			login_username: "required"
		},
		messages: {
			login_password: "Please enter your password to log in.",
			login_username: "Please enter your username to log in."
		},
		submitHandler: function (form) {
			$.post(
				'/wp-content/themes/acg/inc/app/login.php',
				$(form).serialize(),
				function(data)
				{
					if(data.status == '202')
					{
						window.location = "/profile/";
					}
					else
					{
						if(data.errors)
							login_validator.showErrors(data.errors);
						else
							alert('There was a problem logging in');
					}
				},
				'json'
			);
		}
	});

/* FORGOTPASS */
	var forgotpass_validator = $("#forgotpass").validate({
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			email: {
				required: "Please enter your email address in order to reset your password.",
				email: "Enter a valid email address, for example user@example.com."
			}
		},
		submitHandler: function (form) {
			$.post(
				'/wp-content/themes/acg/inc/app/resetpass.php',
				$(form).serialize(),
				function(data)
				{
					if(data.status == '200')
					{
						$('<p class="successmsg">Please check your email for your new password.</p>').insertBefore('#login');
						$('#forgotpass, #login').animate(
							{height: 'toggle'}, 500
						);
					}
					else
					{
						if(data.errors)
							forgotpass_validator.showErrors(data.errors);
						else
							alert('There was a problem sending your password.');
					}
				},
				'json'
			);
		}
	});

/* FORGOT PASSWORD ANIMATION */
	$('.forgotpassword').click(function () {
		$('#errormsg').css('display','none');
		$('#forgotpass, #login').animate(
			{height: 'toggle'}, 500
		);
	});
	
/* REMEMBERED PASSWORD ANIMATION */
	$('.rememberedpassword').click(function () {
		$('#errormsg').css('display','none');
		$('#forgotpass, #login').animate(
			{height: 'toggle'}, 500
		);
	});
});


	
function save_profile_form(goto_page,success_message,error_message){
	if($('.profileform').length > 0)
	{

		$.post(
			'/wp-content/themes/acg/inc/app/update_profile.php',
			$('.profileform').serialize(),
			function(data)
			{

				if(data.status == 401)
				{
					alert('Your changes have not been saved because your session has expired. To save your changes, please log in again');
					window.location = '/log-in/';
				}
				else
				{
					if(goto_page)
						window.location = goto_page;	
					if(success_message && data.status == 200)
						alert(success_message);
					if(error_message && data.status != 200)
						alert(error_message);
				}
			},
			'json'
		);
	}
	else if(goto_page)
	{
		window.location = goto_page;	
	}
}

function submitTest() {
	//Attempt to submit the data to bullhorn. 
	// $.post(
	// 	'/wp-content/themes/acg/inc/app/submit_profile.php',
	// 	$('.profileform').serialize(),
	// 	function(data)
	// 	{			
	// 		// if(data.status == 401)
	// 		// {
	// 		// 	alert('Your changes have not been saved because your session has expired. To save your changes, please log in again');
	// 		// 	window.location = '/log-in/';
	// 		// }
	// 		// else
	// 		// {
				
	// 		// 	$.get(
	// 		// 		'/wp-content/themes/acg/inc/app/logout.php',
	// 		// 		function(){
	// 		// 			//window.location = '/log-in/';
	// 		// 		}
	// 		// 	);
				
	// 		// }
	// 	},
	// 	'json'
	// );

	//Initially try to load the page, instead of a post function.

	$.post('wp-content/themes/acg/inc/app/submit_profile.php', function(data) {
  		console.log(data); 
  		//$('.result').html(data);
	});
	// ('/wp-content/themes/acg/inc/app/searchform.php',function(){
	// }
}

function addProfileTab(i,k){
	var newTab = $("#"+i+" .duplicatable").clone(false).removeClass('duplicatable').addClass('duplicated').find('span').each(function(){
		var newId = this.id.replace("_0","_"+k);
		this.id = newId;
	}).end();
	$(newTab).appendTo("#"+i);
}

function addAccordionTab(newpos){
	//Study this, see how he creates this tab.
	accordionLength = $("h3").length;
	accordionNextActive = $(".duplicated").length + 2;

	var newTab = $(".duplicatable").clone(false).removeClass('duplicatable').addClass('duplicated').find(':input').each(function(){
		newpos = newpos ? newpos : (accordionNextActive - 1);
		var newId = this.id.replace("_0","_"+newpos);
		var newName = this.name.replace("[0]","["+(newpos)+"]");
		
		$(this).prev().attr('for',newId);
		this.id = newId;
		this.name = newName;
		$(this).val('');
	}).end();
	var newTitle = $(".duplicatable").attr('rel') + " #" + accordionNextActive;
	$("#entries").val(accordionNextActive);
	$("#accordion").append('<h3>'+newTitle+ '</h3>');
	$(newTab).appendTo("#accordion");

	//Check and see if the add delete button exists. If it does, then add another button to the end of it.

	if ($('.removeanother').length ==0) 
	{
		addDeleteButton();	
	}
	
}
function removeAccordionTab() {
	var active = $('#accordion').accordion('option', 'active');

	var accordionItemTitle = $("#accordion").find('h3:last');
	//Just get the both and remove them both. 
	var accordionItemDiv = $("#accordion").find('div:last');

	accordionItemTitle.remove();
	accordionItemDiv.remove();

	if ($('h3').length > 0) 
	{
		$('.removeanother').remove();
	}
}
function addDeleteButton() {
	//Find the add another button
	
	var accordianTitle = $(".duplicatable").attr('rel');
	$('.addanother').after('<a href = "" class = "removeanother">Remove '+ accordianTitle +'</a>');
	
	//add the click function. 
	$(".removeanother").click(function(){
		removeAccordionTab();
		save_profile_form();
		$("#accordion").accordion('destroy').accordion(accordionvars).accordion('activate',accordionLength);
		
		$("#accordion").children("div:last").find("input:first").focus(); //Change this to scrollTo
		return false;
	});
	
}



