/**
 * Dynamiczne podpinanie JS i CSS
 */
function loadJsCssFile(filename, filetype){
	
	if (filetype == "js"){
		var fileref = document.createElement("script");
		
		fileref.setAttribute("type", "text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype == "css"){
		var fileref=document.createElement("link");
		
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
	}
	
	if (typeof fileref != "undefined") {
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
}


/**
 * Uniwersalna walidacja formularza
 */
function walidujForm(formNazwa, pola) {
	loadJsCssFile("js/jquery.md5.js", "js");
	
	var wynikWalidacji = true;
	
 	for (nazwaPola in pola) {
 		//Uchwyt pola formularza
		var pole = $("form[name=" + formNazwa + "] [name=" + nazwaPola + "]");
		
		//Wartośc pola
		var wartoscPola = pole.val();
		
		//Typ pola
		var typPola = pole.attr("type");
		
		//Parametry walidacji
		// [0] - typ pola: EMAIL, KODPOCZTOWY, CAPTCHA, NUMBER
		// [1] - dodatkowy parametr, uzależniony od typu pola
		// [2] - komunikat dla użytkownika
		var parWalidacji = pola[nazwaPola].split('_');

		//Wyrażenia regularne
		var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var regKodPocztowy = /^[0-9]{2}\-[0-9]{3}$/;
		var regNumber = /[1234567890]/g;
		
		//Jeżeli pole nie zostało wypełnione
		if (wartoscPola == '' && typPola != 'checkbox') {
			wynikWalidacji = false;
		}
		//Jeżeli typ pola to CHECKBOX
		else if (typPola == 'checkbox' && pole.attr("checked") != true) {
			wynikWalidacji = false;
		}
		//Jeżeli pole CAPTHA
		else if (parWalidacji[0] == 'CAPTCHA' && $.md5(wartoscPola) != parWalidacji[1]) {
			wynikWalidacji = false;
		}
		//Jeżeli pole EMAIL
		else if (parWalidacji[0] == 'EMAIL' && regEmail.test(wartoscPola) == false) {
			wynikWalidacji = false;
		}
		//Jeżeli pole KODPOCZTOWY
		else if (parWalidacji[0] == 'KODPOCZTOWY' && regKodPocztowy.test(wartoscPola) == false) {
			wynikWalidacji = false;
		}
		//Jeżeli pole NUMBER
		else if (parWalidacji[0] == 'NUMBER' && (wartoscPola.replace(regNumber, "") != '' || (wartoscPola.length != parWalidacji[1] && parWalidacji[1] != undefined))) {
			wynikWalidacji = false;
		}
		
		//Jeżeli walidacja nie powiodła się
		if (wynikWalidacji == false) {
			pole.addClass('wfTloRed');
			pole.focus();
			
			pole.bind('click keydown', function() {$(this).removeClass('wfTloRed');});
			
			//Komunikat
			if (parWalidacji[2] != undefined) {
				alert(parWalidacji[2]);
			}
			
			return false;
		}
	}
	
	return true;
}


/**
 * Add/Remove editor
 */
function toggleEditor(id) {
	if (!tinyMCE.get(id)) {
		tinyMCE.execCommand('mceAddControl', false, id);
	}
	else {
		tinyMCE.execCommand('mceRemoveControl', false, id);
	}
}


/**
 * Popup
 */
function otworz_okno_scroll(url, szer, wys) {
 	var nowe_okno = null;
 	nowe_okno = window.open("", "", "toolbar=no, width="+szer+", height="+wys+", directories=no, status=no, scrollbars=yes, resize=no, menubar=no, location=no");
 	nowe_okno.location.href = url;
}


/**
 * Wykonaj/anuluj z komunikatem
 */
function usun(info) {
	fno = confirm(info);

	if(fno) {
		return true
	}
	else {
		return false
	}
}


/**
 * Pokaż/ukryj
 */
function ukrywaj(nazwa_id) {
	if(document.getElementById(nazwa_id).style.display == 'none') {
		document.getElementById(nazwa_id).style.display = 'block';
	}
	else {
		document.getElementById(nazwa_id).style.display = 'none';
	}
}


/**
 * Pokaż/ukryj
 */
function ukrywajOdkryj(nazwa_id, akcja) {
	if (akcja == 'odkryj') {
		document.getElementById(nazwa_id).style.display = 'block';
	}
	else if (akcja == 'ukryj') {
		document.getElementById(nazwa_id).style.display = 'none';
	}
}


/**
 * Textarea autosize
 */
function textareaRozmiar(nazwaTextarea, minimumWierszy) {
	var kolumny = document.getElementById(nazwaTextarea).getAttribute('cols');
	var wiersze = document.getElementById(nazwaTextarea).getAttribute('rows');
	var text = document.getElementById(nazwaTextarea).value;
	var dlugoscTextu = text.length;
	var widacZnakow = kolumny * wiersze;
	var iloscNL = text;
	var tyleWierszy = 0;
	
	iloscNL = iloscNL.split("\n");
	iloscNL = iloscNL.length;

	tyleWierszy = Math.round((dlugoscTextu / kolumny) + iloscNL);
	
	if (tyleWierszy > minimumWierszy) {
		document.getElementById(nazwaTextarea).rows = tyleWierszy;
	}
}


/**
 * Zapis ciastka
 */
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	
	exdate.setDate(exdate.getDate() + expiredays);
	
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null)? "" : ";expires=" + exdate.toUTCString());
	
	return;
}


