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__fullbody'; // name of the div to send the returned content
var autoDivs = ',featurestripleft,pre_sidebar';
function updateClickHandler(){
    $(".ajaxlink").unbind();
    $(".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 = $(this).children().get(0).getAttribute('id').substr(4);
                setHub(hub);
            }
            newHash = getNewHash(el, true, 'link', 'href');
            
            setTarget(el); // set the targetDiv to el's "sendto" attr
            
            //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;
        }
    });
    
    $(".ajaxform").unbind();
    $(".ajaxform").submit( function( evt ) {
        evt.preventDefault();
        el = $(this).get(0);
        
        var newHash = getNewHash(el, true, 'form', 'action');
        
        setTarget(el); // set the targetDiv to el's "sendto" attr
    }) 
       
    $(".silentajaxform").unbind();
    $(".silentajaxform").submit( function( evt ) {
        evt.preventDefault();
        el = $(this).get(0);
        
        var newHash = getNewHash(el, false, 'form', 'action');
        
        setTarget(el); // set the targetDiv to el's "sendto" attr
        
        //var temp = document.location.hash;
        load_page_content(newHash, false);
    })
    
    // without this, the silentajaxlink function gets exponentially bound with
    // each successive silentajax call.
    $(".silentajaxlink").unbind();
    $(".silentajaxlink").click( function( evt ) {
        //alert('triggering');
        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);

            newHash = getNewHash(el, false, 'link', 'href');
            setTarget(el); // set the targetDiv to el's "sendto" attr
            
            //var temp = document.location.hash;
        }
        load_page_content(newHash, false);
    });
    // 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');
}

// @el        The element with the ajaxlink class
// @change    Should we change the url?
// @type      'link' or 'form'
// @dest      Attribute with destination url ('href' or 'action')
function getNewHash(el, change, type, dest) {
    if (el.hasAttribute(dest)) {
        var newHash = el.getAttribute(dest);
        newHash = newHash.replace('?ref=ajax', ""); // combine into one regex?
        newHash = newHash.replace('&ref=ajax', "");
        
        if (type == 'form') {
            PostText = "";
            amp = "";
            form = el;
            for(i=0; i<form.elements.length; i++){
                if(form.elements[i].type == "text" || form.elements[i].type == "textarea" || form.elements[i].type == "hidden"){
                    PostText += amp+form.elements[i].name+"="+encodeURIComponent(form.elements[i].value);
                } else if (form.elements[i].type == "checkbox") {
                    PostText += amp+form.elements[i].name+"="+form.elements[i].checked;
                } else if (form.elements[i].type == "select-one") {
                    PostText += amp+form.elements[i].name+"="+form.elements[i].options[form.elements[i].selectedIndex].text;
                }
                amp = "&";
            }
            if (PostText.length > 0) {
                if (newHash.indexOf('?') == -1)
                    newHash += "?" + PostText;
                else
                    newHash += "&" + PostText;
            }
        }
        
        if (newHash.indexOf('?') == -1)
            newHash += "?ref=ajax";
        else
            newHash += "&ref=ajax";
        if (change)
            window.location.href = "#" + newHash;
        return newHash;
    }
    return '';
}

function setTarget(el) {
    if (el.hasAttribute('sendto'))
        targetDiv = el.getAttribute('sendto');
    else
        targetDiv = 'ajax__fullbody';
}

 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, true);
         }
         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, true);
             }
        }
     }
 }

// url = the url to load
// loadAds = should we reload ads?
 function load_page_content( url, loadAds ){
    // 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, loadAds);
}

// 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, loadAds) {
    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, loadAds);
}

// performs the ajax, recalllign prepare_ajax in something goes wrong.
function doAjax(url, datastring, targetDivs, loadAds) {
    //alert("do ajax: " + url + ", " + datastring + ", " + targetDivs);
     ajax_request = $.ajax({
        url: url,
        type: "GET",
        data: datastring.substring(0,datastring.length-1),
        success: function(html, textStatus) {
            //alert('success');
            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){
                // 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;

                // remove ajax-loader and reset cursor to normal
                clearLoad();
                updateClickHandler(); // enable links inside ajax block to be handled with ajax
                
                // if it's a silentajax link, don't load ads or change active hub
                if (loadAds) {
                    // see if the new content has a hub; if so, change the active hub
                    var hub = $(str).find('#hubid').html();
                    setHub(hub);
                    
                    // only load ads and count as hit if url has changed
                    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']);
                    //alert("ajax obstruction : " + a);
                    prepareAjax(url, a, loadAds);
                }
            }
        }
    });
}

function setHub(hub) {
    if ($('.active_hub').length > 0) { // only if there is an active hub
        removeClass($('.active_hub').get(0), 'active_hub'); // set it to not active
        //$('.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';
    addClass(document.getElementById('hub_' + hub), 'active_hub');
    $('#header_navstretch').get(0).setAttribute('class','header_navstretch_'+hub);
    //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 hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
}