﻿//
// common js functions
//
/// <reference path="jquery.min.js" />
//************************************* 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();
    }
}

//*****************************************
//load ge scripts:

// called in SEOVacancySearch.ascx and VacancySearch.ascx
function LoadGeScripts(latitude, longitude, zoomLevel, showPopupName)
{
	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.location.protocol == "http:")
	{
		script.src = 'http://maps.google.com/maps/api/js?v=3&sensor=false&callback=MapsLoaded&language=de&channel=JS24';
	}
	else
	{
		script.src = 'https://maps-api-ssl.google.com/maps/api/js?v=3&sensor=false&callback=MapsLoaded&language=de&channel=JS24';
	}
	document.getElementsByTagName("head")[0].appendChild(script);
}

//called in LoadGeScripts
function MapsLoaded()
{
	var lat =  g_latitude;
	var lon =  g_longitude
	var zoom = g_zoomLevel;

	var myLatlng = new google.maps.LatLng(lat, lon);

	var myOptions = {
		zoom: zoom,
		center: myLatlng,
		scaleControl: true,
		mapTypeControl: true,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		},
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.SMALL
		},

		mapTypeId: google.maps.MapTypeId.HYBRID
		}

	var map = new google.maps.Map(document.getElementById('myMap'), myOptions);

	var image = '/templates/images/icons/pin.gif';
	var marker = new google.maps.Marker({
		position: myLatlng,
		map: map,
		icon: image
	});
}

//*****************************************

    
// 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().replace(' ', '&nbsp;');
        for (var i = 0; i < list.childNodes.length; i++)
        {
            var text = list.childNodes[i].innerHTML.replace(' ', '&nbsp;');
            var regex = new RegExp('(' + search + ')', 'gi');
            var searchTerm = '<span class="autocomplete_item">' + text.replace(regex, '</span><span class="autocomplete_highlight">$1</span><span class="autocomplete_item">') + '</span><div style="clear:both;"></div>';
            var value = searchTerm.replace('<span class="autocomplete_item"></span>', '');
            list.childNodes[i].innerHTML = value;
        }
    }
    /* hide loading image */
    
}

function AutoCompletePopulatedHighlightWithCounter(source, eventArgs)
{
    source._element.className = 'input';
    if (source._currentPrefix != null)
    {
        var list = source.get_completionList();
        var search = source._currentPrefix.toLowerCase().replace(' ', '&nbsp;');
        for (var i = 0; i < list.childNodes.length; i++)
        {
            var text = list.childNodes[i].innerHTML.replace(' ', '&nbsp;');
            if (text.charAt(0) == '[')
            {
                text = text.substring(1);
            }
            var lengthText = text.length;
            if (text.charAt(lengthText - 1) == ']')
            {
                text = text.slice(0, -1);
            }
            var columns = text.split('][');
            var value = String();
            for (var columnIndex = 0; columnIndex < columns.length; columnIndex++)
            {
                var columnText = columns[columnIndex];
                switch (columnIndex)
                {
                    case 0:
                        // search term
                        var regex = new RegExp('(' + search + ')', 'gi');
                        var searchTerm = '<span class="autocomplete_item">' + columnText.replace(regex, '</span><span class="autocomplete_highlight">' + search + '</span><span class="autocomplete_item">') + '</span>';
                        value += searchTerm.replace('<span class="autocomplete_item"></span>', '');
                        break;
                    case 1:
                        // items found
                        value += '<span class="autocomplete_resultCounter">' + columnText + '&nbsp;Treffer&nbsp;</span><div style="clear:both;"></div>';
                        break;
                }
            }
            list.childNodes[i].innerHTML = value;
        }
    }
    /* hide loading image */
}

function GetAutoCompleteItemValue(element)
{
    if (element != null)
    {
        var value = element.get_value();
        if (value != null)
        {
            return value;
        }
        else if (element.get_item() != null && element.get_item().parentNode != null && element.get_item().parentNode._value != null)
        {
            return element.get_item().parentNode._value;
        }
    }
    return "";
}

function AutoCompleteItemSelected(source, eventArgs)
{
    source.get_element().value = GetAutoCompleteItemValue(eventArgs);
}

function AutoCompleteItemSelectedWithCounter(source, eventArgs)
{
    var regexColumns = /^\[(.*)\]\[(.*)\]$/;
    var text = GetAutoCompleteItemValue(eventArgs);
    var columns = text.match(regexColumns);
    if (columns && columns[1])
    {
        source.get_element().value = columns[1];
    }
}

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);
    }
}

//Filter logik stuff
function mouseX(evt) {
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX)
        return evt.clientX + (document.documentElement.scrollLeft ?
                document.documentElement.scrollLeft :
                document.body.scrollLeft);
    else return null;
}

