// $Id: jquery-sort-pane.js,v 1.11.4.1 2009/06/26 15:40:56 richard Exp $
//
// POD handling and help
//
var noPods = 0 

$(document).ready(

    function () {

        if (noPods == 1) {
            return
        }
        
        // Help
        //
        $('area').click( podButtons )
        $('input#podHelp').click( podHelp )

        // Customisation
        //
        $('img.customise').click( function() { customisePod($(this)) } )

        podSort('podGroup','drag')
        podSort('podGroupSingle','drag-single')
        //restorePosition()
        positionMpu()
    }
);

$(window).unload(

    function () {
        savePositions()
    }
)

function podButtons() {

    switch($(this).attr('alt')) {
        case 'Reset':
            resetPods()
            break
        case 'Open':
            openAllPods()
            break
        case 'Close':
            closeAllPods()
            break
        case 'Help':
            podHelp()
            break
    }
}

var IIMAGE         = 'images/i.gif'
var EXPANDIMAGE    = 'images/layout/pod/structure/pod_bar_expand.gif'
var CONTRACTIMAGE  = 'images/layout/pod/structure/pod_bar_contract.gif'
var APPLYIMAGE     = 'images/apply_button.png'
var NEWSIMAGE      = 'images/help/news2.png'
var SMALLNEWSIMAGE = 'images/help/small_news2.png'
var CHARTIMAGE     = 'images/help/small_chart2.png'
var PRICESIMAGE    = 'images/help/prices2.png'


