function isIE() {
    if (navigator.userAgent.indexOf('MSIE') != -1)
        return true;
    return false;
}

var ajax_request = null;
var is_from_link = false;
var hash = window.location.hash;
// executed on first load - check if we've been linked directy to an ajax page
// if so, refresh as the normal page it's referencing
if (hash.length > 0)
    if (hash.substring(1,2) == "/") {
        var newLoc = hash.substring(1);
        newLoc = newLoc.replace('?ref=ajax', ""); // combine into one regex?
        newLoc = newLoc.replace('&ref=ajax', "");
        window.location = newLoc;
    }


/* AJAX FILTER NAVIGATION */
 $(document).ready(function(){
    //changeLinks();
    updateClickHandler();
    setInterval("checkAnchor()", 300);
    ///setInterval("changeLinks()", 300);

 });

function cancelLoad() {
    ajax_request.abort();
    clearLoad();
}

function clearLoad() {
    $('.active_hub_loading').removeClass('active_hub_loading');
    document.body.style.cursor = "default";
    $('#loader_box').remove();
}

// we must re-set all of the event handlers when we load new content, so
// the new content will trigger the events.
var targetDiv = 'ajax__standardcontent'; // name of the div to send the returned content
var autoDivs = ',featurestripleft,pre_sidebar';
function updateClickHandler(){
    /*
    $(".ajaxlink").click( function( evt ) {
        if (!evt.ctrlKey) { // only do ajax if the control key isn't pressed (it's a shortcut to open a new tab)
            evt.preventDefault();
            is_from_link = true;

            el = $(this).get(0);

            // if this is a main hub link, change active tab immediately
            if ($(this).hasClass('hublink')) {
                hub = (el.parentNode.id).substr(4);
                setHub(hub);
            }
            if (el.hasAttribute('href')) {
                // get rid of any current ref=ajax flags
                var newHash = el.getAttribute('href');
                newHash = newHash.replace('?ref=ajax', ""); // combine into one regex?
                newHash = newHash.replace('&ref=ajax', "");
                if (el.getAttribute('href').indexOf('?') == -1)
                    newHash += "?ref=ajax";
                else
                    newHash += "&ref=ajax";
                window.location.href = "#" + newHash;
            }
            if (el.hasAttribute('sendto'))
                targetDiv = el.getAttribute('sendto');
            else
                targetDiv = 'ajax__standardcontent';
            var temp = document.location.hash

            // add on divs that should be checked at every load, just in case
            // (things we want available, but don't want to have to include in the call)
            targetDiv += autoDivs;
        }
    });
    // every time an ajax request is finished, we trigger the <title>.keyup
    // event (because it's one that will never occur naturally)
    // other js files can use this event reload their own js or perform other actions
    // that need to happen after an ajax request.
    $('title').trigger('keyup');
    */
}

 var currentAnchor = '';
 var oldAnchor = null;
 //Function which check if there are anchor changes, if there are, sends the ajax petition
 function checkAnchor(){
     /*
     if(currentAnchor != document.location.hash){
         // we need to cut off any GET params, don't save them in the old anchor
         if (currentAnchor)
            oldAnchor = currentAnchor.split('?')[0];
         currentAnchor = document.location.hash;
         //if there is no anchor, load the default section in the normal url
         if(!currentAnchor) {
             var curHash = document.location.pathname;
             load_page_content(curHash);
         }
         else {
             // only load if the ref=ajax flag is on. This is a safety precaution,
             // in case there are normal page anchor hashes in old articles. They won't work,
             // but they won't trigger an ajax request either.
             if (document.location.hash.indexOf('ref=ajax') != -1) {
                 var curHash = document.location.hash.substr(1);
                 if(curHash.substr(0,1) == '?') {
                     // this is a GET request, must attach the old hash url to the
                     // begining of the current AJAX hash url
                     if (oldAnchor && oldAnchor.substr(1,1) != '?') //oldAnchor = the old url path
                         curHash = oldAnchor.substr(1) + curHash;
                     else // if none, use the current url path
                         curHash = document.location.pathname + curHash
                     currentAnchor = '#' + curHash;
                     document.location.hash = currentAnchor;

                     //alert('oldanchor: ' + oldAnchor + ', curAnchor: ' + currentAnchor);
                 }
                 load_page_content(curHash);
             }
        }
     }
     */
 }

 function load_page_content( url ){
    // remove all loaders in case last run was interrupted
    // set page cursor to "wait"
    $('.active_hub_loading').removeClass('active_hub_loading');
    document.body.style.cursor = "progress";
    $("<div id='loader_box'><p>loading...</p><a href='javascript:cancelLoad();'><div id='cancel'></div></a></div>").appendTo("body");

    // get the active label
    var active_label = $('.active_hub').get(0);
    if (active_label) // set it to active-loading
        $('.active_hub').addClass('active_hub_loading');

    var loaders = new Array(); // divs containing ajax-loader backgrounds


    // get the divs we're sending data to, and create the url datastring
    var targetDivs = targetDiv.split(',');

    prepareAjax(url, targetDivs);
}

// creates the url (datastring) that will be passed to the ajax response, from targetDivs
// calls the function that will perform the ajax.
var prepareAjaxFails = 0;
function prepareAjax(url, targetDivs) {
    var datastring = 'ajax=True&blocks=';

    // add on each data block to the GET string we will send to the server
    for (var i = 0; i<targetDivs.length; i++) {
        datastring += targetDivs[i] + ',';
    }
    // make the ajax request
    doAjax(url, datastring, targetDivs);
}

