// JavaScript Document
var speed = .3;
var words = ""; //used with wordCount and traverse functions
var fullDescW = 200; //used to determine how large to open description window;
var enableCtrlBtn = true;
var fileType = '.png';
var emailTabEnabled = true;
var shareTabEnabled = true;

//change tabs using scriptaculous
function change_tab(tabId){
    var contentId, otherId, tabBg, shareTextClr;
    var linkInShareTab = $('share_tab').firstChild;
    if (tabId == 'share_tab') {
        contentId = 'share_content';
        otherId = 'email_content';
        tabBg = 'share_tab_on';
        shareTextClr = '#e5e2df';
    } else {
        contentId = 'email_content';
        otherId = 'share_content';
        tabBg = 'email_tab_on';
        shareTextClr = '#000000';
    }
    
    //if both tabs are closed
    if ((tabId == 'share_tab' && shareTabEnabled) || (tabId == 'email_tab' && emailTabEnabled)) {
        if ($(contentId).style.display == 'none' && $(otherId).style.display == 'none') {
            $('share_tab').style.color = '#e5e2df';
            $('tabs').style.background = 'url(img/' + tabBg + fileType + ')';
            Effect.BlindDown(contentId, { duration: speed, queue: 'front' });
            return;
        }
        //if tab being clicked on is closed and other tab is open
        if ($(contentId).style.display == 'none' && $(otherId).style.display != 'none') {
            Effect.BlindUp(otherId, { duration: speed, queue: 'front', afterFinish: function() { $('tabs').style.background = 'url(img/' + tabBg + fileType + ')'; } });
            Effect.BlindDown(contentId, { duration: speed, queue: 'end' });
            return;
        }
        //if tab being clicked on is open
        if ($(contentId).style.display != 'none') {
            Effect.BlindUp(contentId, { duration: speed, queue: 'front' });
            return;
        }
    }
}


function init_divs()
{
    var browserSupportsPng = getBrowserPngSupport();
    if (!browserSupportsPng)
    {
        fileType = '.gif';
        $('tabs').style.background = 'url(img/share_tab_on' + fileType + ')';
        $('share_content').style.background = 'url(img/bg_share_tab' + fileType + ')';
        $('email_content').style.background = 'url(img/bg_email_tab' + fileType + ')';
    }

    var midH = 250; //defines the minimum height of the main_display and associated borders and containers
    var minDisplayH = 250;
    var viewAttachH = 0;
    var moreInfoH = 0;
    var moreH = 0;

    //determines necessary space for display
    if ($('main_display_content_desc'))
    {
        if ($('more')) moreH = $('more').offsetHeight;
        if ($('more_info')) moreInfoH = $('more_info').offsetHeight;
        if ($('view_attachment')) viewAttachH = $('view_attachment').offsetHeight;
        minDisplayH = $('desc_title').offsetHeight + $('lead_paragraph').offsetHeight + moreH + moreInfoH + viewAttachH;
    }
    
    midH = (minDisplayH < midH) ? midH : minDisplayH;
    var topMargin = 0; 	//defines distance between top of main_display and campaign image, used to center image when image is shorter than 200px

    //check to see if this page contains a display image and get it's height
    //if height of display image is larger than calculated min height, set min height to display image height
    if ($('main_display_image'))
    {
        midH = (midH < $('main_display_image').offsetHeight) ? $('main_display_image').offsetHeight : midH;
        if ($('main_display_image').offsetHeight < midH)
        {
            topMargin = parseInt((midH - $('main_display_image').offsetHeight) / 2);
        }
    }

    //set height of all divs to midH
    var divArray = new Array('mid_container', 'main_display', 'mid_left_border', 'mid_right_border');
    for (i = 0; i < divArray.length; i++)
    {
        $(divArray[i]).style.height = midH + 'px';
    }

    //check for a content description box, if it exists, assume existence of an associated image container
    if ($('main_display_content_desc'))
    {    
        $('main_display_image_container').style.height = $('main_display_image').offsetHeight + 'px';
        $('main_display_image_container').style.top    = topMargin + 'px';  // center image container vertically within main_display

        //////////////// test ////////////////////////////////////////////////////////////////////////
        //$('main_display_image_container').style.height = 250 + 'px';
        //$('main_display_image_container').style.top    = 50  + 'px';
        
        $('main_display_content_desc').style.height = midH + 'px';
        $('main_display_content_desc').style.top    = 0    + 'px';                    // content description box does amusing things without this here
        $('control_bar_btn'          ).style.top    = parseInt(midH * .5 - 7) + 'px'; // center control bar button on control bar

        fullDescW = getDescW('full_text');
        fullDescW = (fullDescW > 200) ? fullDescW : 200;

        if (fullDescW == 200)
        {
            enableCtrlBtn = false;
            
            $('lead_paragraph').style.display  = 'none';
            $('more').style.display            = 'none';
            $('full_text').style.display       = 'block';
            $('control_bar_btn').style.display = 'none';
            $('control_bar').style.cursor      = 'default';
        }
    }

    $('loading_div').style.display      = 'none';
    $('mid_container').style.visibility = 'visible';
}


