
var tulpa2 = function () {
return {

siteRoot : '/',
siteName : 'Tulpa2',
loadingIndicator : false,
exchange : function (directive) {
    // Has it's own function because experience tells me there will be a need to expand this beyond a simple passthrough.
    if (typeof(directive.success) != 'function'){
        directive.success = tulpa2.exchangeSuccess;
    }
    //tulpa2.loadingIndicator.show();
    //directive.complete = function() {
        //tulpa2.loadingIndicator.hide();
    //}
    var jqXHR = $.ajax(directive);
    if (directive.data.href){
        jqXHR.href = directive.data.href;
    }
    return jqXHR;
},
exchangeError : function (jqXHR,textStatus,errorThrown){
    //tulpa2.loadingIndicator.hide();
    alert('Exchange error: '+errorThrown+'\n'+textStatus);
},
exchangeSuccess : function (data,textStatus,jqXHR) {
    $('#main').html(data);
    var title = $('#title').text();
    if (title){
        document.title = title + ' - ' + tulpa2.siteName;
    }
    if (typeof(window.history.pushState) == 'function' && jqXHR.href){
        window.history.pushState(jqXHR.href,title,jqXHR.href);
    }
    return true;
},
popstate : function (state) {
    if (state.state){
        var jqXHR = tulpa2.exchange({
            data : {
                call : 'populateMain',
                href : state.state,
            }
        });
        jqXHR.href = false; // Or it'll re-push the popped state and the history will be a MESS!
    }

},
exchangeXHR : function () {
    if (window.XMLHttpRequest && !(window.ActiveXObject)){
        return new window.XMLHttpRequest();
    }
    else {
        return new window.ActiveXObject("Microsoft.XMLHTTP");
    }
},
init : function () {
    var siteRoot = $('#siteRoot');
    if (siteRoot.length){
        tulpa2.siteRoot = siteRoot.val();
    }

    var siteName = $('#siteName');
    if (siteName.length){
        tulpa2.siteName = siteName.val();
    }

    $.ajaxSetup({
        url         : tulpa2.siteRoot+'exchange/',
        dataType    : 'html',
        error       : tulpa2.exchangeError,
        //success     : tulpa2.exchangeSuccess,
        type        : 'POST',
        xhr         : tulpa2.exchangeXHR
    });
    if (typeof(window.history.pushState) == 'function'){ // pushState support means onPopState support!
        window.onpopstate = function (e){
            tulpa2.popstate(e);
        };
    }
    /*
    var loading = $('#loadingIndicator');
    if (loading.length){
        loading.css('opacity','0.5');
        loading.ajaxStart(tulpa2.exhangeStart);
        loading.ajaxComplete(tulpa2.exchangeComplete);
        tulpa2.loadingIndicator = loading;
    }
    else {
        alert('holy crap, no loading indicator!');
    }
    */
}
}}();

$(tulpa2.init);