/**
 * Odczyt ciastka
 */
function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}

	return "";
}


/**
 * Vertigo Tip by www.vertigo-project.com
 */
this.vtip = function() {    
    this.xOffset = -10; // x distance from mouse
    this.yOffset = 10; // y distance from mouse       
    
    $(".vtip").unbind().hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); 
            this.left = (e.pageX + xOffset);
            
            if (this.t != '') {
	            $('body').append( '<p id="vtip"><img id="vtipArrow" />' + this.t + '</p>' );
	                        
	            $('p#vtip #vtipArrow').attr("src", path + "img/tooltip-ar.png");
	            $('p#vtip').css("top", this.top+"px").css("left", this.left+"px").fadeIn(500);
            }
        },
        function() {
            this.title = this.t;
            $("p#vtip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
            this.left = (e.pageX + xOffset);
                         
            $("p#vtip").css("top", this.top+"px").css("left", this.left+"px");
        }
    );            
    
};


/**
 * Pobiera kalendarz zgodnie z przekazanymi parametrami
 */
function pobierzKal(id, rok, miesiac, np, lang, ajaxHtmlId) {
	$('#'+ajaxHtmlId).load('ajax_content.php', {'ajaxC': 'cmsCalendar', 'id': id, 'rok': rok, 'miesiac': miesiac, 'np': np, 'ajaxHtmlId': ajaxHtmlId, 'lang': lang}, function(){vtip();});
}


/**
 * Wyświetla okienko poup
 */
function showPopup(img, id, maxIloscW) {
	//Kontrola ilości wyświetleń
	if (id != '') {
		var maxIloscW = Number(maxIloscW);
		var popupCookie = Number(getCookie('popup_' + id));
		
		if (popupCookie >= maxIloscW) {
			return;
		}
		else if (id != '') {
			setCookie('popup_' + id, popupCookie + 1);
			
			$.get('ajax_content.php?ajaxC=cmsTime', function(TS) {
				setCookie('popup_' + id + '_TS', TS);
			})
		}
	}
	
	var img = img.replace(/\|/g, '"');

	$.fancybox(img,{
       	'autoDimensions'	: true,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
	
	return;
}


/**
 * Document.ready
 */
$(document).ready( function() {
	vtip();
		
	$("a.es_foto").fancybox({
		'titlePosition'	: 'inside'
	});
		
	$("a.dokjpgif").fancybox({
		'titlePosition'	: 'inside'
	});
	
	$("a.gal_foto").fancybox({
		'cyclic'			: true, 
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
		return '<span id="fancybox-title-over">Foto ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	});
	
	$("a.kontakt_google_map").fancybox({
				'width'				: 900,
				'height'			: 700,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
	});
	
	$("a.youtube_popup").click(function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: this.title,
				'width'			: 640,
				'height'		: 505,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
						'wmode'				: 'transparent',
						'allowfullscreen'	: 'true'
				}
			});
	
		return false;
	});
	
	/**
	 * Rozwin / zwin submenu
	 */
	$("h2.menuRozwin").click(function() {
		var thisID = '#' + $(this).attr('id');
		
		$(thisID + ' + ul').toggle();
		
		return false;
	});
});
