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 isURL(www) {
	if (www==undefined || !www.match(/^https?:\/\/([a-z0-9]+)(\.)([a-z]{2,})/) || -1!=www.indexOf("<") || -1!=www.indexOf(">") || -1!=www.indexOf('"') || -1!=www.indexOf("'")) {
		return false;
	}
	return true;
}

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]');
	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});
	
	$(".OL").each(function(){
		var title = $(this).attr('title');
		$(this).attr('title','');
		$(this).attr('title_ol',title);
	});
	
	$(".OL").hover(function(){
		var title = $(this).attr('title_ol');
		if ($(this).hasClass('fullhtml')) {
			return overlib(title, FULLHTML);
		}
		else {
			return overlib(title);
		}
	},function(){
		return nd();
	});
	
	$(".over_szczegoly").hover(function(){
		return overlib('<img src="/css/images/over_szczegoly.png" />', FULLHTML);
	},function(){
		return nd();
	});

	$(".over_powieksz").hover(function(){
		return overlib('<img src="/css/images/over_powieksz.png" />', FULLHTML);
	},function(){
		return nd();
	});
	
	
	$("ul.switcher a").click(function() {
		$(this).parent().parent().find('a').removeClass('a');
		var rel = $(this).attr('rel');
		if (rel=="") {
			$('#projekty_holder .projekty_middle .projekt').show();
		}
		else {
			$('#projekty_holder .projekty_middle .projekt').hide();
			$('#projekty_holder .projekty_middle .pr-'+rel).show();
		}
		$(this).addClass('a');
		Cufon.replace('.projekty_top ul li a');
		return false;
	});
	
	$("a.copy_to_pi").click(function(){
		var rel = $(this).attr('rel');
		var href = $(this).attr('href');
		$('img#project_image_thumb').attr('src',rel);
		$('a#project_image').attr('href',href);
		return false;
	});
	
	
	$('.iframe_loader2').each(function(){
		$(this).removeClass('iframe_loader2');
		$(this).removeClass('din');
		var title = $(this).attr('title');
		var html = trim(title);
		html = htmlspecialchars_decode(html);
		$(this).html(html);
		$(this).attr('title', '');
	});
	
});



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;
}

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 expand_comments() {
	anchor('comments');
	$('#comments div.add_table').slideDown(1000);
}


