/*
 * JavaScript functions for populating form fields
 */

// Bookmark job
function bookmarkJob(job_id, job_title){
	addLoadAlert();
	$.post("ajax/bookmark_job.php", {"job_id": job_id, "job_title": job_title},function(response){
		$("#job_"+job_id+"_container").html(response);
		removeLoadAlert();
	} );
}

// Bookmark resumes
function bookmarkResume(resume_id){
	addLoadAlert();
	$.post("ajax/bookmark_resume.php", {"resume_id": resume_id},function(response){
		$("#resume_"+resume_id+"_container").html(response);
		removeLoadAlert();
	} );
}

function checkUsername(email){
	addLoadAlert();
	$.post("ajax/registration_username_check.php", {"email": email},function(response){
		$("#email_container").html(response);
		removeLoadAlert();
	} );
}

function editApplicationBookmark(application_bookmark_id){
	addLoadAlert();
	$.post("ajax/employer_application_bookmark.php", { "application_bookmark_id": application_bookmark_id },function(response){
		$("#application_bookmark_container").html(response);
		removeLoadAlert();
	});
}

function editConsultants(){
	var consultant_window = window.open(
		"employer_emails_popup_edit.php",
		"consultant_window",
		"status=1,resizable=1,scrollbars=1,width=700,height=600"
	);
	consultant_window.moveTo(0,0);
	//directories, resizable, scrollbars, height, width
}

function editFolder(employer_folder_id){
	addLoadAlert();
	$.post("ajax/employer_folder_edit.php", { "employer_folder_id": employer_folder_id },function(response){
		$("#employer_folder_container").html(response);
		removeLoadAlert();
	});
}

function editJobSearch(job_search_history_id){
	addLoadAlert();
	$.get("ajax/job_search_edit.php", {"job_search_history_id": job_search_history_id},function(response){
		$("#job_search_container").html(response);
		var RPC = document.location.protocol + "//" + document.location.host + "/json.php";
		$("#job_location").change(function() {
			addLoadAlert();
			$.rpcJSON(RPC, "location.getTrainLineList", {"session_id": document.cookie.match(/CC=(.*?);/)[1], "prefecture_id": $(this).val()},{}, function(data) {
				$("#train_line").removeAttr("disabled"); 
				populateSelect("train_line", "train_company", $("html").attr("lang"), $("body").data("lang").any, data.result);
				removeLoadAlert();
			});
		});
		$("#train_line").change(function() {
			addLoadAlert();
			$.rpcJSON(RPC, "location.getTrainStationList", {"session_id": document.cookie.match(/CC=(.*?);/)[1], "train_line_id": $(this).val()},{}, function(data) {
				$("#train_station").removeAttr("disabled"); 
				populateSelect("train_station", "train_line", $("html").attr("lang"), $("body").data("lang").any, data.result);
				removeLoadAlert();
			});
		});
		
		$(".checklist_tools .checklist_unselect").click(unSelectAllClick);
		$(".checklist_tools").siblings("select").change(updateSelectedCount);
		
		removeLoadAlert();
	});
}

function editResumeBookmark(resume_bookmark_id, resume_search_history_id, page){
	addLoadAlert();
	$.post("ajax/resume_search_bookmarks.php", {"resume_bookmark_id": resume_bookmark_id, "resume_search_history_id": resume_search_history_id, "page": page},function(response){
		$("#resume_bookmark_container").html(response);
		removeLoadAlert();
	});
}

function getMultiple(ob) { 
	var selected = '';
	var selected = new Array(); 
	if(ob.options) {
		for( var i = 0; i < ob.options.length; i++ )  {
			if( ob.options[ i ].selected )  {
				selected.push(ob.options[ i ].value);
			}
			else if( ob.options[ i ].checked )  {
				selected.push(ob.options[ i ].value);
			};
		}
	}
	else {		
		for( var i = 0; i < ob.length; i++ )  {
			if( ob[ i ].selected )  {
				selected.push(ob[ i ].value);
			}
			else if( ob[ i ].checked )  {
				selected.push(ob[ i ].value);
			};
		}
	}
	return selected.toString();
}

