﻿//is call onload
$(document).ready(function ()
{
	SearchNavigators.registerSearchNavigatorEvents();
	RegisterAutoCompletion()
	RegisterModalPopups();
	SearchNavigators.pageLoaded();
})

/*script initialisation end*/
function pageLoad(sender, args)
{
	if(args.get_isPartialLoad())
	{
		SearchNavigators.registerSearchNavigatorEvents();
		RegisterModalPopups();
		SearchNavigators.pageLoaded(sender,args);
	}
}

var _navigator;
/*Register script for search navigator start*/
function SearchNavigators() {
}
SearchNavigators.registerSearchNavigatorEvents = function () {
	$(".search-refine-modifier td.search-refine-tdleft").unbind();
	$(".search-refine-modifier td.search-refine-tdleft").click(function(e) {
		var divSelectedFilter = $("#divSelectFilter");
		divSelectedFilter.appendTo($(this).parent().children(".search-refine-tdright"));
		divSelectedFilter.css('display', 'block');
		_navigator = $(this).children("span").attr("class")
	});

	$("#divSelectFilter").unbind();
	$("#divSelectFilter").mouseover(function () {
		$(this).css("display", "block");
	});
	$("#divSelectFilter").mouseout(function () {
		$(this).css("display", "none");
	});

	$("#trAddPMod").unbind();
	$("#trAddNMod").unbind();

	$("#trAddPMod").mouseover(function () {
		$(this).css("backgroundColor", "silver");
	});
	$("#trAddPMod").mouseout(function () {
		$(this).css("backgroundColor", "");
	});
	$("#trAddNMod").mouseover(function () {
		$(this).css("backgroundColor", "silver");
	});
	$("#trAddNMod").mouseout(function () {
		$(this).css("backgroundColor", "");
	});
	$("#trAddPMod").click(function () {
		SearchNavigators.addModifier(true, _navigator);

		var clone = $('#divPositiveFilter').clone();
		clone.css("display", "block");
		clone.click(function () {
			$(this).remove();
			var navigator = _navigator;
			SearchNavigators.removeModifier(true, navigator);
		});
		clone.appendTo($("#divSelectFilter").parent());
		$("#divSelectFilter").css("display", "none");
	});
	$("#trAddNMod").click(function () {
		SearchNavigators.addModifier(false, _navigator);
		var clone = $('#divNegativeFilter').clone();
		clone.css("display", "block");
		clone.click(function () {
			$(this).remove();
			var navigator = _navigator;
			SearchNavigators.removeModifier(false, navigator);
		})

		clone.appendTo($("#divSelectFilter").parent());
		$("#divSelectFilter").css("display", "none");
	});

	$(".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");
		}
	});
}

