﻿//
// common js functions
//

//************************************* Jobs_Ergebnisliste

function avoid()
{
}

// open centered popupWindow
function helpPopup(URL, w, h)
{
    LeftPosition = (screen.width-w)/2;
    TopPosition = (screen.height-h)/2;
    params="status=no,resizable=no,scrollbars=no,menubar=no,toolbar=no,titlebar=no,width="+ w +",height="+ h +",top="+TopPosition+",left="+LeftPosition+",directories=no;"
    js24popup=window.open(URL,"JS24",params);
}

// sets NOT bold style of link
function MarkLinkAsVisited(LinkId)
{
	var link = document.getElementById(LinkId);
	link.style.fontWeight = 'normal';
}

//hides modalpopup with map
function cancelShowMaps()
{
	var modalPopupExtender = $find('mpeShowMaps');
	var mapArea =  $get("myMap");
	
	if(mapArea != null)
	{
		mapArea.innerHTML = '<img class="wirdGeladen" src="/templates/images/icons/loading.gif" alt="In Progress ..." />';
		mapArea.style.backgroundColor = "";
	}

	if (modalPopupExtender != null)
	{
		modalPopupExtender.hide();
	}
}

//show vacancy pin in map; called in function LoadVeScripts
function showTheMap()
{	 
    var map;
    var lat =  g_latitude;
    var lon =  g_longitude
    var zoom = g_zoomLevel;

    map = new VEMap('myMap');   
    map.LoadMap();
	
    map.SetMapStyle(VEMapStyle.Hybrid);
	
    //set pushpin
    var veLatLong = new VELatLong(lat, lon);
    var pushPin = new VEShape(VEShapeType.Pushpin, veLatLong);
    pushPin.SetCustomIcon("/templates/images/icons/pin.gif");
    map.AddShape(pushPin);

    //center the map
    map.SetMapView(new Array(veLatLong));
    map.SetCenterAndZoom(new VELatLong(lat, lon), zoom);
}

var g_latitude = 0.0;
var g_longitude = 0.0;
var g_zoomLevel = 12;

//load ve scripts asynchronous:
function LoadVeScripts(latitude, longitude, zoomLevel, showPopupName)
{
    var head= document.getElementsByTagName('head')[0];
    var script= document.createElement('script');
    script.type= 'text/javascript';

    g_latitude = latitude;
    g_longitude = longitude;
    g_zoomLevel = zoomLevel;
	
    //get click event and show modal popup
    $get(showPopupName).click();
	
    if (!(window.attachEvent)) 
    {
        var noie_script= document.createElement('script');
        noie_script.type= 'text/javascript'; 
        
        if(window.location.protocol == "http:")
        {
            noie_script.src = "http://dev.virtualearth.net/mapcontrol/v6.2/js/atlascompat.js"; 
        }
        else
        {
            noie_script.src = "https://dev.virtualearth.net/mapcontrol/v6.2/js/atlascompat.js";
        }
        head.appendChild(noie_script);
    }

    if(window.location.protocol == "http:")
    {
        script.src= 'http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&mkt=de-DE&onScriptLoad=showTheMap';
    }
    else
    {
        script.src= 'https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1&mkt=de-DE&onScriptLoad=showTheMap';
    }
    head.appendChild(script);
}



//select or deselect all checkboxes in resultlist
function jobSearchResultList_cbxSelectAll_click(evt)
{
	var checked = evt.target.checked;

	var cbxSelectAllFooter = $get('cbxSelectAllFooter');
	var cbxSelectAllHeader = $get('cbxSelectAllHeader');

	if (cbxSelectAllFooter)
	{
		cbxSelectAllFooter.checked = checked;
	}

	if (cbxSelectAllHeader)
	{
		cbxSelectAllHeader.checked = checked;
	}

	var inputElements = document.getElementsByTagName("input");

	for (var i = 0; i < inputElements.length; ++i)
	{
		var inputElement = inputElements[i];

		if (!inputElement.type || inputElement.type != "checkbox")
		{
			continue;
		}

		if (!inputElement.name ||
				inputElement.name.search(/^(?:\w+\$)*cbxVacancy$/) == -1)
		{
			continue;
		}

		if (!inputElement.attributes['vacancyId'] ||
				!inputElement.attributes['vacancyId'].value)
		{
			continue;
		}

		inputElement.checked = checked;
	}
}

//add click handler to checkboxes
function jobSearchResultList_pageLoad(source, args)
{
	if (!args.get_isPartialLoad())
	{
		var cbxSelectAllFooter = $get('cbxSelectAllFooter');
		var cbxSelectAllHeader = $get('cbxSelectAllHeader');

		if (cbxSelectAllFooter)
		{
			$addHandler(cbxSelectAllFooter, 'click', jobSearchResultList_cbxSelectAll_click);
		}

		if (cbxSelectAllHeader)
		{
			$addHandler(cbxSelectAllHeader, 'click', jobSearchResultList_cbxSelectAll_click);
		}
	}
}
	
