// load cookie data for Job Listing
var myHistory = new JobListing();
myHistory.load();
var inInitProgress = true;
	
// objects for disciplines and locations
var disciplineList = new Object();
var disciplineSelectIndex = 0;

var employmentList = new Object();
var employmentSelectIndex = 0;

var locationList = new Object();
var locationSelectIndex = 0;

// title drop downlist
var titleList = new Object();
var titleSelectIndex = 0;

// only for professional board
if ('professional' == boardName) {
	// education dropdownlist
	var educationList = new Object();
	var educationSelectIndex = 0;
	
	// gender dropdownlist
	var genderList = new Object();
	var genderSelectIndex = 0;
}

// only for job board
if ('backend' == boardType) {
	var priorityList = new Object();
	var prioritySelectIndex = 0;

	var consultantList = new Object();
	var consultantSelectIndex = 0;

	var employerList = new Object();
	var employerSelectIndex = 0;
}

// remove all items from dropdown list
function removeListItems(obj) {
	while(obj.length > 0) {
		obj.remove(0);
	}	
}

// add item to dropdown list
function addListItems(obj, items)
{
	for (var i in items) {
		// create a new item
		var item =document.createElement('option');
		item.value = i;
		if (null != items[i]['count']) {
			item.text = items[i]['text'] + '(' + items[i]['count'] + ')';
			
			if (0 == items[i]['count'])	{
				item.className = 'disabled';
				item.disabled = true;
			}
		} else {
			item.text = items[i]['text'];
		}
			
		// add items to object
		try {
			obj.add(item, null); // standards compliant
		} catch(ex) {
			obj.add(item); // IE only
		}
	}	 
}

// reset jobs count in dropdown list
function resetJobCounter(obj)
{
	for (var i in obj) {
		if (null != obj[i]['count']) {
			obj[i]['count'] = 0;
		}
	}
}

// re-populate dropdown discipline and location list etc.
function repopulateList()
{
	// remove all items from list and readd them to list
	removeListItems($("#disciplines")[0]);
	addListItems($("#disciplines")[0], disciplineList);
	$("#disciplines")[0].selectedIndex = disciplineSelectIndex;
	
	removeListItems($("#locations")[0]);
	addListItems($("#locations")[0], locationList);
	$("#locations")[0].selectedIndex = locationSelectIndex;	

	// for title dropdown list
	removeListItems($("#titles")[0]);
	addListItems($("#titles")[0], titleList);
	$("#titles")[0].selectedIndex = titleSelectIndex;
	
	removeListItems($("#employment")[0]);
	addListItems($("#employment")[0], employmentList);
	$("#employment")[0].selectedIndex = employmentSelectIndex;
	
	// only for professional board
	if ('professional' == boardName) {
		// for education dropdown list
		removeListItems($("#educations")[0]);
		addListItems($("#educations")[0], educationList);
		$("#educations")[0].selectedIndex = educationSelectIndex;	
		
		// for genders dropdown list
		removeListItems($("#genders")[0]);
		addListItems($("#genders")[0], genderList);
		$("#genders")[0].selectedIndex = genderSelectIndex;	
	}

	// for job board only
	if ('backend' == boardType) {	
		removeListItems($("#priority")[0]);
		addListItems($("#priority")[0], priorityList);
		$("#priority")[0].selectedIndex = prioritySelectIndex;

		removeListItems($("#consultants")[0]);
		addListItems($("#consultants")[0], consultantList);
		$("#consultants")[0].selectedIndex = consultantSelectIndex;	

		removeListItems($("#employers")[0]);
		addListItems($("#employers")[0], employerList);
		$("#employers")[0].selectedIndex = employerSelectIndex;	
	}
}
                                      
