var prevIloscWynikow;
var tooltipCache = new Array();
var lastUrl = '';

$(function() {
	prepare();
});

function prepare() {
	$('#IloscWynikow').bind('change', iloscWynikowChange);
	$('#DodajDoNotesu').bind('click', dodajDoNotesuClick);
	$('.DodajOferteDoNotesu').bind('click', dodajOferteDoNotesuClick);
	$('.UsunZNotesu').bind('click', usunZNotesuClick);
	$('#PolecLink').bind('click', polecClick);
	$('#FormularzPolec #Close').bind('click', polecCloseClick);
	$('#FormularzPolec form').submit(polecSubmitClick);
	$('#ZapytajZNotesu').bind('click', zapytajZNotesuClick);
	$('#FormularzZapytajNotes #Close').bind('click', zapytajZNotesuCloseClick);
	$('#FormularzZapytajNotes form').submit(zapytajZNotesuSubmitClick);
	$('#FormularzZglos form').submit(zglosSubmitClick);
	$('#TypWlasnosci').bind('change', kalkulatorOblicz);
	$('#ZapiszDoSubskrypcji').bind('click', subskrybujClick);
	$('#FormularzSubskrypcja #Close').bind('click', subskrybujCloseClick);
	$('#FormularzSubskrypcja form').submit(subskrybujSubmitClick);
	
	prevIloscWynikow = $('#IloscWynikow').val();
	
	if ($('#FormularzZglos').length > 0) {
		$('#full_content').addClass('bigform');
	}

	$('[title]').each(function() {
		if ($(this).attr('title') == 'null') $(this).attr('title', '');
	});
	
	osadzWideo('WideoONas', '/assets/Elementy/reklama.flv');
	osadzWideo('Wideo1', '/assets/Elementy/wywiad.flv');
	osadzWideo('WideoPrezentacja', '/assets/Elementy/scn500.flv', 512, 384);
	osadzRadioReklame();
	
	bindSprzedazWynajem();
}

function iloscWynikowChange() {
	var iloscWynikow = $('#IloscWynikow').val();
	if (iloscWynikow != prevIloscWynikow) {
		location.href = iloscWynikow;
	} 	
}

function dodajDoNotesuClick() {
	$('#DodajDoNotesu').html('<b>Chwileczkę...</b>').bind('click', function() {return false;});
	$.get('/app/notes/dodaj/' + offerId, function(data) {
		$('#DodajDoNotesu').before('<i id="JuzWNotesie">Już w notesie</i>').remove();
		Accordion1.openIthPanel(0);
		
		$('#notes').html('<img src="/themes/scn/img/prettyPhoto/loader.gif" alt="Chwileczkę..."/>');
		$.get('/app/notes/pokaz', function(data) {
			$('#notes').html(data);
			Accordion1.openIthPanel(1);
			Accordion1.openIthPanel(0);
			prepare();
		});
	});
	return false;
}

function dodajOferteDoNotesuClick() {
	var offerId = $(this).attr('name');
	var oldimgsrc = $('plus' + offerId).attr('src');
	$('#plus' + offerId).attr('src', '/themes/scn/img/prettyPhoto/loader.gif');

	$.get('/app/notes/dodaj/' + offerId, function(data) {
		$('#plus' + offerId).before('<i id="OfertaJuzWNotesie">Już w notesie</i>').remove();
		prepare();
	});
	return false;
}

function tooltip(id) {
	TagToTip('Span1', BALLOON, true, ABOVE, true);
	if (tooltipCache[id] != null) {
		$('#bALlO0nBdY').html(tooltipCache[id]);
	} else {
		$.get('/app/oferta/dymek/' + id, function(data) {
			$('#bALlO0nBdY').html(data);
			tooltipCache[id] = data;
			prepare();
		});
	}
}

function usunZNotesuClick() {
	var offerId = $(this).attr('name');
	$('#item' + offerId).fadeTo(250, 0.25)
	$(this).bind('click', function() {return false;});
	$.get('/app/notes/usun/' + offerId, function(data) {
		$('#item' + offerId).remove();
		prepare();
	});
}

function polecClick() {
	var url = '/app/oferta/formularz-polec';
	$(this).before('<b id="QuestionLoading">Wczytywanie...</b>').hide();
	$.get(url, {}, function(data) {
		var h = $('#wyniki_content').prepend(data).height();
		var maxH = $(window).height() - 20;
		if (maxH < 300) maxH = 640;
		if (h > maxH) h = maxH;
		$('#FormularzPolec').height(h);
		$('#FormularzPolec #Formularz').height(h - 67);
		prepare();
		$(window).scrollTop($('#FormularzPolec').offset().top - 5);
		$('#QuestionLoading').remove();
	});
	return false;
}

