// JavaScript Document
var walidate_forms_css_ok = 'walidacja_ok';
var walidate_forms_css_blad = 'walidacja_blad';
function walidate_forms(pole,podswietlanie)
{
	
	if(podswietlanie != false)
		{podswietlanie = true;}
	
	function nadaj_styl()
	{
		if(podswietlanie)
		{
			if(walidate_forms_css_ok != '' &&  walidate_forms_css_blad != '')
			{
				/// usuwa stare style			
				$("#"+pole).removeClass(walidate_forms_css_ok);
				$("#"+pole).removeClass(walidate_forms_css_blad);
				
				if(status)
					{$("#"+pole).addClass(walidate_forms_css_ok);}
				else
					{$("#"+pole).addClass(walidate_forms_css_blad);}
			}	
		}
	}
	function txt_email()
	{
		if(wartosc.indexOf('@')>-1 && wartosc.indexOf('.')>-1)
		{
			var malpy = wartosc.split("@");
			
			if(malpy.length == 2)
			{
				var ile = 0;
				var nie = new Array('~','`','!','#','$','%','^','&','(',')','=','+','|','\\','"',"'",':',';',',','<','>','?','/');
					
				for(i=0;nie.length>=i;i++)
				{
					if(wartosc.indexOf(nie[i])>-1)
						{ile++;	}
				}				
				
				if(ile == 0)
					{return true;}
				else
					{return false;}
			}
			else
				{return false;}
		}
		else
			{ return false;	}	
	}
	function txt_pesel()
	{
		var nie = new Array('~','`','!','@','#','$','%','^','&','(',')','=','+','|','\\','"',"'",':',';',',','<','>','?','/');
					
		for(i=0;nie.length>=i;i++)
		{
			if(wartosc.indexOf(nie[i])>-1)
			{
				return false;
				break;
			}
		}
			
		var factor = new Array(1,3,7,9,1,3,7,9,1,3);
		var s = 0;
	
		for (i=0;i<=9;i++)
			{s += wartosc.charAt(i)*factor[i];}
	
		var eleven = (10-s%10)%10;		
		if(eleven==wartosc.charAt(10))
			{	return true;}
		else
			{	return false;	}
	}
	function txt_nip()
	{
		var nipnodash = "";				
		wartosc = String(wartosc);		
		var dl = wartosc.length;
		
		for (licz=0; licz<dl; licz++) 
			{   if (is_numeric(wartosc.charAt(licz)) == true) nipnodash=nipnodash+wartosc[licz];	}
		
		if (nipnodash.length != 10)
			{	return false;}
		
		if (nipnodash.length == 10)
		{
			var wagi = new Array ("6","5","7","2","3","4","5","6","7");
			var wynik = new Array(9);
			var suma = 0;
			for (licz=0; licz<9; licz++) wynik[licz]=nipnodash[licz]*wagi[licz];
			for (licz=0; licz<9; licz++) suma+=wynik[licz];
			suma=suma%11;
			
			if(suma == nipnodash[9]) 
				{	return true;}
			else
				{	return false;	}
		}
	}
	function txt_liczba()
	{
		przed = wartosc.length; 
		var war = parseFloat(wartosc);
		po = String (war).length;
		
		if(przed != po || isNaN(war) || war == '')
			{return false;	}
		else
			{return true;}		
	}
	function txt_data()
	{
		var dzi = wartosc.split('-');
		dzi[0] = parseInt(dzi[0]);
		dzi[1] = parseInt(dzi[1]);
		dzi[2] = parseInt(dzi[2]);
		
		if(dzi[0] > 1900 && dzi[0] <= 2050 && dzi[1] >= 0 && dzi[1] <= 12 && dzi[2] >= 0 && dzi[2] <= 31)
			{	return true;	}
		else
			{	return false;	}
	}
	function txt_kod_pocztowy()
	{
		if(wartosc.indexOf('-') > 0)
		{
			var kpsi = new Array;
			var kps = wartosc.split('-');
			kpsi[0] = parseInt(kps[0]);
			kpsi[1] = parseInt(kps[1]);
			
			if(isNaN(kpsi[0]) || isNaN(kpsi[1]))
				{ return false;		}
			else if(String(kps[0]).length < 2  || (String(kps[1]).length != 3) )
				{ return false; 	}
			else
				{return true;	}
		}
		else
			{ return false;	}	
	}
	function txt_znaki_niedozwolone()
	{
		if(wartosc != '')
		{
			if(typ.indexOf('-') > -1)
			{
				var tt = typ.split('-');
				var nie = new Array();
				
				for(i=0;tt[1].length>=i;i++)
				{	
					var z = tt[1].charAt(i);
					if(z != '')
						{nie.push(z);}	
					z = '';
				}
			}
			else
				{var nie = new Array('~','`','!','@','#','$','%','^','&','(',')','=','+','|','\\','"',"'",':',';','<','>','?','/');}
		
			var val = true;
			for(i=0;nie.length>=i;i++)
			{
				if(wartosc.indexOf(nie[i])>-1)
				{
					val = false;
					break;
				}
			}
			return val;
		}
		else
		{return false;}
	}
	function txt_znaki_min()
	{
		var tt = typ.split('-');
		var ilosc = parseInt(tt[1]);
		
		if(isNaN(ilosc) || ilosc == '')
			{ilosc = 0;}
		
		if(wartosc.length < ilosc)
			{	return false; }
		else
			{	return true; }		
	}
	function txt_znaki_max()
	{
		var tt = typ.split('-');
		var ilosc = parseInt(tt[1]);
		
		if(isNaN(ilosc) || ilosc == '')
			{ilosc = 0;}
		
		if(wartosc.length > ilosc)
			{	return false; }
		else
			{	return true; }	
	}
	function txt_liczba_przedzial()
	{
		var tt = typ.split('-');
		var minmal = parseInt(tt[1]);
		var maximal = parseInt(tt[2]);
		
		if(isNaN(minmal) || minmal == '')
			{minmal = 0;}
		if(isNaN(maximal) || maximal == '')
			{maximal = 0;}
			
		var war = parseFloat(wartosc);
		if(isNaN(war) || war == '')
			{return  false;	}
		else
		{
			if(war >= minmal)
			{
				if(war <= maximal || maximal == 0)
					{return  true;	}
				else
					{return  false;	}
			}
			else
				{return  false;	}
		}
	}
	function txt_data_wieksza()
	{
		var dzi = wartosc.split('-');
		var tt = typ.split('-'); 
		
		if(tt[1] == 'NOW()')
		{
			var d=new Date();
			var timestamp_2 = parseInt(d.getFullYear()+""+d.getMonth()+""+d.getDate());
		}
		else
		{	
			var timestamp_2 = parseInt(tt[3]+""+tt[2]+""+tt[1]);
		}
		
		var timestamp_1 = parseInt(dzi[2]+""+dzi[1]+""+dzi[0]);				
	}
	/// sprawdzanie pola select pojedyncze
	function sprawdz_select()
	{
		if(wartosc == '0')
			{wartosc = '';}
			
		if(wartosc == '')
			{return false;}
		else
			{return true;}
	}
	/// sprawdzanie pola select wielokrotnego wyboru
	function sprawdz_multiple()
	{
		typ = parseInt(typ);		
		if(typ == '0' || isNaN(typ))
			{typ = 1;}
			
		var wybrane = 0;	
		var ob = document.getElementById(pole);
		
		for(var i = 0; i < ob.options.length; i++) 
		{
			if (ob.options[ i ].selected) 
			{	wybrane ++;}
		}	
		if(wybrane <= typ)
			{return false;}
		else
			{return true;}
	}
	/// sprawdza chexboxy i 
	function sprawdz_check()
	{
		if(document.getElementById(pole).checked)
			{return true;}
		else
			{return false;}
		
	}
	/// sprawadza text
	function sprawdz_text()
	{
		var status = true;
		
		if(wartosc == '')	
			{ status = false;}
		else
			{ status = true;}	
		if(typ.search(/email/i) > -1)
		{  
			if(status)
				{ status = txt_email();}		
		}	
		if(typ.search(/pesel/i) > -1)
		{  
			if(status)
				{ status = txt_pesel();}		
		}
		if(typ.search(/nip/i) > -1)
		{  
			if(status)
				{ status = txt_nip();}		
		}
		if(typ.search(/liczba/i) > -1)
		{  
			if(status)
				{ status = txt_liczba();}		
		}
		if(typ.search(/data/i) > -1)
		{  
			if(status)
				{ status = txt_data();}		
		}
		if(typ.search(/kod_pocztowy/i) > -1)
		{  
			if(status)
				{ status = txt_kod_pocztowy();}		
		}
		if(typ.search(/znakiNiedozwolone/i) > -1)
		{  
			if(status)
				{ status = txt_znaki_niedozwolone();}		
		}
		if(typ.search(/znakiMin/i) > -1)
		{  
			if(status)
				{ status = txt_znaki_min();}		
		}
		if(typ.search(/znakiMax/i) > -1)
		{  
			if(status)
				{ status = txt_znaki_max();}		
		}
		if(typ.search(/liczbaPrzedzial/i) > -1)
		{  
			if(status)
				{ status = txt_liczba_przedzial();}		
		}
		if(typ.search(/dataWieksza/i) > -1)
		{  
			if(status)
				{ status = txt_data_wieksza();}		
		}
		
		
		return status;
		/*
		
		if(typ == 'email')
			{ return txt_email();}
		else if(typ == 'pesel')
			{ return txt_pesel();}
		else if(typ == 'nip')
			{ return txt_nip();}
		else if(typ == 'liczba')
			{ return txt_liczba();}
		else if(typ == 'data')
			{ return txt_data();}
		else if(typ == 'kod_pocztowy')
			{ return txt_kod_pocztowy();}
		
		else if(typ.search(/znakiNiedozwolone/i) > -1)
			{  return txt_znaki_niedozwolone();}	
		else if(typ.search(/znakiMin/i) > -1)
			{  return txt_znaki_min();}
		else if(typ.search(/znakiMax/i) > -1)
			{  return txt_znaki_max();}
		else if(typ.search(/liczbaPrzedzial/i) > -1)
			{  return txt_liczba_przedzial();}
		else if(typ.search(/dataWieksza/i) > -1)
			{  return txt_data_wieksza();}
		else
			{
				if(wartosc == '')	
					{ return false;}
				else
					{ return true;}				
			}
			
		*/
	}
	function sprawdz_wysiwyg()
	{
		var y =  tinyMCE.get(pole).getContent();
   		if(y != '')
			{return true;}
		else
			{ return false;}	
	}
	
	if(document.getElementById(pole))
	{
		
		var typ_pola = document.getElementById(pole).type;
		var wartosc = document.getElementById(pole).value;
		var typ = document.getElementById(pole).lang;
		var status = false;

		wartosc = strip_tags (wartosc);
	
		
		if(typ_pola == 'select-one')
			{	status = sprawdz_select();	}
		else if(typ_pola == 'select-multiple')
			{	status = sprawdz_multiple();	}
		else if(typ_pola == 'radio' || typ_pola == 'checkbox')
			{	status = sprawdz_check();	}
		else if(typ_pola == 'textarea' && typ  == 'wysiwyg')
			{	status = sprawdz_wysiwyg();	}	
		else if(typ_pola == 'text' || typ_pola == 'textarea' || typ_pola == 'password' || typ_pola == 'hidden')
			{	status = sprawdz_text();	}
		
		if(!status)
			{ status = false;}
			
		nadaj_styl();
		return status;
	}
	else
		{alert('Brak pola: "'+pole+'"');}
}
function is_numeric(sText)
{
	if(sText != void 0)
	{
		var ValidChars = "0123456789.";
		var IsNumber = true;
		var Char = '';
		var dl = sText.length;
		
		
		for (i = 0; i < dl && IsNumber == true; i++) 
		{ 
			Char = sText.charAt(i); 
			if (ValidChars.indexOf(Char) == -1) IsNumber = false;
		}
		return IsNumber;  
	}
}
function strip_tags (str, allowed_tags) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'

    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';

    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }

    str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }

    return str;
}