var MENU = Array(
        'Getting started...',
        'The MyPLUS PODs',
        'The <img src="' + EXPANDIMAGE + '"> and <img src="' + CONTRACTIMAGE + '"> Symbols',
        'Moving PODs around',
        'POD customisation',
        'News and Market News PODs',
        'Chart PODs',
        'Price PODs',
        'Master POD controls'
)
var TEXT = Array(
        '<p>Welcome to the MyPLUS market micro-site. MyPLUS is a PLUS ' +
        '   companies market data and news resource that is designed ' +
        '   to be interactive as well as user-friendly.</p>' +
        '<p>It allows you to personalise and display your own particular ' +
        '   content and information about companies, prices and news ' +
        '   available on the PLUS website.</p>' +
        '<p>Once you have selected your content and set your page layout, ' +
        '   MyPLUS will then automatically save your selected content and ' +
        '   layout choices for future use.</p>' +
        '<p>All market data and news presented in the PODs on MyPLUS is ' +
        '   streaming, and will automatically update price and news data.</p>' +
        '<p><b>Browser compatibility</b></p>' +
        '<p>MyPLUS uses many of the feature rich elements that modern web ' +
        '   browsers support and although MyPLUS can be used on earlier ' +
        '   versions of browsers such as IE6, you may experience some ' +
        '   performance issues.</p>' +
        '<p>For best operation and user experience, we recommend that you ' +
        '   use one of the following browsers:</p>' +
        '<ul>' +
        '  <li class="req">IE 7.0 upwards</li>' +
        '  <li class="req">Safari 3.0 upwards</li>' +
        '  <li class="req">Firefox 2.0 upwards</li>' +
        '</ul>' +
        '<p>Please note you must have cookies and javascript enabled to use ' +
        '   the features of the MyPLUS service.</p>',

        '<img src="' + CHARTIMAGE + '" class="right">' +
        '<p>MyPLUS has three different sizes of content containers, or ' +
        '   PODs that are arranged into three columns.</p>' +

        '<p>PODs in the left hand column can be moved up and down, above ' +
        '   and below the advertisement block.</p>' +
        '<img src="' + PRICESIMAGE + '" class="left">' +
        '<p>The center and right hand columns have a combination of full ' +
        '   width and half-width column PODs. The half-width PODs can be ' +
        '   exchanged with each other and moved side to side, or up and down. ' +
        '   They can be sited together, or stacked above and below each other ' +
        '   on their own</p>.',

        '<p>To open or close a pod, just click on the lighter grey image in the' +
        '   top right of the POD. When the POD is open, the symbol will be ' +
        '   <img src="' + EXPANDIMAGE + '"> - clicking in it wilL then collapse '+
        '   the POD. When the POD is closed, the symbol will be ' +
        '   <img src="' + CONTRACTIMAGE + '"> - clicking in it will then expand '+
        '   the POD.</p>' +
        '<p>Clicking on the <img src="' + IIMAGE + '" class="inlineI"> on the ' +
        '   top right of any PODs ' +
        '   opens the customise pane, allowing you to set your own information ' +
        '   criteria for any incoming data.</p>',

        '<p>To move a pod, just click on the centre of the bar where the ' +
        '   title is and drag it across, up or down the page.</p>' +
        '<p>As you click and drag the pod, dotted line guides appear to show ' +
        '   you where you can locate the pod. Once you have made your choice, ' +
        '   release and just drop the pod into the space. Please note that ' +
        '   sometimes you may have to position the pod towards the bottom of ' +
        '   the area you are targeting to see the dotted line.</p>' +
        '<p>The pod layout can be re-arranged as often as desired. MyPLUS ' +
        '   uses a cookie that stores your choices, so that on subsequent ' +
        '   visits to the site it automatically re-loads your last selected ' +
        '   page layout.',

        '<p>Individual PODs can also be customised to display the most ' +
        '   useful information.</p>' +
        '<p>To customise a pod to your preferences, just click on the ' +
        '   <img src="' + IIMAGE + '" class="inlineI"> symbol.</p>' +
        '' +
        '<p>A customisation ' +
        '   pane loads with content and display options for you to make your ' +
        '   own choices. This pane displays the current state so that ' +
        '   individual parameters can be changed singly. If a company search ' +
        '   is shown, clicking in the search box will clear the value.</p>' +
        '<p><img src="' + APPLYIMAGE + '" class="left">Once completed, click ' +
        '   on the Apply button and the POD adds your preferences and ' +
        '   re-loads the pod with your new content or display.</p>' +
        '<p>(Please note - PODs can be customised in a closed or open state)',

        '<p><img src="' + NEWSIMAGE + '" class="right">' +
        '   Clicking on the <img src="' + IIMAGE + '" class="inlineI">' +
        '   in the News or Market News allows you to select ' +
        '   news from any one of the five PLUS markets. Alternatively select ' +
        '   <i>All</i> to get a full news service.</p>' +
        '   You can also use the Search boxes in the PODs to find news ' +
        '   for any PLUS company. The company finder is alphabet-responsive, ' +
        '   so just start typing in the company name you require. As you add ' +
        '   more letters, the site will refine the search, accessing all '+
        '   companies that match alphabetically until it displays the one ' +
        '   you are looking for. Mouse over and click on the company name ' +
        '   and this drops it into the search box. Once completed, click on ' +
        '   Apply button to close the customisation pane and it loads your new ' +
        '   settings into the pod.</p>',

        '<p><img src="' + CHARTIMAGE + '" class="right">' +
        '   Clicking on the <img src="' + IIMAGE + '" class="inlineI">' +
        '   symbol in the Charts PODs allows you to choose ' +
        '   company performance charts and their respective time periods ' +
        '   according to your own needs - daily, weekly, monthly or yearly.</p>' +
        '<p>As with the News and Market News PODs, the customisation pane ' +
        '   for the Charts PODs enables you to search for individual companies ' +
        '   and add your selected company to the PODs.</p>',

        '<p><img src="' + PRICESIMAGE + '" class="right">' +
        '   Clicking on the <img src="' + IIMAGE + '" class="inlineI"> symbol ' +
        '   in the Price PODs allows you to choose ' +
        '   the data fields you require.</p>' +
        '<p>Each Price POD has four different field headers, e.g mid, bid, ' +
        '   ask, volume, change, or % change. Any of these can be selected ' +
        '   for any of the data fields.</p>',

        '<img src="/images/pod_menu.png" id="pod_menu">' +
        '<p>On the right hand side of the MyPLUS page there are three ' +
        '   master pod controls that allow you to either open or ' +
        '   close all of the PODs or to reset the MyPLUS page state ' +
        '   back to the default settings.</p>'
)

