/**
*   BEGIN jQUERY
*/

// this is called then the page has loaded
$(document).ready(function()
{
    /**
    *   Find all elements of css class '.droppable' and make them sortable. sortable elements can
    *   be dragged and dropped into columns. 'connectWith' connects all .droppable elements to all other
    *   .droppable elements.
    *
    *   The 'update' function is called after and item has been moved. The order of the panels is then
    *   serialized and saved in a cookie. One cookie for each column.
    */
    $(".droppable").sortable(
        {
            connectWith: '.droppable',
            placeholder: 'draggable_panels-placeholder',
            opacity: 0.6,
            forcePlaceholderSize: false,
            update: function()
            {
                // we need to call the refresh function first to update the orders
                $('.droppable').sortable( 'refresh' );

                // seralise the column order using the 'toArray' function
                var date = new Date();
                date.setTime(date.getTime() + (6* 30 * 24 * 60 * 60 * 1000));
                var path = '/';
                $.cookie("durex[cols]["+$(this).attr('id')+"]", $(this).sortable('toArray'), { expires : date, path : path });
            }
        }
    );

    /**
    *   here we set the default locations for the panels
    */
    var cols = new Array('left', 'centre', 'right');

    var i = 0;
    for (page in panels)
    {
        // the modulous function '%= 3' creates the sequence 0,1,2,0,1,2,0,1,2
        var col = i %= 3;

        // appane the module to the column
        $('#' + cols[col]).filter(':first').append( $('#draggy-' + page));
        i++;
    }

    /**
    *   Here we iterate through the cookies to load the serialized string of the panel positions.
    *
    *   If a cookie is found for the column then the string it split into an array.
    *
    *   For each array string we use a jQuery selector to find the element with that ID and append
    *   it to the start of the column.
    */
    for (col in cols) {
        var cookie = ($.cookie('durex[cols]['+cols[col]+']'));
        if (cookie != null) {
            var objs = cookie.split(',');
            for (obj in objs)
            {
                if (objs[obj] != '') {
                    // append this panel to the top of this column
                    $('#'+cols[col]).filter(':first').append( $('#'+objs[obj]) );
                }
            }
        }
    }

  // call pageRefresh to load user preferences and panel content
  refreshHomePage();
});
// end $(document).ready()

// reflect changes saved by the user, name/theme/panels on|off etc
function refreshHomePage()
{
    // load the user preference for which panels they want to see
    var panelPrefs = $.cookie('durex[panels]');
    $('.moveablePanelDiv').each(function() {
        var id = $(this).attr('id').replace('draggy-', '');

        /*
            look for values like 'bbcnews=0' which would indicate a negative user preference
            for that panel.
        */
        if (panelPrefs != null && panelPrefs.indexOf(id + '=0') > -1)
        {
            if ($(this).is(':visible'))
            {
                $(this).fadeOut('slow');
            }
        } else {
            if (!($(this).is(':visible')))
            {
                $(this).fadeIn('slow');
            }
            // if the HTML is less than 120 chars then assume the panel is empty -
            // panels contain a link to the static conent in order to make them accessible
            if ($(this).html().length < 120)
            {
                //show a loading message
                $(this).html("<br/><img src='" + pathMod + "imgs/loading.gif' alt='loading' /> Loading...");
            }
            var url = pathMod + 'inc/moving_panels/panel_content/' + panels[id]['url'];
            //$(this).load(url, {'id' : id}, loadCallback);

            $.ajaxSetup ({ cache: false });
            var thiss = $(this);
            $.get(url, {'id' : id}, function(responseText){ thiss.html(responseText); loadCallbackTK(thiss); }, 'html');

        }
    });

    return true;
}

// called when a panel is loaded with HTML
function loadCallbackTK(thiss)
{
    if (encode_stop_words)
    {
        thiss.each(function(){
           var code = thiss.html();
           var plaintext = decodeStopWords(code)
           thiss.html(plaintext);
        });
    }
    var id = thiss.attr('id').replace('draggy-', '');
    var html = "<div class='panelButtons'>"
            + "<a href=\"#\" onclick=\"toggleCompactLayout('" + id + "');return false;\">"
            /*+ "<img src='imgs/down.png' width='11' height='11' alt='toggle compact view'></a> "*/
            + "<a href=\"#\" onclick=\"togglePanel('" + id + "');return false;\">"
            + "<img src='imgs/close.png' width='11' height='11' alt='close'></a>"
            + "</div>";
    thiss.prepend(html);
}

// called to toggle the 'compact_layout' setting for a panel
function toggleCompactLayout(id)
{
    $('#draggy-' + id).append("<br/><img src='" + pathMod + "imgs/loading.gif'/> ");

    var key = id + '_compact_layout';

    var url = pathMod + "toggle_pref.php";
    // script var indicates this is an ajax request, otherwise the page will return return HTML
    var script = true;
    $.getJSON(url, {key: key, rand : Math.random(), script: script }, function(data){
        ajaxToggleCompactLayoutCallBack(id,data);
    });
}

