//use: util.js

/**
 * usage:
 *
 * 1.) XML:
 *  - egy servet a parametereknek megfeleloen eloallit egy XML-t, es elkuldi valaszkent
 *  - a callBack fuggveny elso parametere egy response objektum, amely responseXML adattagja tartalmazza a kuldott XML-t
 *  pl:
 *  function sourceCallBack ( response [, callBackParamList] ){
 *      var responseXML = response.responseXML;
 *      ...
 *  }
 *
 * new XMLRequest ( 'TodoServlet', 'p1=v1&p2=v2', 'sourceCallBack', callBackParamList ).todo();
 *
 *
 * 2.) HTML / TEXT:
 * - a server oldal eloallit egy formazott HTML oldalt a parametereknek megfeleloen
 * - ezt a HTML szoveget beallitja a targetDiv objektum forrasakent
 * - a szukseges js utasitasokat vegrehajtja
 *
 * new TextRequest ( 'source.jsp', 'p1=v1&p2=v2', 'targetDivId' ).todo();
 *
 *
 * 3.) FORM:
 * - egy form submit metodusa meghiv egy server oldali url-t
 *  (ha nem adunk meg url-t, akkor onmagat hivja)
 * - a valasz egy formazott HTML szoveg, amit beallit a targetDiv obajktum forrasakent
 *
 * new FormRequest ( 'fileFormId', 'targetId', 'UploadServlet' ).todo();
 *
 *
 *
 *
 *
 *
 * set method of request:
 * var request = new XMLRequest( .. );
 * request.method = 'POST' | 'GET'; /default:'POST'/
 * request.todo();
 *
 * show loading:
 * var request = new XMLRequest( .. );
 * request.showLoading = true | false; /default:false/
 * request.todo();
 */

var seq = 0;
var requestCounter = 0;
var requestLoadedObj = null;

function XMLRequest ( url, urlParamList, callBack, callBackParamList ){
    this.method = 'POST';
    this.async = true;
    this.url = url;
    this.urlParamList = urlParamList;
    this.callBack = callBack;
    this.callBackParamList = callBackParamList;

    this.todo = function ( showLoading ){
        var xmlhttp = getXMLHttp ();
        xmlhttp.onreadystatechange = function() {
            try {
                if(xmlhttp.readyState == 4){
                    if ( xmlhttp.status == 0 ) {
                        //abort
                        inValidReadyState ( xmlhttp );
                    } else if (( xmlhttp.status == 200 ) && ( xmlhttp.statusText == "OK" )){
                        //ok
                        eval ( callBack + ' ( xmlhttp, callBackParamList );' );
                    } else {
                        //error
                        inValidReadyState ( xmlhttp );
                    }
                    if ( showLoading ){
                        endRequest();
                    }
                }
            } catch ( err ){
                openErrorWin (err);
            }
        }
        urlParamList = urlParamList ? urlParamList : '';
        xmlhttp.open( this.method, this.url, this.async );
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //crome: Resufed to set ...
        //xmlhttp.setRequestHeader("Content-length", urlParamList.length );
        //xmlhttp.setRequestHeader("Connection", "close");
        if ( showLoading ){
            startRequest ();
        }
        xmlhttp.send( urlParamList );
    }
}

function TextRequest ( url, urlParamList, targetId ){
    //!!!
    this.win = window;
    this.method = 'POST';
    this.async = true;
    this.url = url;
    this.urlParamList = urlParamList;
    this.onloadFnc = null;

    this.todo = function ( showLoading ){
        var xmlhttp = getXMLHttp ();
        var _win = this.win;
        var onloadFnc = this.onloadFnc;
        xmlhttp.onreadystatechange = function() {
            try {
                if(xmlhttp.readyState == 4){
                    if ( xmlhttp.status == 0 ) {
                        //abort
                        inValidReadyState ( xmlhttp );
                    } else if (( xmlhttp.status == 200 ) && ( xmlhttp.statusText == "OK" )){
                        //ok
                        eval ( 'textRequestCallBack ( xmlhttp, _win, \''+targetId+'\' );' );
                        if ( onloadFnc ){
                            onloadFnc.call();
                        }
                    } else {
                        //error
                        inValidReadyState ( xmlhttp );
                    }
                    if ( showLoading ){
                        endRequest ();
                    }
                }
            } catch ( err ){
                openErrorWin (err);
            }
        }
        urlParamList = urlParamList ? urlParamList : '';
        xmlhttp.open( this.method, this.url, this.async );
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //crome: Resufed to set ...
        //xmlhttp.setRequestHeader("Content-length", urlParamList.length );
        //xmlhttp.setRequestHeader("Connection", "close");
        if ( showLoading ){
            startRequest ();
        }
        xmlhttp.send( urlParamList );
    }
}