function polecCloseClick() {
	$('#FormularzPolec').remove();
	$('#PolecLink').show();
}

function polecSubmitClick() {
	$('#FormularzPolec').prepend('Wysyłanie pytania...');
	$(this).ajaxSubmit(function() {
		$('#FormularzPolec').remove();
		$('#PolecLink').show();
	});
	return false;
}

function zapytajZNotesuClick() {
	var url = '/app/oferta/formularz-notes';
	$(this).before('<b id="QuestionLoading">Chwileczkę...</b>').hide();
	$.get(url, {}, function(data) {
		var h = $('#wyniki_content').prepend(data).height();
		var maxH = $(window).height() - 20;
		if (maxH < 300) maxH = 640;
		if (h > maxH) h = maxH;
		$('#FormularzZapytajNotes').height(h);
		$('#FormularzZapytajNotes #Formularz').height(h - 67);
		prepare();
		$(window).scrollTop($('#FormularzZapytajNotes').offset().top - 5);
		$('#QuestionLoading').remove();
	});
	return false;
}

function zapytajZNotesuCloseClick() {
	$('#FormularzZapytajNotes').remove();
	$('#ZapytajZNotesu').show();
}

function zapytajZNotesuSubmitClick() {
	$('#FormularzZapytajNotes').prepend('Wysyłanie pytania...');
	$(this).ajaxSubmit(function() {
		$('#FormularzZapytajNotes').remove();
		$('#ZapytajZNotesu').show();
	});
	return false;
}

function moneyFormat(n, postfix) {
	if (postfix == null) postfix = '';
	var p = n.toFixed(2).split('.');
	var d = p[0].split('');
	n = '';
	var k = 0;
	for (var i = d.length - 1; i >= 0; i--) {
		n = d[i] + '' + n;
		if (++k % 3 == 0) n = ' ' + n;
	}
	return n + ',' + p[1] + postfix;
};

function kalkulatorOblicz() {
	var price = $('#Kwota').val().replace(',', '.').replace(' ', '');
	var provisionPercent = $('#ProwizjaProcent').val();
	
	if (isNaN(price)) price = 0;
	if (isNaN(provisionPercent)) provisionPercent = 3;

	var ownership = $('#TypWlasnosci').val();
	
	var notary = 0;
	if (price <= 3000) notary = ownership == 'h' ? 100 : 50;
	else if (price > 3000 && price <= 10000) notary = (ownership == 'h' ? 100 : 50) + (price - 3000) * 0.03;
	else if (price > 10000 && price <= 30000) notary = (ownership == 'h' ? 310 : 155) + (price - 10000) * 0.02;
	else if (price > 30000 && price <= 60000) notary = (ownership == 'h' ? 710 : 355) + (price - 30000) * 0.01;
	else if (price > 60000 && price <= 1000000) notary = (ownership == 'h' ? 1010 : 505) + (price - 60000) * 0.004;
	else if (price > 1000000 && price <= 2000000) notary = (ownership == 'h' ? 4770 : 2385) + (price - 1000000) * 0.002;
	else if (price > 2000000) notary = (ownership == 'h' ? 6770 : 3385) + (price - 2000000) * 0.0025;
	if (notary > 10000) notary = 10000;
	
	var notaryVat = notary < 400 ? 0 : notary * 0.22;

	var courtFee = ownership == 's' ? 0 : 200;

	var tax = price * 0.02;

	var provision = provisionPercent * price / 100;
	
	var provisionVat = provision * 0.22;

//	var sum = notary + notaryVat + courtFee + tax + provision + provisionVat;
	var sum = notary + notaryVat + courtFee + tax;
	
	var all = sum + 1.0 * price;
	
	$('#OplataSadowa').html(moneyFormat(courtFee, '') + ' zł');
	if (ownership == 's') $('#OplataSadowaWiersz').hide(); else $('#OplataSadowaWiersz').show();
	$('#Podatek').html(moneyFormat(tax, '') + ' zł');
	$('#Notariusz').html(moneyFormat(notary, '') + ' zł');
	$('#NotariuszVat').html(moneyFormat(notaryVat, '') + ' zł');
//	$('#Prowizja').html(moneyFormat(provision, '') + ' zł');
//	$('#ProwizjaVat').html(moneyFormat(provisionVat, '') + ' zł');
	$('#Suma').html(moneyFormat(sum, '') + ' zł');
	$('#RazemCena').val(moneyFormat(all, ''));
}

function zglosSubmitClick() {
	$('#FormularzZglos').prepend('Wysyłanie zgłoszenia...');
	$(this).ajaxSubmit(function() {
		alert('Zgłoszenie oferty zostało wysłane, dziękujemy. Skontaktujemy się wkrótce.\nZa chwilę powrócisz na stronę główną.');
		location.href = '/home';
	});
	return false;
}

