if(!Array.indexOf){
	// This function does not exists in IE, so ...
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	}
}

// Thanks to http://stackoverflow.com/questions/646628/javascript-startswith
if (typeof String.prototype.startsWith != 'function') {
	String.prototype.startsWith = function (str){
		return this.slice(0, str.length) == str;
	};
}

var lastXhr = null;
function load(element, url) {
	if (lastXhr != null) {
		lastXhr.abort();
	}
	lastXhr = $.ajax({
		url: url,
		success: function(data) {
			$("#" + element).html(data);
		},
		error: function(jqXHR, status, error) {
			if (status == "abort") return;
			window.location.href = baseUrl + "index.html?error=searchExpired";
		}
	});
}

var minDate = parseDate("1900-01-01");
var maxDate = parseDate("2500-12-31");

function refresh(url) {
	if (!url) {
		url = window.location.href;
	}
	load("ajaxResult", url);
}

function doShowMap() {
	if (typeof showMap == 'function') { showMap(); }
}

$(document).ready(function() {
	$(".jsonly").css("display", "block");
});

var validator = null;
function declare_validation_rules(formId, rules, messages, baseUrl, language) {
	$(document).ready(function() {
		$.i18n.properties({
			name:'validationErrors',
			path: baseUrl + "i18n/",
			mode:'map',
			language:language,
			cache: true,
			encoding: 'UTF-8',
			callback: function() {
				validator = $("#" + formId).validate( {
					rules: rules,
					messages: messages,
					validClass: "valid",
					success: "validlabel",
					errorClass: "invalid",
					ignore: ".ignore",
					onsubmit: false,
					onkeyup: false,
					onfocusout: function(element) { // Patch to have jquery validator to correctly handle ignored fields + valid eagerly on focusout
						if ($(element).not(".ignore").size() != 0) {
							$(element).valid();
						}
					},
					highlight: function(element, errorClass, validClass) {
						var e = $(element);
						var main = e.closest(".fieldWrapper");
						var err = main.find(".errorMessage");
						if (e.val() == null || e.val() == '' || (e.is("input[type=checkbox]") && e.parent().find("input[type=checkbox]:checked").size()==0)) {
							main.find("input,select,textarea").removeClass(validClass).removeClass(errorClass);
							main.find(".stateInfo").empty();
							main.find(".input-wrapper").removeClass("valid").removeClass("invalid");
							err.empty(); err.addClass("hidden");
						} else {
							e.parent().find(".period_dependency").prop("checked", false);
							main.find("input,select,textarea").addClass(errorClass).removeClass(validClass);
							main.find(".stateInfo").html("<img src='" + baseUrl + "images/ko-validation.png' width='14' height='12' alt='" + $.i18n.prop("gen.info.FIELD_INVALID") + "' title='" + $.i18n.prop("gen.info.FIELD_INVALID") + "' />");
							main.find(".input-wrapper").removeClass("valid");
							main.find(".input-wrapper").addClass("invalid");
						}
					},
					unhighlight: function(element, errorClass, validClass) {
						var e = $(element);
						var main = e.closest(".fieldWrapper");
						var err = main.find(".errorMessage");
						e.parent().find(".period_dependency").prop("checked", true);
						if (e.val() == null || e.val() == '' || (e.is("input[type=checkbox]") && e.parent().find("input[type=checkbox]:checked").size()==0)) {
							main.find("input,select,textarea").removeClass(validClass).removeClass(errorClass);
							main.find(".stateInfo").empty();
							main.find(".input-wrapper").removeClass("valid").removeClass("invalid");
							err.empty(); err.addClass("hidden");
						} else {
							main.find("input,select,textarea").removeClass(errorClass).addClass(validClass);
							main.find(".stateInfo").html("<img src='" + baseUrl + "images/ok-validation.png' width='14' height='12' alt='" + $.i18n.prop("gen.info.FIELD_VALID") + "' title='" + $.i18n.prop("gen.info.FIELD_VALID") + "' />");
							main.find(".input-wrapper").removeClass("invalid");
							main.find(".input-wrapper").addClass("valid");
							err.empty(); err.addClass("hidden");
						}
					},
					errorPlacement: function(error, element) {
						var e = element;
						var err = $(element).closest(".fieldWrapper").filter(":first").find(".errorMessage");
						if (!(e.val() == null || e.val() == '' || (e.is("input[type=checkbox]") && e.parent().find("input[type=checkbox]:checked").size()==0))) {
							err.first().empty().append(error);
							err.removeClass("hidden");
						}
					}
				});
			}
		});
		$("#" + formId + " input[type=radio]").not(".ignore").change(function() {
			validator.element($(this));
		});

		$("#" + formId + " input[type=checkbox]").not(".ignore").change(function() {
			validator.element($(this));
		});
		$("#" + formId + " select").not(".ignore").change(function() {
			validator.element($(this));
		});
		// ensure pre-loaded values (e.g. restored from the cookie) are validated
		// validator.form() did not work in all cases, e.g. advanced search
		$('#' + formId).find('input,select').not('.ignore').each(function(idx, elem) {
			validator.element(elem);
		});
		if ($("#city").length > 0) {
		$("#city").valid();
		}
	});

}

