/**
 * General note: this javascript file requires the JQuery and the jquery.history.js found at http://plugins.jquery.com/project/history
 */


/*
 *
 * ARTICLE DECORATOR
 *
 */

// put images to frame
// note: this function cannot carry out its purpose if the image being processed has not been fully loaded/downloaded and has no width or height attributes. This is because the width or height attribute is not yet realized.
function mcgiArticle_image() {
    $('.articleContent img:not(.articleContent div img)').not('.articleEnd').each(function() {
        var img = $(this);
        var imgWidth = img.width();
        img.wrap('<div class="imageBox"><div></div></div>');
        var wrapper = img.parents('.imageBox');
        var imgAlign = img.css('float');
        // tweak for IE6 and IE7
        if ($.browser.msie && $.browser.version<'8.0') {
            imgAlign = img.attr('align'); // img.css('float') in IE<8 is problematic.
            if (imgAlign != 'left' && imgAlign != 'right') {
                // default to none
                imgAlign = 'none';
            }
        }
        // tweak for IE6
        if ($.browser.msie && $.browser.version=='6.0') {
          wrapper.css('padding', "10px");
          wrapper.css('width', imgWidth);
        } else {
          wrapper.css('width', imgWidth + 22);
        }
        wrapper.css('clear', imgAlign);
        wrapper.css('float', imgAlign);
        wrapper.children('div').css('width', imgWidth);

        // if the image is not floated, then alignment is panning.
        if (imgAlign == 'none') {
            // the paragraph's alignment determines the panning alignment
            var imgPAlign = wrapper.parent('p').css('text-align');
            if (imgPAlign == 'center') {
                wrapper.css('margin-left', 'auto');
                wrapper.css('margin-right', 'auto');
            } else if (imgPAlign == 'right') {
                wrapper.css('margin-right', '0px');
                wrapper.css('margin-left', 'auto');
            } else { // left is default
                wrapper.css('margin-left', '0px');
                wrapper.css('margin-right', 'auto');
            }
        } else {
            // floating is still applicable
            wrapper.css('margin-'+imgAlign, '0px');
        }
        
        wrapper.children('div').css('float', imgAlign);
        img.css('float', 'none'); // de-float image for webkit rendering
        img.after('<br clear="all"/>' + img.attr('alt')); // opera needs the <br clear="all"/>
    });
}


// put pull quotes into frame
function mcgiArticle_quote() {
    $('.articleContent span.pull_quote').each(function() {
       var q = $(this);
       q.before('<div class="quoteBox"><div><img src="/mcgi/img/quote-open.gif" alt="" style="margin-right:15px;"/>'+q.text()+'<img src="/mcgi/img/quote-close.gif" alt="" style="margin-left:15px;" align="absbottom"/></div></div>');
    });
}

// decorate
function mcgiArticle_decorate() {
    mcgiArticle_quote();
    mcgiArticle_image();
}


/*
 *
 * ARTICLE PAGING
 *
 */

// Used for article paging
var mcgiPaging_currentPage = 0;
var mcgiPaging_pages; // array of strings
var mcgiPaging_continueText;
var mcgiPaging_endText;
var mcgiPaging_suppressJqueryHistory = true;

$(function() {
    // set up paging
    mcgiPaging_setupPageLinks();
    $.historyInit(function(hash) {
        // we only need jquery.history for the browser's back and forward buttons
        if (mcgiPaging_suppressJqueryHistory) {
            mcgiPaging_suppressJqueryHistory = false;
        } else {
            var p;
            if (hash) {
                p = hash.substring(8); // remove artpage=
            } else {
                p = 1;
            }
            mcgiPaging_showPage(p, true);
        }
    });
    $('#article_support').show();
});

function mcgiPaging_buildPageLinks() {
    // build the paging links
    var pageCount = mcgiPaging_pages.length;
    var paging = $('#paging');
    paging.empty();
    //paging.append('Pages ');
    // "next page" link
    if (mcgiPaging_currentPage > 1) {
        var prevPage = parseInt(mcgiPaging_currentPage) - 1;
        paging.append('<a class="pagingLinks pagingArrow" href="#artpage=' + prevPage + '" onclick="mcgiPaging_showPage(' + prevPage + ');">&laquo;</a> ');
    }
    // pages links
    for (i = 1; i <= pageCount; i++) {
        if (i != 1) {
            paging.append('<span>|</span>');
        }
        if (mcgiPaging_currentPage == i) {
            paging.append('<span class="on">' + i + '</span>');
        } else {
            paging.append('<a class="pagingLinks" id="page-' + i + '" href="#artpage=' + i + '" onclick="mcgiPaging_showPage(' + i + ');">' + i + '</a>');
        }
    }
    // "next page" link
    if (mcgiPaging_currentPage < pageCount) {
        var nextPage = parseInt(mcgiPaging_currentPage) + 1;
        paging.append('<a class="pagingLinks pagingArrow" href="#artpage=' + nextPage + '" onclick="mcgiPaging_showPage(' + nextPage + ');">&raquo;</a> ');
    }
}

