﻿var isLoading = false;
var nuovoTitolo = "";
var idBody = "";
document.observe('dom:loaded', function() {

    //bindaMenu();
});
function bindaMenu() {
    $$('.ajM').each(function(el) {
        el.stopObserving('click');
        el.observe('click', menuClick);
    });

}
function menuClick(event) {
    Event.stop(event);
    var el = Event.element(event);
    //alert(el.href);
    //alert(isLoading);
    if (isLoading)
        return;

    caricaPagina(el.href);
}

function caricaPagina(url) {
    isLoading = true;
    // notice the use of a proxy to circumvent the Same Origin Policy.
    new Ajax.Request(url, {
        method: 'get',
        onFailure: function() {
            isLoading = false;
            alert("Errore durante il process della richiesta");
        },
        onSuccess: function(transport) {
            parseHtml(transport.responseText);
        }
        , onComplete: function() { }
    });
}
function parseHtml(html) {
    var parte = html.indexOf("<div id=\"ajax-cont\">") + 20;
    var fine = html.indexOf("<!-- end ajax-cont -->", parte);
    var cont = html.substring(parte, fine);
    //alert(cont);

   // var re = /<title>(.*)<\/title>/;
    var re = /<title>([\r\n]\s*)*(.*)([\r\n]\s*)*<\/title>/;
    html.gsub(re, trovaNuovoTitolo);
    re = /<body\s+id="(.*)"\s*>/;
    html.gsub(re, trovaNuovoIdBody);
    
//    var re = new RegExp(/<title>(.*)<\/title>/);
//    var m = re.exec(html);
//    if (m == null) {
//        alert("No match");
//    } else {
//        var s = "Match at position " + m.index + ":\n";
//        for (i = 0; i < m.length; i++) {
//            s = s + m[i] + "\n";
//        }
//        alert(s);
//    }

    aggiornaPagina(cont);

}

function trovaNuovoIdBody(matches) {
    //increases the prices by 10%
    idBody = matches[1];
    //alert(idBody);
    $$("body").each(function(el) {
        el.writeAttribute("id", idBody);
    });
}

function trovaNuovoTitolo(matches) {
    //increases the prices by 10%
    nuovoTitolo = matches[2];
    //alert(nuovoTitolo);
    Try.these(
        function() {
            $$("title").each(function(el) {
                //alert(el);
                el.update(nuovoTitolo);
            });
        }
    );
}
function aggiornaPagina(html) {

    var id = 'ajax-cont';
    var cont = $('ajax-cont');

    new Effect.Fade(id, { duration: 1, afterFinish:
            function() {
                try { cont.update(html); } catch(e) {}
                try { html.evalScripts(); } catch(e) {}
                try { new Effect.Appear(id, { duration: 1, delay: .5, afterFinish: cleana }); } catch (e) { }
            }
    });
    //new Effect.Appear(id, { queue: 'end' });
    //cont.update(html);
}

function cleana() {
    isLoading = false;
}