// filter job listing with conditions specified
function filterJobListing(reset, page) {
	 $("#shade").addClass("mask");
	 
	 // send request	 
	 var parameters = 'optype:filter;';
	 // for job board only
	 if (!reset) {
		 $("#fieldset-filter li select").each(function() {
			 parameters += $(this)[0].id + ':' + $(this)[0].value + ';';		 
		 });

		// only for professional board
		if ('professional' == boardName) {		 
			 // check if there are additional conditions specified
			 $("#fieldset-filter li input").each(function() {
				 if (parseInt($(this)[0].value) >= 0) {
					 parameters += $(this)[0].id + ':' + $(this)[0].value + ';';
				 } else if ('submitfilter' != $(this)[0].id && 'resetfilter' != $(this)[0].id) {
					 $(this)[0].value = '';
				 }
			 });
		}
	 } else { 
		 $("#fieldset-filter li select").each(function() {
			 parameters += $(this)[0].id + ':;';		 
		 });
	 }
	 
	 // attach page as necessary
	 if ('' != page) {
		 parameters += 'page:' + page;
	 }
	 
	 
	 // send requst...
	 // alert (serverPath + '?parameters=' + parameters);
	 $.post(serverPath, {parameters: parameters}, function(xml) {
	 	// handle Filter response
	 	handleFilterResponse(xml);
	});
	 
	$("#optype")[0].value = 'filter';
}

// filter job listing with keyword specified
function searchJobListing(reset, page) {
	$("#shade").addClass("mask");

	// send request	 
	var keyword = $("#keyword")[0].value;

	// reset job listing 
	if (reset || '' == keyword) {
		filterJobListing(reset, 1);
		return;
	}

	var parameters = 'optype:search;';
	$("#fieldset-filter li select").each(function() {
		parameters += $(this)[0].id + ':;';		 
	});
	
	parameters += 'keyword:' + keyword + ';'; 
	
	// attach page as necessary
	 if ('' != page) {
		 parameters += 'page:' + page;
	 }
	 
	// send request
	$.post(serverPath, {parameters: parameters}, function(xml) {
		// handle Filter response
		handleFilterResponse(xml);
	});
	$("#optype")[0].value = 'search';
}

// reset all filter forms in left layer
function resetFilterForms()
{
	// reset all forms in left layer
	$(".leftnav form").each(function() {
		this.reset();
	});
	
	disciplineSelectIndex = 0;
	locationSelectIndex = 0;
	titleSelectIndex = 0;
	employmentSelectIndex = 0;

	// only for professional board
	if ('professional' == boardName) {
		educationSelectIndex = 0;
		genderSelectIndex = 0;
	}
	
	// only for job board
	if ('backend' == boardType) {	
		prioritySelectIndex = 0;
		consultantSelectIndex = 0;
		employerSelectIndex = 0;
	}
		
	myHistory.reset();
}

// parse a string and check if the number in it is lareger than 0
function isLargerZero(string) {
	var count = string.substring(string.indexOf('(') + 1, string.indexOf(')'));
	if (count > 0) {
		return true;
	} else {
		return false;
	}
}

// active or deactive job or professional
function activeListingItem(e, linkName) {
	e.preventDefault();

	// get id and parameter
	var params = linkName.split(':');
	var id = params[0];
	var status = params[1];
	
	// set the script path on server side
	$.post(activePath, {id: id, status: status}, function(xml) {
	 	// handle Filter response
	 	handleStatusResponse(xml);
	});	
}

// set table sorter for listing
function registerClickEvent() {
	// add markup to container and apply click handlers to anchors
	$(".paginator li a").click(function(e){
		e.preventDefault();
		
		// check if the pagination based on a filter or search operation
		var optype = $("#optype")[0].value;
		var page = $(this)[0].name;
		
		// record the page number once user clicked page number
		myHistory.currentPage = page;
		
		if ('filter' == optype) {
			filterJobListing(false, page);
		} else {
			searchJobListing(false, page);
		}
	});	
	
	$("#career_table .cellTitle a").click(function() {
		// clear unused cookie first and create new one
		myHistory.reset();
		
		// save career board settings		
		// according to job link to get its id
		var linkHref = $(this)[0].href;
		myHistory.setCurrentJobID(linkHref);
		
		myHistory.setJobIDSet($("#idset")[0].value);
		myHistory.setOperationType($("#optype")[0].value);
		myHistory.setDiscipline($("#disciplines")[0].selectedIndex);
		myHistory.setLocation($("#locations")[0].selectedIndex);
		myHistory.setKeyword($(".leftnav #keyword")[0].value);	

		// only for job board
		if ('backend' == boardType) {		
			myHistory.setPriority($("#priority")[0].selectedIndex);
			myHistory.setEmployment($("#employers")[0].selectedIndex);
			myHistory.setConsultant($("#consultants")[0].selectedIndex);
		}
	});	
	
	// only for backend boards include professional and career board
	if ('backend' == boardType) {
		$("#career_table .cellStatus a").click(function(e) {
			var linkName = $(this)[0].name;
			activeListingItem(e, linkName);
		});
	}
}