//remove click handler from checkboxes
function jobSearchResultList_pageUnload()
{
	var cbxSelectAllFooter = $get('cbxSelectAllFooter');
	var cbxSelectAllHeader = $get('cbxSelectAllHeader');

	if (cbxSelectAllFooter)
	{
		$removeHandler(cbxSelectAllFooter, 'click', jobSearchResultList_cbxSelectAll_click);
	}

	if (cbxSelectAllHeader)
	{
		$removeHandler(cbxSelectAllHeader, 'click', jobSearchResultList_cbxSelectAll_click);
	}
}	
// method for similar vacancy search - set doc vector via webservice call 
function SetSimilarVacancyVector(vector)
{
	JobScout24.Templates.WebServices.VacancySearchHelper.SetSimilarVacancySearchVector(vector,SetSimilarVacancyVectorCallback,SetSimilarVacancyVectorCallback);
}
// call back method for similar vacancy search
function SetSimilarVacancyVectorCallback()
{
	if(window.location.href.indexOf("?") != -1)
	{
		
		
		if(window.location.href.indexOf("sv=") == -1)
		{
			window.location.href = RemoveCommandParameterFromQueryString(window.location.href) + "&sv=1";
		}
		else if(window.location.href.indexOf("sv=0") != -1)
		{
			window.location.href = RemoveCommandParameterFromQueryString(window.location.href).replace("sv=0","sv=1");
		}
		else
		{
			window.location.href = RemoveCommandParameterFromQueryString(window.location.href);
		}
		
	}
	else
	{
		window.location.href = window.location.href + "?sv=1";
	}
}

function RemoveCommandParameterFromQueryString(queryString)
{
	var returnValue = "";
	returnValue = queryString.replace(/(&|)cmd\w{1,2}=[^&]*/g,"");
	return returnValue;
}

// redirects a vacancy search with defined url and parameters in asynchronous mode
function RedirectToVacancySearchUrlWithParams(url, searchPhraseCtrlID, internationalCtrlID, zipOrCityCtrlID, distanceCtrlID, flexibleCtrlID, countriesCtrlID) 
{
    return RedirectToVacancySearchUrlWithAllParams(url, searchPhraseCtrlID, internationalCtrlID, zipOrCityCtrlID, distanceCtrlID, flexibleCtrlID, countriesCtrlID, true);
}

// redirects a vacancy search with defined url and parameters in asynchronous mode
function RedirectToVacancySearchUrlWithAllParams(url, searchPhraseCtrlID, internationalCtrlID, zipOrCityCtrlID, distanceCtrlID, flexibleCtrlID, countriesCtrlID, includeNavigators ) {
    var searchPhraseCtrl = $get(searchPhraseCtrlID);
    var internationalCtrl = $get(internationalCtrlID);
    var zipOrCityCtrl = $get(zipOrCityCtrlID);
    var distanceCtrl = $get(distanceCtrlID);
    var flexibleCtrl = $get(flexibleCtrlID);
    var countriesCtrl = $get(countriesCtrlID);

    var searchPhrase = searchPhraseCtrl.value;
    var international = false;
    if (internationalCtrl) {
    	international = getRadioSelectedValue(internationalCtrl) != "1";
    }
    var zipOrCity = new String();
    var distance = new String();
    var flexible = false;
    if (flexibleCtrl) {
    	flexible = flexibleCtrl.checked;
    }
    var countries = new String();
    if (!international) {
        zipOrCity = zipOrCityCtrl.value;
        distance = distanceCtrl.value;
    }
    else {
        if (countriesCtrl) {
            countries = getSelectedItemsText(countriesCtrl, ",", "");
        }
    }

    if (includeNavigators) {
        JobScout24.Templates.WebServices.SearchHelperService.GetVacancySearchUrl(url, //string
		searchPhrase, //string
		international, //boolean
		zipOrCity, //string
		distance, //string
		flexible, //boolean
		countries, //string
		RedirectToVacancySearchUrlSucc, //callback success
		RedirectToVacancySearchUrlFail); //callback failure
    }
    else {
        JobScout24.Templates.WebServices.SearchHelperService.GetVacancySearchUrl(url, //string
		searchPhrase, //string
		international, //boolean
		zipOrCity, //string
		distance, //string
		flexible, //boolean
		countries, //string
		RedirectToVacancySearchUrlNoNavigatorsSucc, //callback success
		RedirectToVacancySearchUrlFail); //callback failure
    }  
}



// redirects a vacancy search with navigators if callback was successfull and uses given result as url
function RedirectToVacancySearchUrlSucc(result)
{
    window.location.href = result + GetParameterValues("n") + GetParameterValues("ps") + GetParameterValues("sf") + GetParameterValues("sd");
}