function podHelp() {

    $('body').append(
        "<div class='podHelp' id='podHelpDiv'>" +
        "  <h1 class='podHelp' id='podHelpMainTitle'>MyPODs Help</h1>" +
        "  <span class='podHelp' id='podHelpClose'>Close</span>" +
        "  <div class='podHelp' >" +
        "    <div class='podHelp' id='podHelpMenu'>" +
        getPodMenu() +
        "    </div>" +
        "    <div class='podHelp' id='podHelpText'>" +
        "      <h3>" + MENU[0] + "</h3><hr>" +
        TEXT[0] +
        "    <div>" +
        "  </div>" +
        "</div>")
    $('div#podHelpText h3').css('color', '#01ADEF')

    $('div#podHelpDiv h1').css('background-color','#DDDDDD')
    $('div#podHelpDiv h1').css('color','#01ADEF')
    $('div#podHelpDiv h1').css('font-weight','normal')

    $('h1#podHelpMainTitle').css('margin', '0px')
    $('h1#podHelpMainTitle').css('padding', '10px')
    $('h1#podHelpMainTitle').css('border-bottom', '1px solid #CCCCCC')
    $('h1#podHelpMainTitle').css('margin-bottom', '12px')

    $('li.podMenuSpan').css('font-weight', 'bold')
    $('li.podMenuSpan').css('color', '#808080')

    $('div#podHelpDiv div').css('margin', '1pt 1pt 1pt 1pt')
    $('div#podHelpDiv').css('background-color', '#EFEFEF')
    $('div#podHelpDiv').css('border-bottom', '1px solid #808080')
    $('div#podHelpDiv').css('border-right', '1px solid #808080')
    $('div#podHelpDiv').css('border-top', '1px solid #DDDDDD')
    $('div#podHelpDiv').css('border-left', '1px solid #DDDDDD')

    $('span#podHelpClose').css('position','absolute')
    $('span#podHelpClose').css('top','10px')
    $('span#podHelpClose').css('right','10px')

    $('div#podHelpDiv').css('min-width', '700px')
    $('div#podHelpDiv').css('width', '700px')
    $('div#podHelpDiv').css('min-height', '500px')
    $('div#podHelpDiv').css('height', '500px')
    $('div#podHelpDiv').css('z-index', '100')
    $('div#podHelpDiv').css('position', 'absolute')
    $('div#podHelpDiv').css('top', '80px')
    $('div#podHelpDiv').css('left', '100px')
    $('div#podHelpDiv').css('background-color', '#F7F7F7')

    $('div#podHelpMenu').css('width', '198px')
    $('div#podHelpMenu').css('min-width', '198px')
    $('div#podHelpMenu').css('float', 'left')

    $('div#podHelpText').css('margin-right', '25px')
    $('div#podHelpText').css('width', '470px')
    $('div#podHelpText').css('min-width', '470px')
    $('div#podHelpText').css('float', 'right')

    $('li.podHelp').css('margin-bottom','10px')
    $('li.podHelp').css('list-style-image', 'url("images/on.gif")')
    $('li.req').css('list-style-image', 'url("images/on.gif")')

    $('li.podMenuSpan').mouseover(
            function() {
                $(this).css('color', '#000000')
                var id = $(this).attr('id').split('_')
                id = id[1]
                $('div#podHelpText').html(
                           '<h3>' + MENU[id] + '</h3><hr>' + TEXT[id]
                           )
                $('img.inlineI').css('position','relative')
                $('img.inlineI').css('top','5px')
                $('img.left').css('float','left')
                $('img.left').css('margin-right', '10px')
                $('img.left').css('margin-bottom', '10px')
                $('img.right').css('float','right')
                $('img.right').css('margin-left', '10px')
                $('img.right').css('margin-bottom', '10px')
                $('img#pod_menu').css('float','right')
                $('div#podHelpText h3').css('color', '#01ADEF')
            })
    $('li.podMenuSpan').mouseout(
            function() {
                $(this).css('color', '#808080')
            })
    $('span#podHelpClose').mouseover( function() { $(this).css('text-decoration', 'underline') })
    $('span#podHelpClose').mouseout( function() { $(this).css('text-decoration', 'none') })
    $('span#podHelpClose').click( function() { $('div#podHelpDiv').remove() })
}

function getPodMenu() {

    var str = '<ul>'
    for (i = 0; i < MENU.length; i++) {
        str = str + "<li class='podHelp podMenuSpan' id='podMenuItem_" + i + "'>" + MENU[i] + "</span><br>"
    }
    return str + '</ul>'
}

var podSort = function(podGroupName,acceptClass) {

        $('.' + acceptClass + ' .bar a.toggle').bind('click', toggleContent);
        $('.' + acceptClass + ' .hide').css('display','none');

        $('#content .' + podGroupName).Sortable(
                        {
                                accept: acceptClass,
                                helperclass: 'sortHelper',
                                activeclass : 'sortableactive',
                                hoverclass : 'sortablehover',
                                handle: 'a.'+ acceptClass +'-handle',
                                tolerance: 'intersect',
                                onChange : function(ser)
                                {
                                },
                                onStart : function()
                                {
                                        $('div.chartDiv').hide()
                                        $('.' + podGroupName + '.sortHelper').css('float','right');
                                        $.iAutoscroller.start(this, $('body'));
                                },

                                onStop : function()
                                {
                                        $(this).css('left','auto');
                                        $(this).css('top','auto');
                                        var currId = $(this).attr('id');
                                        var childDivs = this.parentNode.childNodes;

                                        var index=0;
                                        var currIndex;
                                        var currDiv;
                                        for (var i=0;i<childDivs.length;i++) {
                                                if (/\bdrag\b/.test(childDivs[i].className)) {
                                                        if (childDivs[i].id==currId) {
                                                                currIndex=index;
                                                                currDiv=childDivs[i];
                                                        }
                                                        index++;
                                                }
                                        }

                                        // This seems to be for auto-opening after dragging
                                        //
                                        //var lastIndex = parseInt(index-1);
                                        //if (currIndex==lastIndex && lastIndex>0) {
                                        //        if ($('.content',currDiv).css('display')!='none') {
                                        //                $('.content',currDiv).slideUp(200);
                                        //                //$('.info',currDiv).slideUp(200);
                                        //        }
                                        //}
                                        //else if (currIndex<lastIndex || lastIndex==0) {
                                        //        if ($('.content',currDiv).css('display')=='none') {
                                        //                $('.content',currDiv).slideDown(200);
                                        //        }
                                        //}

                                        $('.' + acceptClass + ' .bar a.toggle').bind('click', toggleContent);

                                        $.iAutoscroller.stop();

                                        if ($(this).parent().attr('className') == 'podGroupSingle') {
                                            positionMpu()
                                        }
                                        $('div.chartDiv').show()

                                }
                        }
                );

                $('.show').click(function(){
                        cName=$(this).attr('class');
                        if (/\boptions\b/.test(cName)) {
                                $('.' + acceptClass + ' .content',this.parentNode.parentNode).slideUp(200);
                                $('.info',this.parentNode.parentNode).slideDown(200);
                                $(this).html('(front)');
                                $(this).removeClass('options');
                                $(this).addClass('front');
                        }
                        else {
                                $('.' + acceptClass + ' .content',this.parentNode.parentNode).slideDown(200);
                                $('.info',this.parentNode.parentNode).slideUp(200);
                                $(this).removeClass('front');
                                $(this).addClass('options');
                                $(this).html('(options)');
                        }
                  });
}