/*
	Sprawdza caly formularz. Wyszukuje pola label ktore posiadaja argument walidacja = true
	A nastepnie dla tych pol wykonuje sprawdzenie wykorzystujac funkcje walidate_form, uwzgledniajac typ pola wpisany w label
*/
function sprawdz_formularz(form_id, class_ok, class_error)
{
	if (form_id)
	{
		var elements = $('#'+form_id + ' label[walidacja="true"]');
	}
	else
	{
		var elements = $('label[walidacja="true"]');	
	}
	
	if (class_ok == undefined)
	{
		class_ok = 	'walidacja_okT';
	}
	if (class_error == undefined)
	{
		class_error = 'walidacja_bladT';
	}
	
	var blad = false;
		
	elements.each(function (index, element) {
		id = $(this).attr('for');
		span = $('#'+id+' ~ span');
		
		// jesli pole jest 'disabled' to pomijamy
		if ($('#'+id).attr('disabled'))
		{
			if (span.length)
			{
				span.remove();
			}
			$('#'+id).removeClass(class_ok);
			$('#'+id).removeClass(class_error);
			return true;	
		}
		
		if (!walidate_forms(id))
		{
			blad = true;
			
			span.remove();
			komunikat = element.lang;
			if (komunikat == '')
			{
				komunikat = "Uzupełnij dane";	
			}
			displayMessage($('#'+id), komunikat, class_error);
				
		}
		else
		{
			span.remove();
			komunikat = "&nbsp;";	
			displayMessage($('#'+id), komunikat, class_ok);
		}	
		
		
	});
	
	return !blad;
	
	
	
}