function FormRequest ( formId, targetId, url ){
    this.url = url;
    this.formId = formId;
    this.targetId = targetId;
    this.todo = function ( showLoading ){
        var form = byId( this.formId );
        if ( form ){
            var iFrameId = 'if_' + (seq++);
            var iFrame = document.createElement("iframe");
            iFrame.name = iFrameId;
            iFrame.id = iFrameId;
            if ( this.url ){
                form.action = this.url;
            }
            iFrame.style.display = 'none';
            document.body.appendChild(iFrame);
            var tid = this.targetId;
            eventPush(iFrame,'load',function () {
                formRequestCallBack(iFrame, tid, showLoading );
                return true;
            });
            form.target = iFrameId;
//            for ( var i = 0; i < form.elements.length; i++ ){
//                alert ( form.elements[i].name );
//            }
            form.submit();
            if ( showLoading ){
                startRequest ();
            }
        }
    }
}

/***     - util -     ****/
function getXMLHttp () {
    var httpRequest = null;
    if (window.XMLHttpRequest){  // for other browsers
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject){ // for IE
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return httpRequest;
}

function inValidReadyState ( xmlhttp ){
    openErrorWin( '<span style="color:red;">Hiba betöltés közben...<br>'+
        xmlhttp.statusText+'<br>'+
        xmlhttp.responseText+'</span>' );
}

function openErrorWin ( txt ){
    //alert ( txt );
    var d = new Dialog ( 'errorDialogId' );
    d.setTitle( 'Hiba' );
    d.setTarget( '<div>'+txt+'</div>' );
    d.addCloseButton();
    d.show( 'Info', 300 );
//    errorWin.focus();
}

function formRequestCallBack (iFrame, targetId, showLoading ){
    //    alert ( iFrame );
    //    alert ( targetId );
    //    alert ( showLoading );
    var d = null;
    if (iFrame.contentDocument) {
        d = iFrame.contentDocument;
    } else if (iFrame.contentWindow) {
        d = iFrame.contentWindow.document;
    } else {
        d = window.frames[iFrame.id].document;
    }
    var targetObj = byId( targetId );
    if ( targetObj ){
        targetObj.innerHTML = d.body.innerHTML;
    } else {
        alert ( 'A FormRequest célja ismeretlen: ' + targetId );
    }
    var iFrameId = iFrame.id;
    setTimeout("document.body.removeChild( byId( '"+iFrameId+"' ) )",100);
    if ( showLoading ){
        endRequest ();
    }
}

function textRequestCallBack ( response, win, targetId  ){
    var targetObj = byId( targetId, win );
    if ( targetObj ){
        var ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
        var html = response.responseText;
        targetObj.innerHTML = html.replace ( new RegExp ( ScriptFragment, 'img' ), '' );
        var scripts = extractScripts ( html, ScriptFragment );
        try {
            for ( var i = 0; i < scripts.length; i++ ) {
                eval ( scripts[ i ] );
            }
        }
        catch ( e ) {
            targetObj.innerHTML = 'JavaScript Error in page!!!<br>Code: ' + scripts[ i ] + '<br>' + e;
        }
    } else {
        alert ( 'A TextRequest célja ismeretlen: ' + targetId );
    }
}

function extractScripts ( html, ScriptFragment ) {
    var matchAll = new RegExp ( ScriptFragment, 'img' );
    var matchOne = new RegExp ( ScriptFragment, 'im' );

    var scripts = ( html.match ( matchAll ) || [] );
    var script  = new Array ();
    for ( var i = 0; i < scripts.length; i++ ) {
        script.push (( scripts[ i ].match ( matchOne ) || [ '', '' ] )[ 1 ] );
    }
    return script;
}

function startRequest (){
    //alert ( 'startReq' );
    requestCounter++;
    showIfLoaded();
}

function endRequest (){
    //alert ( 'endReq' );
    requestCounter--;
    showIfLoaded();
}

function showIfLoaded (){
    if ( requestLoadedObj == null ){
        requestLoadedObj = document.createElement( 'div' );
        requestLoadedObj.style.backgroundColor = 'red';
        requestLoadedObj.style.color = 'white';
        requestLoadedObj.style.position = 'absolute';
        requestLoadedObj.style.left = '15px';
        document.body.appendChild ( requestLoadedObj );
    }
    requestLoadedObj.style.top = (getScrollTop () + 15) + 'px';
    //    var sgn = '';
    //    for ( var i = 0; i < requestCounter; i++ ){
    //        sgn += 'O';
    //    }
    //    requestLoadedObj.innerHTML = requestCounter > 0 ? 'Letöltés... ['+sgn+']' : 'KĂcsz!';
    requestLoadedObj.innerHTML = requestCounter > 0 ? 'Letöltés...' : 'Kész!';
    requestLoadedObj.style.display = requestCounter > 0 ? 'block' : 'none';
}