var toggleContent = function(e)
{

    var barContainerBox = this.parentNode.parentNode.parentNode.parentNode.parentNode;

        switch (barContainerBox.className) {
                case 'box6':
                        var parDiv = barContainerBox.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
                        var childDivs = parDiv.childNodes;
                        break;
                case 'box7':
                        var parDiv = barContainerBox.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
                        var childDivs = parDiv.parentNode.parentNode.parentNode.childNodes;
                        break;
        }
        var targetContent = $('.content', parDiv);
        //var targetInfoPane = $('div.info', this.parentNode.parentNode);

        if (targetContent.css('display') == 'none') {
                targetContent.slideDown(200);
                $('.bar a.toggle',parDiv).removeClass('expand');
                $('.bar a.toggle',parDiv).addClass('contract');
                $('.bar a.toggle',parDiv).attr({title:'Contract this pod'});

        } else {
                targetContent.slideUp(200);
                //targetInfoPane.slideUp(200);
                // Move to bottom on collapse
                //$(parDiv.parentNode).append($(parDiv));
                $('.bar a.toggle',parDiv).removeClass('contract');
                $('.bar a.toggle',parDiv).addClass('expand');
                $('.bar a.toggle',parDiv).attr({title:'Expand this pod'});
        }
        /*
        var index = 0;
        for (var i=0;i<childDivs.length;i++) {
                if (/\bdrag\b/.test(childDivs[i].className)) {
                        if (index==0) {
                                if ($('.drag .content',childDivs[i]).css('display')=='none') {
                                        $('.drag .content',childDivs[i]).slideDown(200);
                                }
                        }
                        index++;
                }
        }
        var lastIndex = index>1? parseInt(index-1) : 0;
        if ($('.drag .content',childDivs[lastIndex]).css('display')!='none') {
                $('.drag .content',childDivs[lastIndex]).slideUp(200);
        }
        */
        //$('a.closeEl').bind('click', toggleContent);

        return false ;
};

// Position Saving
//
function savePositions() {

    var cName = 'FMEstate_p_' + getPage()
    eraseCookie(cName)

    var cookieStr = ''
    if ($('div.podGroupSingle').length) {
        cookieStr = savePodPositions('podGroupSingle')
    }
    if ($('div.podGroup').length) {
        var cStr = savePodPositions('podGroup')
        if (cStr) {
            if (cookieStr) {
                cookieStr = cookieStr + '^'
            }
            cookieStr = cookieStr + cStr
        }
    }
    createCookie(cName, cookieStr, 365)
}

function savePodPositions(group) {

    var cookieStr = ''
    $('div.' + group).parent().each(
            function() {
                var podStr = ''
                $('div#' + $(this).attr('id') + ' .' + group).children().each(
                        function() {
                            var id    = $(this).attr('id')
                            var state = $('div#' + id + ' .content').css('display')
                            if (podStr) {
                                podStr = podStr + '!' + id + '-' + state
                            } else {
                                podStr = id + '-' + state
                            }
                        })
                if (cookieStr != '') {
                    cookieStr = cookieStr + '^'
                }
             cookieStr = cookieStr + $(this).attr('id') + '-' + group + ':' + podStr
            })
    return cookieStr
}