// redirects a vacancy search with no navigators if callback was successfull and uses given result as url
function RedirectToVacancySearchUrlNoNavigatorsSucc(result) {
    window.location.href = result + GetParameterValues("ps") + GetParameterValues("sd") + GetParameterValues("sf") + "&sc=0";
}

// redirects a vacancy search to default url if callback was failed
function RedirectToVacancySearchUrlFail()
{
    window.location.href = '/Jobs_Ergebnisliste.html'
}


/* Gets Navigatorvalues */
function GetParameterValues(paramName) 
{
    var regExpr = new RegExp("[\\?&]" + paramName + "=([^&#]*)","g");
    var regExprSrc = window.location.href;
    var results = regExprSrc.match(regExpr);
    var returnString = "";

    if (results != null) {
        for (var i = 0; i < results.length; i++)
            returnString = returnString + results[i].replace("?"+paramName,"&"+paramName);
    } 
    
    return returnString;
 }


//************************************* ProfileSearch

//select or deselect all checkboxes in resultlist
function profileSearch_cbxSelectAll_click(evt)
{
	var checked = evt.target.checked;

	var cbxSelectAllFooter = $get('cbxSelectAllFooter');
	var cbxSelectAllHeader = $get('cbxSelectAllHeader');

	if (cbxSelectAllFooter)
	{
		cbxSelectAllFooter.checked = checked;
	}

	if (cbxSelectAllHeader)
	{
		cbxSelectAllHeader.checked = checked;
	}

	var inputElements = document.getElementsByTagName("input");

	for (var i = 0; i < inputElements.length; ++i)
	{
		var inputElement = inputElements[i];

		if (!inputElement.type || inputElement.type != "checkbox")
		{
			continue;
		}

		if (!inputElement.name ||
				inputElement.name.search(/^(?:\w+\$)*cbxProfile$/) == -1)
		{
			continue;
		}

		if (!inputElement.attributes['profileId'] ||
				!inputElement.attributes['profileId'].value)
		{
			continue;
		}

		inputElement.checked = checked;
	}
}

//add click handler to checkboxes
function profileSearch_pageLoad(source, args)
{
	if (!args.get_isPartialLoad())
	{
		var cbxSelectAllFooter = $get('cbxSelectAllFooter');
		var cbxSelectAllHeader = $get('cbxSelectAllHeader');

		if (cbxSelectAllFooter)
		{
			$addHandler(cbxSelectAllFooter, 'click', profileSearch_cbxSelectAll_click);
		}

		if (cbxSelectAllHeader)
		{
			$addHandler(cbxSelectAllHeader, 'click', profileSearch_cbxSelectAll_click);
		}
	}
}

//remove click handler from checkboxes
function profileSearch_pageUnload()
{
	var cbxSelectAllFooter = $get('cbxSelectAllFooter');
	var cbxSelectAllHeader = $get('cbxSelectAllHeader');

	if (cbxSelectAllFooter)
	{
		$removeHandler(cbxSelectAllFooter, 'click', profileSearch_cbxSelectAll_click);
	}

	if (cbxSelectAllHeader)
	{
		$removeHandler(cbxSelectAllHeader, 'click', profileSearch_cbxSelectAll_click);
	}
}

// show profile details
function profileSearch_showProfileDetails(profileParams)
{
	if (!window.open(profileParams, '_blank'))
	{
		window.location.href = profileParams;
	}
}

// redirects a profile search with defined url and parameters in asynchronous mode
function RedirectToProfileSearchUrlWithParams(url, searchPhraseCtrlID, zipOrCityCtrlID, lastUpdateCtrlID, referenceCtrlID)
{
	var searchPhraseCtrl = $get(searchPhraseCtrlID);
	var zipOrCityCtrl = $get(zipOrCityCtrlID);
	var lastUpdateCtrl = $get(lastUpdateCtrlID);
	var referenceCtrl = $get(referenceCtrlID);

	var searchPhrase = searchPhraseCtrl.value;
	var zipOrCity = zipOrCityCtrl.value;
	var lastUpdate = lastUpdateCtrl.value;
	var reference = referenceCtrl.value;
	var guildFilter = "";
	var industryFilter = "";
	var salaryFilter = "";
	var availabilityFilter = "";
	var languageFilter = "";
	var languageLevelFilter = "";
	var travelWillingnessFilter = "";
	var actualStatusFilter = "";
	var desiredStatusFilter = "";

	JobScout24.Templates.WebServices.SearchHelperService.GetProfileSearchUrl(url, //string
		searchPhrase, //string
		zipOrCity, //string
		lastUpdate, //string
		reference, //string
		guildFilter, //string
		industryFilter, //string
		salaryFilter, //string
		availabilityFilter, //string
		languageFilter, //string
		languageLevelFilter, //string
		travelWillingnessFilter, //string
		actualStatusFilter, //string
		desiredStatusFilter, //string
		RedirectToProfileSearchUrlSucc, //callback success
		RedirectToProfileSearchUrlFail); //callback failure
}