// performs the ajax, recalllign prepare_ajax in something goes wrong.
function doAjax(url, datastring, targetDivs) {
    //alert("do ajax: " + url + ", " + datastring + ", " + targetDivs);
     ajax_request = $.ajax({
        url: url,
        type: "GET",
        data: datastring.substring(0,datastring.length-1),
        success: function(html, textStatus) {
            var success = true; // assume it's worked
            // we have to wrap response in extra div, since that becomes the doc container
            var str = "<div>" + html + "</div>";
            var a = new Array();
            var adSpots = new Array('leaderboard','banner1','banner2','sidebar1','sidebar2');
            for (var j = 0; j < adSpots.length; j++) {
                if ($(str).find("#ad_" + adSpots[j]).html() == null) {
                    a[a.length] = adSpots[j];
                }
            }
            // for each targetDiv, extract the data from the returned html
            // and load it into the corresponding element in the current document
            for (var i = 0; i<targetDivs.length; i++) {
                // only if this div exists in the current page...
                if ($("#" + targetDivs[i]).size() == 1 && $(str).find("#" + targetDivs[i]).length == 1) {
                    //alert('yes' + targetDivs[i]);
                    var inner = $(str).find('#' + targetDivs[i]).html();
                    document.getElementById(targetDivs[i]).innerHTML = inner;

                    // find any script statements in the loaded html...
                    var scripts = document.getElementById(targetDivs[i]).getElementsByTagName("script");
                    for(var h = 0; h<scripts.length; h++) {
                        eval(scripts[h].text); // ...and execute
                    }

                    // return element to full opacity if it was faded (not IE)
                    if (!isIE()) {
                        $("#" + targetDivs[i]).fadeTo('slow', 1.0);
                    }
                    prepareAjaxFails = 0; //reset counter
                }
                else if (i != targetDivs.length-1)  {// not applicable for featurestripleft
                    //alert('no:' + targetDivs[i]);

                    // this is only a fail if the div was primary content, i.e. explicitly specified in the link.
                    // if it's in autoDivs, then we know it won't necessarily be there, so if that's the case
                    // it's not a fail.
                    if (autoDivs.search(targetDivs[i]) == -1) {
                    // problem finding correct divs to load into.
                    // HACK: not ideal - requries two loads, but it's a rare case
                    // reload page, with the fallback loading div 'ajax__fullbody'
                        if (success) // only increment if this is the first fail in this attempt
                            prepareAjaxFails++; // if it gets above one, it won't do the redo, to avoid an infinite loop
                        success = false;
                    }
                }
            }
            //alert('extracted, ' + success);
            if(success == true){
                //alert('2');
                // change the page title
                var newTitle = $(str).find('title').html();
                if (newTitle != null && newTitle.length > 0)
                    document.title = newTitle
                else
                    document.title = 'nyunews.com'


                // scroll the page up to upper-most loaded div
                var topEl = document.getElementById(targetDivs[0]);
                var topDis = topEl.offsetTop; // distance of top element from top of screen
                var topOff = window.pageYOffset;

                // only scroll if the new div isn't already obviously visible,
                // and if it's a forward-moving link (not a back button hit)
                if (is_from_link && (topDis < (topOff - 45) || topDis > (topOff + 500))) {
                    if (topDis < 250) { // send to top
                        $('html,body').animate({scrollTop: 0}, 'slow')
                    }
                    else {              // send to element's height - 100
                        $('html,body').animate({scrollTop: (topDis-100)}, 'slow')
                    }
                }
                is_from_link = false;


                // see if the new content has a hub; if so, change the active hub
                var hub = $(str).find('#hubid').html();
                setHub(hub);

                // remove ajax-loader and reset cursor to normal
                clearLoad();
                updateClickHandler(); // enable links inside ajax block to be handled with ajax
                pageTracker._trackPageview(url); // Google Analytics
                refreshAds(a);
                //pageTracker._trackPageview(url = "ajax/"); // Google Analytics
            }
            else {
                // something went wrong - reload with the fallback ajax__fullbody
                if (prepareAjaxFails < 2) { // only if this is the first retry attempt, to avoid infinite loop
                    //alert('not found');
                    var a = new Array(['ajax__fullbody']);
                    prepareAjax(url, a);
                }
            }
        }
    });
}

function setHub(hub) {
    if ($('.active_hub').length > 0) { // only if there is an active hub
        $('.active_hub').get(0).setAttribute('class', ''); // set it to not active
    }
    if (! hub) // it's supposed to default to 'home', but just incase, set it to home here
        hub = 'home';
    document.getElementById('hub_' + hub).setAttribute('class', 'active_hub');
}

function change_active( link ) {
    var newActive = document.getElementById('ajax_'+link);
    if(newActive) { // only change if the new link exists
        document.getElementById('active').setAttribute('id', '');
        document.getElementById('ajax_'+link).childNodes[0].setAttribute('id', 'active');
    }
}



/*
function changeLinks(){
    var host = 'http://' + document.location.host;
    // replace normal links with AJAX links
    var links = document.getElementsByName('ajaxlink');
    //alert(links);
    for (var i=0; i<links.length; i++) {
        //alert(links[i].href);
        if (!links[i].href.match("#")) {
            //alert(links[i].href.substr(host.length+1,1));
            links[i].href = links[i].href.replace(host, '#');
        }
    }
}

function set_ajax_link( el, event ){
    event.preventDefault();
    alert('set_ajax_link called');
    var url = el.attr("href");
    load_page_content( url );
}
*/