// Position Restoring
//
function getPage() {

    var href = location.href
    page     = href.split('#')
    page     = page[0].split('?')
    page     = page[0].split('/')
    page     = page[page.length - 1].split('.')[0]

    if (page == 'details') {
        if (href.match(/Group=Traded/)) {
            return 'details_Traded'
        } else if (href.match(/Group=Traded/)) {
            return 'details_Traded'
        } else if (href.match(/Group=Listed/)) {
            return 'details_Listed'
        } else if (href.match(/Group=Quoted/)) {
            return 'details_Quoted'
        } else {
            return page
        }
    } else {
        return page
    }
}

function resetPods() {

    var cName = 'FMEstate_p_' + getPage() + '_CookieReset'
    createCookie(cName, 1, 1)
    location.reload()
}

function openAllPods() {

    $('div.pod').each( function() { setPodState($(this).attr('id'), 'open') })
}

function closeAllPods() {

    $('div.pod').each( function() { setPodState($(this).attr('id'), 'none') })
}

/*
function restorePosition() {

    return
    
    var resetCookie    = readCookie('FMEstate_p_' + getPage() + '_CookieReset')
    var positionCookie = readCookie('FMEstate_p_' + getPage())

    if (resetCookie) {
        eraseCookie('FMEstate_p_' + getPage() + '_CookieReset')
        eraseCookie('FMEstate_p_' + getPage())
        positionCookie = ''
    }
    if (!positionCookie) {
        return
    }

    var cols = positionCookie.split('^')
    for (var i = 0; i < cols.length; i++) {
        var col  = cols[i].split(':')
        var vals = col[1].split('!')
        col      = col[0].split('-')
        var type = col[1]
        col      = col[0]
        for (var j = 0; j < vals.length; j++) {
            var pod   = vals[j].split('-')
            var state = pod[1]
            pod       = pod[0]
            $('div#' + pod).appendTo($('div#' + col + ' .' + type))
            setPodState(pod, state)
        }
    }
}
*/

function setPodState(pod, state) {

    var podContent = 'div#' + pod + ' .content'
    var podToggle  = 'div#' + pod + ' a.toggle'

    if (state == 'none') {
        $(podContent).hide()
        $(podToggle).addClass('expand')
        $(podToggle).removeClass('contract')
        $(podToggle).attr({title:'Expand this pod'});
    } else {
        $(podContent).show()
        $(podToggle).addClass('contract')
        $(podToggle).removeClass('expand')
    }
}

function positionMpu() {

    var i = 0
    $('div#col1 .podGroupSingle .pod').each(
        function() {
            $(this).appendTo($('div#col1 .podGroupSingle'))
            i++
            if (i == 1) {
                $('div#mpu').appendTo($('div#col1 .podGroupSingle'))
            }
        })
}

// Customisation
//
var PODOPEN = {}
function customisePod(elem) {

    // Temporarily disable search (etc.) - bit of a sledgehammer!
    //
    $('input#searchPlus').hide()
    $('img#podmenu_img').css('visibility', 'hidden')
    
    // Hide customise + expand buttons
    //
    $(elem).hide()
    var id = $(elem).attr('id').split('_')
    id     = id[1]
    $('div#' + id + ' .toggle').hide()

    // Clear chart if customising a chart
    //
    if (id == 'DailyChart' || id == 'DailyChart2' || id == 'LargeChart') {
        unloadChartPod(id)
    }

    // Expand POD if not expanded
    //
    PODOPEN[id] = 'yes'
    if ($('div#' + id + ' .content').css('display') == 'none') {
        PODOPEN[id] = 'no'
        setPodState(id, 'show')
    }

    // Unshow POD and show the customiser
    //
    var custom = $('div#' + id + ' .content').clone()
    $(custom).html(customiseContent(id))
    $(custom).attr('id', 'customiseDiv_' + id)
    $('div#' + id + ' .content').hide()
    $('div#' + id + ' .content').parent().append($(custom))

    $(custom).append("<div class='podCustomiseDiv'><img src='images/apply_button.png' id='saveCustomise_" + id + "'></div>");
    $('img#saveCustomise_' + id).click( function() { saveCustomisedPod($(this)) ; return false } )
    $('img#saveCustomise_' + id).css('align', 'right')
    $('img#saveCustomise_' + id).focus()

    // Add any behaviour
    //
    if (id == 'DailyChart' || id == 'DailyChart2' || id == 'LargeChart') {
        companySelector(id)
    }
    if (id == 'News' || id == 'News2') {
        companySelector(id)
        $('select#newsGroup_' + id).change(
                function() {
                    if ($(this).val()) {
                        $('input#CompanySearch_' + id).val('')
                    }
                })
        $('input#CompanySearch_' + id).change(
                function() {
                    if ($(this).val()) {
                        $('select#newsGroup_' + id + ' :selected').attr('selected',0)
                    }
                })
    }

    return false
}

