/**
* @file
* @brief általános scriptek
*
* @ingroup group_ajax
*
*/

/**
* Online időköz (perc)
*/
var onl_int=5;
var domain="http://ttreloaded.localhost/"
/**
* Töltési kép
* @todo animált gif készítés, abszolut path
*/
var wait="<img style='margin:10px auto' src='_images/loading.png' />";

function formfocus(targ, inp){
    if (targ.value==inp){
        targ.value=""
    }
}

function formblur(targ, inp){
    if (targ.value==""){
        targ.value=inp
    }
}

/**
* @brief Trim
*
* @param str igazítandószöveg
*/
function trim(str){
    s = str.replace(/^(\s)*/, '');
    s = s.replace(/(\s)*$/, '');
    return s;
}

/**
* @brief xml node olvasása
*
* @param obj xml objektum
* @param tag xml nodenév
*/
function getNodeValue(obj,tag){
    return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}

/**
* @brief online timestamp
*/
function SetOnline(){
    var _self=this;
    this._constructor = function(){       
        httpobj=new Ajax("_modules");
        _self.update();
    }
    this.update=function(){
        httpobj.sendRequest(_self.feedback,
            "module", "online");           
    }
    this.feedback=function(response){        
        if ((response!=0) && (response!=1)){
            window.notify.write(response);
            window.notify.show();
        }
        setTimeout(_self.update,(onl_int*60000));
    }    
    this._constructor.apply(this, arguments);
}

/**
* @brief boboz toggle
*/
function fxToggle(targ, typ, nodid){
    if (isNaN(nodid)){
        nodid=0;
    }
    var hasimg=false;
    if (targ.getElementsByTagName('img')[0]){
        hasimg=true;
    }
    if (targ.getElementsByTagName(typ)[nodid]){
        var restarg=targ.getElementsByTagName(typ)[nodid];
    }
    if (restarg.style.display=='block'){
        restarg.style.display='none';
        if (hasimg){
            targ.getElementsByTagName('img')[0].src='_images/arrow_r.png';
        }
    }
    else{
        restarg.style.display='block';
        if (hasimg){
            targ.getElementsByTagName('img')[0].src='_images/arrow_d.png';
        }
    }
}
/**
* @brief Node kiürítése
*
* @param inp node id-je
*/
function delChild(inp){
    var node = document.getElementById(inp);
    if ( node.hasChildNodes()){
        while ( node.childNodes.length >= 1 ){
            node.removeChild(node.firstChild);
        }
    }
}


/**
* @brief Debug
*
* @param inp kiírandó info (ha "clrDebug", akkor törli a debug tartalmát)
*/
function debug (inp){
    if ((document.getElementById("debug")=="") || (document.getElementById("debug")==null)){
        eDIV = document.createElement("p");
        eDIV.setAttribute("id","debug");
        eDIV.setAttribute("style","z-index:9999;font-size:9pt; position:fixed; top:5px; left:5px; padding:5px; border:2px solid red; background-color:white; color:red;");
        eDIV.appendChild(document.createTextNode("debugger"));
        document.body.appendChild(eDIV);
    }
    if (inp=="clrDebug"){
        document.getElementById("debug").innerHTML="debugger";
    }
    else{
        document.getElementById("debug").innerHTML += "<br />" +  inp;
    }
}

/**
* @brief toggleLogin
*
*/
function toggleLogin(){
    var targ=document.getElementById('login');
    if (targ.style.width=="200px"){
        targ.style.width="20px";         
    }
    else{
        targ.style.width="200px";
    }
}

function cookieError(){
    document.write('<h1 style=\"color:red\">Az oldal használatához engedélyezni kell a sütiket!</h1>');
}

function toggleSitemap(targ){
    targ=targ.childNodes[3];
    if (targ){
        if (targ.style.display!="block"){
            targ.style.display="block";
        }
        else{
            targ.style.display="none";
        }
    }
}

/**
* @file
* @brief JavaScript ajax osztály
* @ingroup JS lib
*/

/**
 * @brief ajax osztály
 * @param in_dir ajax.php mappája
 * @param in_format formátum (text/xml) [OPCIONÁLIS| default:text]
 */