function mouseY(evt) {
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY)
        return evt.clientY + (document.documentElement.scrollTop ?
                document.documentElement.scrollTop :
                document.body.scrollTop);
    else return null;
}

var _selectedNavigator = new Array();
var _deleteNavigator = new Array();
var _selectFilterTimeout;
var _backGroundNModTimeout;
var _backGroundPModTimeout;
var _deleteTimeout;
var _markedRow;

$(document).ready(function () {
	registerEvents();
	controlCookieForSearchResultListState();
	checkCookie();
});

function checkCookie() {
	var divCtrl = $("#topNavigation_noJavaScriptInfoControl_divCookiesDisabled");
	if (Get_Cookie('cookieCheck') == null) {
		divCtrl.css('display', 'block');
	}
	else {
		divCtrl.css('display', 'none');
	}
}

function registerEvents() {
    $(".search-refine-modifier td.search-refine-tdleft").unbind();
    $(".search-refine-modifier td.search-refine-tdleft").click(function (e) {
        var tgt = $(this).parent().children(".search-refine-tdright");
        //check if already selected
        var filter = tgt.children("div");

        if (filter.length > 0)
            return false;

        var divSelectedFilter = $("#divSelectFilter");
        divSelectedFilter.css('top', mouseY(e));
        divSelectedFilter.css('left', mouseX(e));
        divSelectedFilter.css('display', 'block');

        _markedRow = $(this).parent();
        _markedRow.css('background', 'silver');
        return false;
    });

    $(".searched-for-item-delete").unbind();
    $(".searched-for-item-delete").click(function (e) {
        if (null != _deleteTimeout)
            window.clearTimeout(_deleteTimeout);

        _deleteTimeout = window.setTimeout(deleteSelectedModifier, 1000);
        _deleteNavigator.push($(this).attr("DeleteUrl"));
        $(this).parent().css('display', 'none');
    });

    $("#divSelectFilter").unbind();
    $("#divSelectFilter").mouseover(function () {
        $(this).css("display", "block");
        if (null != _selectFilterTimeout)
            window.clearTimeout(_selectFilterTimeout);
    });

    $("#divSelectFilter").mouseout(function () {
        var root = $(this);
        _selectFilterTimeout = window.setTimeout(function () {
            _markedRow.css('background', '');
            root.css("display", "none");
        }, 250);
    });

    //$(".search-refine-tdright img").unbind();
    //$(".search-refine-tdright img").click(function (e) { refineSearch(); return false; });

    $("#trAddPMod").unbind();
    $("#trAddNMod").unbind();

    $("#trAddPMod").mouseover(function () {
        if (null != _backGroundPModTimeout)
            window.clearTimeout(_backGroundPModTimeout);

        $(this).css("backgroundColor", "silver");
    });
    $("#trAddPMod").mouseout(function () {
        var root = $(this);
        //To avoid flickering in IE
        _backGroundPModTimeout = window.setTimeout(function () {
            root.css("backgroundColor", "");
        }, 40);
    });
    $("#trAddNMod").mouseover(function () {
        if (null != _backGroundNModTimeout)
            window.clearTimeout(_backGroundNModTimeout);
        $(this).css("backgroundColor", "silver");
    });
    $("#trAddNMod").mouseout(function () {
        var root = $(this);
        //To avoid flickering in IE
        _backGroundNModTimeout = window.setTimeout(function () {
            root.css("backgroundColor", "");
        }, 40);
    });

    $("#trAddPMod").click(function () {
        var parent = _markedRow.children(".search-refine-tdright");
        var mod = parent.attr("PosMod");
        var clone = $('#divPositiveFilter').clone();


        _selectedNavigator.push(mod);
        var idx = _selectedNavigator.length - 1;

        clone.css("display", "block");
        clone.click(function () {
            $(this).remove();

            _selectedNavigator[idx] = null;
        });
        clone.appendTo(parent);


        $("#divSelectFilter").css("display", "none");
        _markedRow.css('background', '');
        refineSearch();
    });

    $("#trAddNMod").click(function () {
        var parent = _markedRow.children(".search-refine-tdright");
        var mod = parent.attr("NegMod");
        var clone = $('#divNegativeFilter').clone();

        _selectedNavigator.push(mod);
        var idx = _selectedNavigator.length - 1;

        clone.css("display", "block");
        clone.click(function () {
            $(this).remove();

            _selectedNavigator[idx] = null;
        });
        clone.appendTo(parent);

        $("#divSelectFilter").css("display", "none");
        _markedRow.css('background', '');
        refineSearch();
    });

    $(".search-refine-modifier").each(function () {
        if ($(this).css("display") == 'none') {
            $(this).prev().attr("class", "search-refine-navigator-folded");
        }
    });

    $(".search-refine-modifier").prev().unbind();
    $(".search-refine-modifier").prev().click(function () {
        $(this).next(".search-refine-modifier").slideToggle(400);
        if ($(this).hasClass("search-refine-navigator") || $(this).hasClass("search-refine-navigator-open")) {
            $(this).attr("class", "search-refine-navigator-folded");
            $(this).next(".search-refine-modifier").children("input").attr("value", "none");
        }
        else {
            $(this).attr("class", "search-refine-navigator-open");
            $(this).next(".search-refine-modifier").children("input").attr("value", "block");
        }
	});
	
	// event handler for list behaviour 
	$(".divListenAnsicht").click(function () {
		HideVacancyDetails(null);
	});
	$(".divDetailAnsicht").click(function () {
		ShowVacancyDetails(null);
	});
	$(".divMoreDetails a").click(
		function () {
			if ($(this).text() == "Mehr Details") {
				ShowVacancyDetails($(this));
			}
			else {
				HideVacancyDetails($(this));
			}
		}
	);

	// event handler for national/international search
	RegisterNationalInternationalRegion();
}

