jQuery.fn.height_opera95_fixed = function() {
    if ( this[0] == window && jQuery.browser.opera && jQuery.browser.version >= 9.50)
        return window.innerHeight;
    else return $(this[0]).height();
};

function sendContactInfo(sendButton, subjectId, emailId, messageId, injectContentId){
	var subject = $('#' + subjectId);
	var email = $('#' + emailId);
	var message = $('#' + messageId);
	var inject = $('#' + injectContentId);
	var emptyField = false;
	if (message.val() == ''){
		message.focus();
		$('#empty_' + messageId).css('display', 'block');
		emptyField = true;
	}
	else{
		$('#empty_' + messageId).css('display', 'none');
	}
	if (email.val() == ''){
		email.focus();
		$('#empty_' + emailId).css('display', 'block');
		emptyField = true;
	}
	else{
		$('#empty_' + emailId).css('display', 'none');
	}
	if (subject.val() == ''){
		subject.focus();
		$('#empty_' + subjectId).css('display', 'block');
		emptyField = true;
	}
	else{
		$('#empty_' + subjectId).css('display', 'none');
	}

	if (emptyField){
		return false;
	}

	sendButton.disabled = true;
	inject.attr('style', 'visibility:visible');
	var image = $("<img />").attr('src', global_path + 'images/processing.gif');
	inject.children().next().append(image);
	$.post('/ajax-send-contact-info.html'
		, {	'subject': subject.val(), 'email': email.val(),	'message': message.val()},
			function(data){
				var injectDiv = inject.attr('style', 'visibility:hidden');
				image.remove();
				var dataDiv = $("<div></div>").html(data);
				inject.replaceWith(dataDiv);
				sendButton.disabled = false;
				dataDiv.fadeOut(5000, function(){
					$(this).replaceWith(injectDiv);
				});
			});
}

/**
 * Funkcja wysyla zapytanie o modele dla danej marki pojazdu
 * @param string strVehicleType
 */
function getModelsForCars(selectField, anyText)
{
	if ($("select#cars_makes").val() == '0')
	{
		$("select#cars_models").html("<option value='0'>" + anyText + "</option>");
	}
	else
	{
		selectField.disabled = true;

		var response = $.ajax ({
			url: "advanced-get-cars-models.html",
			type: "POST",
			data: "iMakeId=" + $("select#cars_makes").val(),
			async: false
		}).responseText;

		$("select#cars_models").html(response);
		
		selectField.disabled = false;
	}
}

function getModelsForBikes(selectField, anyText)
{
	if ($("select#bikes_makes").val() == '0')
	{
		$("select#bikes_models").html("<option value='0'>" + anyText + "</option>");
	}
	else
	{
		selectField.disabled = true;
		
		var response = $.ajax ({
			url: "advanced-get-bikes-models.html",
			type: "POST",
			data: "iMakeId=" + $("select#bikes_makes").val(),
			async: false
		}).responseText;

		$("select#bikes_models").html(response);
		
		selectField.disabled = false;
	}
}

function reportExpired(object, advert){
	$.post(global_path + "report-expired-advert-" + advert + ".html", {},
			function(data){
				$(object).replaceWith(data);
			});
	return false;
}

function submit(ev, obj, model, make, type, stringQuery, browse, sorting, order){
	var ev = window.event ? event : ev
	var code = ev.charCode ? ev.charCode : ev.keyCode;
	
	if (code == 13){
		//enter
		check_uncheck_option_query(obj, model, make, type, stringQuery, browse, sorting, order);
	}
	else{
		if ($(obj).val().match(/^[0-9]+$/)){
			$(obj).parent().attr('class', 'rolling_filter_list_li_c');
		}
		else{
			$(obj).parent().attr('class', 'rolling_filter_list_li');
		}
	}
}

function Alerts(className, deleteText, url, updateElementName, updateUrl) {
	this.className	= className;
	this.deleteText = deleteText;
	this.updateElementName = updateElementName;
	this.updateUrl 	= updateUrl + '?format=json';
	this.url 		= url + '?format=json';
	this.prepareDelete();
	this.prepareUpdate();
}