function saveCustomisedPod(elem) {

    var id     = $(elem).attr('id').split('_')
    id         = id[1]

    if (!validateCustomisation(id)) {
        return
    } else {
        storeCustomisation(id)
    }

    $('img#customise_' + id).show()
    $('div#' + id + ' .toggle').show()

    $('div#customiseDiv_' + id).remove()

    $('div#' + id + '_Content').html('')

    if (PODOPEN[id] == 'yes') {
        PODOPEN[id] = 0
        setPodState(id, 'show')
    }

    if (id == 'todaysPrices' || id == 'boxTen' || id == 'boxEleven' || id == 'boxTwelve') {
        loadTablePod(id)
    } else if (id == 'News' || id == 'News2') {
        loadNewsPod(id, 4)
    } else if (id == 'NewsFull') {
        loadNewsPod(id, 6)
    } else if (id == 'DailyChart' || id == 'DailyChart2') {
        loadChartPod(id, 'Small')
    } else if (id == 'LargeChart') {
        loadChartPod(id, 'Large')
    }

    // Re-enable search
    //
    $('input#searchPlus').show()
    $('img#podmenu_img').css('visibility', 'visible')

    return false
}

// var COLUMNS = Array('Mid','Change','% Chg','Volume','Bid','Ask','Open','Close','High','Low')
var COLUMNS    = Array('Mid','Change','% Chg','Volume','Bid','Ask')
var NEWSGROUPS = Array('All','Quoted','Traded','Listed','Unlisted')
var TEXTS   = {
                'LargeChart':'Select the company and display options for this Chart POD',
                'DailyChart':'Select the company and display options for this Chart POD',
                'DailyChart2':'Select the company and display options for this Chart POD',
                'NewsFull':'Select either the type of News you would like to see in this News POD',
                'News':'Select either the type of News, or a company you would like to see in this News POD',
                'News2':'Select either the type of News, or a company you would like to see in this News POD',
                'todaysPrices':'Select the fields you would like to see in the Today\'s Prices POD',
                'boxTen':'Select the fields you would like to see in the PLUS-traded POD',
                'boxEleven':'Select the fields you would like to see in the PLUS-quoted POD',
                'boxTwelve':'Select the fields you would like to see in the PLUS-traded (listed) POD',
                'boxThirteen':'Select the fields you would like to see in the PLUS-traded (unlisted) POD'
}

