var jobSectorEmpty = true;
var jobLocationEmpty = true;
var jobLondonEmpty = true;
function setLoader(id)
{
	var e = document.getElementById(id);
	if(e != null)
	{
		e.innerHTML = '<div style="height: 340px; margin-left: 545px;"><img src="/v3/gfx/loader.gif"></div>';
	}
}
function showJobSector() 
{
	$.ajax({
            url: "v3/blocks/jobsector.shtml",
            success: function(responseText) {
							document.getElementById("jobSector").innerHTML=responseText;
							addCommas("number");
            },
            error: function() {
            }
        });

	
}


function loadSWFMap()
{
	var map = new SWFObject("/v3/swf/map/clickajob_uk_map.swf", "map", "250", "410", "8","#000000");
	map.useExpressInstall("/v3/swf/expressinstall.swf");
	map.addParam("wmode", "transparent");
	map.addVariable("xmlFile", escape("/v3/swf/map/xml/uk_counties.xml")); 
	map.write("clickajob-map");
}

function loadSWFMapLondon()
{
	var map = new SWFObject("/v3/swf/map/clickajob_london_map.swf", "map", "550", "410", "8","#000000");
	map.useExpressInstall("/v3/swf/expressinstall.swf");
	map.addParam("wmode", "transparent");
	map.addVariable("xmlFile", escape("/v3/swf/map/xml/london_cities.xml")); 
	map.addVariable("countFile", escape("/v3/swf/map/xml/job_count.xml")); 
	map.write("clickajob-map-london");
}

function showLocation() 
{
	$.ajax({
            url: "v3/blocks/location.shtml",
            success: function(responseText) {
							document.getElementById("location").innerHTML=responseText;
							addCommas("number");
							loadSWFMap();
            },
            error: function() {
            }
        });
}

function showLondon() 
{
	$.ajax({
            url: "/v3/blocks/london.shtml",
            success: function(responseText) {
							document.getElementById("london").innerHTML=responseText;
							addCommas("number");
							loadSWFMapLondon();
            },
            error: function() {
            }
        });
}

function displayJobs(ccode)
{
	linkUrl =  "/cgi-bin/user.cgi?module=vacancy_search&save_search=1&task=search_results&sort=&vacancy_type=&keywords=&postcode=" + ccode + "&min_salary=0&max_salary=99999999";
	this.location.href = linkUrl;
}

/* AJAX function for getting ClickAJob news*/
function showNews()
{
		$.ajax({
            url: "/cgi-bin/user.cgi?module=news&task=get_news_for_frontpage",
            success: function(responseText) {
						document.getElementById("contentNewsContent").innerHTML=responseText;
            },
            error: function() {
            }
        });	
	
}

/* AJAX function for getting ClickAJob content*/
function showCareer()
{
		$.ajax({
            url: "/v3/blocks/content_career_centre.shtml",
            success: function(responseText) {
						document.getElementById("contentCareerContent").innerHTML=responseText;
            },
            error: function() {
            }
        });	
	
}

function loadJobSector()
{
	setLoader('jobSector');
	showJobSector();
}
function sbChangeTab(id) { 
	document.getElementById('searchboxKL').style.display = (id == 'searchboxKL') ? 'block' : 'none';
	document.getElementById('searchboxJS').style.display = (id == 'searchboxJS') ? 'block' : 'none';
	document.getElementById('searchboxL').style.display = (id == 'searchboxL')  ? 'block' : 'none';	
	if(id == "searchboxJS" && jobSectorEmpty) {
		loadJobSector();
		jobSectorEmpty = false;
	}
	
	if(id == "searchboxL" && jobLocationEmpty) {
		showLocation();	
		jobLocationEmpty = false;
	}

	return false;
}

function check_salary(minValue, maxId) {
    var maxElm = document.getElementById(maxId);
    for (var i=0; maxElm.options[i]; i++) {
        if (parseInt(maxElm.options[i].value) < parseInt(minValue)) maxElm.options[i].disabled = true;
        else maxElm.options[i].disabled = false;
    }
    maxElm.options[maxElm.options.length-1].selected = true;
}

function check_max_salary(maxElm, minId) {
    var minValue = document.getElementById(minId).value;
    var maxValue = maxElm.value;
    if (parseInt(minValue) > parseInt(maxValue)) {
        for (var i=0; maxElm.options[i]; i++) {
            if (parseInt(minValue) < parseInt(maxElm.options[i].value)) {
                maxElm.options[i].selected = true;
                break;
            }
        }
    }

}



function swapImage(destImage, element) {
	element.src = destImage;
}

function keyUpHandler(event) {
	if(event.keyCode == 13) {//enter 
		var a = document.getElementById('searchboxFormKeywordsId').value;
		if(a == 'Enter skill or Job Title') {
			document.getElementById('searchboxFormKeywordsId').value = '';
		}
		a = document.getElementById('searchboxFormLocationId').value;
		if(a == 'Enter town or postcode') {
			document.getElementById('searchboxFormLocationId').value = '';
		}
		__validate(document.getElementById('adsfl-id')); //adsfl-id WTF?
	}
}