/*Register script for search navigator end*/
/**/
var timeoutID;
SearchNavigators.pageLoaded = function (sender, args) {
	var span = document.getElementById('spanLocation');
	if (span != null) {
		var hf = document.getElementById($("[id*=_hfLocation]").attr("id"));
		var split = hf.value.split('~');
		var divLoc = document.getElementById('divLocation');

		//Render selected location
		if (split[0] != '') {
			var text = split[0];
			var renderTgt = document.getElementById('divRenderTgt');

			if (split.length > 1)
				text += ' (' + split[1] + ')';

			span.innerHTML = text;

			renderTextToSize(span, renderTgt, 105);
			divLoc.style.display = 'block';
		}
		else {
			divLoc.style.display = 'none';
		}
	}
}
SearchNavigators.removeModifier = function(positive, ModifierValue)
{
	if(positive)
	{
		var hfPMods = $("#"+hiddenFieldPositiveModifier);
		hfPMods.attr("value",hfPMods.attr("value").replace(ModifierValue, ''));
	}
	else
	{
		var hfNMods = $("#"+hiddenFieldNegativeModifier);
		hfNMods.attr("value",hfNMods.attr("value").replace(ModifierValue, ''));
	}
	if (refineTimeoutID) {
		window.clearTimeout(refineTimeoutID);
	}

	refineTimeoutID = window.setTimeout(SearchNavigators.postBackRefine, 2000);
}
SearchNavigators.addModifier = function(positive, ModifierValue)
{
	var hfPMods = $("[id*=_hfPMods]");
	var hfNMods = $("[id*=_hfNMods]");

	if(positive)
	{
		hfNMods.attr("value",hfNMods.attr("value").replace(ModifierValue, ''));
		hfPMods.attr("value",hfPMods.attr("value") + ModifierValue);
	}
	else
	{
		hfPMods.attr("value",hfPMods.attr("value").replace(ModifierValue, ''));
		hfNMods.attr("value",hfNMods.attr("value") + ModifierValue);
	}
	refineTimeoutID = window.setTimeout(SearchNavigators.postBackRefine, 2000);
}
SearchNavigators.deleteModifier = function (divModifierId, navigator) {
	var divModifier = document.getElementById(divModifierId);
	var hfPMods = $("[id*=_hfPMods]");
	var hfNMods = $("[id*=_hfNMods]");


	hfPMods.attr("value", hfPMods.attr("value").replace(navigator, ''));
	hfNMods.attr("value", hfNMods.attr("value").replace(navigator, ''));
	
	divModifier.style.display = 'none';

	if (timeoutID) {
		window.clearTimeout(timeoutID);
	}

	timeoutID = window.setTimeout(function () {
		showBusyLayer();
		$("[id*=_btnDeleteModifier]").click();
	},800);
}

SearchNavigators.postBackRefine = function () {
	showBusyLayer();
	$("[id*=_hfSeoMode]").attr("value", '0');
	$("[id*=_btnRefineSearch]").click();
}

/**/
/******************************************************************************************/
/* Autocompletion registration - start */
function RegisterAutoCompletion() {
	/* Registration for job name completion */

	$("[id*=_tbxJobname]").attr("autocomplete", "off");
	$("[id*=_tbxJobname]").autocomplete({
		source: function (request, response) {
			$.ajax({
				url: "/WebServices/SearchLocationAutoCompletion.asmx/GetSearchTermCompletionListJSON",
				dataType: "json",
				type: "POST",
				data: '{"prefixText":"' + request.term + '","count":6}',
				contentType: "application/json; charset=utf-8",
				success: function (data) {
					var items = jQuery.parseJSON(data.d);
					var parsed = [];
					for (var i = 0; i < items.length; i++) {
						parsed[i] = new Array();
						parsed[i].value = items[i].suggestion;

						var resultString = '<span class="autocomplete_item"><span class="autocomplete_highlight">';
						resultString += items[i].suggestion.substring(0, request.term.length);
						resultString += '</span>' + items[i].suggestion.substring(request.term.length) + '</span>';

						resultString += '<span class="autocomplete_resultCounter">';
						resultString += items[i].count + '&nbsp;Treffer&nbsp;</span><div style="clear:both;"></div>';

						parsed[i].label = resultString;
					};
					response(parsed);
				}
			});
		},
		minLength: 2,
		delay:200
	});
	/* Registration for location name completion */
	$("[id*=_tbxLocation]").attr("autocomplete", "off");
	$("[id*=_tbxLocation]").autocomplete({
		source: function (request, response) {
			$.ajax({
				url: "/WebServices/SearchLocationAutoCompletion.asmx/GetLocationCompletionList",
				dataType: "json",
				type: "POST",
				data: '{"prefixText":"' + request.term + '","count":6}',
				contentType: "application/json; charset=utf-8",
				success: function (data) {
					var items = data.d;
					var parsed = [];
					for (var i = 0; i < items.length; i++) {
						parsed[i] = new Array();
						parsed[i].value = items[i];

						var resultString = '<span class="autocomplete_item"><span class="autocomplete_highlight">';
						resultString += items[i].substring(0, request.term.length);
						resultString += '</span>' + items[i].substring(request.term.length) + '</span><div style="clear:both;"></div>';

						parsed[i].label = resultString;
					};
					response(parsed);
				}
			});
		},
		minLength: 2,
		delay: 200
	});
}
/* Autocompletion registration - end */
/* Search helper method for autocompletion preselections - start */
function setWhat(value) {
	$("[id*=_tbxJobname]").attr("value", value);
}
function setWhere(value) {
	$("[id*=_tbxLocation]").attr("value", value);
}
/* Search helper method for autocompletion preselections - end */