// Load resume form
function employerApplicationDetails(form_name, job_application_id, job_id, page){
	addLoadAlert();
	$.get("ajax/employer_application_details.php", {"form_name": form_name, "job_application_id": job_application_id, "job_id": job_id, "page": page},function(response){
		$("#employer_application_bookmark_tab").removeClass("current");
		$("#employer_application_respond_tab").removeClass("current");
		$("#employer_application_forward_tab").removeClass("current");
		$("#employer_application_blocked_tab").removeClass("current");
		$("#"+form_name+"_tab").addClass("current");
		$("#form_container").html(response);
		removeLoadAlert();
		$.get("ajax/employer_application_details.php", {"form_name": form_name, "job_application_id": job_application_id, "job_id": job_id, "page": page, "json": 1},function(res_json){
			eval("var validate=" + res_json + ";"); 
			$("#form_container").ccValidate(validate);
		});
	});
}

// Load resume form
function employerResumeDetails(form_name, resume_id, resume_search_history_id, job_id, page){
	addLoadAlert();
	
	$.get("ajax/employer_resume_details.php", {"form_name": form_name, "resume_id": resume_id, "resume_search_history_id": resume_search_history_id, "job_id": job_id, "page": page},function(response){
		$("#employer_resume_bookmark_tab").removeClass("current");
		$("#employer_contact_candidate_tab").removeClass("current");
		$("#employer_resume_forward_tab").removeClass("current");
		$("#employer_resume_block_tab").removeClass("current");
		$("#"+form_name+"_tab").addClass("current");
		$("#form_container").html(response);
		removeLoadAlert();
		$.get("ajax/employer_resume_details.php", {"form_name": form_name, "resume_id": resume_id, "resume_search_history_id": resume_search_history_id, "job_id": job_id, "page": page, "json": 1},function(res_json){
			eval("var validate=" + res_json + ";"); 
			$("#form_container").ccValidate(validate);
		});
	});
}

function countChecked(container) {
	var n = $("input:checked", container).length;
	if(n) $(".checklist_total", container).text(n + ($("body").data("lang")["total selected"]));
	else $(".checklist_total", container).text(" ");
}

function loadChecked() {
	$(".checklist").each(function() {
		var container2 = $(this).parents("div")[0];
		countChecked(container2);
	});
}

function initChecklist(container) {
	$(".checklist li",container).mouseover(function() {$(this).addClass("hover");}).mouseout(function() {$(this).removeClass("hover");});
	$(".checklist li:even",container).addClass("alt");	
	$(".checklist li:has(input:checked)",container).addClass("checked");
	$(".checklist li label",container).click(function() {
		if($("input:checked", this).length)
			$($(this).parents("li")[0]).addClass("checked");
		else
			$($(this).parents("li")[0]).removeClass("checked");
    	var container2 = $(this).parents("div")[0];
    	countChecked(container2);
	});
}