function RegisterNationalInternationalRegion()
{
	$(".rblRadio input").click(
		function ()
		{
			if ($(this).next().is("label")
				&& ($(this).next().text() == "National"
				|| $(this).next().text() == "International"))
			{
				if ($(this).attr("checked") == true
					&& $(this).next().text() == "National")
				{
					ShowNationalRegion();
				}
				else
				{
					ShowInternationalRegion();
				}
			}
		}
	);
}

function ShowNationalRegion()
{
	$(".joblisteSuchbegriff div[id*='pnlFlexibleLocation']").css("display", "block");
	$(".joblisteRegion div[id*='pnlNational']").css("display", "block");
	$(".joblisteRegion div[id*='pnlInternational']").css("display", "none");
}

function ShowInternationalRegion()
{
	$(".joblisteSuchbegriff div[id*='pnlFlexibleLocation']").css("display", "none");
	$(".joblisteRegion div[id*='pnlNational']").css("display", "none");
	$(".joblisteRegion div[id*='pnlInternational']").css("display", "block");
}

function ShowVacancyDetails(currentNode) {
	if (currentNode != null) {

		$(currentNode).parent().parent().parent().find(".vacancyItemContentExtended").slideDown(300);
		$(currentNode).text("Weniger Details");
		$(currentNode).attr("title", "Weniger Details");
		$(currentNode).attr("class", "moreDetailsIconActive");
	}
	else {
		// Set cookie for next request
		Set_Cookie("SearchResultListState", "detail", 180);

		$(".divMoreDetails a").each(function () { ShowVacancyDetails($(this)) });

		$(".divDetailAnsicht").find(".linkDetailViewIcon").addClass("linkDetailViewIconActive");
		$(".divDetailAnsicht").find(".linkDetailViewIcon").removeClass("linkDetailViewIcon");

		$(".divListenAnsicht").find(".linkListViewIconActive").addClass("linkListViewIcon");
		$(".divListenAnsicht").find(".linkListViewIconActive").removeClass("linkListViewIconActive");
	}
}

function HideVacancyDetails(currentNode) {
	if (currentNode != null) {

		$(currentNode).parent().parent().parent().find(".vacancyItemContentExtended").slideUp(300);
		$(currentNode).text("Mehr Details");
		$(currentNode).attr("title", "Mehr Details");
		$(currentNode).attr("class", "moreDetailsIcon");
	}
	else {
		// Set cookie for next request
		Set_Cookie("SearchResultListState", "liste", 180);

		$(".divMoreDetails a").each(function () { HideVacancyDetails($(this)) });

		$(".divListenAnsicht").find(".linkListViewIcon").addClass("linkListViewIconActive");
		$(".divListenAnsicht").find(".linkListViewIcon").removeClass("linkListViewIcon");

		$(".divDetailAnsicht").find(".linkDetailViewIconActive").addClass("linkDetailViewIcon");
		$(".divDetailAnsicht").find(".linkDetailViewIconActive").removeClass("linkDetailViewIconActive");
	}
}


function controlCookieForSearchResultListState()
{
    //check if our cookie exists; if not then create it
    if (Get_Cookie("SearchResultListState") == null)
    {
        Set_Cookie("SearchResultListState", "liste", 180);
    }
    //if our cookie exists:
    else
    {
        if (Get_Cookie("SearchResultListState") == "liste")
        {
        	$(".divListenAnsicht").click();
        }
        else
        {
        	$(".divDetailAnsicht").click();
        }
    }
}