var newsShown = false;
var careerShown = false;
function contentChangeTab(id) { 
	document.getElementById('contentServices').style.display = (id == 'contentServices') ? 'block' : 'none';
	document.getElementById('contentCareer').style.display = (id == 'contentCareer') ? 'block' : 'none';
	document.getElementById('contentNews').style.display = (id == 'contentNews') ? 'block' : 'none';
	if(id == "contentNews" && document.getElementById('contentNewsContent') && !newsShown) {
		showNews();	
		newsShown = true;
	}
	else(id == "contentCareer" && document.getElementById('contentCareerContent') && !careerShown)
	{
		showCareer();
		careerShown = true;
	}
	
	return false;
}

function loadAdvert()
{
	var advert = new SWFObject("/v3/swf/Rectangle_300x250_01.swf", "advert", "300", "250", "8","#000000");
	advert.useExpressInstall("/v3/swf/expressinstall.swf");
	advert.addParam("wmode", "transparent");
	advert.write("clickajob-advert");
}

function changeMapEntryClass(task, id, isHover)
{
	var e = null;
	if(task == "region_areas")
	{
		e = document.getElementById("region_"+id);
	}
	else if(task== "area_counties")
	{
		e = document.getElementById("area_"+id);
	}
	else if(task == "county_cities")
	{
		e = document.getElementById("county_"+id);
	}
	
	//for fucking IE
	if(!isHover) 
	{
		e.style.textDecoration = "none";
	}
	else {
		e.style.textDecoration = "underline";
	}
}


function hoverMapEntry(task,id) {
	changeMapEntryClass(task, id, true);
}

function unhoverMapEntry(task,id) {
	changeMapEntryClass(task, id, false)
}

function hoverMapAndFlashEntry(task, id, root_task, root_id) {
	//flashLoadMap(task,id);
	if(root_task != null && root_id != null)
	{
		flashLoadMap(root_task, root_id);
	}
	else
	{
		flashLoadMap(task,id);
		
	}
	hoverMapEntry(task,id);
}

function unhoverMapAndFlashEntry(task,id, root_task, root_id) {
	flashLoadMap(root_task, root_id, '1');
	unhoverMapEntry(task,id);
}

//loads map and updates flash map
function loadMapAndUpdate(task, id) 
{
	flashLoadMap(task, id, '2');
	loadMap(task, id);
	
}

//indicate whether we are on city level
var isOnCityLevel = false;

function loadMap(task, id)
{
	//workaround for bug in flash
	task = task == "region_list" ? "regions_list" : task;
	var placeholder = "locations";
	var loc = document.getElementById(placeholder);
	loc.innerHTML = "<img src='/v3/gfx/loader.gif'>";
	$.ajax({
            url: "/cgi-bin/user.cgi?module=vacancy_search&task=" + escape(task) +"&id=" + escape(id),
            success: function(responseText) {
							if(task == "county_cities")
							{
								//hide map
								$("td#clickajob-map-td").hide();
								//hide content so we don't se flickering
								$("#" + placeholder).hide();
								//indicate that we are on city level
								isOnCityLevel = true;
							}
							document.getElementById(placeholder).innerHTML=responseText;
							addCommas("number");
							if(task == "county_cities")
							{
								//show again
								$("#" + placeholder).show();
							}
							else if(isOnCityLevel)
							{
								//we want to load 
								$("#" + placeholder).show();
								

								flashMovie = document.getElementById("map");							
								
								if(!flashMovie.flashLoadMap)
								{
									loadSWFMap();
									setTimeout("checkIfIsLoaded('" + task + "','" +id+ "')", 50);
								}
								
								
								//show map
								$("td#clickajob-map-td").show();
								//this is for IE, in case we need to reload the map
								//we are not on city level
								isOnCityLevel =  false;
							}
            },
            error: function() {
            }
  });
	return false;
}

function loadSubcategory(subcategoryUrl)
{
	setLoader("jobSector");
	$.ajax({
		   	url: "/cgi-bin/user.cgi?module=vacancy_search&task=subcategories&id=" + escape(subcategoryUrl),
            //url: "/catalog/" + escape(subcategoryUrl),
			dataType: "xml",
            success: function(xml) {
							var jobSector = document.getElementById("jobSector"); 
							var myeval = xml.getElementsByTagName('eval').item(0).childNodes[0].nodeValue;
							var page = xml.getElementsByTagName('page').item(0).childNodes[0].nodeValue;
							eval(myeval);
							jobSector.innerHTML=page;
							jobSector.className="";
							addCommas("number");
							
        					setMovableBox('tableCategories', 'tableCategoriesMore', 13, 'viewAll', 'block', 'All ' + categoryName + ' job titles&hellip;<img src="/v3/gfx/arrow_down_blue.gif">', 'Popular job titles only&hellip;<img src="/v3/gfx/arrow_up_blue.gif">');
            },
            error: function() {
            }
 	});
	return false;
}

