
var d = document;
var winIE = (navigator.userAgent.indexOf("Opera") == -1 && (d.getElementById && d.documentElement.behaviorUrns)) ? true : false;

function bodySize() {
	if (winIE && d.documentElement.clientWidth) {
		sObj = d.getElementsByTagName("body")[0].style;
		sObj.width = (d.documentElement.clientWidth < 1220) ? "1220px" : "100%";
	}
}

function init() {
	if (winIE) { bodySize(); }
}
onload = init;
if (winIE) { onresize = bodySize; }

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: '/gfx/blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img").each(function() {

			jQuery(this).attr('width', jQuery(this).width());
			jQuery(this).attr('height', jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:' + this.style.border + ';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:' + this.style.padding + ';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:' + this.style.margin + ';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span ' + imgId + imgClass + imgTitle + imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;' + imgAlign + imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle + '"></span>';
			if (prevStyle != '') {
				strNewHTML = '<span style="position:relative;display:inline-block;' + prevStyle + imgHand + 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;' + '">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function() {
			var bgIMG = jQuery(this).css('background-image');
			if (bgIMG.indexOf(".png") != -1) {
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});

		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
			jQuery(this).attr('src', settings.blankgif)
		});

	}

	return jQuery;

};

(function($) {

	$.fn.filestyle = function(options) {

		/* TODO: This should not override CSS. */
		var settings = {
			width: 250
		};

		if (options) {
			$.extend(settings, options);
		};

		return this.each(function() {
			var cssClass = settings.cssclass;
			var self = this;
			var wrapper = $("<div class=" + cssClass + ">")
                            .css({
                            	"width": settings.imagewidth + "px",
                            	"height": settings.imageheight + "px",
                            	"background": "url(" + settings.image + ") 0 0 no-repeat",
                            	"background-position": "right",
                            	"display": "inline",
                            	"position": "absolute",
                            	"overflow": "hidden"
                            });

			var filename = $('<input class="file">')
                             .addClass($(self).attr("class"))
                             .css({
                             	"display": "inline",
                             	"width": settings.width + "px"
                             });

			$(self).before(filename);
			$(self).wrap(wrapper);

			$(self).css({
				"position": "relative",
				"height": settings.imageheight + "px",
				"width": settings.width + "px",
				"display": "inline",
				"cursor": "pointer",
				"opacity": "0.0"
			});

			if ($.browser.mozilla) {
				if (/Win/.test(navigator.platform)) {
					$(self).css("margin-left", "-142px");
				} else {
					$(self).css("margin-left", "-168px");
				};
			} else {
				$(self).css("margin-left", settings.imagewidth - settings.width + "px");
			};

			$(self).bind("change", function() {
				filename.val($(self).val());
			});

		});


	};

})(jQuery);
function lightBoxShow(contentId, modal, height, className) {//function called when the user clicks on a thickbox link

	try {
		if (className == undefined)
		{ className = "popUp" }
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body", "html").css({ height: "100%", width: "100%" });
			$("html").css("overflow", "hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("#page").append("<iframe id='TB_HideSelect'></iframe><div id='LightBoxOverlay'></div><div id='lightBox' class='" + className + "'><div id='lightBoxBottom'></div>");
				$("#LightBoxOverlay").click(tb_remove);
			}
		} else {//all others
			if (document.getElementById("LightBoxOverlay") === null) {
				$("#page").append("<div id='LightBoxOverlay'></div><div id='lightBox' class='" + className + "'><div id='lightBoxBottom'></div>");
				$("#LightBoxOverlay").click(tb_remove);
			}
		}

		if (tb_detectMacXFF()) {
			$("#LightBoxOverlay").addClass("LightBoxOverlayMacFFBGHack"); //use png overlay so hide flash
		} else {
			$("#LightBoxOverlay").addClass("LightBoxOverlayBG"); //use background and opacity
		}
		TB_WIDTH = 510; //defaults to 630 if no paramaters were added to URL
		TB_HEIGHT = height + 40 || 496;  //defaults to 440 if no paramaters were added to URL
		ajaxContentW = TB_WIDTH - 80;
		ajaxContentH = TB_HEIGHT - 45;

		$("#TB_iframeContent").remove();
		if (modal != 1) {//ajax no modal
			$("#lightBox").append("<a href='#' onclick='return false;' id='lightBoxClose'></a> <div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
		} else {//ajax modal
			$("#LightBoxOverlay").unbind();
			$("#lightBox").append("<div id='TB_ajaxContent' class='TB_modal' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
		}
		$("#lightBoxClose").click(tb_remove);

		$("#TB_ajaxContent").append($('#' + contentId).children());
		$("#lightBox").unload(function() {
			$('#' + contentId).append($("#TB_ajaxContent").children()); // move elements back when you're finished
		});
		tb_position();
		$("#TB_load").remove();
		$("#lightBox").css({ display: "block" });
		if (modal != 1) {
			document.onkeyup = function(e) {
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if (keycode == 27) { // close
					tb_remove();
				}
			};
		}

		$("#TB_ajaxContent input")[0].focus();

	} catch (e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe() {
	$("#TB_load").remove();
	$("#TB_window").css({ display: "block" });
	iframe = document.getElementById('TB_iframeContent').contentWindow.document;
	link = iframe.getElementById('logo');
	irframeBody = iframe.getElementsByTagName("body")
	$(irframeBody).addClass("iframe");
	if (link || false)
		$(link).click(function() {
			tb_remove();
			return false;
		});

}
function tb_remove() {

	$("#lightBoxClose").unbind("click");
	//$("#lightBox").fadeOut(10, function() {
	$("#lightBox").hide();
	$('#lightBox,#LightBoxOverlay,#TB_HideSelect').trigger("unload").unbind().remove();

	//});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body", "html").css({ height: "auto", width: "auto" });
		$("html").css("overflow", "");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
	$("#lightBox").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
	if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#lightBox").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
	}
}


function tb_getPageSize() {
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w, h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
	var userAgent = navigator.userAgent.toLowerCase();
	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
		return true;
	}
}
function cuttingLink(object, width, char) {
	$(object).each(function(index) {
		if ($(this).width() >= width) {
			$(this).html($(this).html().substring(0, char)).append("..");

		}

	});

}
function saveStatus() {
	var statusValue = '';
	$('#searchFilters dl').not(".collapsed").each(function(index) {
		if ($(this).hasClass("expanded")) {
			statusValue += $(this).attr("id") + ' expanded;';
		}
		else {
			statusValue += $(this).attr("id") + ';';
		}
	});
	$('#status').val(statusValue);
}
function paginatorLoad() {
	var ulWrapper = $(".paginator .wrapper ul");
	if (ulWrapper.length > 0) {
		var index = $(".paginator .wrapper li").index($(".paginator .wrapper li.active")) + 1;
		var step = Math.ceil(index / 5) - 1;



		$(".paginator .wrapper ul").css("left", step * -150);
		var ulWrapperPos = ulWrapper.position();
		var ulChildLength = ulWrapper.children().length;

		if ((Math.abs(ulWrapperPos.left) / 150) == (Math.ceil(ulChildLength / 5) - 1)) {
			$(".paginator .next").addClass("disabled");
		}
		if (Math.abs(ulWrapperPos.left) == 0) {
			$(".paginator .prev").addClass("disabled");
		}
	}
}
function paginatorNext(el) {


	var ulWrapper = $(el).parent().children(".wrapper").children();
	var queue = ulWrapper.queue("fx").length;
	if (!queue) {
		var ulWrapperPos = ulWrapper.position();
		var ulChildLength = ulWrapper.children().length;

		if ((Math.abs(ulWrapperPos.left) / 150) != (Math.ceil(ulChildLength / 5) - 1)) {
			ulWrapper.animate({ left: ulWrapperPos.left - 150 + "px" }, 250);
			ulWrapperPos = ulWrapper.position();
			$(".paginator .prev").removeClass("disabled")
			if ((Math.abs(ulWrapperPos.left) / 150) == (Math.ceil(ulChildLength / 5) - 2)) {
				$(".paginator .next").addClass("disabled");
			}

		}
	}
	return false;
}
function paginatorPrev(el) {
	$(this).unbind('click');
	var ulWrapper = $(el).parent().children(".wrapper").children();
	var queue = ulWrapper.queue("fx").length;
	if (!queue) {
		var ulWrapperPos = ulWrapper.position();
		$(".paginator .prev").unbind
		var ulChildLength = ulWrapper.children().length;

		if (Math.abs(ulWrapperPos.left) != 0) {
			ulWrapperPos = ulWrapper.position();
			$(".paginator .next").removeClass("disabled");

			if (Math.abs(ulWrapperPos.left) == 150) {
				$(".paginator .prev").addClass("disabled");
			}
			ulWrapper.animate({ left: ulWrapperPos.left + 150 + "px" }, 250);


		}

	}
}
function collapseFilterBox(SearchFilterId, animate) {
	var item = $('#' + SearchFilterId);
	var height = item.height();

	item.data("number", item.children("dd").not(".bottomShaddow, .map, :hidden").length);
	if (animate) { item.animate({ height: "9px" }, 250); }


	item.children("dd").not(".bottomShaddow").addClass("hidden").hide();
	item.addClass("collapsed");
}

function expandFilterBox(SearchFilterId, animate) {
	var item = $('#' + SearchFilterId);
	var shownByDefault = parseInt(item.children('input[type="hidden"]:eq(0)').val());
	var visibleLinksNumber = item.children("dd").not(".bottomShaddow, .map, .link, .showMorePopup, #navigatorEmptyMessage").length;
	var height = 0;

	if (visibleLinksNumber == 0) {
		item.children('#navigatorEmptyMessage').show();
	}

	if (item.data("number") > 0) {
		if (item.hasClass("expanded") && item.data("number") > shownByDefault) {
			height = (shownByDefault + 1) * 18;
			if (height <= 72) {
				item.addClass("small")
			}
		}
		else {
			height = (item.data("number") + 1) * 18;
			if (height <= 72) {
				item.addClass("small")
			}
		}
	}
	else {
		if (item.hasClass("expanded") && visibleLinksNumber > shownByDefault) {
			height = (shownByDefault + 1) * 18;
			if (height <= 72) {
				item.addClass("small")
			}
		}
		else {
			height = (visibleLinksNumber + 1) * 18;
			if (height <= 72) {
				item.addClass("small")
			}
		}
	}

	var fixedHeight = false;
	// If we have a map in the box, the min height is 108.	
	if (item.hasClass("searchPageMapLinks") && height < 108) {
		fixedHeight = true;
		height = 108;
	}


	if (animate) {
		item.animate({ height: height + "px" }, { complete: function() { if (!fixedHeight) { $(this).css("height", ""); } } }, 250);
	}
	else {
		if (fixedHeight) {
			item.css("height", height + "px");
		}
		else {
			item.css("height", "");
		}
	}

	item.children("dd").not(".link, .bottomShaddow, .map, .showMorePopup, #navigatorEmptyMessage").each(function(index) {
		if (!item.hasClass("expanded") || index < shownByDefault) {
			$(this).removeClass("hidden").show();
		}
	});
	if (visibleLinksNumber > shownByDefault) {
		item.children("dd.link").removeClass("hidden").show();
	}
	if (!item.hasClass("expanded") || visibleLinksNumber <= shownByDefault) {
		item.children("dd.showMorePopup").removeClass("hidden").show();
	}
	item.children("dd").filter(".bottomShaddow, .map").removeClass("hidden").show();

	item.removeClass("collapsed");
}


function moreLinkCollapseFilterBox(SearchFilterId, animate) {

	var item = $('#' + SearchFilterId);
	var namberOfdd = item.children("dd").not(".link, .bottomShaddow, .map, #navigatorEmptyMessage, .showMorePopup").length;
	var shownByDefault = item.children('input[type="hidden"]:eq(0)').val();
	if (namberOfdd > shownByDefault) {
		var ddLength = item.children("dd").not(".bottomShaddow, .map, #navigatorEmptyMessage").length;
		var ddHeight = item.children("dd").height();
		if (animate) { item.animate({ height: ddHeight * ddLength + 16 + "px" }, { complete: function() { $(this).css("height", ""); } }, 250); }
		else { $(this).css("height", ddHeight * ddLength + 16 + "px") }
		item.children("dd").not("#navigatorEmptyMessage").show().removeClass("hidden");
		item.removeClass("expanded");
	}
}
function moreLinkExpandFilterBox(SearchFilterId, animate) {
	var item = $('#' + SearchFilterId);
	var namberOfdd = item.children("dd").not(".link, .bottomShaddow, .map, #navigatorEmptyMessage").length;
	var shownByDefault = parseInt(item.children('input[type="hidden"]:eq(0)').val());
	if (namberOfdd > shownByDefault) {
		var ddHeight = item.children("dd").height();
		var serviceLinksNumber = item.children("dd").filter(".link, .bottomShaddow").length;
		if (animate) {
			item.animate({ height: ddHeight * (shownByDefault + serviceLinksNumber) + 16 + "px" }, { complete: function() { $(this).css("height", ""); } }, 250);
		}
		else {
			$(this).css("height", ddHeight * (shownByDefault + serviceLinksNumber) + 16 + "px");
		}
		item.children("dd").not(".link, .bottomShaddow, .map, #navigatorEmptyMessage").each(function(index) {
			if (index >= shownByDefault) {
				$(this).addClass("hidden").hide();
			}
		});

		item.addClass("expanded");
	}
}

function FilterBoxSlideDown() {
	$(".filtersWrapper ul li.temp").slideDown(500).removeClass("temp").removeClass("hidden");
}

function SaveSearch(nameControlId, errorControlId) {
	var theForm = document.getElementsByTagName("form");
	var formAction = theForm[0].action;
	var searchName = $('#' + nameControlId).val();

	$.ajax({
		async: true,
		type: "POST",
		url: formAction,
		data: { ajax: true,
			isSavingSearch: true,
			CreationName: searchName,
			__VIEWSTATE: $("input[id='__VIEWSTATE']").val(),
			__ASYNCPOST: true
		},
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		success: function(msg) {
			if (msg.length == 0) {
				$('#' + errorControlId).hide();
				tb_remove();
				lightBoxShow('saveSearchSuccess', 0, 100, 'saveSearchResult');
			}
			else {
				var urlString = msg.split('=');
				if (urlString.length == 2 && urlString[0] == 'URL') {
					document.location = urlString[1];
				}
				else {
					$('#' + errorControlId).show();
					$('#' + errorControlId).html(msg);
				}
			}
		}
	});
}

function SaveJobAgent(nameControlId, frequencyControlId, errorControlId) {
	var theForm = document.getElementsByTagName("form");
	var formAction = theForm[0].action;
	var jobAgentName = $('#' + nameControlId).val();
	var frequency = $('#' + frequencyControlId).val();

	$.ajax({
		async: true,
		type: "POST",
		url: formAction,
		data: { ajax: true,
			isSavingJobAgent: true,
			CreationName: jobAgentName,
			Frequency: frequency,
			__VIEWSTATE: $("input[id='__VIEWSTATE']").val(),
			__ASYNCPOST: true
		},
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		success: function(msg) {
			if (msg.length == 0) {
				$('#' + errorControlId).hide();
				tb_remove();
				lightBoxShow('saveJobAgentSuccess', 0, 100, 'saveSearchResult');
			}
			else {
				var urlString = msg.split('=');
				if (urlString.length == 2 && urlString[0] == 'URL') {
					document.location = urlString[1];
				}
				else {
					$('#' + errorControlId).show();
					$('#' + errorControlId).html(msg);
				}
			}
		}
	});
}

function UserLogin(loginControlId, passwordControlId, loginErrorControlId, passwordErrorControlId, loginButtonName) {
	var theForm = document.getElementsByTagName("form");
	var formAction = theForm[0].action;
	var loginErrorLabel = $('#' + loginErrorControlId);
	var passwordErrorLabel = $('#' + passwordErrorControlId);

	var responseText =
		$.ajax({
			async: false,
			type: "POST",
			url: formAction,
			data: { ajax: true,
				isLoggingIn: true,
				UserName: $('#' + loginControlId).val(),
				Password: $('#' + passwordControlId).val(),
				__VIEWSTATE: $("input[id='__VIEWSTATE']").val(),
				__ASYNCPOST: true
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8"
		}).responseText;

	$(loginErrorLabel).hide();
	$(passwordErrorLabel).hide();
	if (responseText.length == 0) {
		WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(loginButtonName, "", false, "", "", true, true));
	}
	else {
		var splitResult = responseText.split('##');
		if (splitResult.length > 1) {
			if (splitResult[0] == '0') {
				$(loginErrorLabel).show();
				$(loginErrorLabel).html(splitResult[1]);
			}
			else {
				$(passwordErrorLabel).show();
				$(passwordErrorLabel).html(splitResult[1]);
			}
		}
		if (splitResult.length > 3) {
			if (splitResult[2] == '0') {
				$(loginErrorLabel).show();
				$(loginErrorLabel).html(splitResult[3]);
			}
			else {
				$(passwordErrorLabel).show();
				$(passwordErrorLabel).html(splitResult[3]);
			}
		}
	}
}

function SendSms(nameControlId, phoneControlId, checkBoxId, nameErrorId, phoneErrorId, totalErrorId) {
	var theForm = document.getElementsByTagName("form");
	var formAction = theForm[0].action;

	var responseText =
		$.ajax({
			async: false,
			type: "POST",
			url: formAction,
			dataType: "json",
			data: { ajax: true,
				isSendingSms: true,
				CreationName: $('#' + nameControlId).val(),
				PhoneNumber: $('#' + phoneControlId).val(),
				SendSmsCheckBox: $('#' + checkBoxId).attr('checked'),
				__VIEWSTATE: $("input[id='__VIEWSTATE']").val(),
				__ASYNCPOST: true
			},
			contentType: "application/x-www-form-urlencoded; charset=utf-8"
		}).responseText;

	$('#' + nameErrorId).hide();
	$('#' + phoneErrorId).hide();
	$('#' + totalErrorId).hide();
	var urlString = responseText.split('=');
	if (urlString.length == 2 && urlString[0] == 'URL') {
		var idx = urlString[1].indexOf('[');
		document.location = urlString[1].substring(0, idx);
	}
	else {
		var data = eval(responseText);
		if (data != null && data.length > 0) {
			for (var i = 0; i < data.length; i++) {
				var errorLabel = $('#' + data[i].Key);
				errorLabel.html(data[i].Value);
				errorLabel.show();
			}
		}
		else {
			tb_remove();
			lightBoxShow('sendSmsConfirmation', 0, 250, '');
		}
	}
}

function SaveVisitedAdvert(cookieValue, cookieExpiry, headerId) {
	var savedCookies = document.cookie;
	var cookieNumber = 0;
	var advertsBeggining = savedCookies.indexOf('VisitedAdverts=', 0);
	var advertCookies = '';
	if (advertsBeggining > -1) {
		advertsBeggining = advertsBeggining + 15;
		var advertsEnd = savedCookies.indexOf(';', advertsBeggining);
		if (advertsEnd == -1) {
			advertsEnd = savedCookies.length;
		}
		else {
			advertsEnd--;
		}
		advertCookies = savedCookies.substring(advertsBeggining, advertsEnd);
		var advertCookiesEntries = advertCookies.split('&');
		var advertCookiesLastEntryKey = advertCookiesEntries[advertCookiesEntries.length - 1].split('=')[0];
		cookieNumber = parseInt(advertCookiesLastEntryKey.substring(14)) + 1;
		advertCookies += '&';
	}

	var header = $('#' + headerId);
	if (!header.hasClass('visited')) {
		header.addClass('visited');
	}

	advertCookies += 'VisitedAdverts' + cookieNumber + '=' + cookieValue;
	document.cookie = 'VisitedAdverts=' + advertCookies + '; expires=' + cookieExpiry + '; path=/';
}

function OpenJobnetAdvert(cookieValue, cookieExpiry, navigateUrl, headerId) {
	SaveVisitedAdvert(cookieValue, cookieExpiry, headerId);
	window.open(navigateUrl, 'jobnetadvert', 'status=1');
}
function fileInputTheme() {
	$("input[type=file]").filestyle({
		image: "/gfx/choose_the_file-picture.png",
		imageheight: 30,
		imagewidth: 96,
		width: 205,
		cssclass: "fileInputButton"
	});
};
function preload(images) {
	if (typeof document.body == "undefined") return;
	try {
		var div = document.createElement("div");
		var s = div.style;
		s.position = "absolute";
		s.top = s.left = 0;
		s.visibility = "hidden";
		document.body.appendChild(div);
		div.innerHTML = "<img src=\"" + images.join("\" /><img src=\"") + "\" />";
	} catch (e) {
		// Error. Do nothing.
	}
}




$(document).ready(function() {

	paginatorLoad();
	markReadAdverts();
	fileInputTheme();
	FilterBoxSlideDown();

	$('.mainLogo').pngFix();
	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		DD_belatedPNG.fix('a#lightBoxClose, a.lightBoxClose, #lightBoxBottom, .lightBoxBottom, #lightBox, .modalPopup, .modalPopupWide');
	}

	$('input[type="text"]').each(function(index) {
		// Getting the attached label for later references
		var $label = $(this).siblings('label');
		// if a label is absolute positioned we take it for
		// granted that it's placed on top of the input field
		// and hides and show it depending on focus on the input field
		if ($label.css('position') == 'absolute') {
			if ($(this).val() == '') { $label.show() };
			$(this).focus(function() { $label.hide() });
			$(this).blur(function() {
				if ($(this).val() == '') { $label.show() };
			});
		};
	});

	$("#regionContent ul li").each(function(index) {
		var linkName = $(this).attr("id").split('Link');
		var areaName = $("#Area" + linkName[1]);
		if ($(areaName).length) {
			if ($(this).hasClass('disabled')) {
				$(areaName).addClass("disabled");
				$(areaName)[0].href = "javascript:void(0);";
				$(this).children("a")[0].href = "javascript:void(0);";
			}
			else {
				$(areaName)[0].href = $(this).children("a")[0].href;
			}
		}
	});

	$(".filtersWrapper ul li a").live("click", function() {
		if ($(".filtersWrapper ul li").length == 2) {
			$(".filtersWrapper ul li").not(".last").parent().slideUp(500, function() { $(this).remove(); });
			$(".filtersWrapper ul").next().slideUp(500, function() { });
		}
		$(this).not(".last").parent().slideUp(500, function() { $(this).remove(); });

	});

	$(".filtersWrapper ul li.last a").click(function() {
		$(".filtersWrapper ul li").not(".last").parent().slideUp(500, function() { $(this).remove(); });
		$(".filtersWrapper ul").next().slideUp(500, function() { });
	});


	$("#searchFilters dd:not(.link, .map, .showMorePopup) a").click(function() {
		var controlId = $(this).parent().parent().attr("id");
		if (controlId.indexOf("uiSubCategory") == -1) {
			collapseFilterBox(controlId, 1);
		}
	});

	$("#searchFilters dd.map area").click(function() {
		if (!$(this).attr('href')) {
			var areaName = $(this).attr("id").split('Area');
			var linkName = $("#Link" + areaName[1]).children('a');
			if ($(linkName).length) {
				var SearchFilterId = $(this).parent().parent().parent().attr("id");
				var numberOfdd = $('#' + SearchFilterId).children("dd").not(".link, .bottomShaddow, .map, .showMorePopup").length;
				if (numberOfdd == 1 || ($(linkName).data('filterType') != 2 && $(linkName).data('filterType') != 6)) {
					collapseFilterBox(SearchFilterId, 1);
				}
				__doPostBack(SearchFilterId, $(linkName).data('filterKey') + "##" + $(linkName).data('filterName') + "##" + $(linkName).data('filterType'));

				return false;
			}
			else {
				return false;
			}
		}
	});


	$(".tabName a").click(function() {
		$(".tabName").removeClass("active");
		$(this).parent().addClass("active");
		$(".tabContent").removeClass("active");
		var id = $(this).parent().attr("id").split('Tab');
		$("#" + id[0] + "Content").addClass("active");
		return false;
	});
	var t = 1;
	var p = 0;
	var m = 0;
	var s = $(".teaser").size();
	var w = $(".teaser").outerWidth();
	var autoStartSliderInretval = 8000;
	$(".filtersWrapper ul li a").each(function() {
		if ($(this).outerWidth() > 0) {
			$(this).parent('li').width($(this).outerWidth());
		}

	});
	$(".teaser").each(function() {
		$(this).css({ position: 'absolute', left: p, display: 'block' });
		p = p + w;
	});
	if ($(".teaser").size()) {
		if (autoStartSliderInretval) {
			sliderIntervalID = setInterval(
		function() {
			nextTeaser();
		},
		autoStartSliderInretval);
		}
	}
	$(".nextTeaser").click(function() {
		nextTeaser();
		return false;
	});
	$(".previosTeaser").click(function() {
		previosTeaser();
		return false;
	});
	function nextTeaser() {
		var teaserQueue = $(".teaserWrapper").queue("fx").length;
		if (!teaserQueue) {

			t = t + 1;
			m = (-(t * w - w - 20));
			$(".teaserWrapper img").slideUp(50);
			$(".teaserWrapper").animate({ left: m }, 300, function() {
				if (t === s + 1) {
					t = 1;
					$(".teaserWrapper").css({ left: 20 }, function() { $(".teaserWrapper").animate({ left: m }) });
					$(".teaserWrapper").children(':eq(0)').css({ left: 0 });
					$(".teaserWrapper").children(':eq(' + (s - 1) + ')').css({ position: 'absolute', left: -w });
				}
				if (t === s) {
					$(".teaserWrapper").children(':eq(0)').css({ left: (s * w) });
				}
				if (t === s - 1) {
					$(".teaserWrapper").children(':eq(' + (s - 1) + ')').css({ left: s * w - w })
				};
				$(".teaserWrapper img").slideDown(150);
			});
		}
		return false;
	}


	function previosTeaser() {
		var teaserQueue = $(".teaserWrapper").queue("fx").length;
		if (!teaserQueue) {
			t = t - 1;
			m = (-(t * w - w - 20));
			$(".teaserWrapper img").slideUp(50);
			$(".teaserWrapper").animate({ left: m }, 300, function() {
				if (t === 0) {
					t = s;
					$(".teaserWrapper").children(':eq(' + (s - 1) + ')').css({ position: 'absolute', left: (s * w - w) });

					$(".teaserWrapper").css({ left: -(s * w - w - 20) });
					$(".teaserWrapper").children(':eq(0)').css({ left: (s * w) });
				}
				if (t === 2) $(".teaserWrapper").children(':eq(0)').css({ position: 'absolute', left: 0 });
				if (t === 1) $(".teaserWrapper").children(':eq(' + (s - 1) + ')').css({ position: 'absolute', left: -w });
				$(".teaserWrapper img").slideDown(150);

			});
		}

	};


	$(".paginator .next").click(function() {
		paginatorNext(this);
		return false;
	});

	$(".paginator .prev").click(function() {
		paginatorPrev(this);
		return false;
	});
	/*
	Toggles
	*/

	$("#searchFilters dt").click(
		function() {
			var SearchFilterId = $(this).parent().attr("id");
			var currentId = $(this).attr("id");
			//saveStatus();
			if ($(this).parent().hasClass("collapsed")) {
				var item = $(this).parent();
				if (item.children("dd").not(".link, .bottomShaddow, .map, .showMorePopup, #navigatorEmptyMessage").length == 0) {
					var theForm = document.getElementsByTagName("form");
					var formAction = theForm[0].action;
					var usePageShadow = initHourglass(false, 'page');
					var requestParams = item.children('input[type="hidden"]:eq(1)').val().split("##");
					var shownByDefault = item.children('input[type="hidden"]:eq(0)').val();
					if (usePageShadow) {
						canEnable = false;
						disablePage();
					}

					$.ajax({
						async: true,
						type: "POST",
						url: formAction,
						data: { ajax: true,
							PopulatingNavigator: true,
							CategoryType: requestParams[0],
							ParentValue: requestParams[1],
							ShowByDefault: shownByDefault,
							__VIEWSTATE: $("input[id='__VIEWSTATE']").val(),
							__ASYNCPOST: true
						},
						contentType: "application/x-www-form-urlencoded; charset=utf-8",
						dataType: "json",
						success: function(msg) {
							var categoryBoxResponse = eval(msg);
							// In the other way around, because inserting after <dt> [$('#' + currentId).after(dd)]
							for (var i = categoryBoxResponse.length - 1; i >= 0; i--) {
								var filter = categoryBoxResponse[i];
								var dd = $('<dd ' + filter.ElementAttributes + '></dd>');
								var anchor = $('<a></a>')
													.attr({ title: filter.FilterName })
													.attr({ href: '' })
													.text(filter.FilterName)
													.data("filterType", filter.FilterType)
													.data("filterKey", filter.FilterKey)
													.data("filterName", filter.FilterName)
													.click(
														function() {
															var namberOfdd = $(this).parent().parent().children("dd").not(".link, .bottomShaddow, .map, .showMorePopup").length;

															if (namberOfdd == 1 || ($(this).data('filterType') != 2 && $(this).data('filterType') != 6)) {
																collapseFilterBox(SearchFilterId, 1);
															}
															__doPostBack($(this).parent().parent().attr("id"), $(this).data('filterKey') + "##" + $(this).data('filterName') + "##" + $(this).data('filterType'));

															return false;
														})
													.hover(
														function() {
															var areaName = $(this).parent().attr("id").split('Link');
															if (areaName.length > 1) {
																$("#Link" + areaName[1]).addClass("hover");
																$("#searchPageMap").attr("src", "/gfx/search_page/" + areaName[1] + ".png");
															}
															else {
																$(this).parent().addClass("hover");
															}
														},
														function() {
															var areaName = $(this).parent().attr("id").split('Link');
															if (areaName.length > 1) {
																$("#Link" + areaName[1]).removeClass("hover");
																$("#searchPageMap").attr("src", "/gfx/search_page/denmark.png");
															}
															else {
																$(this).parent().removeClass("hover");
															}
														});
								dd.append(anchor).append('<span>(' + filter.MatchingResultsCount + ')</span>');

								$('#' + currentId).after(dd);
							}
							if (usePageShadow) {
								enablePage();
							}

							$('#' + SearchFilterId).data("number", categoryBoxResponse.length);

							//$('#' + currentId).after(msg);
							expandFilterBox(SearchFilterId, 1);
						}
					});
				}
				else {
					expandFilterBox(SearchFilterId, 1);
				}
			}
			else {
				collapseFilterBox(SearchFilterId, 1);
			}
		}
	);

	$("#searchFilters dd:not(.link, .bottomShaddow, .map, .showMorePopup) a").hover(
			function() {
				var areaName = $(this).parent().attr("id").split('Link');
				if (areaName.length > 1) {
					$("#Link" + areaName[1]).addClass("hover");
					$("#searchPageMap").attr("src", "/gfx/search_page/" + areaName[1] + ".png");
				}
				else {
					$(this).parent().addClass("hover");
				}
			},
			function() {
				var areaName = $(this).parent().attr("id").split('Link');
				if (areaName.length > 1) {
					$("#Link" + areaName[1]).removeClass("hover");
					$("#searchPageMap").attr("src", "/gfx/search_page/denmark.png");
				}
				else {
					$(this).parent().removeClass("hover");
				}
			});

	$(".showMorePopup a").click(
		function() {
			var popupPanelId = $(this).parent().parent().parent().children('div.lightBoxContainer').attr("id");
			var theForm = document.getElementsByTagName("form");
			var formAction = theForm[0].action;

			var usePageShadow = initHourglass(false, 'page');
			if (usePageShadow) {
				canEnable = false;
				disablePage();
			}

			$.ajax({
				async: true,
				type: "POST",
				url: formAction,
				data: { ajax: true,
					CategoryType: 4,
					__VIEWSTATE: $("input[id='__VIEWSTATE']").val(),
					__ASYNCPOST: true
				},
				contentType: "application/x-www-form-urlencoded; charset=utf-8",
				dataType: "json",
				success: function(msg) {
					var firstLetter = '';
					var categoryBoxResponse = eval(msg);
					for (var i = 0; i < categoryBoxResponse.length; i++) {
						var filter = categoryBoxResponse[i];
						var anchor = $('<a></a>')
										.attr({ href: '' })
										.attr({ title: filter.FilterName })
										.text(filter.FilterName)
										.data("filterType", filter.FilterType)
										.data("filterKey", filter.FilterKey)
										.data("filterName", filter.FilterName)
										.click(function() {
											__doPostBack('industryPopup', $(this).data('filterKey') + "##" + $(this).data('filterName') + "##" + $(this).data('filterType'));
											return false;
										});
						var li = $('<li></li>');
						var currentFirstLetter = filter.FilterName.substr(0, 1);
						if (currentFirstLetter != firstLetter) {
						    firstLetter = currentFirstLetter.toUpperCase();
						    li.append('<strong>' + firstLetter + '</strong>').append('<br/>');
						}
						li.append(anchor).append('<span>(' + filter.MatchingResultsCount + ')</span>');

						var ul = $('<ul></ul>').append(li);
						$('#' + popupPanelId).append(ul);
					}
					if (usePageShadow) {
						enablePage();
					}
					lightBoxShow(popupPanelId, 0, 250, 'AlphabeticalList');
				}
			});
			return false;
		}
	);

	$("#searchFilters .link").click(
		function() {
			var SearchFilterId = $(this).parent().attr("id");
			if ($(this).parent().hasClass("expanded")) {
				moreLinkCollapseFilterBox(SearchFilterId, 1);
				$(this).children().html("Vis f&aelig;rre");
			}
			else {
				moreLinkExpandFilterBox(SearchFilterId, 1);
				$(this).children().html("Vis flere");
			}
			//saveStatus();
			return false;
		}
	);
	$("#searchResultBox dl").click(
		function() {
			window.location = ($(this).children("dt").children("a").attr("href"));
		}
	);
	$("#viewAllIndusties").click(
		function() {
			lightBoxShow('allSubIndustriesPopup', 0, 250, 'allSubIndustriesPopup');
			return false;
		}
	)

	$("#viewAllAbroadCountries").click(
		function() {
			lightBoxShow('allForeignCountriesPopup', 0, 100, 'allForeignCountriesPopup');
			return false;
		}
	)


	/*
	HOVERS
	*/

	$(".bannerWrapper").hover(
		function() {
			$(this).addClass("hover");
			$(this).parent().addClass("hover");
		},
		function() {
			$(".bannerWrapper").removeClass("hover");
			$(this).parent().removeClass("hover");
		}
	);
	$("#benefits").hover(
		function() {

			clearInterval(sliderIntervalID);

		},
		function() {

			sliderIntervalID = setInterval(
		function() {
			nextTeaser();
		},
		autoStartSliderInretval);

		}
	);

	$(".filtersWrapper ul").hover(
		function() {
			$(this).children('.last').slideDown();

		},
		function() {
			$(this).children('.last').slideUp();
		}
	);
	$(".paginator li").not(".wrapper").hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(".paginator li").removeClass("hover");
		}
	);
	$(".filtersWrapper ul li").live("mouseover",
		function() {
			$(this).addClass("hover");
		}
	);
	$(".filtersWrapper ul li").live("mouseout",
		function() {
			$(this).removeClass("hover");
		}
	);
	$("#searchResultBox dl").hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		}
	);
	$(".tabName").hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		}
	);
	$(".logos a img").hover(
		function() {
			$(this).animate({ opacity: 0.5 }, 300);
		},
		function() {
			$(this).animate({ opacity: 1 }, 300);
		}
	);
	$("map area").hover(
		function() {
			var areaName = $(this).attr("id").split('Area');
			$("#Link" + areaName[1]).addClass("hover");
			$("#fronpageMap, #searchPageMap").attr("src", "/gfx/fronpage_map/" + areaName[1] + ".png");
		},
		function() {
			var areaName = $(this).attr("id").split('Area');
			$("#Link" + areaName[1]).addClass("hover");
			$("#fronpageMap, #searchPageMap").attr("src", "/gfx/fronpage_map/denmark.png");
		}
	);

	$("#regionContent ul li").hover(
		function() {
			$("#regionContent ul li").removeClass("hover");
			var areaName = $(this).attr("id").split('Link');
			$("#Link" + areaName[1]).addClass("hover");
			$("#fronpageMap, #searchPageMap").attr("src", "/gfx/fronpage_map/" + areaName[1] + ".png");
		},
		function() {

			$("#regionContent ul li").removeClass("hover");
			$("#fronpageMap, #searchPageMap").attr("src", "/gfx/fronpage_map/denmark.png");
		}
	);
	$("#regionContent").mouseout(
		function() {
			$("#regionContent ul li").removeClass("hover");
		}
	);
	$(".searchPageMapLinks map area").hover(
		function() {
			var areaName = $(this).attr("id").split('Area');
			$("#Link" + areaName[1]).addClass("hover");
			$("#searchPageMap").attr("src", "/gfx/search_page/" + areaName[1] + ".png");
		},
		function() {
			var areaName = $(this).attr("id").split('Area');
			$("#Link" + areaName[1]).addClass("hover");
			$("#searchPageMap").attr("src", "/gfx/search_page/" + areaName[1] + ".png");
		}
	);
	$(".searchPageMapLinks map").mouseout(
		function() {
			$(".searchPageMapLinks dd").removeClass("hover");
		}
	);
	$(".searchPageMapLinks map area").each(
		function() {
			var areaName = $(this).attr("id").split('Area');
			var linkName = $("#Link" + areaName[1]).children('a');
			if ($(linkName).length) {
				$(this).attr({ href: $(linkName).attr('href') });
			}

		}
	);



	Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
	function BeginRequestHandler(sender, args) {
		var elem = args.get_postBackElement();
		/* ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');*/
	}
	function EndRequestHandler(sender, args) {
		fileInputTheme();
	}
	function ActivateAlertDiv(visstring, elem, msg) {
		/* var adiv = $get(elem);
		adiv.style.visibility = visstring;
		adiv.innerHTML = msg;                     */
	}


})


