$(document).ready(ready1);

function ready1() {
	$('#menu li a').hover(function(){
		$(this).parent().css({'backgroundImage': 'url("/css/images/menu_a.png")'});
	},function(){
		$(this).parent().css({'backgroundImage': 'none'});
	});
	
	
	$('.slider_holder .control_next').click(function(){
		switchImage($(this).parent(), 'next');
	});
	$('.slider_holder .control_prev').click(function(){
		switchImage($(this).parent(), 'prev');
	});
	
	$('.slider_holder').hover(function(){
		clearInterval(ss);
	}, function(){
		clearInterval(ss);
		ss = setInterval(sw, 5000);
	});
	clearInterval(ss);
	ss = setInterval(sw, 5000);
	
	$('.slider_holder .slider .slider_content').each(function(){
		$(this).width($(this).parent().find('.banner').length*$(this).parent().width());
	});
	
	
	$('.slider_holder').attr('count',$('.slider_holder .slider_banners .banner').length);
	$('.slider_holder').attr('current',1);
	var x=1;
	$('.slider_holder .controls').html('');
	$('.slider_holder .slider_banners .banner').each(function(){
		$('.slider_holder .controls').append('<a rel="'+(x++)+'"></a>');
	});
	$('.slider_holder .controls a[rel="1"]').addClass('on');
	
	$('.slider_holder .controls a').click(function(){
		var rel = $(this).attr('rel');
		switchImage($(this).parent().parent(), rel);
	});
	
	$('.slider_holder .contents .content:first').show();
	$('.slider_holder .slider_banners .banner:first').show();
	
	
	$('.dlakogo ul li:last').addClass('last');
}

var ss = null;
function sw() {
	$('.slider_holder').each(function(){
		switchImage($(this), 'next');
	});
}

function switchImage(slider_obj, image_id) {
	var s = $(slider_obj).children('.slider');
	$(s).stop(true, true);
	var width = $(slider_obj).children('.slider').width();

	var current = $(slider_obj).attr('current');
	var count = $(slider_obj).attr('count');
	
	if (image_id=='prev') {
		if (current<=1) { current = count; }
		else { current--; }
	}
	else if (image_id=='next') {
		if (current>=count) { current = 1; }
		else { current++; }
	}
	else {
		if (current==image_id) { return; }
		current=image_id;
	}
	$(slider_obj).find('.contents .content').hide();
	$(slider_obj).find('.contents .content:nth-child('+current+')').fadeIn(500);
	$(slider_obj).attr('current',current);
	
	$(slider_obj).find('.controls a').removeClass('on');
	$(slider_obj).find('.controls a[rel="'+(current)+'"]').addClass('on');

	$(slider_obj).find('.slider_banners .banner').stop(true,true);
	$(slider_obj).find('.slider_banners .banner').fadeOut(500);
	$(slider_obj).find('.slider_banners .banner:nth-child('+(current)+')').fadeIn(500);
	
	//$(s).animate({scrollLeft: (current-1)*width}, 500, 'swing', c);
}

function c() {
	return;
	var l = $('.slider_holder .slider').scrollLeft();
	var w = $('.slider_holder .slider').width();
	var i = l/w;
	$('.slider_holder .controls a').removeClass('on');
	$('.slider_holder .controls a[rel="'+(i+1)+'"]').addClass('on');
}


$(document).ready(ajax_load);
function ajax_load() {
	$('.ajax_load').each(function(){
		var url = $(this).html();
		var a = fast_ajax(url, $(this), function(){}, function(obj) {$(obj).removeClass('din');});
	});
}



function anchor(target) {
	var targetOffset = $('#'+target).offset().top;
	$('html').animate({scrollTop: targetOffset}, 1000);
	return false;
}

function fast_ajax(url, obj, onError, callBack) {
	$.ajax({
		type: "GET",
		url: htmlspecialchars_decode(url),
		cache: false,
		success: function(info) {
			if (info) {
				if (info=='ERROR') {
					onError();
				}
				else {
					$(obj).html(info);
					callBack(obj);
				}
			}
			else {
				onError();
			}
         } // success
	});// ajax
}

$(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);
	});
}


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;
}

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]');
	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});
	
	
	$("#newsletter input.s").click(function(){
		var mail = $('#newsletter input[name="newsletter_mail"]').val();
		if (isEmail(mail)) {
			$('#newsletter input[name="newsletter_mail"]').val("Wysyłanie żądania..");
			//fast_ajax(, obj, onError, callBack)
			$.ajax({
				type: "GET",
				url: '/ajax.php?module=newsletter&action=add&row='+encodeURIComponent(mail),
				cache: false,
				success: function(info) {
					if (info) {
						if (info=='ERROR') {
							$('#newsletter input[name="newsletter_mail"]').val("Nieznany błąd, spróbuj ponownie..");
						}
						else {
							$('#newsletter input[name="newsletter_mail"]').val("Adres e-mail został zapisany..");
						}
					}
					else {
						$('#newsletter input[name="newsletter_mail"]').val("Nieznany błąd, spróbuj ponownie..");
					}
		         }
			});
		}
		else {
			alert('Podaj poprawny adres e-mail');
			$('#newsletter input[name="newsletter_mail"]').focus();
		}
	});
	
	$('.quote3').addClass('quote1').removeClass('quote3');
	$('.quote1').each(function(){
		$(this).html('<p class="quote2"><p class="quote3">'+$(this).html()+'</p></p>');
	});
	
	
});



function kontakt(id) {
	if (validacja_formy(id)) {
		var url='/ajax.php?module=kontakt&action=send_form';
		var i=0;
		for (i=1; i<=15; i++) {
			url+='&f'+i+'='+encodeURIComponent($('[name="f'+i+'"]').val())+'';
		}
		
		$('#forma').slideUp(500);
		$('#wysylanie').slideDown(500);
		
		$.ajax({
			type: "GET",
			url: url,
			cache: false,
			success: function(info) {
				if (info) {
					if (info=='OK') {
						$('#wysylanie').slideUp(500);
						$('#wyslane').slideDown(500);
					}
					else {
						alert('Nieznany błąd, spróbuj ponownie.');
						$('#wysylanie').slideUp(500);
						$('#forma').slideDown(500);
					}
				}
				else {
					alert('Nieznany błąd, spróbuj ponownie.');
					$('#wysylanie').slideUp(500);
					$('#forma').slideDown(500);
				}
	         } // success
		});// ajax

	}
}

/**
 * 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')) && $(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;
	}
}