// called from the small 'x' icon on each panel, used to close the panel
function togglePanel(id)
{
    $('#draggy-' + id).fadeOut('slow');

    var panelPrefs = $.cookie('durex[panels]');

    var val = id + '=0';
    if (!panelPrefs)
    {
        panelPrefs = val;
    } else if (panelPrefs.indexOf(val) < 0)
    {
        panelPrefs = panelPrefs + ',' + val;
    }

    //clean cookie
    var cleanCookie = '';

    var arr = panelPrefs.split(',');
    var del = '';
    for(var key in arr)
    {
        if(arr[key].indexOf('=0') > 0)
        {
            cleanCookie = cleanCookie + del + arr[key];
            del = ',';
        }
    }

    var url = pathMod + "customise_page.php";
    // script var indicates this is an ajax request, otherwise the page will return return HTML
    var script = true;
    $.getJSON(url, {panels: cleanCookie, script : script}, function(data){
        ajaxDefaultCallBack(id,data);
    });

    return false;
}

// called when a panel is loaded with HTML
function loadCallback(responseText, textStatus, XMLHttpRequest)
{
    if (encode_stop_words)
    {
        $(this).each(function(){
           var code = $(this).html();
           var plaintext = decodeStopWords(code)
           $(this).html(plaintext);
        });
    }
    var id = $(this).attr('id').replace('draggy-', '');
    var html = "<div class='panelButtons'>"
            + "<a href=\"#\" onclick=\"toggleCompactLayout('" + id + "');return false;\">"
            + "<img src='imgs/down.png' width='11' height='11' alt='toggle compact view'></a> "
            + "<a href=\"#\" onclick=\"togglePanel('" + id + "');return false;\">"
            + "<img src='imgs/close.png' width='11' height='11' alt='close'></a>"
            + "</div>";
    $(this).prepend(html);
}

// function fires after a user has changed a panel's 'compact_layout' setting
function ajaxToggleCompactLayoutCallBack(id,data)
{
    var url = pathMod + 'inc/moving_panels/panel_content/' + panels[id]['url'];
    $('#draggy-' + id).load(url, {'id' : id}, loadCallback);
}

/**
*   END jQUERY
*/


showPastPoll.flagInPollIdLinks = "poll_";
function showPastPoll(clicked, options) {

    //prep
    var ac = arguments.callee;
    var drObj = document.getElementById('draggy-research');

    if (clicked) { //init

        //hardwiring
        ac.clicked = clicked;
        ac.options = options.split("**");

        //grab real height and enforce this after fade out, to avoid bump in elements caused by momentary display:none set by jquery
        var panelRealHeight = window.getComputedStyle ? getComputedStyle(drObj, null).height : drObj.currentStyle.height;

        //fade out
        $('#draggy-research').fadeOut('slow', showPastPoll );

        //enforce height (see above)
        drObj.style.height = panelRealHeight;

    } else { //re-DOM with data from selected previous poll

        //prep
        var currPollObj = document.getElementById('currentPoll');
        var selectedPollId = ac.clicked.id.substr(ac.flagInPollIdLinks.length);

        //first make any elements killed by a vote in the current poll reappear
        var counter = 0;
        while (node = currPollObj.childNodes[counter]) {
            try { if (node.style.display == 'none') node.style.display = 'block'; } catch(e) {}
            counter++;
        }

        //poll question
        currPollObj.getElementsByTagName('p')[0].innerHTML = ac.clicked.innerHTML;

        //options
        var ul = currPollObj.getElementsByTagName('ul')[0];
        ul.innerHTML = '';

        for(var r in ac.options) {

            var splitter = ac.options[r].split("|");

            var li = document.createElement('li');
            li.innerHTML = "<input type='radio' name='poll' id='"+splitter[0]+"'><label for='"+splitter[0]+"'>"+splitter[1]+"</label><div></div>";
            ul.appendChild(li);

        }

        //reload pie
        document.getElementById('cpPie').src = "inc/moving_panels/related_scripts/research/pie.php?poll="+selectedPollId+"&amp"+Math.random(Math.floor()*100000);

        //update hidden var which tells handler what poll was voted in
        document.getElementById('currentPollQuestionId').value = selectedPollId;

        //change 'past polls' stuff to link back to current poll
        document.getElementById('pastPolls').innerHTML = "<br /><strong><a href='javascript:location.reload()'>&#8592; Back to current poll</a></strong>";

        //ready, so fade back in
        $('#draggy-research').fadeIn('slow');

        //let natural height take over again
        drObj.style.height = "";


    }

}

//recent articles drop-down
function goRecentArticle() {
    var selObj = document.getElementById('recentArticles');
    //location.href = "full_article.php?a="+selObj.options[selObj.selectedIndex].value;
	location.href = selObj.options[selObj.selectedIndex].value;
}

