$.ajaxSetup({type:'POST',timeout:0});

String.prototype.ajax=function(v,c)
{
    $.ajax(
    {
        url:'/lib/a.php',
        data:'p=ajax&a='+this+'&'+v,
        timeout:120000,
        success:c,
        error:function(x,er,er2)
        {
            dbg('Whoops! An unexpected error has occurred'+er+' '+er2);
            $.isLoading = false;
        }
    })
};

$.getJs = function(s,v)
{$.ajax({url:'/lib/a.php',data:'p=ajax&a='+s+'&'+v,dataType:'script',beforeSend:function(x){x.setRequestHeader('Accept','text/javascript');$.loading()}})};

$.btnLoading = function(e)
{
    var button = $('button[type="submit"]',e);
    if(button.is('.loading')) return;
    button.addClass('loading').prepend('<img src="/img/loading.gif" />');
};
$.btnLoaded = function()
{
    $('img',$('button').removeClass('loading')).remove();
};


$.urlFilter = function(q)
{
    // remove double "/" && trim "/"
    q = q ? q.replace(/\/\//g,'/').replace(/^(\/)+|(\/)+$/g,'') : HOMEPAGE;
    /*
    q=q.replace('__page__',p);
    */
    return q || HOMEPAGE;
};

$.isLoading = false;
display = function(q, isBack)
{
    q = $.urlFilter(q);
    
    if(window['MOBILE'] && q.substr(0,6) !== 'mobile')
    {
        q = 'mobile/'+q;
    }
    
    IB.page++;
    
    IB.hist[IB.page] = q;
    
    if(html5.historymanagement)
    {
        if(!isBack) window.history.pushState('', '', '/'+q);
    }
    else
    {
        window.location.hash = q;
    }
    
    scroll(0,0);
    $.isLoading = true;
    
    if(html5.localstorage && localStorage[q])
    {
        //dbg(q + ' : try to get from cache');
        date = new Date();
        
        if(date.getTime() < localStorage[q+'time'])
        {
            //dbg(q + ' : cache got');
            displaid(localStorage[q],1);
            return;
        }
        
        delete localStorage[q];
        delete localStorage[q+'time'];
        delete localStorage[q+'skin'];
        //dbg(q + ' : ' +localStorage[q])
    }
    $.ajax({url:'/lib/a.php',data:'q=x/'+q,ifModified:true,success:displaid});
    $.loading();
    firstLoad =false;
};


displaid = function(d,cachedData)
{
    $.e.div_content.html(d);
    //$.loadSkin();
    
    IB.init();
            
    $.hideTooltips();
    $.initTooltip();

    //$('textarea:not(.markItUpEditor)',$.e.div_content).markItUp(myBbcodeSettings);
    
    $.isLoading = false;
    $.stats();
    $.loaded();
    
    
    cache = $.getCookie('LS');

    if(html5.localstorage && cachedData!==1 && cache)
    {
        cache*= 1000;
        
        //dbg(IB.hist[IB.page] + ' : record cache');
        date = new Date();
        
        localStorage[IB.hist[IB.page]+'time'] = date.getTime() + cache;
        
        localStorage[IB.hist[IB.page]] = d;
        
        localStorage[IB.hist[IB.page]+'skin'] = $.getCookie('skin');
        
        $.delCookie('LS');
    }
    if(html5.localstorage && cachedData===1)
    {
        if(localStorage[IB.hist[IB.page]+'skin'] !== 'null')
        {
            $.setCookie('skin',localStorage[IB.hist[IB.page]+'skin'],1);
        }
        else
        {
            $.delCookie('skin');
        }
    }
    
    IB.skin();
};


IB.goBack = function()
{
    display(IB.hist[--IB.page]);IB.page--;
};
var firstLoad = 1;
$(function()
{
    // $.historic.init();
    
    var h = window.location.hash.substr(1);
    
    var v = hex2str($.getCookie('hash'));
    
    // dbg('h = '+h);
    // dbg('v = '+v);
    
    if(h && v.replace(/\//g,'') !== h.replace(/\//g,''))
    {
        display(h);
    }
    else
    {
        if(html5.historymanagement)
        {
            window.history.replaceState('', '', '/'+$.urlFilter(v));
        }
        else
        {
            window.location.hash = IB.hist[IB.page] = $.urlFilter(v);
        }
        
        
        IB.init();
        
        if(v!==HOMEPAGE)
        {
            setTimeout(function()
            {
                // $('#C textarea:not(.markItUpEditor)').markItUp(myBbcodeSettings);
                // $.loadSkin();
            },420);
        }
    }
    
    $('a[href^="/"]:not(.rss,.atom)').live('mousedown',function()
    {
        display($(this).attr('href'));
    }).live('click',function(){return false});
    
    $('form').live('submit',function()
    {
        var e = $(this);
        
        if($.FreezeForm){return false;}
        $.FreezeForm = 1;
        
        var vars = IB.parseQuery(e.attr('action'));
        var postHtml = '';
        for(var key in vars)
        {
            if(!$('input[name="'+key+'"]',e)[0])
            {
                postHtml+= '<input type="hidden" name="'+key+'" value="'+vars[key]+'"/>';
            }
        }
        if(!$('input[name="p"]',e)[0])
        {
            postHtml+= '<input type="hidden" name="p" value="ajax"/>';
        }
        
        if(postHtml){e.append(postHtml);}
        
        var successForm = function(){$.btnLoaded();$.FreezeForm=false};
        
        var eid = e.attr('id');
        if(eid==='login' || eid==='register')
        {
            successForm = function(){$.FreezeForm=false};
        }
        
        e.ajaxSubmit(
        {
            url:'/lib/a.php', // then rm all GET for faster request
            dataType:'script',
            type:'POST',
            timeout:0,
            beforeSend:function(xhr){xhr.setRequestHeader('Accept','text/javascript')},
            success:successForm,
            error:function(x,er,er2){dbg('Whoops! An unexpected error has occurred'+er+' '+er2);$.btnLoaded();$.FreezeForm=false}
        });
        
        $.btnLoading(e);
        
        return false;
    });
    
    
    if(html5.historymanagement)
    {
        onpopstate = function(event)
        {
            if(!$.isLoading && !firstLoad)
            {
                display(window.location.pathname);IB.page--;
            }
        };
    }
    else if(html5.hashchange)
    {
        $(window).bind('hashchange', function()
        {
            if(!$.isLoading)
            {
                display(window.location.hash.substr(1));
            }
        });
    }
    else
    {
        setInterval(function()
        {
            if(!$.isLoading && window.location.hash!=='#'+IB.hist[IB.page])
            {
                display(window.location.hash.substr(1));
            }
        },800);
    }

});