// redirects a profile search if callback was successfully and uses given result as url
function RedirectToProfileSearchUrlSucc(result)
{
	window.location.href = result;
}

// redirects a profile search to default url if callback was failed
function RedirectToProfileSearchUrlFail()
{
	window.location.href = '/Profile_Ergebnisliste.html'
}

//************************************* LoginStatusControl

//add eventhandler to document
function loginStatusControl_pageLoad(source, evt)
{
	if (!evt.get_isPartialLoad())
	{
		$addHandler(document, "keydown", loginStatusControl_document_onKeyPress);
	}
}

//remove eventhandler from document
function loginStatusControl_pageUnload()
{
	$removeHandler(document, "keydown", loginStatusControl_document_onKeyPress);
}

//show modal popup login control
function ShowLoginModalPopupWithParams(loginControlName,loginUserName)
{
    var loginControl = $find(loginControlName);
    var loginUser = $get(loginUserName);

    if (loginControl && loginUser == null)
    {
    	loginControl.set_destinationPageUrl('');
	    loginControl.show();
	    return false;
    }
    else
    {
        return true;
    }
}

function ShowLoginModalPopupWithDestinationUrl(loginControlName, loginUserName, destinationUrl)
{
	var loginControl = $find(loginControlName);
	var loginUser = $get(loginUserName);

	if (loginControl && loginUser == null)
	{
		loginControl.set_destinationPageUrl(destinationUrl);
		loginControl.show();
		return false;
	}
	else
	{
		return true;
	}
}
//************************************* HTML functions

// gets the selected value of a radio button list
function getRadioSelectedValue(radioList)
{
	var options = radioList.getElementsByTagName('input');
	for(i = 0;i < options.length; i++)
	{
		var opt = options[i];
		if(opt.checked)
		{
			return opt.value;
		}
	}
}

// gets the selected texts of listbox separated of a defined character excepting given values
function getSelectedItemsText(listBox, separator, exceptValues)
{
	var exceptValuesArray = new Array();
	exceptValuesArray = exceptValues.toString().split(separator);
	
	var itemsArray = new Array();
	var items = listBox.options;

	for (var i = 0; i < items.length; ++i)
	{
		var item = items.item(i);
		var pushItem = new Boolean();
		pushItem = true;
		if(item.selected)
		{
			for (var j = 0; j < exceptValuesArray.length; j++)
			{
				if(exceptValuesArray[j] == item.value)
				{
					pushItem = false;
					break;
				}
			}
			if(pushItem)
			{
				itemsArray.push(escape(item.text));
			}
		}
	}
	return itemsArray.join(separator);
}

/* ********************************************************************
    UltimateCalendar 
*/
//gets current month in ultimateCalender:
function SetVisibleDateYear(yearOffset, ctrlName) 
{
    var ultimateCalendarObj = UltimateCalendars[ctrlName];
    var visibleDate = ultimateCalendarObj.GetVisibleDate();
    var visibleDateYear = visibleDate.getFullYear() + yearOffset;
    ultimateCalendarObj.SetVisibleDate(new Date(visibleDateYear, visibleDate.getMonth(), visibleDate.getDate()));
}

/* *********************************************************************
    AutoComplete highlightning
*/
function AutoCompletePopulatedHighlight(source, eventArgs)
{
    source._element.className = 'input';
    if (source._currentPrefix != null)
    {
        var list = source.get_completionList();
        var search = source._currentPrefix.toLowerCase();
        for (var i = 0; i < list.childNodes.length; i++)
        {
            var text = list.childNodes[i].innerHTML; 
            var index = text.toLowerCase().indexOf(search);
            if (index != -1)
            {
                var value = text.substring(0, index);
                value += '<span class="autocomplete_highlight">';
                value += text.substr(index, search.length);
                value += '</span>';
                value += text.substring(index + search.length);
                list.childNodes[i].innerHTML = value;
            }
        }
    }
    /* hide loading image */
    
}

function AutoCompleteItemSelected(source, eventArgs) {
    source.get_element().value = (document.all) ? eventArgs._item.innerText : eventArgs._item.textContent;
}
function AutoCompletePopulating(source, eventArgs) {
    /* show loading image */
    source._element.className = 'input autocomplete_image';
    setTimeout( "$get('" + source._element.id + "').className = 'input';", source._completionInterval);
}

function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}

// Just enables/disables validator without to validate at the same moment (Workaround of ValidatorEnable)
function EnableValidator(val, enable) {
    if (val && val.enabled != null) {
        val.enabled = (enable != false);
    }
}