//called by a click on the "more" link or the arrow bar
function extend_article(newWidth)
{
    var mainDisplayAreaW = 728;
    var mainDisplayImageW = $('main_display_image').offsetWidth;
    var collapseTo = mainDisplayImageW;
    var articleW = $('main_display_content_desc').offsetWidth;

    if (articleW == 200 && enableCtrlBtn)
    {
        new Effect.Morph('main_display_content_desc', { style: 'width:' + fullDescW + 'px', duration: .6, afterFinish: function() { $('control_bar_btn').src = 'img/btn_close.gif'; } });
        if (mainDisplayImageW < 528)
        {
            if ((mainDisplayAreaW - fullDescW) < mainDisplayImageW)
            {
                new Effect.Morph('main_display_image_container', { style: 'width:' + collapseTo + 'px', duration: .6 });
            }
            else
            {
                new Effect.Morph('main_display_image_container', { style: 'width:' + (mainDisplayAreaW - fullDescW) + 'px', duration: .6 });
            }
        }
        
        $('lead_paragraph').style.display = 'none';
        $('more').style.display = 'none';
        $('full_text').style.display = 'block';
        return;
    }

    if (articleW == fullDescW && enableCtrlBtn)
    {
        new Effect.Morph('main_display_content_desc', { style: 'width:200px', duration: .6, afterFinish: function() { $('control_bar_btn').src = 'img/btn_open.gif'; } });
        
        if (mainDisplayImageW < 528)
        {
            new Effect.Morph('main_display_image_container', { style: 'width:528px', duration: .6 });
        }

        $('full_text').style.display = 'none';
        $('lead_paragraph').style.display = 'block';
        $('more').style.display = 'block';
        return;
    }
}


//returns total count of all words in specific ID tag
function getDescW(tagName) {
    traverse($(tagName));
    var longestWordlength = 0;
    var widthPerChar = 8; //approximate width per char in pixels
    var widthPerWord = 54; //estimated width per word in pixels based off average of 6 letters per word at 9 pixels per char;
    var workingH = $('main_display').offsetHeight - $('desc_title').offsetHeight - 20; //available vertical space for text (20 is for top padding of full-text)
    //var numChar = 0;
    //var longestWord = null;
    var wordsArray = words.match(/\b[^\s]+\b/g);
    var numWords = wordsArray.length;
    for (i = 0; i < wordsArray.length; i++) {
        //numChar+=wordsArray[i].length;  //remove this line after testing
        if (wordsArray[i].length > longestWordlength) {
            longestWordlength = wordsArray[i].length;
            //longestWord = wordsArray[i];  //for debugging
        }
    }
    var wordsPerLine = parseInt(numWords / parseInt(workingH / 15));
    var lineWidth = wordsPerLine * widthPerWord;
    //alert('Average word size:' + parseInt((numChar-longestWordlength)/(wordsArray.length-1)) + ' chars');
    words = "";
    if (lineWidth > (longestWordlength * widthPerChar + 20)) {
        return lineWidth;
    } else {
        return (longestWordlength * widthPerChar + 20);
    }
}

//consolidates all words within a specific id tag by searching through child nodes to find text tags (value 3 of nodeType)
//
function traverse(node) {
    if (node.nodeType == 3) {
        words += node.nodeValue;
    }
    if (node.childNodes != null) {
        for (var i = 0; i < node.childNodes.length; i++) {
            traverse(node.childNodes.item(i));
        }
    }
}

//simple get browser function that returns true if browser is of known type that supports
//png file format
//
function getBrowserPngSupport() {
    var browserAgent = navigator.userAgent.toLowerCase();
    if (browserAgent.indexOf("opera") != -1) return true;
    if (browserAgent.indexOf("firefox") != -1) return true;
    if (browserAgent.indexOf("safari") != -1) return true;
    if (browserAgent.indexOf("msie") != -1) {
        var re = new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
        var rv = parseFloat(RegExp.$1);
        if (rv < 7) return false;
        return true;
    }
    if (browserAgent.indexOf("netscape") != -1) return true;
    if (browserAgent.indexOf("mozilla/5.0") != -1) return true;
    if (browserAgent.indexOf('\/') != -1) return true;
    return false;
}


// Initialize the page.
//
Event.observe(window, 'load', init_divs);