$(document).ready(function() {
	$(".form_date").change(function() {
		var fieldWrapper = $(this).closest(".fieldWrapper");
		var day = fieldWrapper.find(".date_day").val();
		var month = fieldWrapper.find(".date_month").val();
		var year = fieldWrapper.find(".date_year").val();
		var date_value = fieldWrapper.find(".date_value");
		date_value.val(year + "-" + month + "-" + day);
		if (day == '' && month == '' && year == '') {
			date_value.val('');
		}
		if ((day != '' && month != '' && year != '') || (day == '' && month == '' && year == '')) {
			validator.element(date_value);
			change_period(date_value);
		}
	});

	$(".form_datetime").change(function() {
		var fieldWrapper = $(this).parents(".fieldWrapper").filter(":first");
		var day = fieldWrapper.find(".date_day").val();
		var month = fieldWrapper.find(".date_month").val();
		var year = fieldWrapper.find(".date_year").val();
		var time = fieldWrapper.find(".date_time").val();
		var date_value = fieldWrapper.find(".date_value");
		date_value.val(year + "-" + month + "-" + day + "/" + time);
		if (day == '' && month == '' && year == '' && time == '') {
			date_value.val('');
		}
		if ((day != '' && month != '' && year != '' && time != '') || (day == '' && month == '' && year == '' && time == '')) {
			validator.element(date_value);
		}
	});
});

function focusOnField() {
	$("input:visible:enabled:first").focus();
}

function change_period(date_value) {
	if (date_value.filter(".period_start, .period_end").size() == 0) {
		return;
	}
	var parent = date_value.parents(".fieldWrapper");
	var startDate = parent.find(".period_start");
	var endDate = parent.find(".period_end");
	var value = parent.find(".period_value");
	value.val(startDate.val() + endDate.val());
	if (parent.find("input[type=checkbox]:checked").size() == 2) {
		validator.element(value);
	}
}

// overwrite default minlength validation
$.validator.addMethod('minlength',function(value, element, minlength) {
	return !(value == null || $.trim(value).length < minlength);
});

$.validator.addMethod('ValidDate',function(value, element) {
	if (this.optional(element)) {
		return true;
	}
	var date = element.value.split("-");
	var JDate = new parseDate(element.value);

	return (parseInt(date[1], 10) - 1 == JDate.getMonth() && parseInt(date[2], 10) == JDate.getDate() && parseInt(date[0], 10) == JDate.getFullYear());
});

$.validator.addMethod('MinDate',function(value, element, minDate) {
	if (this.optional(element)) {
		return true;
	}
	var JDate = new parseDate(element.value);
	return !(minDate > JDate);
});

$.validator.addMethod('MaxDate',function(value, element, minDate) {
	if (this.optional(element)) {
		return true;
	}
	var JDate = new parseDate(element.value);
	return !(minDate < JDate);
});

$.validator.addMethod('ValidDateTime',function(value, element) {
	if (this.optional(element)) {
		return true;
	}
	var splitted = element.value.split("/");
	var date = splitted[0].split("-");
	var time = splitted[1].split(":");
	var JDate = new parseDateTime(element.value);

    return (parseInt(date[1], 10) - 1 == JDate.getMonth() && parseInt(date[2], 10) == JDate.getDate() && parseInt(date[0], 10) == JDate.getFullYear() && parseInt(time[0], 10) == JDate.getHours() && parseInt(time[1], 10) == JDate.getMinutes() && parseInt(time[2], 10) == JDate.getSeconds());
});

$.validator.addMethod('MinDateTime',function(value, element, minDate) {
	if (this.optional(element)) {
		return true;
	}
	var JDate = new parseDateTime(element.value);
	return !(minDate > JDate);
});

$.validator.addMethod('MaxDateTime',function(value, element, minDate) {
	if (this.optional(element)) {
		return true;
	}
	var JDate = new parseDateTime(element.value);
	return !(minDate < JDate);
});