function checkIfIsLoaded(task, id)
{
	flashMovie = document.getElementById("map");
	//if the map is still not loaded - wait again
	if(!flashMovie.flashLoadMap)
	{
		setTimeout("checkIfIsLoaded('" + task + "','" +id+ "')", 100);
	}
	else
	{
		setTimeout("flashLoadMap('" + task + "','" +id+ "','2')", 1000);
	}
}
function flashLoadMap(task,id, flag) { 
	flashMovie = document.getElementById("map");
	flashMovie.flashLoadMap(task,id, flag);
}
		
//this init's autocomplete control, requires jquery and jquery autocomplete to work
function initAutocomplete() {
	var s= $("#searchboxFormKeywordsId");
	s && s.autocomplete("/cgi-bin/user.cgi", { minChars:2, cacheLength:20, extraParams:{module:"jobkeywords", task:"search"}, lineSeparator:"|", width:220 });
}

/* this is for subcategories */

function sort_alpha(array) {
        alphaFlag = true;
        return build_table(sortAssocArray(array, 'name'), 'alpha');
    }
    function sort_cnt(array) {
        alphaFlag = false;
        return build_table(sortAssocArray(array, 'cnt', true), 'cnt');
    }
    function build_table(arr, type) {
        var tableId, addTable;
        switch (type) {
            case 'alpha':
                tableId = '';
                addTable = '';
                var delim = (arr.length%2 == 0) ? arr.length/2 : (arr.length+1)/2;
                var temp0 = new Array();
                var temp1 = arr.slice(0,delim);
                var temp2 = arr.slice(delim);
                for (var j=0; j<temp1.length; j++) {
                    temp0[temp0.length] = temp1[j];
                    if (temp2[j]) temp0[temp0.length] = temp2[j];
                }
                arr = temp0;
                break;
            case 'cnt':
                tableId = 'id="tableCategories"';
                addTable = '<table class="searchbox-js-inside" id="tableCategoriesMore"><tbody></tbody></table><font class="searchbox"id="viewAll">All ' + categoryName + ' job titles&hellip;<img src="/v3/gfx/arrow_down_blue.gif"></font>';
                break;
        }
		
		var finExtract = '<table id="tableCategories" class="searchbox-js-inside"><tbody>';
		for (var i=0; typeof arr[i]=='object'; i++) {
			
			var jtName = (arr[i].cnt > 0) ?'<font class="searchbox"><a name="cat_link_' + arr[i].catId + '_' + arr[i].id + '" href="/catalog/' + arr[i].catLink +'_'+ arr[i].catId +'/'+ arr[i].link +'_'+ arr[i].id +'.html" class="searchbox" title=" Click to see ' + arr[i].name +' vacancies">' + CheckStrByJobs(arr[i].name)+ '</a></font><font class="searchbox-red">&nbsp;(<span class="number">'+arr[i].cnt.makeRanged() + '</span>)</font>': '<font class="searchbox"><html:abbr title="No such vacancies at the moment">' + CheckStrByJobs(arr[i].name) + '</html:abbr> <a href="/candidate/jobs-by-email/?keywords=title:('+ arr[i].name +')"><img title=" No such vacancies at the moment.   Click here to be notified about new ' + arr[i].name + ' jobs by email." src="/v3/gfx/save_subcat_search.jpg"></a></font>';
			
			var jtCell = (i%2==0) ? ' style="width: 249px"' : '';

            if (i%2 == 0) finExtract += '<tr>';
            finExtract += '<td class="searchbox-js" ' + jtCell + ' >'+ jtName +'</td>';
            if (i%2==0 && i==arr.length-1) finExtract += '<td class="emptyCell"></td></tr>';
            if (i!=0 && i%2!=0) finExtract += '</tr>';
        }
        finExtract += '</table>' + addTable;
        
        return finExtract;
    }
    
    function CheckStrByJobs (str){
		return /.+Jobs$/.test(str)? str : str+' Jobs';
	}

    function sorter(elm) {
        if (alphaFlag == true) {
            document.getElementById('jtContainer').innerHTML = sort_cnt(jtArray);
            setMovableBox('tableCategories', 'tableCategoriesMore', 13, 'viewAll', 'block', 'All <TMPL_VAR NAME="category_name" ESCAPE="HTML"> job titles&hellip;<img src="/v3/gfx/arrow_down_blue.gif">', 'Popular job titles only&hellip;<img src="/v2/images/accessory/arrow_up_blue.gif">');
            elm.innerHTML = 'Sort by Job Title';
        } else {
            document.getElementById('jtContainer').innerHTML = sort_alpha(jtArray);
            elm.innerHTML = 'Sort by Job Popularity';
        }
    }
	
	
$('*').click(function(event) {
		event = event || window.event;
		var target = event.target || event.srcElement;
		var flag = 1;
		if(target.id == 'nohide') {
			return;
		}
		while(target != document) {
			target = target.parentNode;
			if(target.id == "recentSearches") {
				flag = 0;
				break;
			}
		}
		if(flag == 1) {
			hide_block('recentSearches');
		}
});