// handle Filter response
function handleStatusResponse(xml) {
	var id = '#' + $("id", xml).text();
	var status = $("link", xml).text();
	if ('null' != status) {
		$("#career_table").find(id).find('#status').html(status);
	}

	registerClickEvent();
}

// init the current filter condition
function initFilterConditionByID(ctrlID, ctrlList) {
	ctrlID = '#' + ctrlID;
	var disciplineLength = $(ctrlID)[0].length;	
	for(i=0; i<disciplineLength; i++) {	
		// elimiate the items with null value, example: [Disciplines:]
		var key = $(ctrlID)[0][i].value;			
		ctrlList[key] = new Object();
		var discipline = $(ctrlID)[0][i].text;
		ctrlList[key]['text'] = discipline;
		
		if ('' != $(ctrlID)[0][i].value) {
			ctrlList[key]['count'] = 0;
			ctrlList[key]['text'] = discipline.substring(0, discipline.indexOf('('));
			
			// check if we need to disable this item
			if (!isLargerZero(discipline)) {
				$(ctrlID)[0][i].className = 'disabled';
			}
		}
	}
}

// set the current search condition
function setFilterConditionByID(ctrlID, savedCtrlIndex, sleep) {
	ctrlID = '#' + ctrlID;
	if (sleep) {
		myHistory.sleep(300);
	}
	
	var ctrlSelectIndex = parseInt(savedCtrlIndex);
	if (ctrlSelectIndex > 0) {
		$(ctrlID)[0].selectedIndex = ctrlSelectIndex;
		$(".leftnav " + ctrlID).change();
	}	
}

// init Filter conditions for AJAX functionality
function initFilterConditions() {
	// init the current filter conditions: Disciplines
	initFilterConditionByID('disciplines', disciplineList);
	initFilterConditionByID('locations', locationList);
	initFilterConditionByID('titles', titleList);
	initFilterConditionByID('employment', employmentList);

	// only for professional board
	if ('professional' == boardName) {		
		initFilterConditionByID('educations', educationList);
		initFilterConditionByID('genders', genderList);
	}

	// only for job board
	if ('backend' == boardType) {	
		initFilterConditionByID('priority', priorityList);
		initFilterConditionByID('consultants', consultantList);
		initFilterConditionByID('employers', employerList);
	}
	
	// just change the value of filter conditions
	// or fire the keyword search
	if ('filter' == myHistory.operationType) {
		setFilterConditionByID('disciplines', myHistory.discipline, false);
		setFilterConditionByID('locations', myHistory.location, true);
		setFilterConditionByID('titles', myHistory.title, true);
		setFilterConditionByID('employment', myHistory.employment, true);
		
		// only for professional board
		if ('professional' == boardName) {			
			setFilterConditionByID('educations', myHistory.education, true);
			setFilterConditionByID('genders', myHistory.gender, true);
		}
		
		// for job board only
		if ('backend' == boardType) {
			setFilterConditionByID('priority', myHistory.priority, true);
			setFilterConditionByID('employers', myHistory.employer, true);
			setFilterConditionByID('consultants', myHistory.consultant, true);
		}
	} else if ('search' == myHistory.operationType) {	
		// perform filter search with keyword specified
		$(".leftnav #keyword")[0].value = myHistory.keyword;
		performSearchOperation();
	} else {
		// TODO
	}
}

// perform filter with conditions specified
function performFilterOperation(filterItem, reset) {
	$(".leftnav #resetfilter").removeClass("hide");
	
	// filter job listing only for job count > 0
	if (isLargerZero(filterItem) || reset)
	{
		var page = 1;
		if (inInitProgress) {
			page = myHistory.currentPage;
			if ('' == page) page = 1;
		}
		filterJobListing(false, page);
	}
} 