Alerts.prototype.prepareDelete = function() {
	var self = this;
	$(this.className).click(function(){
		var confirmValue = confirm(self.deleteText);
		if (confirmValue) {
			self.deleteAlert(this);
		}
	});
}

Alerts.prototype.deleteAlert = function(object) {
	var self = this;
	var alert = $(object).attr('id');
	$.post(this.url, {'alert': alert}, function(resp){
		self.redirect(resp);
	}, 'json');
}

Alerts.prototype.redirect = function(resp) {
	window.location = resp['url'];
}

Alerts.prototype.removeFromDOM = function(object) {
	$(object).parent().parent().parent().remove();
}

Alerts.prototype.prepareUpdate = function() {
	self = this;
	$(this.updateElementName).change(function(){
		self.updateAlert(this);
	});
}

Alerts.prototype.updateAlert = function(object) {
	var value = $(object).val();
	var alert = $(object).attr("id");
	$.post(this.updateUrl, {'alert': alert, 'frequency': value});
}
/**
 * Class responsible for managing creating alerts from search page
 * @param {Object} objectId
 * @param {Object} filters
 */
function SearchAlerts(objectId, filters) {
	this.objectId = objectId;
	this.filters = filters;
	this.url = $(objectId).attr('action') + '?format=json';
	this.prepareCreate();
}

SearchAlerts.prototype.prepareCreate = function() {
	var self = this;
	$(this.objectId).submit(function(){
		self.create();
		return false;
	});
}

SearchAlerts.prototype.create = function() {
	$('#alert_create_loading').css('display', 'inline');
	$(this.objectId).find('input[@type="submit"]').attr('disabled', true);
	var self = this;
	var selectedItems 	= this.filters.getSelected();
	var ranges 			= this.filters.getRanges();
	var merged 			= this.filters.mergeObjects(selectedItems, this.filters.params);
	merged 				= this.filters.mergeObjects(merged, ranges);
	merged['email'] 	= $(this.objectId).find('input[name="email"]').val();
	merged['url'] 		= $(this.objectId).find('input[name="url"]').val();
	$.post(this.url, merged, function(data){
		self.showResponse(data);	
	}, 'json');
}

SearchAlerts.prototype.showResponse = function(data) {
	var form = $(this.objectId);
	$(this.objectId).find('input[@type="submit"]').removeAttr('disabled');
	$('#alert_create_loading').css('display', 'none');
	if (data['isValidEmail'] == false) {
		form.parent().css('display', 'block');
		form.parent().next().css('display', 'block');
		return;
	}
	else {
		form.parent().css('display', 'block');
		form.parent().next().css('display', 'none');
	}
	
	form.css('display', 'none');
	
	if (data['hasAccount'] == false && data['created'] == true) {
		form.parent().css('display', 'block');
		form.parent().next().next().css('display', 'block');
		$('#email_alert').replaceWith(form.parent().next().next().css('display', 'inline'));
		return;
	}
	else if(data['created'] == true) {
		form.parent().css('display', 'block');
		form.parent().next().next().next().css('display', 'block');
		$('#email_alert').replaceWith(form.parent().next().next().next().css('display', 'inline'));
		return;
	}
	else {
		form.parent().css('display', 'block');
		form.parent().next().next().next().next().css('display', 'block');
		$('#email_alert').replaceWith(form.parent().next().next().next().next().css('display', 'inline'));
		return;
	}
}
/**
 * Searches class
 * @param {string} createUrl
 * @param {string} createClass
 * @param {string} deleteUrl
 * @param {string} deleteClass
 * @param {string} deleteMessage
 */
function Searches(createUrl, createClass, deleteUrl, deleteClass, deleteMessage) {
	this.createUrl 		= createUrl + '?format=json';
	this.deleteUrl 		= deleteUrl + '?format=json';
	this.createClass 	= createClass;
	this.deleteMessage 	= deleteMessage;
	this.deleteClass 	= deleteClass;
	this.prepareCreateAlert();
	this.prepareDelete();
}

Searches.prototype.prepareCreateAlert = function() {
	var self = this;
	$(this.createClass).click(function(){
		self.createAlert(this);
	})
}

