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 findPos(obj){
	var posX = obj.offsetLeft;var posY = obj.offsetTop;
	while(obj.offsetParent) {
		if(obj==document.getElementsByTagName('body')[0]) { break; }
		else {
			posX=posX+obj.offsetParent.offsetLeft;
			posY=posY+obj.offsetParent.offsetTop;
			obj=obj.offsetParent;
		}
	}
	var posArray=[posX,posY];
	return posArray;
}

$(document).ready(function(){
	var tt = $('#tooltip2');
	$('.xp').hover(function(){
		var obj = $(this).get(0);
		var pos = findPos(obj);
		var w = $(this).width();
		var h = $(this).height();
		$(tt).show();
		var path = $(this).attr('src');
		var big_y = $(this).attr('title');
		var diff = h-big_y;
		diff /= 2;
		$(tt).html('<img src="'+path.replace('/_','/')+'" alt="" />');
		$(tt).css({top: pos[1]+diff+'px', left: pos[0]+w+10+'px'});
	}, function(){
		$(tt).hide();
	});
});

function prenumerata(id) {
	var o = $('#'+id);
	if (validacja_formy(id)) {
		var t='';
		var od=$(o).find('#ff1').val();
		var okres=$(o).find('input[name=okres]').val();
		var imie=$(o).find('#ff2').val();
		var ulica=$(o).find('#ff3').val();
		var kod=$(o).find('#ff4').val();
		var miejscowosc=$(o).find('#ff5').val();
		var nip=$(o).find('#ff6').val();
		var telefon=$(o).find('#ff7').val();
		var fax=$(o).find('#ff8').val();
		var mail=$(o).find('#ff9').val();
		var skad=$(o).find('#ff10').val();
		t = 'Prenumerata od: '+od+'\n'+
		'Okres: '+okres+'\n'+
		'Imię/nazwisko/firma: '+imie+'\n'+
		'Ulica: '+ulica+'\n'+
		'Kod pocztowy: '+kod+'\n'+
		'Miejscowosc: '+miejscowosc+'\n'+
		'NIP: '+nip+'\n'+
		'Telefon: '+telefon+'\n'+
		'Fax: '+fax+'\n'+
		'Mail: '+mail+'\n'+
		'Skąd wiesz o estilo?: '+skad+'\n';
		
		$('#wysylanie').slideDown(500);
		$(o).slideUp(500);
		
		$.ajax({
			type: "GET",
			url: "/ajax2.php?tekst="+encodeURIComponent(t),
			cache: false,
			success: function(info) {
				if (info) {
					if (info=="OK") {
						$('#wysylanie').slideUp(500);
						$('#sukces').slideDown(500);
					}
					else {
						alert("Nieznany błąd, spróbuj ponowić próbę wysłania formularza");
						$('#wysylanie').slideUp(500);
						$(o).slideDown(500);
					}
				}
				else {
					alert("Nieznany błąd, spróbuj ponowić próbę wysłania formularza");
					$('#wysylanie').slideUp(500);
					$(o).slideDown(500);
				}
	         }
		});// ajax
	}
}

String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('%s', 'i');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};