/* google maps features - start */
function RegisterModalPopups()
{
	$("#GMModalPopUp").dialog({
		autoOpen: false,
		height: 400,
		width: 600,
		modal: true,
		closeText: ' '
	});
}

function ShowGMMapPopUp(parameters)
{
	var scrollPos = $("html").scrollTop();
	$("#GMModalPopUp").dialog('open');
	$("#GMModalPopUpIFrame").attr("src", parameters);
	$("html").scrollTop(scrollPos);
}
/* google maps features - end */


String.formatEx = function(str) {
    for (var i = 1; i < arguments.length; i++) {
        str = str.replace('{' + (i - 1) + '}', arguments[i].toString());
    }
    return str;
}

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;
}

function getWindowSize() {
    var width = 0, height = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        width = window.innerWidth;
        height = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }
    return [width, height];
}

function showBusyLayer() {
    var divBusy = document.getElementById('divBusy');
    var divImg = document.getElementById('divImgBusy');
    var windowSize = getWindowSize();
    var scrollTop = document.documentElement.scrollTop ? document.documentElement.scrollTop :
        document.body.scrollTop;

    if (windowSize[0] > 1077)
        divBusy.style.left = ((windowSize[0] - 1077) / 2).toString() + "px";
    else
        divBusy.style.left = "0px";

    divImg.style.top = (scrollTop + (windowSize[1] - 54) / 2).toString() + "px";
    divBusy.style.display = 'block';
}

var selectedNavigator = new Array();
function toogleVisibility(elemId) {
    var elem = document.getElementById(elemId);

    if (elem.style.display == 'block') {
        elem.style.display = 'none';
        var i = 0;
        for (; i < selectedNavigator.length; i++) {
            if (selectedNavigator[i] == elemId)
                break;
        }
        
        if(i < selectedNavigator.length)
            selectedNavigator.splice(i, 1);
        
    }
    else {
        elem.style.display = 'block';
        selectedNavigator.push(elemId);
    }
}


function renderTextToSize(tgtElement, renderTgt, maxWidth) {
    var text = tgtElement.innerHTML.replace(/^\s+|\s+$/g, '')
        .replace(/&amp;/g, '&');
    
    for (var i = 0; i < text.length && renderTgt.offsetWidth < maxWidth; i++) {
        renderTgt.innerHTML += text.charAt(i) == ' ' ? '&nbsp;' : text.charAt(i) == '&' ? '&amp;' : text.charAt(i);
    }
    tgtElement.innerHTML = renderTgt.innerHTML;
    if (i < text.length) {
        tgtElement.innerHTML += '...';
        tgtElement.setAttribute('title', text);
    }
        
    renderTgt.innerHTML = '';
}

/* *********************************************************************
AutoComplete highlightning
*/
function AutoCompletePopulatedHighlight(source, eventArgs) {
    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) {
    var autoCompleteResultText = 'Treffer';

    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;' + autoCompleteResultText + '&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 = 'txt1';", source._completionInterval);
   }

   /******************/





/*****************************************************************************/
   function loadScriptOnDemand(scriptPath) {
   	var head = document.getElementsByTagName('head')[0];
   	var script = document.createElement('script');
   	script.type = 'text/javascript';
   	script.src = scriptPath;
   	head.appendChild(script);
   }
/*****************************************************************************/