// perform filter search with keyword specified
function performSearchOperation() {		
	$(".leftnav #resetsearch").removeClass("hide");
	
	var page = 1;
	if (inInitProgress) {
		page = myHistory.currentPage;
		if ('' == page) page = 1;
	}
	searchJobListing(false, page);
}

// take user to the specified page
function filterJobListingEx(page) {
	$(".leftnav #resetfilter").addClass("hide");
	$(".leftnav #resetsearch").addClass("hide");

	// filter job listing with null conditions
	filterJobListing(true, page);
}

// fire up change event
function fireUpChangeEvent(e, ctrlID, ctrlIndex) {
	e.preventDefault();
	ctrlID = '#' + ctrlID;
	
	ctrlIndex = $(ctrlID)[0].selectedIndex;
	
	// perform filter with conditions specified
	var reset = ('' == $(ctrlID)[0].value);
	performFilterOperation($(ctrlID)[0][ctrlIndex].text, reset);

	// move focus to reset button
	$(".leftnav #resetfilter").focus();
	
	return ctrlIndex;
	
}

$(document).ready(function() {	
	// reset job listing
	$(".leftnav #resetfilter").addClass("hide");
	$(".leftnav #resetfilter").click(function(e) {
		e.preventDefault();	
		$(".leftnav #resetfilter").addClass("hide");
		$(".leftnav #resetsearch").addClass("hide");

		// filter job listing with null conditions
		filterJobListing(true, 1); 

		// reset all filter forms in the left layer
		resetFilterForms();		
	});
	
	// filter job listing according to conditions specified
	$(".leftnav #locations").change(function(e) {
		locationSelectIndex = fireUpChangeEvent(e, 'locations');
	});	
	
	// filter job listing according to discipline specified
	$(".leftnav #disciplines").change(function(e) {
		disciplineSelectIndex = fireUpChangeEvent(e, 'disciplines');
	});
	
	$(".leftnav #employment").change(function(e) {
		employmentSelectIndex = fireUpChangeEvent(e, 'employment');
	});
	
	// filter job listing according to discipline specified
	$(".leftnav #titles").change(function(e) {
		titleSelectIndex = fireUpChangeEvent(e, 'titles');
	});
	
	// only for professional board
	if ('professional' == boardName) {	
		
		// filter job listing according to discipline specified
		$(".leftnav #educations").change(function(e) {
			educationSelectIndex = fireUpChangeEvent(e, 'educations');
		});
		
		// filter job listing according to discipline specified
		$(".leftnav #genders").change(function(e) {
			genderSelectIndex = fireUpChangeEvent(e, 'genders');
		});
		
		// filter job listing with keyword specified
		$(".leftnav #submitfilter").click(function(e) {
			e.preventDefault();
			$(".leftnav #resetfilter").removeClass("hide");
			
			// perform filter search with experience, age and hours specified
			filterJobListing(false, 1);
		});
	}
	
	// only for job board
	if ('backend' == boardType) {
		$(".leftnav #priority").change(function(e) {
			prioritySelectIndex = fireUpChangeEvent(e, 'priority');
		});

		// filter job listing according to consultant specified
		$(".leftnav #consultants").change(function(e) {
			consultantSelectIndex = fireUpChangeEvent(e, 'consultants');
		});

		// filter job listing according to consultant specified
		$(".leftnav #employers").change(function(e) {
			employerSelectIndex = fireUpChangeEvent(e, 'employers');
		});
	}
	
	// reset job listing
	$(".leftnav #resetsearch").addClass("hide");
	$(".leftnav #resetsearch").click(function(e) {
		e.preventDefault();
	
		// take user to the first page
		filterJobListingEx(1);
		
		// reset all filter forms in left layer
		resetFilterForms();			
	});	
	
	// filter job listing with keyword specified
	$(".leftnav #submitsearch").click(function(e) {
		e.preventDefault();

		// perform filter search with keyword specified
		performSearchOperation();
	});

	$("#career_table").tablesorter({
		// striping looking
		widgets: ['zebra']	
	});
	
	// set table sorter for listing
	registerClickEvent();
	
	// initialize Filter conditions for AJAX functionality
	initFilterConditions();	
	inInitProgress = false;
});

