try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}
var baseURLend = 'js/behaviors-site.js';
var baseURL = '';
$('script[@src$='+baseURLend+']').each(function(){
	var src = $(this).attr('src');
	baseURL = src.slice(0, src.indexOf( baseURLend ) );
})

function ismaxlength(obj){
                var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
                if (obj.getAttribute && obj.value.length>=mlength)
                    obj.value=obj.value.substring(0,mlength)
            }

/***************************
		IMPORT
****************************/

//From( baseURL+'js')
//	.Import('prototypes', 'jquery-plugins');
//if ( /ogloszenie\/dodaj/.test( document.location.toString() ))
//	From( baseURL+'js').Import('forms');

function validatePhone(p,keyCode) {
	if ( /prefix/i.test( p.name ))
		return;
	
	var zablokowane = new Array(
		"000-000-0000",
		"111-111-1111",
		"222-222-2222",
		"333-333-3333",
		"444-444-4444",
		"555-555-5555",
		"666-666-6666",
		"777-777-7777",
		"888-888-8888",
		"999-999-9999",
		"718-707-7035"
		);

	// do przepiski ;)
	var tresc = p.value;
	var name = p.name;
	var telefon2 = new Array();
	var reg_liczba = /\d$/;
	var a=0;
	for(var i=0; i<tresc.length; i++){
		tel = tresc.charAt(i)
		if (tel.match(reg_liczba) != null){
			telefon2[a] = tresc.charAt(i);
			a++
		}
	}
	tablica = new Array();
	if (telefon2[0] == 0 || telefon2[0] == 1) {
		var b=1;
	} else {
		var b=0;
	}
	var c=0;
	do{
		tablica[c] = telefon2[b];
		b++
		c++
	}
	while (c < tresc.length)

	if (tablica[3] == 0 || tablica[3] == 1) {
		b=4;
	} else {
		b=3;
	}
	var d=3;
	do{
		tablica[d] = telefon2[b];
		b++
		d++
	}
	while (d < tresc.length - c )

	wynik = Array();
	for (var i=0; i<10; i++){
		if(tablica[i] != null){
			wynik += tablica[i];
			if(i==2){
				if(keyCode != 8) { //backspace
					wynik +='-';
				}	
				
			}
			if(i==5){
				if(keyCode != 8) { //backspace
					wynik +='-';
				}	
			}
		}
	}
	for (x in zablokowane)
	{
		if (zablokowane[x] == wynik) {
			wynik = '';
		}
	}
	
	$(p).val(wynik);
}
function zamknijAnkiete(){
	$("#sonda").remove();
	createCookie('ukryjAnkiete', '1', 1);
	if(readCookie('ukryjAnkiete') == null) {
		alert("Co zrobic aby pomaranczowy modul ankietowy nie pojawial się wiecej na Twoim komputerze?:\nWlacz obsługę 'Cookies/Ciasteczek' – Jak to zrobic: \n1) Internet Explorer: Tools/Narzędzia > Internet Options/Opcje internetowe > Privacy/Prywatność > Advanced/Zaawansowane > Pole 'Override automatic cookie handling'/'Zastąp automatyczną obsługę plików cookie' powinno byc puste (BEZ ptaszka)\n2) Firefox: Tools/Narzędzia > Options/Opcje > Privacy/Prywatność > Cookies/Ciasteczka > pole 'Enable cookies'/'Akceptuj ciasteczka' powinno być zaznaczone");
	}
}
function resizeWin(newWidth, newHeight){
	if (self.innerWidth) {
		frameWidth  = self.innerWidth;
		frameHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		frameWidth  = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		frameWidth  = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	} else {
		return false;
	}
	if (document.layers) {
		newWidth  -= (parent.outerWidth - parent.innerWidth);
		newHeight -= (parent.outerHeight - parent.innerHeight);
	}
	window.resizeBy(newWidth - frameWidth, newHeight - frameHeight);
}