function send_mail(obj) {
	var id = $(obj).attr('id');
	if (validacja_formy(id)) {
		$(obj).slideUp(500);
		$('#wysylanie').slideDown(500);
		var name = $(obj).find('[name="name"]').val();
		var mail = $(obj).find('[name="mail"]').val();
		var tel = $(obj).find('[name="tel"]').val();
		var url = $(obj).find('[name="url"]').val();
		var typeofhelp = $(obj).find('[name="typeofhelp"]').val();
		var message = $(obj).find('[name="message"]').val();
		var budget = $(obj).find('[name="budget"]').val();
		var when = $(obj).find('[name="when"]').val();
		var about = $(obj).find('[name="about"]').val();
				
		name = encodeURIComponent(name);
		mail = encodeURIComponent(mail);
		tel = encodeURIComponent(tel);
		url = encodeURIComponent(url);
		typeofhelp = encodeURIComponent(typeofhelp);
		message = encodeURIComponent(message);
		budget = encodeURIComponent(budget);
		when = encodeURIComponent(when);
		about = encodeURIComponent(about);
		
		$.ajax({
			type: "GET",
			url: "/ajax.php?module=form&mail="+mail+"&name="+name+"&tel="+tel+"&url="+url+"&typeofhelp="+typeofhelp+"&message="+message+"&budget="+budget+"&when="+when+"&about="+about,
			cache: true, // to prevent doubles ;)
			success: function(info) {
				if (info) {
					$('#loader').slideUp(500);
					if (info=="OK") {
						$('#wysylanie').slideUp(500);
						$('#sukces').slideDown(500);
					}
					else {
						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 += "- " + $(this).attr('title') + "\n";
		}
	});

	$('#'+id+' .req_tel').each (function () {
		var val = $(this).attr('value');
		if (val.length <= 9) {
			blad += "- " + $(this).attr('title') + "\n";
		}
	});

	
	$('#'+id+' .type_url').each (function () {
		if (!isURL($(this).attr('value')) && ($(this).attr('value')!='')) {
			if (!isURL('http://'+$(this).attr('value'))) {
				blad += "- " + $(this).attr('title') + "\n";
			}
			else {
				$(this).attr('value', 'http://'+$(this).attr('value'));
			}
		}
	});

	$('#'+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(load1);
function load1() {
	var x = 50.06013;
	var y = 21.977138;
	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 GSmallMapControl());
			mapa.addControl(new GMapTypeControl());
			mapa.setCenter(new GLatLng(x,y), zoom); 
			mapa.addOverlay(marker);
		}
	}
}

function add_newsletter() {
	var m=$('#form_mail').val();
	if (isEmail(m)) {
		$('#submit').hide();
		$('#loader-2').show();
		m = encodeURIComponent(m);
		$.ajax({
			type: "GET",
			url: "/ajax.php?module=newsletter&mail="+m+"&action=add",
			cache: true,
			success: function(info) {
				if (info) {
					$('#loader-2').hide();
					if (info=="OK") {
						$('#ok').show();
						$('#form_mail').attr('readonly','readonly');
						$('#form_mail').val('Adres e-mail zapisany.');
					}
					else if (info=="ALREADY_IN_DATABASE") {
						$('#ok').show();
						//$('#form_mail').attr('readonly','readonly');
						$('#form_mail').val('Adres jest już zapisany.');
					}
					else {
						$('#submit').show();
						$('#form_mail').val('Nieznany błąd!');
						//alert(info);
					}
				}
				else {
					alert("Żądanie przekroczyło dozwolony czas oczekiwania. Sprawdź połączenie z internetem, odśwież stronę i spróbuj ponownie.");
					$('#submit').show();
					$('#loader-2').hide();
				}
	         } // success
		});// ajax
	}
	else {
		alert('Podaj poprawny adres e-mail');
	}
}


function add_newsletter_4() {
	var m=$('#form_mail-4').val();
	if (isEmail(m)) {
		$('#submit-4').hide();
		$('#loader-4').show();
		m = encodeURIComponent(m);
		$.ajax({
			type: "GET",
			url: "/ajax.php?module=newsletter&mail="+m+"&action=add",
			cache: true,
			success: function(info) {
				if (info) {
					$('#loader-4').hide();
					if (info=="OK") {
						$('#ok-4').show();
						$('#form_mail-4').attr('readonly','readonly');
						$('#form_mail-4').val('Adres e-mail zapisany.');
						setTimeout(hideDim, 3000);
					}
					else if (info=="ALREADY_IN_DATABASE") {
						$('#ok-4').show();
						//$('#form_mail-3').attr('readonly','readonly');
						$('#form_mail-4').val('Adres jest już zapisany.');
					}
					else {
						$('#submit-4').show();
						$('#form_mail-4').val('Nieznany błąd!');
						//alert(info);
					}
				}
				else {
					alert("Żądanie przekroczyło dozwolony czas oczekiwania. Sprawdź połączenie z internetem, odśwież stronę i spróbuj ponownie.");
					$('#submit-4').show();
					$('#loader-4').hide();
				}
	         } // success
		});// ajax
	}
	else {
		alert('Podaj poprawny adres e-mail');
	}
}



$(document).ready(komentarze);

function komentarze() {
	$('.comments').waypoint(function() {
		var that=$(this);
		$.ajax({
			type: "GET",
			url: document.location+"comments/?ajax=1",
			cache: false,
			success: function(info) {
				if (info) {
					$(that).html(info);
				}
	         } // success
		});// ajax
	}, {triggerOnce:true, offset: '100%'});
}


function add_comment(obj) {
	var id=$(obj).attr('id');
	if(validacja_formy(id)) {
		$("#"+id).slideUp(500);
		$("#loading").slideDown(500);
		$.ajax({
			type: "get",
			url: "/ajax.php",
			data: {
				"id":	$("#"+id+" [name=id]").val(),
				"id_a":	$("#"+id+" [name=ida]").val(),
				"nick":	$("#"+id+" [name=nick]").val(),
				"email":$("#"+id+" [name=email]").val(),
				"www":	$("#"+id+" [name=www]").val(),
				"text":	$("#"+id+" [name=text]").val(),
				"id_replyto":	$("#"+id+" [name=replyto]").val(),
				"module":	"comments",
				"action":	"add"
			},
			cache: false,
			success: function(info) {
				//alert(info);
				if (info && info=='OK') {
					//document.location.href = document.location;
					$("#loading").slideUp(500);
					$("#added").slideDown(500);
				}
				else {
					alert("Błąd dodawania komentarza, spróbuj ponownie.");
					$("#loading").slideUp(500);
					$("#"+id).slideDown(500);
				}
	         } // success
		});// ajax
	}
	return false;
}


function podswietl(obj) {
	anchor("komentuj");
	$("#replying").removeAttr("id");
	$(obj).parent().parent().attr("id","replying");
	
	var that=$("#replyto");

	var id=$(obj).attr('rel');
	var nick=$(obj).attr('rev');
	$("#formc [name=replyto]").val(id);
	
	$(that).html("Odpowiadasz na komentarz użytkownika <b>"+nick+"</b> <a href=\"#\" onclick=\"del(this); return false;\"><img alt=\"\" src=\"/css/images/ico_close.png\" class=\"vm\"/></a>");
	$(that).slideDown(500);
}

function del(obj) {
	var that =$(obj).parent();
	$(that).slideUp(500);
	$("#formc [name=replyto]").val(0);
	$("#replying").removeAttr("id");
}








$(document).ready(function(){
	if (readCookie('eighteen')=='ok') { }
	else {
		dimAndBox();
		scrolled();
		$('#dim, #dimclose').live('click',hideDim);
		showDim();
	}
});


function scrolled() {
	var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
	var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();
	dimAndBox(viewportWidth, viewportHeight, $(window).scrollTop());
}

function dimAndBox(vw_, vh_, st_) {
	var h_ = $('#main_container').outerHeight();
	$('#dim').height(h_);
	if (vh_) {
		var bh_ = $('#dimbox').height();
		var bw_ = $('#dimbox').width();
		var posTop = (vh_-bh_)/2;		
		var posLeft = (vw_-bw_)/2;
		$('#dimbox').css({top:(posTop+st_)+'px',left:posLeft+'px'});
	}
}

function copyContents(from, to) {
	$('#'+to).html('<div id="closedim">X</div>');
	$('#'+from).clone(true).appendTo('#'+to);
}

function showDim(showClose) {
	$(window).scroll(scrolled);
	$(window).resize(scrolled);
	scrolled();
	$('#dim, #dimbox').fadeIn(500);
	if (showClose) {
		$('#closedim').fadeIn(500);
	}
	//$('#dimbox').children().removeClass('din');
	scrolled();
}
function hideDim() {
	createCookie('eighteen', 'ok', 666);
	$('#dim, #dimbox').fadeOut(500);
	$(window).unbind('scroll');
	$(window).unbind('resize');
}

/* ---------------------------------------
 * 
 * 
 * 888888888888888888888888888888888888888
 */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