function mcgiPaging_showPage(newPage, fromJqueryHistory) {
    var cont = $('.articleContent');
    var index = newPage - 1;
    if (index >= 0 && index <= mcgiPaging_pages.length) {
    	cont.html($.trim(mcgiPaging_pages[index]));
    }

    mcgiPaging_currentPage = newPage;
    // build page links
    mcgiPaging_buildPageLinks();

    // if last page, apply article end mark; else, continue link
    if (newPage == mcgiPaging_pages.length) {
        //$('.articleContent p:last').append('<img src="/mcgi/img/article-end.gif" alt="" class="articleEnd"/>');
        if (mcgiPaging_pages.length > 1) {
            $('.articleContent p:last').append('<span class="endText">' + mcgiPaging_endText + '</span>');
        }
        if ($('.author').html() != null) {
            $('.articleContent p:last').append(' <span class="author">(' + $('.author').html() + ')</span>');
        }
    } else {
        var nextPage = parseInt(mcgiPaging_currentPage) + 1;
        $('.articleContent p:last').append(' <a class="pagingLinks continueText" style="padding:0;" href="#artpage=' + nextPage + '" onclick="mcgiPaging_showPage(' + nextPage + ');">' + mcgiPaging_continueText + '</a>');
    }

    // page ? of ?
    if (mcgiPaging_pages.length > 1 && newPage > 1) {
        var pagetrack = $('#pagetrack').html();
        if (pagetrack) {
            pagetrack = pagetrack.replace("{current}", newPage);
            pagetrack = pagetrack.replace("{total}", mcgiPaging_pages.length);
            $('.articleContent p:first').prepend(pagetrack);
        }
    }

    // decorate the article
    mcgiArticle_decorate();
    // inhibit context menu on images
    inhibitContext('.articleContent');

    if (!fromJqueryHistory) {
        // suppress jquery.history callback
        mcgiPaging_suppressJqueryHistory = true;
    }
}

function mcgiPaging_setupPageLinks() {
    mcgiPaging_continueText = $('span.continueText').text();
    mcgiPaging_endText = $('span.endText').text();
    var loc = location.href;
    var artpageIndex = loc.indexOf('#artpage=');
    var artpage_unclean = (artpageIndex == -1) ? '1' : loc.substring(artpageIndex + 9);
    mcgiPaging_currentPage = artpage_unclean.replace(/#.*/, '');
    if (isNaN(mcgiPaging_currentPage)) {
        mcgiPaging_currentPage = 1;
    }

    // the page separator is... <div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>
    // but this is how IE transform and use the page separator... <DIV style="PAGE-BREAK-AFTER: always"><SPAN style="DISPLAY: none">&nbsp;</SPAN></DIV>
    var pageSeparator = /<div\s+style\s*\=\s*"\s*page-break-after\s*:\s*always\s*;*\s*"\s*>[\s\S]*?<\/div>/i; // [\s\S]*? dapat hindi .*? para damay pati newlines. the i flag is important since other browsers like opera/IE turns HTML tags into upper case.
    mcgiPaging_pages = $('.fullArticleContent').html().split(pageSeparator);
    // empty .fullArticleContent so that it can't compete with the generated content of .articleContent
    $('.fullArticleContent').empty();
    // then finally, show the page
    mcgiPaging_showPage(mcgiPaging_currentPage);

    var pageCount = mcgiPaging_pages.length;
    for (i = pageCount; i > 0; i--) {
        // populate the anchor
        // <a name="artpage=?"></a>
        //$('.content a[name=artpage]').after('<a name="artpage='+i+'"></a>');
        $('#article_box').prepend('<a name="artpage='+i+'"></a>');
    }
    // if more than one page...
    if (pageCount > 1) {
            // show #paging because it is initially hidden with the style="display:none" attribute
            $('#paging').show();
    }
}