function customiseContent(id) {

    var cust = retrieveCustomisation(id)

    var pod    = $('div#' + id + ' h2:first').html()
    var colour = $('div#' + id + ' h2:first').attr('class')
    if (!pod) {
        pod    = $('div#' + id + ' h3:first').html()
        colour = $('div#' + id + ' h3:first').attr('class')
    }
    if (pod.length > 25) {
        pod = pod.substr(0, 25) + '...'
    }

    var st = "<div class='text'>" +
             "  <h2 class='" + colour + "'>Customise " + pod + "</h2>" +
             "  <p>" + TEXTS[id] + "</p>" +
             "</div>" +
             "<div class='podCustomiseDiv'>" +
             "  <table>"

    if (id == 'todaysPrices' || id == 'boxTen' || id == 'boxEleven' || id == 'boxTwelve' || id == 'boxThirteen') {

        var colsSaved = 0
        if (cust != '') {
            colsSaved = 1
            var cols  = retrieveCustomisation(id).split('^')
        }
        for (i = 1; i < 5; i++) {
            st = st + "    <tr>"
                    + "      <td>Field " + i + "</td>"
                    + "      <td><select id='column" + i + "'>"
            for (j = 0; j < COLUMNS.length; j++) {
                if ((colsSaved && cols[i - 1] == COLUMNS[j]) || (!colsSaved && i - 1 == j)) {
                   st = st + "    <option value='" + COLUMNS[j] + "' selected='1'>" + COLUMNS[j] + "</option>"
                } else {
                   st = st + "    <option value='" + COLUMNS[j] + "'>" + COLUMNS[j] + "</option>"
                }
            }
            st = st + "      </select></td>"
                    + "    </tr>"
        }
        st = st + '<tr><td>&nbsp;</td></tr>'

    } else if (id == 'NewsFull') {

        cust      = cust.split(':')
        var type  = cust[0]
        var group = cust[1]

        st = st + "<tr>"
                + "  <td>News Type </td>"
                + "  <td><select id='newsGroup_" + id + "'>"
                + "        <option value='0'>-- Select --</option>"

        for (i = 0; i < NEWSGROUPS.length; i++) {
            if (group == NEWSGROUPS[i]) {
                st = st + "<option selected='1' value='" + NEWSGROUPS[i] + "'>" + NEWSGROUPS[i] + "</option>"
            } else {
                st = st + "<option value='" + NEWSGROUPS[i] + "'>" + NEWSGROUPS[i] + "</option>"
            }
        }
        st = st + "</select></td>"
                + "</tr>"

    } else if (id == 'News' || id == 'News2') {

        cust      = cust.split(':')
        var type  = cust[0]
        var val   = cust[1]

        st = st + "<tr>"
                + "  <td>News Type </td>"
                + "  <td><select id='newsGroup_" + id + "'>"
                + "        <option value='0'>-- Select --</option>"

        var group = retrieveCustomisation(id)
        for (i = 0; i < NEWSGROUPS.length; i++) {
            if (type == 'GROUP' && val == NEWSGROUPS[i]) {
                st = st + "<option selected='1' value='" + NEWSGROUPS[i] + "'>" + NEWSGROUPS[i] + "</option>"
            } else {
                st = st + "<option value='" + NEWSGROUPS[i] + "'>" + NEWSGROUPS[i] + "</option>"
            }
        }
        var company =''
        if (type == 'ISIN') {
            company = val
        }
        st = st + "</select></td>"
                + "</tr>"
                + "<tr>"
                + "  <td>Search</td>"
                + "  <td><input type='text' id='CompanySearch_" + id + "' value='" + company + "'>"
                + "</tr>"
                + "<tr>"
                + "  <td valign='top'>Select</td>"
                + "  <td><div id='CompanyList_" + id + "' class='CompanyList'></div></td>"
                + "</tr>"

    } else if (id == 'DailyChart' || id == 'DailyChart2' ) {

        cust = cust.split('^')
        var company = cust[0]
        var period  = cust[1]
        var type    = cust[2]

        var periods = new Array('1 week', '2 weeks', '3 weeks', 'current month',
                                '1 month', '2 month', '3 month', '6 month', '9 month',
                                'year to date', '1 year')
        var types   = new Array('Mountain', 'Line')

        if (!period) { period = '1 year'   }
        if (!type)   { type   = 'Mountain' }

        st = st + "<tr>"
                + "  <td>Options</td>"
                + "  <td><select id='ChartPeriod_" + id + "'>"
        for (i = 0; i < periods.length; i++) {
            if (period == periods[i]) {
                st = st + "            <option selected='1'>" + periods[i] + "</option>"
            } else {
                st = st + "            <option>" + periods[i] + "</option>"
            }
        }
        st = st + "    </select>"
                + "          <br>"
                + "          <select id='ChartType_" + id + "'>"
        for (i = 0; i < types.length; i++) {
            if (type == types[i]) {
                st = st + "            <option selected='1'>" + types[i] + "</option>"
            } else {
                st = st + "            <option>" + types[i] + "</option>"
            }
        }
        st = st + "          </select>"
                + "  </td>"
                + "</tr>"
                + "<tr>"
                + "  <td>Company</td>"
                + "  <td><input type='text' id='CompanySearch_" + id + "' value='" + company + "'></td>"
                + "</tr>"
                + "<tr>"
                + "  <td valign='top'>Select</td>"
                + "  <td><div id='CompanyList_" + id + "' class='CompanyList'></div></td>"
                + "</tr>"

    } else if (id == 'LargeChart') {

        cust = cust.split('^')
        var company = cust[0]
        var period  = cust[1]
        var type    = cust[2]

        var periods = new Array('1 week', '2 weeks', '3 weeks', 'current month',
                                '1 month', '2 month', '3 month', '6 month', '9 month',
                                'year to date', '1 year', '2 years', '3 years',
                                '4 years', '5 years')
        var types   = new Array('Mountain', 'Line')

        st = st + "<tr>"
                + "  <td>Options</td>"
                + "  <td><select id='ChartPeriod_" + id + "'>"
        for (i = 0; i < periods.length; i++) {
            if (period == periods[i]) {
                st = st + "            <option selected='1'>" + periods[i] + "</option>"
            } else {
                st = st + "            <option>" + periods[i] + "</option>"
            }
        }
        st = st + "          </select>"
                + "          <br>"
                + "          <select id='ChartType_" + id + "'>"
        for (i = 0; i < types.length; i++) {
            if (type == types[i]) {
                st = st + "            <option selected='1'>" + types[i] + "</option>"
            } else {
                st = st + "            <option>" + types[i] + "</option>"
            }
        }
        st = st + "          </select>"
                + "  </td>"
                + "</tr>"
                + "<tr>"
                + "  <td>Company</td>"
                + "  <td><input type='text' id='CompanySearch_" + id + "' value='" + company + "'></td>"
                + "</tr>"
                + "<tr>"
                + "  <td valign='top'>Select</td>"
                + "  <td><div id='CompanyList_" + id + "' class='CompanyList'></div></td>"
                + "</tr>"
    }

    st = st + "  </table>"
            + "  <input type='hidden' id='currentLetter' value=''>"
            + "</div>"

    return st
}