// invoked when one of the current poll answers is clicked. answer passed as int.
function poll_vote(gate) {

    var cp = document.getElementById('currentPoll')
    var cpId = document.getElementById('currentPollQuestionId').value;

    if (gate == null) {

        //retrieve selected radio
        var cpUlLis = cp.getElementsByTagName('ul')[0].getElementsByTagName('li');
        var checked;
        for (var t=0; t<cpUlLis.length; t++) {
            if ((thisRadio = cpUlLis[t].getElementsByTagName('input')[0]).checked == true) { checked = thisRadio.id; break; }
        }

        //do ajax, if an answer has been selected
        if (checked != null) {
            gateway = startAjax();
            if (!gateway)
            return;
            else {
                gateway.open('GET', 'inc/moving_panels/related_scripts/research/voteHandler.php?question='+cpId+'&answer='+checked, true);
                gateway.onreadystatechange = function() { poll_vote(1); }
                gateway.send(null);
            }
        } else
            alert('You haven\'t selected an option to vote for!');

    } else if (gate == 1) {
        //after ajax
        if (gateway.readyState == 4) {
            if (gateway.status == 200) {
                //instantiate json
                var jsonObj = eval("(" + gateway.responseText + ")");

                //if vote was logged, update piechart and kill form
                if (jsonObj.bool == true) {
                    document.getElementById('cpPie').src = "inc/moving_panels/related_scripts/research/pie.php?poll="+cpId+"&rand="+Math.floor(Math.random()*11);
                    for (var p=0; p<cp.childNodes.length; p++) {
                        if (cp.childNodes[p].className != "keepme" && cp.childNodes[p].tagName != undefined) cp.childNodes[p].style.display = 'none';
                    }

                }

                //put out result message
                alert(jsonObj.text);

            } else alert('Sorry, there was an unexpected server error and your vote could not be logged. Please try again later.');
        }
    }
}


/*****************************************
* Rearrange the homepage panels to try
* and get the heights equal
*/
lastMovedTo = {"div": 'a', "col": 'a'};
lastMovedFrom = {"div": 'b', "col": 'b'};

function doPanelRearrangement() {
    do
    {
        colsObj = {
            "left": [null, []],
            "centre": [null, []],
            "right": [null, []]
        };
        getDivHeights();
        rearrange();
    } while ( checkHeightsForConsistency() == true )
}

function checkHeightsForConsistency () {
    var endNow = false;
    if (lastMovedFrom['div'] == lastMovedTo['div']) endNow = true;
    lastMovedTo['div'] = lastMovedFrom['div'];
    return endNow;
}

function getDivHeights() {
    for (var h in colsObj) {
        var thisCol = document.getElementById(h);
        for (var y=0; y<thisCol.childNodes.length; y++) {
            thisCN = thisCol.childNodes[y];
            if (thisCN.tagName == "DIV") { colsObj[h][1][thisCN.id] = thisCN.offsetHeight; }
        }
    }
}

function getColHeights() {
    var colHeights = [];
    for (var e in colsObj) {
        var sum = 0;
        for (var i in colsObj[e][1]) sum += colsObj[e][1][i];
        colHeights[e] = sum;
    }
    return colHeights;
}

function arrayMax(arr) {
    var maxValue, col;
    for (var x in arr) {
        if (arr[x] > maxValue || maxValue == undefined) { maxValue = arr[x]; col = x; }
    }
    return [col, maxValue]; //returns array of name of column and its total height
}

function arrayMin(arr) {
    var minValue, col;
    for (var x in arr) {
        if (arr[x] < minValue || minValue == undefined) { minValue = arr[x]; col = x; }
    }
    return [col, minValue]; //returns array of name of column and its total height
}

function arraysort(a, b){ return (a-b); } //only to be used within generic array.sort()

function rearrange() {

    var colHeights = getColHeights();
    var longestCol = arrayMax(colHeights)[0];
    var shortestCol = arrayMin(colHeights)[0];

    //find most movable div in longest col (shortest, but not near top)
    var divToMove = arrayMin(colsObj[longestCol][1])[0];

    //now move!
    lastMovedFrom['div'] = divToMove;
    lastMovedFrom['col'] = shortestCol;

    divToMove = document.getElementById(divToMove);
    document.getElementById(shortestCol).appendChild(divToMove);

}

function setAsHomePageNew()
{
    $.blockUI({ css: { width: '30%', left: '30%', top: '40%', cursor: 'default' }, message: $('#sethomepage') });
    $('.blockOverlay').click( $.unblockUI );
    $('#sethomepage button').click( $.unblockUI );
}

function setLocationNew()
{
    $.blockUI({ css: { width: '30%', left: '30%', top: '40%', cursor: 'default' }, message: $('#my_location') });
    $('.blockOverlay').click( $.unblockUI );
    $('#my_location button').click( $.unblockUI );
}