function dieta(id) {
	var o = $('#'+id);
	if (validacja_formy(id)) {
		var t='';
		
		var imie = o.find('#ff1').val();
		var nazwisko = o.find('#ff2').val();

		var mail = o.find('#ff3').val();
		var tel = o.find('#ff4').val();
		
		var plec = o.find('[name=plec]:checked').val();
		var data = o.find('#ff5').val();

		var waga = o.find('#ff6').val();
		var wzrost = o.find('#ff7').val();
		var talia = o.find('#ff8').val();
		var biodra = o.find('#ff9').val();

		var akt1 = o.find('#ff10').val();
		var akt2 = o.find('#ff11').val();

		var choroby = o.find('#ff13').val();
		var dolegli = o.find('#ff14').val();
		
		var posilki = o.find('#ff15').val();
		var motywacja = o.find('#ff16').val();

		t = 'Imię: %s\nNazwisko: %s\nE-mail:%s\nTelefon: %s\nPłeć: %s\nData urodzenia: %s\n'+
		'Waga: %s kg\nWzrost: %s cm\nTalia: %s cm\nBiodra: %s cm\n'+
		'Aktywność zawodowa:\n%s\nAktywność fizyczna:\n%s\n'+
		'Potwierdzone choroby:\n%s\nInne dolegliwości:\n%s\n'+
		'Posiłki w ciągu dnia:\n%s\nMotywacja:\n%s';
		
		t = t.format(imie, nazwisko, mail, tel, plec, data, waga, wzrost,
				talia, biodra, akt1, akt2, choroby, dolegli, posilki, motywacja);
		$('#wysylanie').slideDown(500);
		$(o).slideUp(500);
		
		$.ajax({
			type: "GET",
			url: "/ajax2.php?a=2&tekst="+encodeURIComponent(t),
			cache: false,
			success: function(info) {
				if (info) {
					if (info=="OK") {
						$('#wysylanie').slideUp(500);
						$('#sukces').slideDown(500);
					}
					else {
						alert("Nieznany błąd, spróbuj ponowić próbę wysłania formularza");
						$('#wysylanie').slideUp(500);
						$(o).slideDown(500);
					}
				}
				else {
					alert("Nieznany błąd, spróbuj ponowić próbę wysłania formularza");
					$('#wysylanie').slideUp(500);
					$(o).slideDown(500);
				}
	         }
		});// ajax
	}
}


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(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);
	});
	$('.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', '');
	});
}

var t=null;

$(document).ready(mover);
function mover() {
	$('.mover').each(function(){
		var area_h = $(this).find('.mover_area_height').html();
		$(this).find('.mover_area').css({height: area_h+'px'});
		$(this).find('.mover_area').addClass('.mover_dir_bottom');
	});
	t = setInterval(mover_tick, 50);
	
	$('.mover').hover(function(){
		$(this).find('.mover_area').addClass('mover_stop');
	}, function(){
		$(this).find('.mover_area').removeClass('mover_stop');
	});
	
	$('.mover>.mover_top').click(function(){
		var ts = $(this).parent().find('.mover_area');
		var t = $(ts).scrollTop();
		var ah = $(ts).find('.mover_area_height').html();
		var ch = $(ts).attr('scrollHeight');
		if (t>scrollAmount) {
			if (t-scrollAmount*clickScroll>=0) {
				$(ts).scrollTop(t-scrollAmount*clickScroll);
			}
			else {
				$(ts).scrollTop(0);
			}
		}
	});
	
	$('.mover>.mover_bottom').click(function(){
		var ts = $(this).parent().find('.mover_area');
		var t = $(ts).scrollTop();
		var ah = $(ts).find('.mover_area_height').html();
		var ch = $(ts).attr('scrollHeight');
		if (t<ch-ah) {
			if (t+scrollAmount*clickScroll<ch-ah) {
				$(ts).scrollTop(t+scrollAmount*clickScroll);
			}
			else {
				$(ts).scrollTop(ch-ah);
			}
		}
	});
}

var scrollAmount = 1;
var clickScroll = 20;
function mover_tick() {
	$('.mover .mover_area').each(function(){
		var t = $(this).scrollTop();
		var ah = $(this).find('.mover_area_height').html();
		var ch = $(this).attr('scrollHeight');
		
		if (!$(this).hasClass('mover_stop')) {
			if ($(this).hasClass('mover_dir_bottom')) {
				if (t<ch-ah && t+scrollAmount<ch-ah) {
					$(this).scrollTop(t+scrollAmount);
				}
				else {
					$(this).removeClass('mover_dir_bottom');
					$(this).addClass('mover_dir_top');
				}
			}
			else if ($(this).hasClass('mover_dir_top')) {
				if (t>scrollAmount && t-scrollAmount>=0) {
					$(this).scrollTop(t-scrollAmount);
				}
				else {
					$(this).removeClass('mover_dir_top');
					$(this).addClass('mover_dir_bottom');
				}
			}
		}
	});
}