function Ajax(){
    /**
    * @brief XmlHttpObject
    */
    var xmlHttp;

    /**
    * @brief az aktuális ajax.php könyvtára
    */
    var dir;
    /**
    * @brief response formátum (text/xml) [OPCIONÁLIS| default:text]
    */
    var format;

    /**
    * @brief konstruktor
    * @param in_dir ajax.php mappája
    * @param in_format formátum (text/xml) [OPCIONÁLIS| default:text]
    */
    this._constructor = function(in_dir, in_format){
        dir = in_dir;
        if (in_format=="xml"){
            format="xml";
        }
        else{
            format="text";
        }
        setXmlHttpObject();
    };

    /**
    * @brief XmlHttpObject létrehozása
    */
    var setXmlHttpObject = function(){
        xmlHttp=null;
        try{
            // Firefox, Opera 8.0+, Safari
            xmlHttp=new XMLHttpRequest();
        }
        catch (e)
        {
            //Internet Explorer
            try{
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e){
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
    };

    /**
    *@brief Kérelemküldés
    * Ajax (SJAX) kérelem küldése
    * Ha az első paramétert üresen hagyjuk (""), akkor SJAX kérésként funkcionál, ekkor a response lesz a függvény visszatérési értéke.
    * Sikeres kérés esetén az megadott függvény fut le, sikertelen kéréskor (404, 500, stb.) pedig (amennyiben létezik) a reportAjaxError függvényt hívja meg (az ennek átadott paraméterek: httpStatus, url)
    * @param 1 az első paraméter a response-kezelő függvény (onstatechange)
    * @param 2 további, az URL-be kerülő paraméterek, egyesével
    */
    this.sendRequest = function(){
        var args=arguments;
        var isAsync = false;
        //var url = "http://kockart.cube-x.hu/" +dir + "/ajax.php?";
        var url =dir + "/ajax.php?";
        for(var i = 1; i < args.length; i+=2){
            url += args[i] + "=" + args[i+1] + "&"
        }
        url += "sid=" + Math.random();
        //itt kell ellenőrzés, hogy létezik-e a funkció?
        if (args[0]!=""){
            xmlHttp.onreadystatechange=function(){
                var state=xmlHttp.readyState;
                if (state==4 || state=="complete"){
                    var httpStatus=xmlHttp.status;
                    if ((httpStatus >= 200 && httpStatus < 300) || httpStatus==304){
                        if (format=="xml"){
                            args[0](xmlHttp.responseXML);
                        }
                        else{
                            args[0](xmlHttp.responseText);
                        }
                    }
                    else{
                        if(typeof window.reportAjaxError == 'function') {
                            reportAjaxError(httpStatus, url);
                        }
                    }
                }
            }
            isAsync=true;
        }
        xmlHttp.open("GET",url,isAsync);
        xmlHttp.send(null);
        if (!isAsync){
            var state=xmlHttp.readyState;
            if (state==4 || state=="complete"){
                var httpStatus=xmlHttp.status;
                if ((httpStatus >= 200 && httpStatus < 300) || httpStatus==304){
                    if (format=="xml"){
                        return (xmlHttp.responseXML);
                    }
                    else{
                        return (xmlHttp.responseText);
                    }
                }
                else{
                    if(typeof window.reportAjaxError == 'function') {
                        reportAjaxError(httpStatus, url);
                        return false;
                    }
                }
            }
        }
    }
    this._constructor.apply(this, arguments);
}

function MsgPanel(t_id, place, initPos, targPos, time){
    var target;   
    var speed=30;
    var pos=initPos;
    var step=(targPos-initPos)/(time/speed);
    var _self = this;
    
    this._constructor = function(){
        if (document.getElementById(t_id)){
            target=document.getElementById(t_id);            
            target.onclick=this.hide;
            target.style[place]=initPos+"px";
        }
    }
    this.show = function(timeout){
        if (Math.round(pos+step)<targPos)
        {
            curPos=parseInt(target.style[place],10);
            pos=curPos+step;
           
            target.style[place]=Math.round(pos)+"px";
            setTimeout(function(){
                _self.show(timeout);
            }, speed);
        }
        else{
            target.style[place]=targPos+"px";
        }
        timeout=parseInt(timeout);
        if (timeout==NaN){
            timeout=2000;
        }
        if (timeout>100){
            setTimeout(function(){
                _self.hide();
            }, timeout);
        }
    }
    this.hide=function(){
        if (Math.round(pos-step)>initPos)
        {
            curPos=parseInt(target.style[place],10);
            pos=curPos-step;
            target.style[place]=Math.round(pos)+"px";
            setTimeout(function(){
                _self.hide();
            }, speed);
        }
        else{
            target.style[place]=initPos+"px";
        }
    }
    this.write = function(msg){
        target.innerHTML=msg;
    }
    this.clear = function(){
        target.innerHTML="";
    }
    this._constructor.apply(this, arguments);
}

function Login(){
    var state;
    var tmpstate;
    var button;
    var httpobj;
    var name;
    var pass;
    var _self = this;
    this._constructor = function(){
        if (document.getElementById('loginform')){
            button=document.getElementById('loginform');
            state=0;
            button.onsubmit=this.enter;
        }
        else{
            if (document.getElementById('logoutbutton')){
                button=document.getElementById('logoutbutton');
                state=1;
                button.onclick=this.leave
            }
        }
        if (button){
            httpobj=new Ajax("_modules");
        }
    }
    this.enter = function(){
        if (state<2){
            tmpstate=state;
            state=2;
            window.notify.write("LOGIN");
            window.notify.show();
            name=document.getElementById("login_name").value;
            name=encodeURIComponent(trim(name));
            pass=document.getElementById("login_pass").value;
            if ((name=="")||(pass=="")){
                    window.notify.write("Üres név, vagy jelszó!");
                    state=tmpstate;
                    return false;
            }
            httpobj.sendRequest(_self.feedback,
                "module", "login",
                "action", "enter",
                "name", name,
                "pass", md5(pass),
                "remember", document.getElementById("login_remember").value);
            return false;
        }
        return false;
    }
    this.leave = function(){
        if (state<2){
            tmpstate=state;
            state=2;
            window.notify.write("LOGOUT");
            window.notify.show();
            httpobj.sendRequest(_self.feedback,
                "module", "login",
                "action", "leave",
                "name", getCookie("name"),
                "pass", getCookie("pass"));
            return false;
        }
        return true;
    }
    this.feedback=function(response){
        switch (response){
            case "0":{
                window.notify.write("Sikeres bejelentkezés<br />Üdv az oldalon!");
                setTimeout(_self.refresh,1000);
            };
            break;
            case "1":{
                window.notify.write("Sikeres kijelentkezés<br />Viszlát!");
                setTimeout(_self.refresh,1000);
            }
            break;
            default:{
                window.notify.write(response);
                state=tmpstate;
                if (document.getElementById("login_pass")){
                document.getElementById("login_pass").value="";
                }
            }
        }
    /*
        if (response==0){
             window.notify.write("Sikeres bejelentkezés!");
            setTimeout(_self.refresh,1000);
        }
        else{
            window.notify.write(response);
            state=tmpstate;
            document.getElementById("login_pass").value="";
        }*/
    }
    this.refresh =function(){
        if(window.location=="http://ttreloaded.localhost/register/"){
            window.location="http://ttreloaded.localhost/";
        }else{
        window.location.reload()
        }
    }
    this._constructor.apply(this, arguments);
}


//forrás w3schools.com
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 "";
}

function rememberWarn(targ){
    if (targ.checked){
        window.notify.write("Az \"Emlékezz rám\" funkció használatát nyilvános gép használata esetén (pl. iskolai, vagy munkahelyi gép) NEM ajánljuk!")
        window.notify.show();
    }
}

function reportAjaxError(httpstatus, url){
    //window.notify.write("Hiba: "+ httpstatus +"<br />"+url);
    //window.notify.show();
}

function toggleTag(targ){    
    if (targ.style.color!="rgb(255, 255, 255)"){
        targ.style.color="#ffffff";
        targ.style.fontWeight="bold";
        targ.style.backgroundColor="#111111";
        document.getElementById('tagholder').value+=targ.firstChild.data + " ";
    }
    else{
        targ.style.color="#666666";
        targ.style.fontWeight="normal";
        targ.style.background="none";
    }    
}

function mailTo(id, name){
    if (document.getElementById('mail_to_id')){
            document.getElementById('mail_to_id').value=id;
    }
     if (document.getElementById('mail_to')){
            document.getElementById('mail_to').value=name;
    }
    if (document.getElementById('mailtobox')){            
            fxToggle(document.getElementById('mailtobox'), "div");
    }
}

function init(){
    window.notify=new MsgPanel("msgpanel", "top", -55, 0,300);
    //window.loginbox=new MsgPanel("login", "right", 0, -200, 300)
    window.login=new Login();
    var online = new SetOnline();
    chat = new chatObj();
}