function Set() {
    this._set = new Array();
}

Set.prototype = {
    put: function (value) {
        for (var i = 0; i < this._set.length; i++) {
            if (this._set[i] == value)
                break;
        }
        if (i == this._set.length)
            this._set.push(value);
    },

    contains: function (value) {
        for (var i = 0; i < this._set.length; i++) {
            if (this._set[i] == value)
                return true;
        }

        return false;
    }
}

function getQueryParam(navigators) {
    var queryParams = new Set();

    for (var i = 0; i < navigators.length; i++) {
        if (navigators[i] == null)
            continue;

        var split = navigators[i].split("&");

        for (var j = 0; j < split.length; j++) {
            queryParams.put(split[j]);
        }
    }

    return queryParams;
}


function refineSearch() {
    if (_selectedNavigator.length == 0)
        return;

    var queryParam = getQueryParam(_selectedNavigator);
    var link = "/Jobs_Ergebnisliste.html?";

    for (var i = 0; i < queryParam._set.length; i++) {
        link += queryParam._set[i] + "&";
    }

    window.location.href = link;
}

function deleteSelectedModifier() {
    var queryParam = getQueryParam(_deleteNavigator);

    for (var i = 0; i < _deleteNavigator.length; i++) {
        var split = _deleteNavigator[i].split("&");

        for (var j = 0; j < queryParam._set.length; j++) {
            for (var k = 0; k < split.length; k++) {
                if (split[k] == queryParam._set[j])
                    break;
            }

            if (k == split.length)
                queryParam._set[j] = null;
        }
    }

    var link = "/Jobs_Ergebnisliste.html?";

    for (i = 0; i < queryParam._set.length; i++) {
        if(queryParam._set[i] != null)
            link += queryParam._set[i] + "&";
    }

    window.location.href = link;
}

/******************* cookie helper functions */
//check for a cookie by its name
function Get_Cookie(check_name)
{
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++)
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name)
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1)
            {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            //alert(cookie_value);
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found)
    {
        return null;
    }
}

//create a cookie
function Set_Cookie(name, value, expires, path, domain, secure)
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires)
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
       var expires_date = new Date(today.getTime() + (expires));
	   //to avoid multiple path values:
       path = "/";

    document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
}

/******************* cookie helper functions */
/********* Link masking functions ************/
function AssembleUrlAndRedirect() {
	if (arguments != null && arguments.length > 0) {
		var resultUrl = "";
		for (var i = 0; i < arguments.length; i++) {
			resultUrl = resultUrl + arguments[i];
		}
		document.location.href = resultUrl;
	}
}
/*********************************************/


jQuery(document).ready(function () {
	jQuery(".joblisteJobtitel").click(function () {
		var currentPage = jQuery("#hidCurrentPage");
		if (currentPage != null) {
			track_vacancy_position(this, this.name, currentPage.val());
		}
		jQuery(this).attr("style", "font-weight:normal;");

	});
});

//*********************** webservice call to save vacancy search for B2C
jQuery(document).ready(function () {
	$("#spnActionSaveSearch").click(function () {
		ExecuteSavingVacancySearch();
	});
});
jQuery(document).ready(function () {
	$("#tbxEmailAdressForJMSSAbo").keypress(function (event) {
		if (event.which == '13') {
			ExecuteSavingVacancySearch();
			return false;
		}
	});
});
function ExecuteSavingVacancySearch() {
	var mailAddress = $("#tbxEmailAdressForJMSSAbo").val();
	var spnValidationMessage = $("#spnValidationMessage");
	var strLength = mailAddress.length;
	if (strLength > 0) {
		if (isValidEmailAddress(mailAddress)) {
			JobScout24.Templates.WebServices.VacancySearchHelper.SaveVacancySearch(document.location.href, mailAddress, SaveVacancySearchSuccCallback, SaveVacancySearchErrorCallback);
			track_AngeboteAnfordern(this);
		}
		else {
			spnValidationMessage.css("display", "block");
			spnValidationMessage.html("Bitte das Format der E-Mail Adresse prüfen.");
			return false;
		}
	}
	else {
		spnValidationMessage.css("display", "block");
		spnValidationMessage.html("Bitte eine E-Mail Adresse angeben.");
		return false;
	}
}
function SaveVacancySearchSuccCallback(result) {
	$("#divSaveVacancySearchContainer").html(result);
}
function SaveVacancySearchErrorCallback(result) {
	$("#divSaveVacancySearchContainer").html("Das Speichern Ihrer Suche ist fehlgeschlagen! Bitte versuchen Sie es später noch einmal.");
}
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
};