function osadzWideo(id, url, w, h) {
	if (w == null) {
		w = 352;
	}
	if (h == null) {
		h = 288;
	}
	if ($('#' + id).length > 0) {
		$('#' + id).show();
		flashembed(id, 
			{
				src:'/assets/Elementy/FlowPlayerLight.swf',
				width: w, 
				height: h
			},
			{config: {   
				autoPlay: false,
				autoBuffering: true,
				controlBarBackgroundColor:'0x102044',
				initialScale: 'scale',
				videoFile: url,
				loop: false
			}} 
		);
		$('#' + id).append("<p style='font-size: 0.5em; font-style: italic; text-align: right'>wykorzystano odtwarzacz <a target='_blank' href='http://flowplayer.org/'>FlowPlayer</a></p>");
	}
}

function subskrybujClick() {
	var url = '/app/oferta/formularz-subskrypcja';
	$(this).before('<b id="QuestionLoading">Chwileczkę...</b>').hide();
	$.get(url, {}, function(data) {
		var h = $('#wyniki_content').prepend(data).height();
		var maxH = $(window).height() - 20;
		if (maxH < 300) maxH = 640;
		if (h > maxH) h = maxH;
		if (h < 491) h = 491;
		$('#FormularzSubskrypcja').height(h);
		$('#FormularzSubskrypcja #Formularz').height(h - 67);
		prepare();
		$(window).scrollTop($('#FormularzSubskrypcja').offset().top - 5);
		$('#QuestionLoading').remove();

		if (document.all) { // blessed be the IE
			$('#PoCo').hide();
			$('#CzegoSzukam').hide();
			$('#Dzielnica').hide();			
		}
	});
	return false;
}

function subskrybujCloseClick() {
	$('#FormularzSubskrypcja').remove();
	$('#ZapiszDoSubskrypcji').show();

	if (document.all) { // blessed be the IE
		$('#PoCo').show();
		$('#CzegoSzukam').show();
		$('#Dzielnica').show();			
	}
}

function subskrybujSubmitClick() {
	$('#FormularzSubskrypcja').prepend('Wysyłanie pytania...');
	$(this).ajaxSubmit(function() {
		$('#FormularzSubskrypcja').remove();
		$('#ZapiszDoSubskrypcji').show();

		if (document.all) { // blessed be the IE
			$('#PoCo').show();
			$('#CzegoSzukam').show();
			$('#Dzielnica').show();			
		}
	});
	return false;
}




function bindSprzedazWynajem() {
	if ($('img.oferta-m').length == 0) return;
	
	$('img.oferta-m').hover(function() {
		pokazSprzedazWynajem('img.oferta-m');
	}, function() {});
	$('img.oferta-d').hover(function() {
		pokazSprzedazWynajem('img.oferta-d');
	}, function() {});
	$('img.oferta-l').hover(function() {
		pokazSprzedazWynajem('img.oferta-l');
	}, function() {});
	$('img.oferta-o').hover(function() {
		pokazSprzedazWynajem('img.oferta-o');
	}, function() {});

	$('img.oferta-e').hover(function() {
		pokazNadmorskie('img.oferta-e');
	}, function() {});
}

function pokazSprzedazWynajem(img, pominUrl) {
	var BGOPACITY = 0.25;
	var OPACITY = 0.75;

	schowajSprzedazWynajem();
	img = $(img);
	var parent = img.parent();
	if (!pominUrl) {
		lastUrl = parent.attr('href');
	}
	parent.before('<div id="SprzedazWynajemBg"/><div id="Sprzedaz">Sprzedaż</div><div id="Wynajem">Wynajem</div>');
	$('#SprzedazWynajemBg').css('opacity', BGOPACITY).height(img.height() - 33).width(img.width());
	$('#Sprzedaz').height(img.height() - 33).width(img.width() / 2).hover(function() {
		$(this).addClass("hover").css('opacity', OPACITY);
	}, function() {
		$(this).removeClass("hover").css('opacity', 1);
		setTimeout(function() {
			if (!$('#Wynajem').hasClass('hover')) {
				schowajSprzedazWynajem();
			}
		}, 25);
	});
	
	$('#Wynajem').height(img.height() - 33).width(img.width() / 2).hover(function() {
		$(this).addClass("hover").css('opacity', OPACITY);
	}, function() {
		$(this).removeClass("hover").css('opacity', 1);
		setTimeout(function() {
			if (!$('#Sprzedaz').hasClass('hover')) {
				schowajSprzedazWynajem();
			}
		}, 25);
	}).css('margin-left', (img.width() / 2) + 'px');
	
	$('#Sprzedaz').bind('click', function() {
		location.href = lastUrl + '/sprzedaz';
	});
	$('#Wynajem').bind('click', function() {
		location.href = lastUrl + '/wynajem';
	});
}

