function anchor(target) {
	var targetOffset = $('#'+target).offset().top;
	$('html').animate({scrollTop: targetOffset}, 1000);
	return false;
}

function defaultValueRestore(selector) {
	$(selector).focus(function(){
		var def = $(this)[0].defaultValue;
		var cur = $(this).val();
		if (def==cur) {
			$(this).attr('value','');
		}
	});
	$(selector).blur(function(){
		var def = $(this)[0].defaultValue;
		var cur = $(this).val();
		if (def==cur || cur=='') {
			$(this).attr('value',def);
			$(this).removeClass('ok');
		}
		else {
			$(this).addClass('ok');
		}
	});	
}

function isEmail(email) {
	email = email.replace(/[ ]/g, '');
	var regEmail = /^([a-zA-Z0-9._-]{1,})@([a-zA-Z0-9._-]{1,})\.([a-zA-Z]{2,4})$/;
	if (!regEmail.test(email)) return false;
	else return true;
}



$(document).ready(function() {
	defaultValueRestore('input[type=text].default');
	var hash = (window.location.hash).replace("#", "");
	if (hash!='' && hash!=undefined) {
		var val = hash.match(/^JS:([0-9A-Za-z_-]+)$/);
		if (val[1]!=null && val[1]!=undefined) {
			anchor(val[1]);
		}
	}
	
	$("a.LB").attr('rel','prettyPhoto[gal1]');
	$("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded', hideflash:true});
	//$("a.LB").prettyPhoto({theme:'dark_rounded', hideflash:true});
	
	
	setTimeout(switchPhoto, 2000);
});

photoid=1;

var i = undefined;
function switchPhoto() {
	if (photoid==1) {
		$('#bnr1').fadeOut(3000);
		$('#bnr2').fadeIn(3000);
		photoid=2;
	}
	else {
		$('#bnr1').fadeIn(3000);
		$('#bnr2').fadeOut(3000);
		photoid=1;
	}
	setTimeout(switchPhoto, 6000);
}


function send_mail(obj) {
	var id = $(obj).attr('id');
	if (validacja_formy(id)) {
		$(obj).slideUp(500);
		$('#wysylanie').slideDown(500);
		var imie = $(obj).find('input[name="imie"]').val();
		var mail = $(obj).find('input[name="mail"]').val();
		var tresc = $(obj).find('textarea[name="tresc"]').val();
		imie = encodeURIComponent(imie);
		mail = encodeURIComponent(mail);
		tresc = encodeURIComponent(tresc);
		
		$.ajax({
			type: "GET",
			url: "/ajax.php?module=form&mail="+mail+"&imie="+imie+"&tresc="+tresc,
			cache: true, // to prevent doubles ;)
			success: function(info) {
				if (info) {
					$('#loader').slideUp(500);
					if (info=="OK") {
						$('#wysylanie').slideUp(500);
						$('#sukces').slideDown(500);
					}
					else {
						//alert(info);
						alert("Nieznany błąd. Spróbuj ponownie. Jeżeli błąd będzie się powtarzał - proszę skorzystaj z innej formy kontaktu.");
						$(obj).slideDown(500);
						$('#wysylanie').slideUp(500);
					}
				}
				else {
					alert("Żądanie przekroczyło dozwolony czas oczekiwania. Sprawdź połączenie z internetem, odśwież stronę i spróbuj ponownie.");
					$(obj).slideDown(500);
					$('#wysylanie').slideUp(500);
				}
	         } // success
		});// ajax
	}
	return false;
}



/**
 * Waliduje formularze
 * @param id - [atrybut html] id formularza 
 * @return bool - jezeli wszystko ok to true
 * TODO przepisac
 */
function validacja_formy(id, or_ok) {
	var blad='';
	$('#'+id+' .req_text').each (function () {
		var def = $(this)[0].defaultValue;
		var cur = $(this).val();
		if (cur=='' || cur==def) {
			blad += "- " + $(this).attr('title') + ".\n";
		}
	});
	$('#'+id+' .req_mail').each (function () {
		if (!isEmail($(this).attr('value'))) {
			blad += "- " + $(this).attr('title') + "\n";
		}
	});
	$('#'+id+' .type_mail').each (function () {
		if (!isEmail($(this).attr('value')) && ($(this).attr('value')!='')) {
			blad += "- Niepoprawny " + $(this).attr('title') + "\n";
		}
	});
	$('#'+id+' .req_checkbox').each (function () {
		if (!$(this).attr('checked')) {
			blad += "- " + $(this).attr('title') + "\n";
		}
	});
	
	if (or_ok != undefined) {
		or_ok = false;
		dodaj_txt = "Podaj ";
		$('#'+id+' .req_or').each (function () {
			dodaj_txt += $(this).attr('title')+" lub ";
			if ($(this).attr('value')!='') {
				or_ok=true;
			}
		});
		dodaj_length=dodaj_txt.length;
		dodaj_txt=dodaj_txt.substring(0, dodaj_length-5)+'.';
		
		if (or_ok==false) {
			blad += "- "+dodaj_txt+"\n";
		}
	}
	

	if (blad != '') {
		alert(blad);
		return false;
	}
	else {
		return true;
	}
}


$(document).ready(iframe_loader);
function iframe_loader() {
	$('.iframe_loader').each(function(){
		$(this).removeClass('iframe_loader');
		$(this).removeClass('din');
		var html = $(this).html();
		html = trim(html);
		html = htmlspecialchars_decode(html);
		$(this).html(html);
	});
}

$(document).ready(load1);
function load1() {
	var x = 52.177312;
	var y = 21.016492;
	var zoom=15; 
	var point = new GLatLng(x,y);  
	var marker = new GMarker(point);
	
	if (GBrowserIsCompatible()) {
		var mapka1 = document.getElementById("mapka");
		if (mapka1) {
			var mapa = new GMap2(document.getElementById("mapka")); 
			//GEvent.addListener(marker, "click", function(){
				//var myHtml = document.getElementById("text_mapka").innerHTML;
			    //mapa.openInfoWindowHtml(point, myHtml);
			//});
			mapa.addControl(new GSmallZoomControl());
			mapa.setCenter(new GLatLng(x,y), zoom); 
			mapa.addOverlay(marker);
		}
		var mapka2 = document.getElementById("mapka2");
		if (mapka2) {
			var mapa2 = new GMap2(document.getElementById("mapka2")); 
			GEvent.addListener(marker, "click", function(){
				var myHtml = document.getElementById("mapka2_html").innerHTML;
			    mapa2.openInfoWindowHtml(point, myHtml);
			});
			mapa2.addControl(new GLargeMapControl());
			mapa2.addControl(new GScaleControl());
			mapa2.addControl(new GMapTypeControl());
			mapa2.setCenter(new GLatLng(x,y), zoom); 
			mapa2.addOverlay(marker);
		}
	}
}


function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


function htmlspecialchars_decode (string, quote_style) {
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined') {
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            } else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded
    string = string.replace(/&amp;/g, '&');
 
    return string;
}