function moveTop() {
	window.scroll(0, 0);
}

// From old design
function reallyCenterWindow(page, w, h) {
	leftPos = 0
	topPos = 0
	if (screen) {
		leftPos = (screen.width / 2) - 251
		topPos = (screen.height / 2) - 162
	}
	ElementWindow = window.open(page, 'ElementWin',
'width=' + w + ',height=' + h + ',left=' + leftPos + ',top=' + topPos + ',scrollbars=1,resizable=1')
}

function markReadAdverts() {
	var savedCookies = document.cookie;
	var advertsBeggining = savedCookies.indexOf('VisitedAdverts=', 0);
	var advertCookies = '';
	if (advertsBeggining > -1) {
		advertsBeggining = advertsBeggining + 15;
		var advertsEnd = savedCookies.indexOf(';', advertsBeggining);
		if (advertsEnd == -1) {
			advertsEnd = savedCookies.length;
		}
		else {
			advertsEnd--;
		}
		advertCookies = savedCookies.substring(advertsBeggining, advertsEnd);
		var advertCookiesEntries = advertCookies.split('&');
		for (var i = 0; i < advertCookiesEntries.length; i++) {
			var advertId = advertCookiesEntries[i].split('=')[1];
			$('#searchResultBox dt').each(function(index) {
				if ($(this).attr('id') == advertId) {
					if (!($(this).parent().hasClass('visited'))) {
						$(this).parent().addClass('visited');
					}
				}
			});
		}
	}
}