/***************************
		BEHAVIORS
****************************/
$(function(){
//$.meta.setType("class");
	// POPUPY
	$('.obrazek a')
		.click(function(e){ 
			e.preventDefault();
			var $img = $(this).find('img');
			var height = 500/$img.width()*$img.height();
			var okno = window.open("","displayWindow",'width=650,height='+ height +',resizable=0,scrollbars=yes,menubar=no' );
			okno.document.write('<HTML><HEAD><TITLE>Bazarynka</TITLE><SCRIPT language=Javascript src="js/ccb.js"></SCRIPT></HEAD><BODY oncontextmenu="return false" onselectstart="return false" ondragstart="return false" topmargin=0 leftmargin=0 marginwidth=0 marginheight=0 background="'+$(this).attr('href')+'" OnClick="window.close()" style="cursor:hand;background-repeat: no-repeat;"><table height="100%"><tr><td valign=bottom style="font-family:Helvetica,Tahoma;font-size: 9px;color: red;">(C) This image is the property of their respective owners. </td></tr></table></BODY></HTML>');
		});
	$('.obrazki a')
		.click(function(e){ 
			e.preventDefault();
			var $img = $(this).find('img');
			//var plik = $img.attr('src').substring( $img.attr('src').lastIndexOf('/')+1 );
			var plik = this.href.substring( this.href.lastIndexOf('/')+1 );
			if( plik.indexOf("watch?v=") > -1 ){
			    plik = plik.substring( plik.indexOf("watch?v=")+8 );
			}
			var height = 500/$img.width()*$img.height()+200;
			var okno = window.open("/ogloszenia/zdjecia/"+$(this).parent().siblings('em').html()+"/plik:"+plik,"displayWindow",'width=650,height='+ height +',resizable=0,scrollbars=yes,menubar=no' );
		});
	$('.obrazki-abo a')
		.click(function(e){ 
			e.preventDefault();
			var $img = $(this).find('img');
			//var plik = $img.attr('src').substring( $img.attr('src').lastIndexOf('/')+1 );
			var plik = this.href.substring( this.href.lastIndexOf('/')+1 );
			if( plik.indexOf("watch?v=") > -1 ){
			    plik = plik.substring( plik.indexOf("watch?v=")+8 );
			}
			var height = 500/$img.width()*$img.height()+200;
			var okno = window.open("/ogloszenia_abonamentowe/zdjecia/"+ (this.parentNode.id.replace('id','')) +"/plik:"+plik,"displayWindow",'width=525,height='+ height +',resizable=0,scrollbars=yes,menubar=no' );
		});
	if( $('.popup-thumb').get(0) ){
		$('.popup-thumb')
			.click(function(e){
				
				$('.video').hide();
				
				$("#glowne")
					.attr('src', $(this).attr('src').replace('/thumb','')).show();

                resizeWin(550, $('#div_main').height()+25);
			});
	}
	if( $('.popup-video').get(0) ){
		$('.popup-video')
			.click(function(){
							
				$("#glowne").hide();
				$('.video').hide();
				
				var id = $(this).find('img').get(0).id;
				id = id.substring(1);
										
				$('#'+id).show();

				resizeWin(550, $('#div_main').height()+25);
			});
	}
	$('.popupmapa a')
		.click(function(e){ 
			e.preventDefault();
			window.open($(this).attr('href'),"displayWindow",'width=660,height=380,resizable=0,scrollbars=yes,menubar=no' );	
		});
	$('.email_popup_kf a')
		.click(function(e){ 
			e.preventDefault();
			window.open($(this).attr('href'),"displayWindow",'width=480,height=400,resizable=0,scrollbars=no,menubar=no' );	
		});
	$('.lf a')
		.click(function(e){ 
			e.preventDefault();
			window.open($(this).attr('href'),"displayWindow",'width=480,height=400,resizable=0,scrollbars=no,menubar=no' );	
		});
	$('.lp a, .polec a').not('.mg').not('.skip')
		.click(function(e){ 
			e.preventDefault();
			window.open($(this).attr('href'),"displayWindow",'width=480,height=720,resizable=0,scrollbars=no,menubar=no' );	
		});
	$('.laa a')
		.click(function(e){ 
			e.preventDefault();
			window.open($(this).attr('href'),"displayWindow",'width=480,height=560,resizable=0,scrollbars=no,menubar=no' );	
		});
		
	$('.cmn-close')
		.click(function(e){
			$("#cmn1").remove();
		});
		
	$(".zamknij")
		.click(function(e){
			e.preventDefault();
			createCookie('ukryjAnkiete', '1', 1);
			if(readCookie('ukryjAnkiete') == null) {
				alert('Włącz obsługę cookie albo zagłosuj w ankiecie');
			}
			$("#sonda").remove();
	});
	
	// TARGET BLANK
	$('a.blank, .lb .tresc a, a.www').attr('target', '_blank');
		
	// SKROTY OGLOSZEN
 	var ogloszenieIloscZnakow = 270;
 	var ogloszeniePodwojneIloscZnakow = 540;
	$('.ads ul .tresc').each(function(){ 
		if ( $(this).html().length < ogloszenieIloscZnakow+15 ) {
			id_ogloszenia = $(this).siblings('em').html();
			skrot = '<a href="#' + id_ogloszenia + '" class="m">&lt;more&gt;</a>';
			$(this)
				.siblings('em')
					.before('<span class="skrot">'+skrot+"</span>")
					.prev()
						.find('.m')
							.click(function(e){
								// e.preventDefault();
								$(this)
									.parents('.skrot')
										.hide();
							});
			return;
		}
		var text = $(this).html();
		var stack = 0, i = 0, skrot = '';
		while( i < text.length-1 ) {
			// <tag
			if ( text[i] == '<' && text[i+1] != '/' ) {
				stack++;
				i++;
			// </tag
			} else if ( text[i] == '<' && text[i+1] == '/' ) {
				stack--;
				i = text.slice(i).indexOf('>')+i+1;
			// />
			} else if ( text[i] == '>' && i && text[i-1] == '/' ) {
				stack--;
				i++;
			} else {
				i++;
			}
			if ( i > ogloszenieIloscZnakow && stack == 0 ) {
				skrot = text.slice(0, i-1);
				break;
			}
		}
		if (! skrot )
			return;
		id_ogloszenia = $(this).siblings('em').html();
		skrot += '<a href="#' + id_ogloszenia + '" class="m">&lt;more&gt;</a>';
		$(this)
			.hide()
			.siblings('em')
				.before('<span class="skrot">'+skrot+"</span>")
				.prev()
					.find('.m')
						.click(function(e){
							// e.preventDefault();
							$(this)
								.parents('.skrot')
									.hide()
									.siblings('.tresc')
									.show();
							var cc = $('#cc').height();
							var cr = $('#cr').height() - parseInt($('#mla').css('margin'));
							if (cc > cr) {
								document.getElementById('mla').style.margin = cc - cr + 'px 0 0 0';
							}
						});
	});

	$('.ads ul .tresc_podwojna').each(function(){ 
		if ( $(this).html().length < ogloszeniePodwojneIloscZnakow+15 )
			return;
		var text = $(this).html();
		var stack = 0, i = 0, skrot = '';
		while( i < text.length-1 ) {
			// <tag
			if ( text[i] == '<' && text[i+1] != '/' ) {
				stack++;
				i++;
			// </tag
			} else if ( text[i] == '<' && text[i+1] == '/' ) {
				stack--;
				i = text.slice(i).indexOf('>')+i+1;
			// />
			} else if ( text[i] == '>' && i && text[i-1] == '/' ) {
				stack--;
				i++;
			} else {
				i++;
			}
			if ( i > ogloszeniePodwojneIloscZnakow && stack == 0 ) {
				skrot = text.slice(0, i-1);
				break;
			}
		}
		if (! skrot )
			return;
		skrot += ' <a href="#" class="m">more&gt;</a>';
		$(this)
			.hide()
			.siblings('em')
				.before('<span class="skrot">'+skrot+"</span>")
				.prev()
					.find('.m')
						.click(function(e){
							e.preventDefault();
							$(this)
								.parents('.skrot')
									.hide()
									.siblings('.tresc_podwojna')
									.show();
						});
	});

 	var errors = {
		data: {},
		add: function( name, txt) {
			if (! this.data[ name ] )
				this.data[ name ] = [txt];
			else
				this.data[ name ].push(txt);
		},
		get: function(separator){
			var result = '';
			if (! separator)
				separator = "\n";
			$.each(this.data, function(field, msgs){
				$.each(msgs, function(k2, msg){
					result += field+' '+msg+separator;
				});
			});
			return result;
		},
		clear: function(){
			this.data = {};
		}
	};
	var __ = new function(){
		var lang = {
			'pl': {
				'wymagane': 'Pole wymagane',
				'zly-format': 'Zły format'
			}
		};
		return function(token){
			return lang['pl'][token] || 'LANG::'+token;
		}
	}
	var emailRegexp = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
	// var emailRegexp = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
	
	// VALIDOWANIE FORMULARZA
	$('#ogloszenia-dodaj')
		.submit(function(e){
		//	validateForm();
			//e.preventDefault();
			$(this)
				// wymagane
				.find('label.req input')
					.each(function(){
						var name = $(this).attr('name');
						if (! $(this).val() ) {
							errors.add(
								$(this).siblings('.em').find('em:eq(1)').text(),
								__('wymagane')
							);
						}
					})
				.end()

				// telefony - format
				.find('[@name*=telefon], [@name*=fax]')
					.not('[@name*=telefonPrefix], [@name*=telefon2_niepub], [@name*=faxPrefix], [@name*=_ext]')
						.each(function(){
							if ( this.value && ! /\d{3}-\d{4}$/.test( this.value ) )
								errors.add(
									$(this).siblings('.em').find('em:eq(1)').text(),
									__('zly-format')
								);
						})
						
				.find('[@name*=email]')
						.each(function(){
							if ( this.value && ! emailRegexp.test( this.value ) )
								errors.add(
									$(this).siblings('.em').find('em:eq(1)').text(),
									__('zly-format')
								);
						})

				if ( this.elements['dane[Ogloszenia_Katalog][id_kategorii]'] ) {
					if ( this.elements['dane[Ogloszenia_Katalog][id_kategorii]'].value == '' ) {
						errors.add(
							' branza: ',
							__('wymagane')
						);
					}
				}
				
				if ( $("#tresc").val() == '' ) {
					errors.add(
						' tresc: ',
						__('wymagane')
					);
				}

				if ( $("#email").val().length > 0 && ! emailRegexp.test( $("#email").val() ) ) {
					errors.add(
						' email: ',
						__('zly-format')
					);
				}
				
				$('#regulamin_ogloszenie')
					.each(function(){
						if ( ! $("#regulamin_ogloszenie")[0].checked ) {							errors.add(
								' regulamin: ',
								__('wymagane')
							);
						}
					});
							
			if ( errors.get() ) {
				if ( $("#komunikat").length ) {
					document.getElementById('komunikat').style.display = '';
				}
				alert(	
					'Formularz zawiera błędy:\n'
					+errors.get()+'\n'
					+'Prosze poprawić powyższe pola'
				);
				errors.clear();
				if ( $("#komunikat").length ) {
					document.getElementById('komunikat').style.display = 'none';
				}
				return false;
			}
			else {
				$('#komunikat').show('fast');
			}
		})
		.find('[@name*=telefonPrefix]')
			.change(function(){
				// tylko liczby
				if (! /^\d+$/.test( this.value ))
					this.value = '';
			})
		.end()
		.find('[@name*=email], [@name*=www]')
			.keypress(function(){
				// trimowanie
				// plewtak: bylo uzyte wyrazenie regularne '\s', ale zamiast bialych znakow wycinalo litere s
				// byc moze warto zastosowac poprawne wyrazenie regularne wycinajace rowniez inne znaki
				if(this.value.indexOf(' ') > -1) {
					this.value = this.value.replace(/ /g,'');
				}
				
			})
		.end()
		// AUTOMOTO
		.find('.automoto input')
			.change(function(){
				var $form = $(this).parents('form:first');
				var $tresc = $form.find('[@name*=tresc]');
				if ( $form.find('[@name*=model]').val() != "" ) {
					var tresc = ['opcje','rokProdukcji','marka','model'];
					$.each(tresc, function(k, v) {
						tresc[k] = $form.find('[@name*='+ v +']')
							.disable()
							.val();
					});
					if ($tresc.createTextRange) {
						var r = $tresc.createTextRange();
						r.collapse(false);
						r.select();
					}

					$tresc.val( tresc.join(' ')+' ' );
					$tresc.removeAttr('readonly');
					//$tresc.focus();
				}
			})
		.end()
		.find('[@name*=tresc]')
			// domyslne wylaczanie textarea dla automoto
			.each(function(){
				if ( /kategoria:11/.test( document.location.toString() ) )
					$(this).attr('readonly','readonly');
			})
			.click(function(){
				var $form = $(this).parents('form:first');
				if ( $form.find('[@name*=model]').val() != "" ) {
					// wylacza wszystkie pola od automoto po przejsciu do textarea
					if (this.createTextRange) {
						var r = this.createTextRange();
						r.collapse(false);
						r.select();
					}
					
					$(this).focus(); //set focus
					$form.find('.automoto input').disable();
				}
			})
		.end()
		.find('[@name*=cena]')
			.focus(function(){
				if ( this.value == 'n/a' || this.value == 'do uzg.' )
					this.value = '';
			})
		.end()
		.find('[@name*=lokalizacja]')
			.change(function(){
				// TODO: potrzeba t_podstaw odzwierciedlajacy typ nieruchomosci
				// lokalDoWynajeciaTrescPL('Do wynajecia');
				var $form = $(this).parents('form:first');
				var $tresc = $form.find('[@name*=tresc]');
				var $stan = $form.find('[@name*=stan]');
				var $lokalizacja = $form.find('[@name*=lokalizacja]');
				if ( $stan.val() != '' && $lokalizacja.val() != '' ) {
					$stan.disable();
					$lokalizacja.disable();
					$tresc.val (
						$stan.val()
						+ ' '
						+ $lokalizacja.val()
						+ ': '
					);
					this.focus();
				}
			})
		.end()
		.find('[@name*=stan]')
			.change(function(){
				if ( /kategoria/.test( document.location.toString() ) ) {
					var $form = $(this).parents('form:first');
					var $tresc = $form.find('[@name*=tresc]');
					var $stan = $form.find('[@name*=stan]');
					if ( $stan.val() != '' ) {
						$stan.disable();
						$tresc.val (
							$stan.val()
							+ ': '
						);
					}
				}
			})
		.end()
		.find('[@name*=telefon], [@name*=telefon2], [@name*=fax]')
			.change(function(event){
				
				validatePhone(this,event.keyCode);
			})
			.keydown(function(event){
							
				validatePhone(this,event.keyCode);
			})
		.end();
	// FORMULARE GET	
	$('form.rewrite-get')
		.attr('method', 'get')
		.submit(function(e){
			var urlSuffix = '';
			$.each( $(this).formToArray(), function(k, r){
				urlSuffix += r.name.match(/dane\[(\w+)\]/ )[1] +':'+ r.value +'/';
			});
			window.location = $(this).attr('action')+urlSuffix;
			e.preventDefault();
	});

	$('input[@id]')
		.click(function(){
			$(this)
			.siblings('#wolne')
				.check();
			$(this)
			.parents()
				.siblings('#wolne')
				.check();
		});

});


function zegar ( id, czas ) {
	$(function(){
		if ( czas > 0 ) {
			$( id ).countdown({until: new Date(czas), compact: true, onExpiry: liftOff});
		}
	});
}

function liftOff() {
	window.location.reload();
	return false;
}	
$(document).ready(function(){
	$("#mla").each(function(){
		var cc = $('#cc').height();
		var cr = $('#cr').height();
		
		if (cc > cr) {
			document.getElementById('mla').style.margin = cc - cr + 'px 0 0 0';
		}
	});
});

var resizeTimer = null;


function banerTapeta(url){
	$(document).ready(function(){
		$('html,body').css('background', "url('"+url+"')");
	});
}

function createCookie(name,value,hours){
	if (hours)
	{
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function expandBaner(id){
	document.getElementById('ContainerDivID'+id).style.height = "300px"; // expanded height  
}

function foldBaner(id){
	document.getElementById('ContainerDivID'+id).style.height = "100px"; // normal height  
}

function readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/***************************
		FUNKCJE
****************************/
	
function goToUrl( url ) {
	location.href = url;
}

function jqToggle(element_selector){
	$(element_selector).toggle();
}