function displayMessage(pole, tresc, klasa)
{
	if (!pole.parent().hasClass('walidacja_wrapper'))
	{
		pole.wrap('<div class="walidacja_wrapper" />');
	}
	
	var komunikat = '<span class="'+klasa+'">'+tresc+'</span>';
	
	if (pole.length)
	{
		pole.after(komunikat);
	}

}


function data_wieksza(pole1,pole2)
{
	var status = false;
	
	var d1 = $('#'+pole1).val();
	var d2 = $('#'+pole2).val();
	
	d1 = d1.replace(/-/g, '');
	d2 = d2.replace(/-/g, "");
	d1 = parseInt(d1);
	d2 = parseInt(d2);
	
	if(!isNaN(d1) && !isNaN(d2))
	{
		if(d1 > d2)
			{ status = true;} 
	}
	
	return status;
	
}

function password_analizer(pole)
{
	var strength = getStrength(pole.val());
	if(strength > 35)
		{strength = 35;}
		
	var width = (100/22)*strength;
	
	var kolor = '#FFFFFF';
	if(strength > 30)
		{ kolor = '#88BA00'; txt = 'bardzo dobre'; }
	else if(strength > 20)
		{ kolor = '#D5CE00'; txt = 'dobre'; }
	else if(strength > 10)
		{kolor = '#CA5900'; txt = 'dostateczne';}
	else if(strength > 5)
		{kolor = '#BA2B00'; txt = 'słabe';}
	else
		{kolor = '#B61600'; txt = 'słabe'; }
	
	$('#passSTR').css({'background-color' : kolor, 'width' : width+'px' }) ;
	$('#passSTR span').text(txt);
	//$('#passSTR').animate( {width:width+'px'}); 
}
function getStrength(passwd) 
{
		intScore = 0;
		if (passwd.match(/[a-z]/)) // [verified] at least one lower case letter
			{intScore = (intScore+1);} 
		if (passwd.match(/[A-Z]/)) // [verified] at least one upper case letter
			{intScore = (intScore+5); } 
			
		// NUMBERS
		if (passwd.match(/\d+/)) // [verified] at least one number
			{intScore = (intScore+5);} 
		if (passwd.match(/(\d.*\d.*\d)/)) // [verified] at least three numbers
			{intScore = (intScore+5);} 
			
		// SPECIAL CHAR
		if (passwd.match(/[!@#$%^&*?_~\.\+]/)) // [verified] at least one special character
			{ intScore = (intScore+5);} 
		if (passwd.match(/([!@#$%^&*?_~\.].*[!@#$%^&*?_~\.\+])/)) // [verified] at least two special characters
			{ intScore = (intScore+5); } 
			
		// COMBOS
		if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/)) // [verified] both upper and lower case
			{ intScore = (intScore+2); } 
		if (passwd.match(/\d/) && passwd.match(/\D/)) // [verified] both letters and numbers
			{intScore = (intScore+2);}
			
		// [Verified] Upper Letters, Lower Letters, numbers and special characters
		if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/) && passwd.match(/\d/) && passwd.match(/[!@#$%^&*?_~\.\+]/))
			{ intScore = (intScore+2); 	}
		
		return intScore;
}
function NRBvalidate(nrb)
{
    nrb = nrb.replace(/[^0-9]+/g,'');
    var Wagi = new Array(1,10,3,30,9,90,27,76,81,34,49,5,50,15,53,45,62,38,89,17,73,51,25,56,75,71,31,19,93,57);

    if(nrb.length == 26) {
      nrb = nrb + "2521";
      nrb = nrb.substr(2) + nrb.substr(0,2);
      var Z =0;
      for (var i=0;i<30;i++) {
        Z += nrb[29-i] * Wagi[i];
      }
      if (Z % 97 == 1) {
        return true;
      }else{
        return false;
      }

    }else{
      return false;
    }
}

$(function() {
	$('input, textarea').blur(function(){
		$(this).next('.walidacja_bladT_rejestracja').fadeOut('slow', function () {
			$(this).remove();
		});
	});
});