Searches.prototype.createAlert = function(object){
	var self = this;
	var query = $(object).parent().parent().find("input[name='q']").val();
	var url = $(object).parent().parent().find("input[name='url']").val();
	$.post(this.createUrl, {'q': query, 'url': url}, function(resp){
		self.readResponse(resp, object);
	}, 'json');
}

Searches.prototype.readResponse = function(resp, object) {
	if (resp['created'] == true) {
		$(object).replaceWith($(object).next().css('display', 'block'));
	}
	else {
		$(object).replaceWith($(object).next().next().css('display', 'block'));
	}
		
	$(object).remove();
}

Searches.prototype.prepareDelete = function() {
	var self = this;
	$(this.deleteClass).click(function(){
		self.deleteSearch(this);
	});
}

Searches.prototype.deleteSearch = function(object) {
	var search = $(object).attr("id");
	var self = this;
	$.post(this.deleteUrl, {'search': search}, function(resp){
		self.redirect(resp);
	}, 'json');
}

Searches.prototype.redirect = function(response) {
	window.location = response['url'];
}

Searches.prototype.removeFromDOM = function(object) {
	$(object).parent().parent().remove();
}


/**
 * 
 * @param {String} className
 * @param {String} url
 */
function Adverts(className, url) {
	this.className 	= className;
	this.url 	= url;
}

Adverts.prototype.init = function() {
	this.prepareElements();
}

Adverts.prototype.prepareElements = function() {
	var self = this;
	$(self.className).click(function() {
		self.save(this);
	});
}

Adverts.prototype.save = function(object) {
	var self = this;
	var id = $(object).attr('id');
	$.post(this.url + '?format=json', {"advert": id}, function(data){
		self.respond(object, data);
	}, 'json');
}

Adverts.prototype.respond = function(object, response) {
	if (response['added'] == false) 
		$(object).html($(object).next().next().html()).css('color', 'red');
	else
		$(object).html($(object).next().html()).css('color', 'green');
}

/**
 * Class for managing quick search in catalogue
 */
function CatalogueQuickSearch(strings){
	this.strings = strings;
	this.marque = $("select#marque");
	this.serie 	= $("select#series");
	this.model 	= $("select#models");
	this.init();
}
CatalogueQuickSearch.prototype.init = function() {
	var self = this;
	this.marque.change(function(){self.getSeriesForMarque()});
	this.serie.change(function(){self.getModelsForSerie()});
	this.model.change(function(){self.startSearch()});
}
/**
 * Searches for items if serie was searched
 * @param {Object} selectField
 */
CatalogueQuickSearch.prototype.getSeriesForMarque = function(){
	if (this.marque.val() == '0') {
		this.serie.html("<option value='0'>" + this.strings['selectSerie'] + "</option>");
		this.model.html("<option value='0'>" + this.strings['selectModel'] + "</option>");
	}
	else {
		this.model.html("<option value='0'>" + this.strings['selectModel'] + "</option>");
		this.marque.disabled = true;
		var response = $.ajax ({
			url: "get-series-for-marque.html",
			type: "POST",
			data: "iMarqueId=" + this.marque.val(),
			async: false
		}).responseText;
		this.serie.html(response);
		this.marque.disabled = false;
	}
}
/**
 * Searches for models if serie was changed
 * @param {Object} selectField
 */
CatalogueQuickSearch.prototype.getModelsForSerie = function() {
	if (this.serie.val() == '0'){
		this.model.html("<option value='0'>" + this.strings['selectModel'] + "</option>");
	}
	else {
		this.serie.disabled = true;
		var response = $.ajax ({
			url: "get-models-for-series.html",
			type: "POST",
			data: "sid=" + this.serie.val(),
			async: false
		}).responseText;
		
		this.model.html(response);
		this.serie.disabled = false;
	}
}

CatalogueQuickSearch.prototype.startSearch = function() {
	var marque = this.marque.find("option:selected").text().replace(/[^a-zA-Z0-9\-]+/gi, '_');
	var clearModel = this.model.find("option:selected").text().replace(/[^a-zA-Z0-9\-]+/gi, '_');
	
	window.location = 'specification-' + marque + '-' + clearModel + '-' + this.model.val() + '.html';
}
