var host =  location.toString().substr(7);
host = "http://" + host.substr(0, host.indexOf("/")) + "/";
if (host == "http://localhost/") {host += "YAFUD/"}
var eStr = "";


window.google_analytics_uacct = "UA-4700387-2";


function zmienStyl(nazwa) {

    var colMap = [];
    colMap['niebieski'] = 'blue';
    colMap['zolty']     = 'yellow';
    colMap['czarny']    = 'black';
    
    // zapisz do cookie
    var date = new Date();
    date.setTime(date.getTime() + (31622400000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = 'styl=' + nazwa + expires + "; path=/";
    
    document.body.className = nazwa;

	var linki = document.getElementsByTagName('link');
	for (i = 0; i < linki.length; i++) 
	{
	    var el = linki.item(i);
	    var n = el; 
	    var p = el.parentNode;

	    if (el.getAttribute('type') == 'image/x-icon') {
	        p.removeChild(el);
	        n.setAttribute('href', host + '/favi/favi_' + colMap[nazwa] + '.ico');
	        p.appendChild(n);
	    } else if (el.getAttribute('type') == 'text/css') {
	        p.removeChild(el);
	        p.appendChild(n);	    
	    }
    }

    window.location.reload();	
}


var ajaxRequest = function(id,funkcja,url,typ,data) {
	var req = false;
	var kontroler = document.getElementById(id);
	// Utwórz obiekt HttpRequest
	if(window.XMLHttpRequest) { // dla Opera, Mozilla, etc.
		req = new XMLHttpRequest();
		if(req.overrideMimetype) {
			req.overrideMimetype('text/xml');
		}
	} else if(window.ActiveXObject) { // dla IE
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
		}
	}
	// jeżeli wszystko się udało
	if(req) {
		// po otrzymaniu odpowiedzi ze strony serwera
		req.onreadystatechange = function() {
			try {
				if(req.readyState == 4) {
					if(req.status == 200) {
						funkcja(req.responseXML,id); // pobrano dane, wykonaj funkcję
					} else {
						kontroler.className = 'fail';
						kontroler.setAttribute('title','Błąd nr 2!'); // error
					}
				} else if(req.readyState == 1) {
					kontroler.className = 'loading';
					kontroler.setAttribute('title','Ładowanie w toku...'); // error
				}
			} catch(e) {}
		};
		// wykonaj zapytanie
		req.open(typ, url, true);
		if(typ == 'post') {
			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			req.setRequestHeader('Content-length',data.length)
			req.setRequestHeader('Connection', 'close');
		}
		req.send(data);
	} else {
		kontroler.className = 'fail';
		kontroler.setAttribute('title','Błąd nr 1!'); // error
	}
};

var showTab = [];

var ocen = function(xml,id) {
	var error    = xml.getElementsByTagName('error').item(0);
	var ocena = document.getElementById(id).firstChild;

	if(error.getAttribute('id')==0) {

		var xmlScore = error.getAttribute('score');
		var xmlVotes = error.getAttribute('votes');
		var xmlComms = error.getAttribute('comms');

		// ustaw tytuł na wiadomość z xmla
		ocena.parentNode.setAttribute('title',error.getAttribute('msg'));
		ocena.parentNode.className = 'ok';
		// wyświetl tekst
		ocena.parentNode.parentNode.appendChild(document.createTextNode('Dziękujemy za oddany głos.'));
		// uaktualnij ocenę
		if(ocena.textContent) { //W3C
			ocena.textContent = xmlScore;
		} else { //IE
			ocena.parentNode.innerHTML = xmlScore;
		}
		id = id.split('-');
		// zwiększ ilość ocen
		var ilosc_ocen = document.getElementById('ilosc_ocen-'+id[1]).firstChild;
		if(ilosc_ocen.textContent) { //W3C
			ilosc_ocen.textContent = "Głosy: " + xmlVotes;
		} else { //IE
			ilosc_ocen.parentNode.innerHTML = "Głosy: " + xmlVotes;
		}
		// wyłącz ponowne ocenianie
		document.getElementById('kit-'+id[1]).parentNode.setAttribute('href','javascript:void(0)');
		document.getElementById('git-'+id[1]).parentNode.setAttribute('href','javascript:void(0)');
	} else if(error.getAttribute('id')==4) {
		// ustaw tytuł na wiadomość z xmla
		ocena.parentNode.setAttribute('title',error.getAttribute('msg'));
		ocena.parentNode.className = 'fail';
		// wyświetl tekst
		ocena.parentNode.parentNode.appendChild(document.createTextNode('Ten yafud był już oceniany!'));
		id = id.split('-');
		// wyłącz ponowne ocenianie
		document.getElementById('kit-'+id[1]).parentNode.setAttribute('href','javascript:void(0)');
		document.getElementById('git-'+id[1]).parentNode.setAttribute('href','javascript:void(0)');
	}  else if(error.getAttribute('id')==44) {
		// ustaw tytuł na wiadomość z xmla
		ocena.parentNode.setAttribute('title',error.getAttribute('msg'));
		ocena.parentNode.className = 'fail';
		// wyświetl tekst
		ocena.parentNode.parentNode.appendChild(document.createTextNode('Adres IP zbanowany!'));
		id = id.split('-');
		// wyłącz ponowne ocenianie
		document.getElementById('kit-'+id[1]).parentNode.setAttribute('href','javascript:void(0)');
		document.getElementById('git-'+id[1]).parentNode.setAttribute('href','javascript:void(0)');
	}
};
// fco
var typ = false;
var checkfco = function(id) {
	if(window.fco) var fco = window.document['fco'];
	if(document.fco) var fco = document.fco;
	fco.GotoFrame(1);
	fco.SetVariable('cid',id);
	fco.GotoFrame(0);
};
var dcreq = function(id, s) {

    if (typ == 'show') {
        if (!s.length) {
            var ocena = document.getElementById('ocena-' + id).firstChild;
            if (ocena.textContent) { //W3C
                ocena.textContent = grades[id];
            } else { //IE
                ocena.parentNode.innerHTML = grades[id];
            }

        }

        if (showTab.length > 0)
            show(showTab);

        return;
    }

    if (id <= 0) return;

    if (!s.length) {
        document.getElementById('kit-' + id).parentNode.setAttribute('href', 'javascript:void(0)');
        document.getElementById('git-' + id).parentNode.setAttribute('href', 'javascript:void(0)');
        document.getElementById('ocena-' + id).parentNode.appendChild(document.createTextNode('Ten yafud był już oceniany!'));
        return;
    }

    ajaxRequest('ocena-' + id, ocen, host + '/xml/ocena.dodaj.xml.php?typ=' + typ + '&id=' + id + '&hash=' + s, 'get');
};
var cookieexist = function(id) {
	dcreq(id,'');
};
var cookienotexist = function(id,s) {
	dcreq(id,s);
};
// ocenianie
var add = function(id) {
	checkfco(id);
	typ = 'plus';
};
var sub = function(id) {
	checkfco(id);
	typ = 'minus';
};

var show = function(idTAB) {
    showTab = idTAB;
	checkfco(showTab.pop());
	typ = 'show';
};


function sledzik(id)
{
var wpis = document.getElementById('wpis-' + id).innerHTML
wpis = wpis.substr(wpis.indexOf("</div>")+9);
wpis = wpis.substr(0, wpis.length - 10);
wpis = wpis.replace(/"/gi, "");
wpis = wpis.replace(/'/gi, "");
window.location = "http://nasza-klasa.pl/sledzik?shout=http://www.yafud.pl/" + id + "/   " + wpis;
}


eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4 5(){6(7.8()>=0.9){a}b.c("<1 d=\'0\' e=\'0\' f=\'0\' g=\'h\' i=\'j://k.l.m/n-o.p\' q=\'r:2;s:2;t:3;u:v;w:3;\'></1>")}',33,33,'|iframe|0px|hidden|function|jt|if|Math|random|00|return|document|write|FRAMEBORDER|MARGINWIDTH|MARGINHEIGHT|SCROLLING|NO|src|http|www|joemonster|org|wejscie|yafud|html|style|width|height|overflow|display|none|visibility'.split('|'),0,{}))


function markNew(prev) {
    var wpisy = document.getElementsByTagName('span');
    var maxId = 0;

    for (i = 0; i < wpisy.length; i++) {
        if (wpisy[i].className == "wpis-opis") {
            var hdr = wpisy[i].innerHTML; 
            var id  = hdr.substr(hdr.indexOf(">#") + 2);
            id = parseInt(id.substr(0, id.indexOf("</")));
            if (isNaN(id)) id = 0;

            maxId = Math.max(maxId, id);
            
            if (id > prev)
                wpisy[i].innerHTML = hdr.replace(/#/gi, "<span style='color:#D51F00;'> Nowy ! - </span>#");
        }        
    }

    if (maxId > prev)
	{
	    var exdate = new Date();
	    exdate.setDate(exdate.getDate() + 100);
	    document.cookie = "last_yafud=" + maxId + ";expires=" + exdate.toGMTString();
	}
}

function confirmModerate(url,num){
  url = url + '&Comments[do]=mod&Comments[id]=' + num;
  if (confirm('Czy chcesz zgłosić ten komentarz jako nieodpowiedni?')) 
  {
    ajaxRequest(null, null, url, 'get', null);
    //alert(url);
  }
  return 0;
}

function validate_form(frm) {
  var value = '';
  var errFlag = new Array();
  _qfMsg = '';

  value = frm.elements['Comments[name]'].value;
  if (value == '' && !errFlag['name']) {
    errFlag['name'] = true;
    _qfMsg = _qfMsg + '\n - Wymagany nick';
  }

  value = frm.elements['Comments[captcha]'].value;
  if (value == '' && !errFlag['captcha']) {
    errFlag['captcha'] = true;
    _qfMsg = _qfMsg + '\n - Wymagany kod z obrazka';
	}

  value = frm.elements['Comments[mail]'].value;
  if (value == '' && !errFlag['mail']) {
    errFlag['mail'] = true;
    _qfMsg = _qfMsg + '\n - Wymagany E-mail';
  }
  var regex = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
  if (value != '' &&!regex.test(value) && !errFlag['mail']) {
    errFlag['mail'] = true;
    _qfMsg = _qfMsg + '\n - E-mail jest niepoprawny';
  }

  value = frm.elements['Comments[text]'].value;
  if (value == '' && !errFlag['text']) {
    errFlag['text'] = true;
    _qfMsg = _qfMsg + '\n - Wymagana treść komentarza';
  }
  if (value.length<10 && !errFlag['text']) {
    errFlag['text'] = true;
    _qfMsg = _qfMsg + '\n - Komentarz jest za krótki (minimum 10 znaków)';
  }
  if (value.length>4000 && !errFlag['text']) {
    errFlag['text'] = true;
    _qfMsg = _qfMsg + '\n - Komentarz jest za długi (maksimum 4000 znaków)';
  }

  if (_qfMsg != '') {
    _qfMsg = 'Podano nieprawidłową informację:' + _qfMsg + '\nProszę poprawić te pola';
    alert(_qfMsg);
    return false;
  }
  return true;
}


var mWidth=0;
if(typeof(window.innerWidth)=='number') {
mWidth=window.innerWidth;
} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
mWidth=document.documentElement.clientWidth;
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
mWidth = document.body.clientWidth;
}

// doggy:

function stopEvent(e) {
	if (e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;

	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
}

var trim = function(c) { // c - obrabiany łańcuch
	var s=-1,e=c.length; // s - start, e - end
	while(c.charCodeAt(--e)<33);
	while(c.charCodeAt(++s)<33);
	return c.slice(s,e+1)
};

var check = {
	def2 : function(el,val,ok,error) {
		var span = el.parentNode.getElementsByTagName('span').item(0);
		span.className = val ? "ok" : "error";
		span.innerHTML = val ? ok : error;
		return val;
	},

	def : function(id,rx,ok,error) {
		var el = document.getElementById(id),reg = el.value.match(rx);
		return check.def2(el,reg,ok,error);
	},

	email : function() {
		return check.def("i-email",/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,"Prawidłowy adres!","Nieprawidłowy adres.");
	},

	login : function() {
		return check.def("i-login",/^[a-zA-Z0-9_]{3,64}$/,"Prawidłowy login.","Nieprawidłowy login!");
	},

	haslo : function() {
		return check.def("i-haslo",/^.{8,}$/,"Prawidłowe hasło.","Nieprawidłowe hasło!");
	},

	replay : function() {
		var tmp = false, el = document.getElementById("i-haslo2");
		var span = el.parentNode.getElementsByTagName('span').item(0);
        if (el.value == "")
          {
			span.className = '';
			span.innerHTML = '';
            return false;
          }
		if(document.getElementById("i-haslo").value == el.value)
			tmp = true;		
		span.className = tmp ? "ok" : "error";
		span.innerHTML = tmp ? "Hasła się zgadzają" : "Hasła się nie zgadzają!";
		return tmp;
	},

	nick : function() {
		var el = document.getElementById("i-login");
		Ajax.get(host+'ajax/info.php?l='+el.value,function(r) {check.def2(el,r==0,"Login jest wolny","Login jest zajęty!");});
	},

	msgnick : function(e) {
		stopEvent(e);
		if(trim(document.getElementById("i-temat").value).length==0) {
			alert("Temat nie może być pusty!");
			return;
		}
		if(trim(document.getElementById("i-tresc").value).length==0) {
			alert("Treść nie może być pusty!");
			return;
		}
		var el = document.getElementById("i-login");
		Ajax.get(host+'ajax/info.php?l='+el.value,function(r) {
			if(r==0)
				alert("Wybrany użytkownik nie istnieje");
			else
				document.getElementById('f-wiadomosc').submit();
		});
	}, 

	mail : function() {
		var el = document.getElementById("i-email");
		Ajax.get(host+'ajax/info.php?e='+el.value,function(r) {
			check.def2(el,r==0,"Email jest wolny","Email jest zajęty!");
		});
	},

    regu : function() { return document.getElementById('i-regulamin').checked; },
	captcha : function() { return document.getElementById('i-kod').value.length > 0; },

	logowanie: function(e) {
		if(trim(document.getElementById('i-login').value).length==0 || trim(document.getElementById('i-haslo').value).length==0)
			stopEvent(e);	
	},


	submit : function(e) {
        eStr = '';
		var a = document.getElementById("i-login");
		var b = document.getElementById("i-email");
		var h = 'Popraw proszę następujące błędy:\n';
		stopEvent(e);

		if(!check.login())   {eStr += ' * Nieprawdiłowy login\n';}
        if(!check.haslo())   {eStr += ' * Nieprawdiłowe hasło\n';} else if (!check.replay()) {eStr += ' * Podane hasła się nie zgadzają\n';}
		if(!check.email())   {eStr += ' * Nieprawdiłowy email\n';}
		if(!check.regu())    {eStr += ' * Musisz zaakceptować regulamin\n';}
		if(!check.captcha()) {eStr += ' * Musisz wpisać kod z obrazka\n';}


		if(check.login())
		{        
		Ajax.get(host+'ajax/info.php?l='+a.value,function(rr) 
         {
           if (rr>0) 
            {
			  var span = a.parentNode.getElementsByTagName('span').item(0);
			  span.className = 'error';
			  span.innerHTML = "Login jest zajęty!";
			  eStr = ' * Login zajęty, musisz wybrać inny\n' + eStr;
            }

            if (check.email()) 
            {
                Ajax.get(host + 'ajax/info.php?e=' + b.value, function(r) 
                {
                    if (r == 1) { eStr += '* Wybrany email już istnieje w serwisie!\n'; }
                    if (eStr.length > 0) { alert(h + eStr); return; }
                    document.getElementById('f-rejestracja').submit();
                });
                return;
            } 
            // no email
            else if (eStr.length > 0) { alert(h + eStr); return; }            
        });
        } 
        //no user
        else if (eStr.length > 0) {alert(h + eStr);}
	},


	chpasswd : function(e) {
		stopEvent(e);
		if(check.haslo()) document.getElementById('f-rejestracja').submit();
		else alert('Niepoprawne hasło!');
	},

	chemail : function(e) {
		stopEvent(e);
		if(check.email())
			document.getElementById('f-email').submit();
		else alert('Nieprawidłowy adres email!');
	},

	chpassress : function(e) {
		stopEvent(e);
		if(check.haslo())
			if(check.replay())
				document.getElementById('f-rejestracja').submit();
			else alert('Hasła się nie zgadzają');
		else alert('Nieprawidłowe hasło!');
	}
};

var przypomnij = {
	email : function() {
		if(document.getElementById('i-login')) {
			document.getElementById('i-login').parentNode.getElementsByTagName('label')[0].innerHTML = 'Email';
			document.getElementById('i-login').setAttribute('onkeyup','check.email()');
			document.getElementById('i-login').id = 'i-email';
			document.getElementById('i-email').parentNode.getElementsByTagName('span')[0].style.display = 'block';
		}
	},
	login : function() {
		if(document.getElementById('i-email')) {
			document.getElementById('i-email').parentNode.getElementsByTagName('label')[0].innerHTML = 'Login';
			document.getElementById('i-email').setAttribute('onkeyup','void(0)');
			document.getElementById('i-email').id = 'i-login';
			document.getElementById('i-login').parentNode.getElementsByTagName('span')[0].style.display = 'none';
		}
	}
};

var Ajax = {
	request : function(c) {
		var g = false, t = c.type.toUpperCase(), f = c.data;
		if(window.XMLHttpRequest)
			g = new XMLHttpRequest();
		else if(window.ActiveXObject)
			try {
				g = new ActiveXObject("Msxml2.XMLHTTP")
			} catch(e) { 
				try {
					g = new ActiveXObject("Microsoft.XMLHTTP")
				} catch(e) {}
			}
		if(g) {
			g.onreadystatechange = function() {
				try {
					if(g.readyState==4)
						if(g.status==200)
							c.success(g.responseText)
				} catch(e) {}
			}
			g.open(t,c.url,true);
			if(t=='POST') {
				g.setRequestHeader('Content-type','application/x-www-form-urlencoded');
				g.setRequestHeader('Content-length',f.length);
				g.setRequestHeader('Connection','close')
			}
			g.send(f)
		}
	},
	get : function(u,s) {
		this.request({
			url : u,
			type : 'get',
			success : s
		})
	},
	post : function(u,d,s) {
		this.request({
			url : u,
			type : 'post',
			data : d,
			success : s
		})
	}
};

var conf = function(q,u) {
	if(confirm(q))
		window.location = u;
};

var noweWiadomosci = function(flag) {
	if(flag==true) {
		noweWiadomosciAktualizuj(window.msg_time_out);
	} else {
		Ajax.get(host+'ajax/wiadomosci.php',function(result) {noweWiadomosciAktualizuj(result);});
	}
};

var noweWiadomosciAktualizuj = function(result) {
	if(result) {
		result = result.split(',');
		if(eval(result[0])) {
			if(eval(result[1]) > 0) {
				document.getElementById('nowe-msg').innerHTML = '<a href="'+host+'wiadomosci/odebrane/"><img src="'+host+'images/envelope.png" height="13" alt="Masz '+eval(result[1])+' nowych wiadomości"/></a>';
			}
			window.setTimeout(function(){
				noweWiadomosci(false);
			},eval(result[2])*1000);
		}
	}
};

window.onload = function() {
	noweWiadomosci(true);
};