// Load feature job
function jobCategoryFeature(job_id, remaining, ed){
	addLoadAlert();
	$.post("ajax/employer_job_category_feature.php",{"job_id": job_id, "remaining": remaining, "ed": ed}, function(response){
		$("#job_category_feature").remove();
		$("#job_category_feature_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Load job form
function jobseekerJobDetails(form_name, job_id, job_search_history_id, page){
	addLoadAlert();
	$.get("ajax/jobseeker_job_details.php", {"form_name": form_name, "job_id": job_id, "job_search_history_id": job_search_history_id, "page": page},function(response){
		$("#jobseeker_apply_tab").removeClass("current");
		$("#job_send_to_friend_tab").removeClass("current");
		$("#jobseeker_add_to_job_basket_tab").removeClass("current");
		$("#"+form_name+"_tab").addClass("current");
		$("#form_container").html(response);
		removeLoadAlert();
		$.get("ajax/jobseeker_job_details.php", {"form_name": form_name, "job_id": job_id, "job_search_history_id": job_search_history_id, "page": page, "json": 1},function(res_json){
			eval("var validate=" + res_json + ";"); 
			$("#form_container").ccValidate(validate);
		});
	} );
}

// Populate auto response (table: job_application_thankyou_template)
function populateAutoResponseMessage(template_id){
	addLoadAlert();
	$.post("ajax/populate_application_auto_response.php",{"template_id": template_id}, function(response){
		$("#custom_reply").remove();
		$("#custom_reply_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate app response message (table: job_application_response_template)
function populateApplicationResponseMessage(message_id){
	addLoadAlert();
	$.post("ajax/populate_application_response_message.php",{"job_application_response_template_id": message_id}, function(response){
		$("#message").remove();
		$("#message_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate Cities (Robust)
function populateCitiesInPrefecture(prefecture_id, city_field_id, array_field, css_class, message, return_function){
	addLoadAlert();
	// params: city id (e.g. city_id, location_city_id, desired_city), return function
	$.get("ajax/populate_cities.php", {"prefecture_id": prefecture_id, "type": city_field_id, "array_field": array_field, "css_class": css_class, "message": message, "return_function": return_function}, function(response){
		$("#"+city_field_id).remove();
		$("#"+city_field_id+"_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate company description (new - use FCK editor)
function populateCompanyDescription(lang){
	if( !lang ) return false;
	addLoadAlert();
	$.post("ajax/populate_company_description.php",{"lang": lang}, function(response){
		$("#company_description_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate cover letter for job seeker
function populateCoverLetter(cover_letter_id, job_seeker_id){
	addLoadAlert();
	$.post("ajax/populate_cover_letter.php", {"cover_letter_id": cover_letter_id, "job_seeker_id": job_seeker_id}, function(response){
		$("#coverletter").remove();
		$("#coverletter_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate employer contact name
function populateEmployeeName( employer_consultant_id ) {
	addLoadAlert();
	$.post("ajax/populate_employee_name.php", {"employer_consultant_id": employer_consultant_id}, function(response){
		$("#name_container").html(response);
		removeLoadAlert();
	});
	return false;
}

// Fill in location select boxes from postcode details
function populateFromPostcode(postcode, params){
	var foo = eval(params);
	addLoadAlert();
	for( var $i=0; $i<foo.length; $i++ ){
		// usual $.post method didnt work. this works, but its alot of AJAX calls... 
		$("#"+foo[$i]).remove();
		$("#"+foo[$i]+"_container").load("ajax/populate_from_postcode.php", {"postcode": postcode, "variable": foo[$i]} );
	};
	// have to slow this down because javascript jumps the for loop and removes it instantly otherwise.
	var temp = setTimeout('removeLoadAlert()',600);
	return false;
};

// Fill in job category select box
function populateJobCategory(job_group, array_field, css_class, message){
	addLoadAlert();
	$.get("ajax/select_job_category.php", {"job_group": job_group, "array_field": array_field, "css_class": css_class, "message": message}, function(response){
		$("#job_category_container").html(response);
		$("#job_category_container .checklist_target").change(updateSelectedCount);
		$("#job_category_container .checklist_tools .checklist_unselect").click(unSelectAllClick);
		removeLoadAlert();
	});
	return false;
};

function populateMultipleCheckJobCategories(job_group, select_name, container){
	addLoadAlert();
	var selected = getMultiple($("input[name=\"" + select_name + "[]\"]"));
	$.post("ajax/multiple_job_category.php", { "job_group": job_group, "select_name": select_name, "selected": selected },function(response){
		$(container).html(response);
		removeLoadAlert();
		initChecklist($(container));
    	countChecked(container);
	} );
	return true;
};

function populateMultipleCheckTrainLines(prefectures) {
	addLoadAlert();
	var selected = getMultiple($("input[name=\"train_line[]\"]"));
	$.post("ajax/multiple_train_line.php", { "prefectures": prefectures, "selected": selected },function(response) {
		$("#train_line_container").html(response);
		initChecklist($("#train_line_container"));
    	countChecked("#train_line_container");
		removeLoadAlert();
	});
	return true;
};

function populateMultipleCheckTrainStations(train_lines) {
	addLoadAlert();
	var selected = getMultiple($("input[name=\"train_station[]\"]"));
	$.post("ajax/multiple_train_station.php", { "train_lines": train_lines, "selected": selected },function(response) {
		$("#train_station_container").html(response);
		initChecklist($("#train_station_container"));
    	countChecked("#train_station_container");
		removeLoadAlert();
	});
	return true;
};

function populateMultipleJobCategories( job_group, select_name, css_class, container, category_limit ){
	addLoadAlert();
	$.post("ajax/multiple_job_category.php", { "job_group": job_group, "selected": getMultiple($("#" +select_name).get(0)), "select_name": select_name, "css_class": css_class, "category_limit": category_limit },function(response){
		$(container).html(response);
		$(".checklist_target", container).change(updateSelectedCount);
		$(".checklist_tools .checklist_unselect", container).click(unSelectAllClick);
		removeLoadAlert();
	} );
	return false;
};

// Populate contact name and email (references special styles for suggestion box)
function populateNameEmail(query){
	if( query.length == 0 ){
		$("#contact_name_suggestion").remove();
		return false;
	}
	addLoadAlert();
	$.post("ajax/populate_name_email.php",{"query": query}, function(response){
		if( response.length > 1 ){
		// if there are any results, append new suggestion container and show
			if( $("#contact_name_suggestion") ){
				$("#contact_name_suggestion").remove();
				$("#contact_name_wrap").append('<div id="contact_name_suggestion" style="position: absolute; width: 308px; font-size: 10px; background:#FFFFFF"></div>');
			}
			// remove any previous list of suggestions and append new list.
			$("ul.suggestions").remove();
			$("#contact_name_suggestion").append(response);
		} else {
			$("#contact_name_suggestion").remove();
		}
		removeLoadAlert();
	});
	return false;
};

// Populate prefectures and countries depending on region selected
function populatePrefectureCountry(job_location, array_field, css_class){
	addLoadAlert();
	$.get("ajax/select_prefecture_country.php",{"job_location": job_location, "array_field": array_field, "css_class": css_class}, function(response){
		$("#prefecture_country_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate Resume Contact Message (table: resume_contact_template)
function populateResumeContactMessage(message_id){
	addLoadAlert();
	$.post("ajax/populate_contact_message.php",{"resume_contact_template_id": message_id}, function(response){
		$("#message").remove();
		$("#message_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate stations on trainline
function populateStations(line_id){
	addLoadAlert();
	$.post("ajax/populate_train_station.php", {"line_id": line_id}, function(response){
		// remove old select box and append the new one (returned response)
		$("#train_station_id").remove();
		$("#train_station_id_container").html(response);
		removeLoadAlert();
	});
	return false;
};

// Populate receiver name and email
function populateReceiverNameEmail(query){
	var type = 'receiver';
	if( query.length == 0 ){
		$("#contact_name_suggestion").remove();
		return false;
	}
	addLoadAlert();
	$.post("ajax/populate_name_email.php",{"query": query, "type": type}, function(response){
		if( response.length > 1 ){
			// if there are any results, append new suggestion container and show
			if( $("#contact_name_suggestion") ){
				$("#contact_name_suggestion").remove();
				$("#receiver_name_wrap").append('<div id="contact_name_suggestion" style="position: absolute; width: 308px; font-size: 10px; background:#FFFFFF"></div>');
			}
			// remove any previous list of suggestions and append new list.
			$("ul.suggestions").remove();
			$("#contact_name_suggestion").append(response);
		} else {
			$("#contact_name_suggestion").remove();
		}
		removeLoadAlert();
	});
	return false;
};

// part 2 of the populate name/email function
function updateField(name, email, type){
	if( type == 'receiver' ){
		$("#receiver_name").attr("value",name);
		$("#receiver_email").attr("value",email);
		$("#contact_name_suggestion").remove();
	} else {
		$("#contact_name").attr("value",name);
		$("#contact_email").attr("value",email);
		$("#contact_name_suggestion").remove();
	}
	return false;
};

// Populate contact_name and contact_email from the drop down select box.
function populateNameEmailSelect(employer_consultant_id){
	addLoadAlert();
	$.post("ajax/populate_name_email_select.php",{"employer_consultant_id": employer_consultant_id}, function(response){
		eval(response);
		removeLoadAlert();
	});
	return false;
}
// Populate contact_name and contact_email from the drop down select box.
function populateReceiverNameEmailSelect(employer_consultant_id){
	var type = 'receiver';
	addLoadAlert();
	$.post("ajax/populate_name_email_select.php",{"employer_consultant_id": employer_consultant_id, "type": type}, function(response){
		eval(response);
		removeLoadAlert();
	});
	return false;
}

// Populate Select box, keeping selected options selected
function populateSelect(select_id, optgroup_id, lang, any_text, options) {
	var $select = $("#" + select_id);
	var selected = [];
	$("option:selected", $select).each(function(i) { selected.push(this.value); });
	
	//clear select box
	$select.html("<option value=\"\">"+any_text+"</option>");
	
	if(options.length) {
		var v="";
		prev_v="";
		$.each(options, function(k,v) {
			if(v[optgroup_id+"_"+lang] != prev_v) {
				$select.append("<optgroup label=\""+v[optgroup_id + "_" + lang] +"\" title=\""+v[optgroup_id + "_" + lang]+"\"></optgroup>");
			}
			var optgrp = $("optgroup:last-child", $select);
			var select_str = "";
			$.each(selected, function(k2,v2) { if(v2 == v[select_id + "_id"]) { select_str = "selected=\"selected\""; }});
			optgrp.append("<option value=\"" + v[select_id + "_id"] + "\" " + select_str + "/>");
			$(":last-child", optgrp).text(v[select_id + "_" + lang]);
			prev_v = v[optgroup_id+"_"+lang];
		});
	}
	// if nothing selected, select the 1st option ('any').
	if(!$("option:selected", $select).length) $("> option:first-child", $select).attr("selected","selected");
		
	//trigger change.
	$select.change();
	
	//disable if nothing to select
	if(!options.length) $select.attr("disabled", "disabled");
}

// Update select box to match
function updateConsultantsSelect(employer_consultant_id, type){
	if( type == 'receiver' ){
		$("#rec"+employer_consultant_id).attr("selected","selected");
	} else {
		$("#con"+employer_consultant_id).attr("selected","selected");
	}
	return false;
}

// Populate train line / station:
function populateLines(prefecture_id, message){
	addLoadAlert();
	$.post("ajax/populate_train_line.php", {"prefecture_id": prefecture_id}, function(response){
																					
		// remove old select box and append the new one (returned response)
		$("#train_line_id").remove();
		$("#train_line_id_container").html(response);

		// append empty train station opt group
		$("#train_station_id").remove();
		$("#train_station_id_container").append('<select name="train_station_id" id="train_station_id" class="field" disabled="disabled"><option value="" selected="selected">'+message+'</option></select>');
		removeLoadAlert();
	});
	return false;
};

// Resume Contact Reminder
function resumeContactReminder(resume_id,resume_contact_id){
	addLoadAlert();
	$.post("ajax/resume_contact_reminder.php", {"resume_id": resume_id,"resume_contact_id": resume_contact_id},function(response){
		$("#"+resume_contact_id+"_container").html(response);
		removeLoadAlert();
	} );
};

// Select All Above/Below
// target is id of select
// criteria - 0 for all, -1 for below, +1 for above.
function selectMultipleAll(target, criteria) {
	var $target = $("select#" + target);
	if(criteria > 0) { // select above
		// determin minimum selected value
		var $options = $("option[selected]", $target);
		var min = $options.eq(0).val();
		$options.each(function(i) {
			val = $(this).val();
			if(val != "" && val < min) min = val;
		});
		// select all options with value above that of min value
		$("option", $target).each(function(i) {
			var $option = $(this);
			var val = $option.val();
			if(val != "" && val >= min) $option.attr("selected", "selected");
		});
	}
	else if(criteria < 0) { // select below
		// determine maximum selected value
		var $options = $("option[selected]", $target);
		var max = $options.eq(0).val();
		$options.each(function(i) {
			val = $(this).val();
			if(val != "" && val > max) max = val;
		});
		// select all options with value above that of max value
		$("option", $target).each(function(i) {
			var $option = $(this);
			var val = $option.val();
			if(val != "" && val <= max) $option.attr("selected", "selected");
		});
	}
	else {
		// select all
		$("option[value!=\"\"]", $target).attr("selected", "selected");
		$("option[value=\"\"]", $target).removeAttr("selected");
	}
};

// aliases
function selectMultipleAllAbove(target) { selectMultipleAll(target, 1); };
function selectMultipleAllBelow(target) { selectMultipleAll(target, -1); };

// uncheck all
function unCheckAll(target, child) {
	var $target = $("input[@name='" + target + "[]']");
	var container = $($target).parents("div")[0];
	$("input[@type='checkbox']", container).each(function() {
		this.checked = false;
		$($(this).parents("li")[0]).removeClass("checked");
	});
	countChecked(container);
	if(child == "train_line") {
		populateMultipleTrainLines("");
		populateMultipleTrainStations("");
	}
	else if(child == "train_station") {
		populateMultipleTrainStations("");
	}
	else if(child == "job_category" || child == "experienced_job_category" || child == "desired_job_category") {
		var child_container = "#" + child + "_container";
		populateMultipleJobCategories("", "", child_container);
	}
};

function unSelectAll(target) {
	$(target).val("").change();
}

//custom event handlers
function unSelectAllClick(event) {
	unSelectAll($(event.target).parent().siblings("select")[0]);
	return false;
}

function updateSelectedCount(event) {
	$(".checklist_total_num", $(event.target).siblings(".checklist_tools")).text($("option:selected[value!=\"\"]", event.target).length);
}

//enable unselect links
$(function() {
	$(".checklist_tools .checklist_unselect").click(unSelectAllClick);
	$(".checklist_tools").siblings("select").change(updateSelectedCount);
});