$(document).ready(function(){
	$('#newsletter_ok').click(function(){
		var mail = $('#newsletter_mail').val();
		if (isEmail(mail)) {
			$('span#ok').hide();
			$('span#loading').show();
			
			$('span#error').hide();
			$('span#exist').hide();
			$('span#done').hide();
			$.ajax({
				type: "GET",
				url: "/ajax.php?module=newsletter&action=add&row="+encodeURIComponent(mail),
				cache: false,
				success: function(info) {
					if (info) {
						if (info=="OK") {
							$('span#loading').hide();
							$('span#done').show();
						}
						else if (info=="ALREADY_IN_DATABASE"){
							$('span#loading').hide();
							$('span#exist').show();
							$('span#ok').show();
						}
						else {
							$('span#loading').hide();
							$('span#error').show();
							$('span#ok').show();
						}
					}
					else {
						$('span#loading').hide();
						$('span#error').show();
						$('span#ok').show();
					}
		         }
			});// ajax
		}
		else {
			alert('Podaj poprawny adres e-mail');
		}
	});
});



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 add_comment(id) {
	if (validacja_formy(id)) {
		var nick = encodeURIComponent($('[name=nick]').val());
		var tresc = encodeURIComponent($('[name=tresc]').val());
		var mail = encodeURIComponent($('[name=mail]').val());
		var www = encodeURIComponent($('[name=www]').val());
		$.ajax({
			type: "GET",
			url: "?ajax=1&aaction=add_comment&nick="+nick+'&tresc='+tresc+'&mail='+mail+'&www='+www,
			cache: false,
			success: function(info) {
				if (info) {
					if (info=="OK") {
						alert("Komentarz dodany!");
						$('.add_table, .nocomments').slideUp(1000);
						$('.add_table input[type!=submit], .add_table textarea').val('');
						$('#comments_div').slideUp(1000, function(){
							$('#comments_div').html("Ładowanie komentarzy..");
							$('#comments_div').slideDown(500,function(){
								reload_comments();
							});
						});
					}
					else {
						alert("Błąd dodawania komentarza! Spróbuj ponownie, a jak nie podziała to zgłoś to proszę gg:2928054");
					}
					//alert(info);
				}
				else {
					alert("Ajax request timed out. Please refresh this page (F5) and try again.");
				}
	         }
		});// ajax
		return false;
	}
	else {
		return false;
	}
}

function reload_comments() {
	$.ajax({
		type: "GET",
		url: "?ajax=1&aaction=load_comments",
		cache: false,
		success: function(info) {
			if (info) {
				if (info!='ERROR') {
					$('#comments_div').slideUp(500, function(){
						$('#comments_div').html(info);
						$('#comments_div').slideDown(1000);
					});
				}
				else {
					alert("Błąd żądania. Proszę odśwież stronę.");
				}
				//alert(info);
			}
			else {
				alert("Ajax request timed out. Please refresh this page (F5) and try again.");
			}
         }
	});// ajax
}



$(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});

	$('.bt').bt({
		  centerPointX: .2,
		  spikeLength: 5,
		  spikeGirth: 8,
		  padding: 5,
		  cornerRadius: 5,
		  fill: 'rgba(0, 0, 0, .70)',
		  strokeWidth: 0,
		  positions: ['right', 'top', 'bottom', 'left'],
		  strokeStyle: 'rgba(255,255,255,.99)',
		  cssStyles: {
				color: '#dfffff',
				fontWeight: 'normal',
				lineHeight: '14px',
				textAlign: 'left',
				paddingLeft: '16px',
				paddingRight: '16px',
				width: 'auto',
				fontSize: '10px'
		  }
	});
	
	$('.n3 ul li a').hover(function(){
		var rel = $(this).attr('rel');
		$('.n2>div').stop(true, true);
		
		$('.n2>div').each(function(){
			var id = $(this).attr('id');
			if (id!=rel) {
				$('.n2>div#'+id).fadeOut(500);
			}
			else {
				$('.n2>div#'+id).fadeIn(500);
			}
		});
	},
	function(){});
	
	$('.n2').css('position','relative');
	$('.n2>div').each(function(){
		$(this).css('position','absolute');
	});
});

function expand_comments() {
	anchor('comments');
	$('#comments div.add_table').slideDown(1000);
}

/**
 * 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+' .req_num').each (function () {
		var val = $(this).attr('value');
		if (!val.match(/^[0-9]+$/)) {
			blad += "- " + $(this).attr('title') + "\n";
		}
	});
	$('#'+id+' .req_date').each (function () {
		var val = $(this).attr('value');
		if (!val.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/)) {
			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;
	}
}