function schowajSprzedazWynajem() {
	$('#SprzedazWynajemBg').remove();
	$('#Sprzedaz').remove();
	$('#Wynajem').remove();
	$('#Mieszkania').remove();
	$('#Domy').remove();
	$('#Dzialki').remove();
	$('#Lokale').remove();
}

function pokazNadmorskie(img) {
	var BGOPACITY = 0.25;
	var OPACITY = 0.75;

	schowajSprzedazWynajem();
	img = $(img);
	var parent = img.parent();
	lastUrl = parent.attr('href');
	parent.before('<div id="SprzedazWynajemBg"/><div id="Mieszkania">Mieszkania</div><div id="Domy">Domy</div><div id="Dzialki">Działki</div><div id="Lokale">Lokale/Obiekty</div>');
	$('#SprzedazWynajemBg').css('opacity', BGOPACITY).height(img.height() - 33).width(img.width());

	$('#Mieszkania').height((img.height() - 33) / 2).width(img.width() / 2).hover(function() {
		$(this).addClass("hover").css('opacity', OPACITY);
	}, function() {
		$(this).removeClass("hover").css('opacity', 1);
		setTimeout(function() {
			if (!$('#Domy').hasClass('hover') && !$('#Dzialki').hasClass('hover') && !$('#Lokale').hasClass('hover')) {
				schowajSprzedazWynajem();
			}
		}, 25);
	});

	$('#Domy').height((img.height() - 33) / 2).width(img.width() / 2).hover(function() {
		$(this).addClass("hover").css('opacity', OPACITY);
	}, function() {
		$(this).removeClass("hover").css('opacity', 1);
		setTimeout(function() {
			if (!$('#Mieszkania').hasClass('hover') && !$('#Dzialki').hasClass('hover') && !$('#Lokale').hasClass('hover')) {
				schowajSprzedazWynajem();
			}
		}, 25);
	}).css('margin-left', (img.width() / 2) + 'px');

	$('#Dzialki').height((img.height() - 33) / 2).width(img.width() / 2).hover(function() {
		$(this).addClass("hover").css('opacity', OPACITY);
	}, function() {
		$(this).removeClass("hover").css('opacity', 1);
		setTimeout(function() {
			if (!$('#Mieszkania').hasClass('hover') && !$('#Domy').hasClass('hover') && !$('#Lokale').hasClass('hover')) {
				schowajSprzedazWynajem();
			}
		}, 25);
	}).css('margin-top', ((img.height() - 33) / 2) + 'px');

	$('#Lokale').height((img.height() - 33) / 2).width(img.width() / 2).hover(function() {
		$(this).addClass("hover").css('opacity', OPACITY);
	}, function() {
		$(this).removeClass("hover").css('opacity', 1);
		setTimeout(function() {
			if (!$('#Mieszkania').hasClass('hover') && !$('#Domy').hasClass('hover') && !$('#Dzialki').hasClass('hover')) {
				schowajSprzedazWynajem();
			}
		}, 25);
	}).css('margin-left', (img.width() / 2) + 'px').css('margin-top', ((img.height() - 33) / 2) + 'px');
	
	$('#Mieszkania').bind('click', function() {
		lastUrl = lastUrl + '/m';
		pokazSprzedazWynajem('img.oferta-e', true);
	});
	$('#Domy').bind('click', function() {
		lastUrl = lastUrl + '/d';
		pokazSprzedazWynajem('img.oferta-e', true);
	});
	$('#Dzialki').bind('click', function() {
		location.href = lastUrl + '/z/sprzedaz';
	});
	$('#Lokale').bind('click', function() {
		lastUrl = lastUrl + '/l';
		pokazSprzedazWynajem('img.oferta-e', true);
	});
}

function osadzRadioReklame() {
	if ($("#RadioReklama").length > 0) {
		$("#RadioReklama").show();
		$('#RadioReklama').html('<object type="application/x-shockwave-flash" data="http://flash-mp3-player.net/medias/player_mp3.swf" width="200" height="20">' +
				'<param name="movie" value="http://flash-mp3-player.net/medias/player_mp3.swf" />' +
				'<param name="bgcolor" value="#ffffff" />' +
				'<param name="FlashVars" value="mp3=http%3A//www.scn.pl/assets/Elementy/radioreklama.mp3&amp;slidercolor1=ffffff" /></object>');
		$("#RadioReklama").append("<p style='font-size: 0.5em; font-style: italic; text-align: right'>wykorzystano odtwarzacz <a target='_blank' href='http://flash-mp3-player.net/'>MP3 Player</a></p>");
	}
	
}