$.validator.addMethod('ValidTime',function(value, element) {
	if (this.optional(element)) {
		return true;
	}
	var date = element.value.split(":");
	var JDate = new parseTime(element.value);

	return (parseInt(date[0], 10) == JDate.getHours() && parseInt(date[1], 10) == JDate.getMinutes() && parseInt(date[2], 10) == JDate.getSeconds());
});

$.validator.addMethod('MinTime',function(value, element, minDate) {
	if (this.optional(element)) {
		return true;
	}
	var JDate = new parseTime(element.value);
	return !(minDate > JDate);
});

$.validator.addMethod('MaxTime',function(value, element, minDate) {
	if (this.optional(element)) {
		return true;
	}
	var JDate = new parseTime(element.value);
	return !(minDate < JDate);
});

function parseDate(str) {
	var date = str.split("-");
    return new Date(parseInt(date[0], 10), parseInt(date[1], 10) -1, parseInt(date[2], 10))
}

function parseDateTime(str) {
	var splitted = str.split("/");
	var date = splitted[0].split("-");
	var time = splitted[1].split(":");
    return new Date(parseInt(date[0], 10), parseInt(date[1], 10) -1, parseInt(date[2], 10), parseInt(time[0], 10), parseInt(time[1], 10), parseInt(time[2], 10))
}

function parseTime(str) {
	var date = str.split(":");
	return new Date(2000, 0, 1, parseInt(date[0], 10), parseInt(date[1], 10), parseInt(date[2], 10))
}

function formatTime(time) {
	var hours = time.getHours();
	if (hours < 10) {
		hours = "0" + hours;
	}
	var minutes = time.getMinutes();
	if (minutes < 10) {
		minutes = "0" + minutes;
	}
	var seconds = time.getSeconds();
	if (seconds < 10) {
		seconds = "0" + seconds;
	}
	return hours + ":" + minutes + ":" + seconds;
}

function formatDate(date) {
	var month = (date.getMonth() +1)
	if (month < 10) {
		month = "0" + month;
	}
	var day = date.getDate();
	if (day < 10) {
		day = "0" + day;
	}
	return day + "/" + month + "/" + date.getFullYear();
}

function formatDateTime(date) {
	return formatDate(date) + " " + formatTime(date);
}

var actualHeight = 0;
var currentUrl;

$(document).ready(function() {
	$(":submit, :checkbox").bind('keypress', function(e) {
		if (e.key !== ' ' && e.key !== 'Spacebar' && e.key !== 'Enter') {
			return;
		}
		$(this).click();
		e.preventDefault();
	});
});

function  callResize()
{
	var height = $("#wrapAll_integrated").height();
	if (height != actualHeight && height != (actualHeight + 20)) {
		try { window.top.iri_resizeIframe(height); } catch(e) {}
		actualHeight = $("#wrapAll_integrated").height();
	}
	t=setTimeout("callResize();", 50);
}

/* Function taken from http://www.w3schools.com/js/js_cookies.asp */

function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()) + "; path=/";
	document.cookie=c_name + "=" + c_value;
}

function delCookie(c_name) {
	setCookie(c_name, "", -100);
}

function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
			return unescape(y);
		}
	}
}

function setCurrentUrl(url) {
	if (!url.startsWith("http")) {
		var location = window.location;
		url = location.protocol + "//" + location.host + ("/" + url).replace("//", "/");
	}
	setCookie("iriSerializedFormUrl", url);
}

function serializableForm(formId, langsElement) {
	var cookie = getCookie("serializedForm" + formId);
	var $form=$("#" + formId);
	if (cookie) {
		$form.deserialize(cookie);
		delCookie("serializedForm" + formId);
	}
	langsElement.click(function() {
		setCookie("serializedForm" + formId, $form.serialize());
	});
	langsElement.change(function() {
		setCookie("serializedForm" + formId, $form.serialize());
	});
}

/*
 * Trigger window resize function in javascript source path :
 * http://codrate.com/questions/how-can-trigger-the-window-resize-event-manually-in-javascript
 */
function ESresize() {

	if (typeof (Event) === 'function') {
		// modern browsers
		window.dispatchEvent(new Event('resize'));
	} else {
		// This will be executed on old browsers and especially IE
		var resizeEvent = window.document.createEvent('UIEvents');
		resizeEvent.initUIEvent('resize', true, false, window, 0);
		window.dispatchEvent(resizeEvent);
	}
}