function validateCustomisation(id) {

    if (id == 'todaysPrices' || id == 'boxTen' || id == 'boxEleven' || id == 'boxTwelve' || id == 'boxThirteen') {
        var col1 = getSelectValue('column1')
        var col2 = getSelectValue('column2')
        var col3 = getSelectValue('column3')
        var col4 = getSelectValue('column4')
        if (col1 == col2 || col1 == col3 || col1 == col4 || col2 == col3 || col2 == col4 || col3 == col4) {
            alert('Please select a different value for each field')
            return 0
        }
    }

    return 1
}

function companySelector(id) {

    $('input#CompanySearch_' + id).click(
                function() {
                    $(this).val('')
                    $('div#CompanyList_' + id).html('')
                })

    $('input#CompanySearch_' + id).keyup(
                function() {

                    // Get 1st letter
                    //
                    var val           = $(this).val().toUpperCase()
                    $(this).val(val)
                    if (!val) {
                        $('div#CompanyList_' + id).html('')
                        return
                    }

                    var currentLetter = $('input#currentLetter').val()
                    var len           = val.length
                    var thisLetter    = val.substr(0, 1)

                    if (currentLetter != thisLetter || $('div#CompanyList_' + id).html() == '') {
                        $('input#currentLetter').val(thisLetter)
                        getCompanies(thisLetter, 'CompanySearch_' + id, 'CompanyList_' + id)
                    }

                    // Filter list based on typed input
                    //
                    var companies    = $('div#CompanyList_' + id).html()
                    companies = companies.split(/<BR>/i)
                    var newCompanies = new Array()
                    for (i = 0; i < companies.length; i++) {
                        var company = companies[i]
                        company = company.substr(company.indexOf('>') + 1)  // Remove opening span
                        company = company.substr(0, company.length - 7)     // Remove closing span
                        if (company.substr(0, len).toUpperCase() == val) {
                            newCompanies.push('<span>' + company + '</span>')
                        }
                    }
                    $('div#CompanyList_' + id).html(newCompanies.join("<br>"))
                    $('div#CompanyList_' + id + ' span').mouseover( function() { $(this).css('color', '#FF0000') } )
                    $('div#CompanyList_' + id + ' span').mouseout( function() { $(this).css('color', '#000000') } )
                    $('div#CompanyList_' + id + ' span').click( function() { $('input#CompanySearch_' + id).val($(this).html()) } )
                })
}


function storeCustomisation(id) {

    var cookieStr = ''
    if (id == 'todaysPrices' || id == 'boxTen' || id == 'boxEleven' || id == 'boxTwelve' || id == 'boxThirteen') {

        cookieStr = getSelectValue('column1') + '^' +
                    getSelectValue('column2') + '^' +
                    getSelectValue('column3') + '^' +
                    getSelectValue('column4')

    } else if (id == 'News' || id == 'News2') {

        if ($('input#CompanySearch_' + id).val())  {
            cookieStr = 'ISIN:' + $('input#CompanySearch_' + id).val()
        } else if (getSelectValue('newsGroup_' + id)) {
            cookieStr = 'GROUP:' + getSelectValue('newsGroup_' + id)
        }

    } else if (id == 'NewsFull') {

        if (getSelectValue('newsGroup_' + id)) {
            cookieStr = 'GROUP:' + getSelectValue('newsGroup_' + id)
        }

    } else if (id == 'DailyChart' || id == 'DailyChart2' || id == 'LargeChart') {

        cookieStr = $('input#CompanySearch_' + id).val() + '^' +
                    getSelectValue('ChartPeriod_' + id)  + '^' +
                    getSelectValue('ChartType_' + id)
    }

    if (cookieStr) {
        var cName = 'FMEPods_p_' + getPage() + '_' + id
        eraseCookie(cName)
        createCookie(cName, cookieStr, 365)
    }
}

function retrieveCustomisation(id) {

    var cName     = 'FMEPods_p_' + getPage() + '_' + id
    var cookieStr = readCookie(cName)
    if (cookieStr) {
        return cookieStr
    } else {
        return ''
    }
}

function getSelectValue(id) {

    var selectedOption = 0
    $('select#' + id + ' option').each(
        function() {
            if ($(this).attr('selected') && $(this).html() != '-- Select --') {
                selectedOption = $(this).html()
            }
            i++
        })
    return selectedOption
}

// Cookie Handling
//
function createCookie(name, value, days) {

    if ( days ) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
        var expires = "; expires=" + date.toGMTString()
    } else {
        var expires = ""
    }
    document.cookie = name + "=" + value + expires +"; path=/"
}

function eraseCookie(name) {

    createCookie(name,"",-1);
}

function readCookie(name) {

    var nameEQ = name + "="
    var ca = document.cookie.split(';')

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length)
            if (c.indexOf(nameEQ) == 0) {
                return c.substring(nameEQ.length, c.length)
            }
    }
    return null;
}

