var siteName = '';
var watchList = [];
var watchCount = 0;
var iFeatured = 0;
var iFundCount = 0;
var currFundType = '';
var currTab = '';
var currArea = '';
var getResults;
var siteRoot = '/Investor/';

$(document).ready(function () {
    $(document).pngFix();
    // Get site name from URL - used as a cookie name
    siteName = location.href.split('/')[3];
    // Prepare page structure and css
    // --------------------------------------------
    $('#vals').show();
    // Move contents to a new div
    $('#ie_msg, #ie_buttons, .fundtype').appendTo($('#ie_content'));
    // Grand total table
    $('#ie_content').append('<div id="quickValsTotal"><table><tfoot><tr><td>Total</td><td align="right"><input type="text" id="inputGrandTotal" value="0.00" /></td></tr><tfoot></table></div>');
    // Duplicate buttons at the bottom of the table
    $('#ie_buttons').clone(true).attr('id', 'ie_buttons2').appendTo($('#ie_content'));
    $('input.button, #ie_mainfilters .f_topbutton').mouseover(function () {
        if (!$(this).is('#f_all')) {
            $(this).addClass('hover');
        }
    }).mouseout(function () {
        $(this).removeClass('hover');
    });
    if (typeof featuredFunds == 'undefined') {
        $('#f_featured').addClass('disabled').attr('disabled', 'disabled');
    }
    // Count lists - watchlist, featured and all
    // --------------------------------------------	
    $('#ie_content .fundtype').each(function () {
        //iFeatured += $(this).find('table tr[@featured="1"]').length;
        iFundCount += $(this).find('table tr[@isin]').length;
    });
    /*if (iFeatured == 0){
    	$('#f_featured').insertAfter($('#f_all')).addClass('hidden');	
    }*/
    if ($.cookie(siteName)) {
        watchList = $.cookie(siteName).split(';');
        watchCount = watchList.length;
    }
    else {
        $('#f_watchlist, #f_watchlist+label, .buttonClear').attr('disabled', 'true').addClass('disabled');
    }
    $('#f_watchlist .f_title').append('<span id="watchlist_count">' + watchCount + '</span>');
    // Initiate filter menus, fund range
    // --------------------------------------------
    $('#ie_filters select').change(function () {
        filterRows();
    });
    $('#f_ranges li').mouseover(function () {
        $(this).addClass('hover');
        $('#f_all').addClass('hover');
        return false;
    }).mouseout(function () {
        $(this).removeClass('hover');
        return false;
    }).click(function () {
        if (!$(this).is('.on')) {
            $('#f_ranges li.on').removeClass('on');
            $(this).addClass('on');
            $('#f_all').addClass('on');
            toggleAdvanced('show');
            resetFilters('#' + this.id);
            $.cookie(siteName + '-range', this.className.split(' ')[0]);
            $.cookie(siteName + '-state', null);
            $.cookie(siteName + '-search', null);
            ajaxLoad();
            return false;
        }
    });
    // Initiate search
    // --------------------------------------------
    $('#f_search').focus(function () {
        $('#f_searchbox').addClass('on')
        resetFilters('#f_searchbox');
        //toggleAdvanced('hide');
		currArea  = 'searchfund';
    });
    // Sliders
    // --------------------------------------------	
    // Make markers draggable	
    $('.marker').mousedown(function () {
        var m = $(this);
        var s = Math.floor(m.parent().find('.slider').width() / m.parent().find('.slider div').length);
        var w = m.parent().find('.slider div').width();
        var t = m.parent().find('.sliderOn');
        var sX = m.parent().offset().left;
        $(document).bind('selectstart', function () {
            return false;
        }).mousemove(function (e) {
            var x = e.pageX - sX;
            if (x > 0 && x < m.parent().width() && ((m.is('.from') && x < m.parent().find('.to').offset().left - sX) || (m.is('.to') && x > m.parent().find('.from').offset().left - sX))) {
                m.css('left', x + 'px');
            }
            t.css('left', m.parent().find('.from').offset().left - sX + 'px').css('width', m.parent().find('.to').offset().left - m.parent().find('.from').offset().left + 'px');
        }).mouseup(function (e) {
            if (e.pageY < m.parent().offset().top || e.pageY > m.parent().offset().top + m.parent().height) { return false; }
            var x = e.pageX - sX;
            if (x > 0 && x < m.parent().width() && ((m.is('.from') && x < m.parent().find('.to').offset().left - m.parent().offset().left) || (m.is('.to') && x > m.parent().find('.from').offset().left - m.parent().offset().left))) {
                m.css('left', (Math.floor(x / s)) * s + w / 2 - m.width() / 2 + 'px');
            }
            t.css('left', m.parent().find('.from').offset().left - sX + 'px').css('width', m.parent().find('.to').offset().left - m.parent().find('.from').offset().left + 'px');
            m.attr('value', Math.floor(x / s));
            $(document).unbind('mousemove').unbind('mouseup').unbind('selectstart');
            filterRows();
        });
    });
    // Show and hide featured funds
    // --------------------------------------------
    $('#f_featured').click(function () {
        if ($(this).is('.disabled') || $(this).is('.hidden')) {
			currArea  = 'featuredfund';
            $('#f_all').trigger('click');
            return false;
        }
        else if (!$(this).is('.on')) {
            $(this).addClass('on');
            toggleAdvanced('hide');
            resetFilters('#' + this.id);
            filterRows('featured');
            $.cookie(siteName + '-state', 'featured');
            $.cookie(siteName + '-range', null);
            $.cookie(siteName + '-search', null);
        }
        else {
            return false;
        }
    });
    // Show and hide watchlist
    // --------------------------------------------
    $('#f_watchlist').click(function () {
        if (!$(this).is('.on') && !$(this).is('.disabled')) {
			currArea  = 'watchlist';
            $(this).addClass('on');
            toggleAdvanced('hide');
            resetFilters('#' + this.id);
            filterRows('watchlist');
            $.cookie(siteName + '-state', 'watchlist');
            $.cookie(siteName + '-range', null);
            $.cookie(siteName + '-search', null);
        }
        else {
            return false;
        }
    });
    // Show all funds
    // --------------------------------------------
    $('#f_all').click(function () {
        if (!$(this).is('.on')) {
            toggleAdvanced('show');
            resetFilters('#' + this.id);
            $.cookie(siteName + '-state', 'all');
            $.cookie(siteName + '-search', null);
            ajaxLoad();
        }
        else {
            return false;
        }
    });
    // Freetext auto-completer and search
    // --------------------------------------------
    $('#f_search').focus(function () {
        $(this).attr('oldValue', this.value);
        this.value = '';
    }).keydown(function (e) {
        // Keyboard arrow control for autocompleter
        if ((e.which == 40 || e.which == 38 || e.which == 13) && $('#searchResults div').length > 0) {
            var hoverFund = $('#searchResults div.hover').length > 0 ? $('#searchResults div.hover') : '';
            // Downwards arrow
            if (e.which == 40) {
                if (hoverFund && hoverFund.next()) { hoverFund.removeClass('hover').next().addClass('hover'); }
                else { $('#searchResults div:first').addClass('hover'); }
            }
            // Upwards arrow
            else if (e.which == 38) {
                if (hoverFund && hoverFund.prev()) { hoverFund.removeClass('hover').prev().addClass('hover'); }
                else { $('#searchResults div:last').addClass('hover'); }
            }
            // Enter key
            else if (e.which == 13) {
                if (hoverFund) {
                    hoverFund.trigger('mousedown');
                }
                else {
                    $('#buttonSearch').trigger('click');
                }
                return false;
            }
        }
        else {
            //resetFilters('#f_searchbox');
            if ($('#searchResults').length == 0) {
                $('body').append('<div id="searchResults"></div>');
                $('#searchResults').css('left', $(this).offset().left + 'px').css('top', $(this).offset().top + $(this).height() + 5 + 'px');
            }
            getResults = window.setTimeout('searchRows()', 200);
        }
    }).blur(function () {
        if (this.value == '' && $(this).attr('oldValue')) { this.value = $(this).attr('oldValue'); }
        $('#searchResults').remove();
        window.clearTimeout(getResults);
    });
    $('#buttonSearch').click(function () {
        window.clearTimeout(getResults);
        var s = $('#f_search').val();
        $('#searchResults').remove();
        //resetFilters('#f_searchbox');
        toggleAdvanced('hide');
        filterRows('text', s);
        $.cookie(siteName + '-search', s);
        return false;
    });
    // Swap tabs and contents
    // --------------------------------------------
    $('#ie_tabs div').mouseover(function () {
        $(this).addClass('hover');
    }).mouseout(function () {
        $(this).removeClass('hover');
    }).click(function () {
        if (!$(this).is('.on')) {
            $('#ie_tabs .on').removeClass('on');
            $(this).addClass('on');

            // Save tab state
            $.cookie(siteName + '-tab', this.id);

            // Swap columns if not showing All funds
            if ($('#f_featured.on, #f_watchlist.on').length > 0 || $('#f_search').val() != '') {
                t = this.id;
                filterColumns(t);
            }
            // Otherwise, load new data
            else {
                ajaxLoad();
            }
        }
    });
    // Show / hide more filters
    // --------------------------------------------
    $('#f_showmore').click(function () {
        if ($('#f_advanced').is(':visible')) {
            $('#f_advanced').slideUp();
            $(this).html('? More').removeClass('on');
        }
        else {
            $('#f_advanced').slideDown();
            $(this).html('? Less').addClass('on');
        }
    });
    // Adding and removing funds from Watchlist
    // --------------------------------------------
    $('.buttonWatchlist').click(function () {
        // Only works if a fund is selected
        if ($('#ie_content table tr.selected').length == 0) {
            alertUser('Please select at least one fund first');
            return;
        }
        //watchList.length = 0;
        $('#ie_content tbody tr.selected').each(function () {
            isin = $(this).attr('isin');
            // See if fund is already watched
            isWatched = -1;
            for (i = 0; i < watchList.length; i++) {
                if (isin == watchList[i].split(',')[0]) {
                    isWatched = i;
                }
            }
            // Add or remove from array as needed
            if (isWatched == -1 && $('.buttonWatchlist').attr('action') == 'add') {
                watchList.push(isin + ',0');
                var ga_fundname;
                ga_fundname = $(this).attr('fund');
                ga_fundname = ga_fundname + ' - ' + isin;
                recordWatchListEvents('add',ga_fundname);
            }
            if (isWatched != -1 && $('.buttonWatchlist').attr('action') == 'remove') {
                watchList.splice(isWatched, 1);
                 recordWatchListEvents('remove');
                // Refresh the view if we are in the watchlist
                if ($('#f_watchlist').is('.on')) {
                    resetFilters('#f_watchlist');
                    filterRows('watchlist');
                }
            }
        });
        // Append back to cookie and fix the watchlist tickbox
        $.cookie(siteName, watchList.join(';'), { expires: 90 });
       
         updateWatchlistSharedCookies(watchList);

        watchCount = watchList.length;
        $('#watchlist_count').text(watchCount);
        if (watchCount > 0) {
            $('#f_watchlist, #f_watchlist+label, .buttonWatchlist, .buttonClear').removeAttr('disabled').removeClass('disabled');
        }
        else {
            $('#f_watchlist, #f_watchlist+label, .buttonWatchlist, .buttonClear').attr('disabled', 'true').addClass('disabled');
            if ($('#f_watchlist').is('.on')) {
                $('#f_featured').trigger('click');
            }
        }
        markWatchlistItems();
        deselectAll();
        alertUser('Your watchlist has been updated.');
    });
    // Clear watchlist
    $('.buttonClear').click(function () {
        if ($.cookie(siteName)) {
            $.cookie(siteName, '');
            $('#watchlist_count').text('0');
            $('tr[@isin] .watchlistIcon').removeClass('watched').removeAttr('title');
            if ($('#f_watchlist').is('.on')) {
                $('#f_featured').trigger('click');
            }
            $('#f_watchlist, .buttonClear').addClass('disabled').attr('disabled', 'disabled');
            watchList.length = 0;
            updateWatchlistSharedCookies(watchList);

            deselectAll();
            alertUser('Your watchlist has been cleared.');
             recordWatchListEvents('remove');
        }
        else {
            alertUser('You have no items in your watchlist.');
        }
    });
    // Print and download buttons
    $('.buttonPrint').click(function () {
        window.print();
    });
    $('.buttonDownload').click(function () {
        loadData();
    });
    initExplorer();
});
// Deselect all rows
// --------------------------------------------
function deselectAll() {
    $('#ie_content tr.selected').removeClass('selected').find('input[@type=checkbox]').removeAttr('checked');
    $('.buttonWatchlist').val('My watchlist').attr('disabled', 'true').removeAttr('action');
}

// Initate screen by displaying in defaults
// -------------------------------------------
function initExplorer() {

    // Restore screen from cookie
    var _tab = $.cookie(siteName + '-tab') ? $.cookie(siteName + '-tab') : '';
    _tab = urlParameter('tab') && _tab == '' ? urlParameter('tab').toLowerCase() : _tab;

    var _state = $.cookie(siteName + '-state') ? $.cookie(siteName + '-state') : '';
    _state = urlParameter('list') && _state == '' ? urlParameter('list') : _state;

    var _search = $.cookie(siteName + '-search') ? $.cookie(siteName + '-search') : '';
    _search = urlParameter('search') && _search == '' ? urlParameter('search') : _search;

    var _range = $.cookie(siteName + '-range') ? $.cookie(siteName + '-range') : '';
    _range = urlParameter('range') && _range == '' ? urlParameter('range').toLowerCase() : _range;

    //alert(_tab + '; ' + _state + '; ' + _search + '; ' + _range);

    // Show/hide UI elements
    if (urlParameter('hideFilters') == 'true') {
        $('#ie_filters').hide();
    }
    if (urlParameter('hideTabs') == 'true') {
        $('#ie_content').css('border', 'none');
        $('#ie_tabs').hide();
    }

    // Default to a specific tab
    if (_tab) {
        $('#ie_tabs #' + _tab).addClass('on');
    }

    // Simulate search
    if (_search) {
        $('#f_searchbox').addClass('on');
        $('#f_search').val(_search);
        $('#buttonSearch').trigger('click');
    }
    // Default to a specific fund range
    else if (_range) {
        $('#f_all').addClass('on');
        $('#f_ranges li.on').removeClass('on');
        $('#f_ranges li.' + _range).trigger('click');
    }
    // Absolute lists
    else if (_state) {
        if (_state == 'watchlist') {
            $('#f_watchlist').trigger('click');
        }
        else if (_state == 'featured' && !$('#f_featured').is('.disabled')) {
            $('#f_featured').trigger('click');
        }
        else if (_state == 'all') {
            $('#f_all').trigger('click');
        }
    }
    else if (watchCount > 0) {
        $('#f_watchlist').trigger('click');
    }
    else {
        $('#f_featured').trigger('click');
    }
}

// Search through rows and populate the auto-completer
// --------------------------------------------
function searchRows(submit) {
    terms = $('#f_search').val();
    mode = submit ? '&isinonly=true' : '';
    if (terms != '' && terms.length > 2 && terms.toLowerCase() != 'jpm') {
        $.ajax({
            type: 'GET',
            cache: false,
            url: siteRoot + '/data/allfunds.aspx?terms=' + terms + mode,
            beforeSend: function () {
                if (submit) { toggleLoader('show'); }
            },
            success: function (data) {
                if (!submit) {
                    $('#searchResults').html(data);
                    if ($('#searchResults div[isin]').length > 0) {
                        $('#searchResults div[isin]').mousedown(function () {
                            $('#f_search').val($(this).text());
                            //resetFilters('#f_searchbox');
                            $.cookie(siteName + '-search', $(this).text());
                            filterRows('isin', $(this).attr('isin'));
                            $('#f_search').attr('isinlist', $(this).attr('isin'));
                            $('#searchResults').hide();
                        });
                        $('#searchResults div.showall').mousedown(function () {
                            $('#buttonSearch').trigger('click');
                        });
                        $('#searchResults').show();
                    }
                    else {
                        $('#searchResults').hide();
                    }
                }
                else {
                    ajaxLoad('', '', data);
                }
            }
        });
    }
    else {
        $('#searchResults').hide();
    }
}
// *******************************************
// Main filtering functions
// --------------------------------------------
// Filter columns depending on tab
function filterColumns(tab) {
    $('.fundtype td, .fundtype th').show();
    // Present columns according to tab
    switch (tab) {
        case 'keyfacts': $('.fundtype td:not(.fundlabel, .first,.fundname,.keyfacts), .fundtype th:not(.first,.fundname,.keyfacts)').hide(); break;
        case 'prices': $('.fundtype td:not(.fundlabel,.first,.fundname,.prices), .fundtype th:not(.first,.fundname,.prices)').hide(); break;
        case 'objectives': $('.fundtype td:not(.fundlabel, .first,.fundname,.objective), .fundtype th:not(.first,.fundname,.objective)').hide(); break;
        case 'docs': $('.fundtype td:not(.fundlabel, .first,.fundname,.docs), .fundtype th:not(.first,.fundname,.docs)').hide(); break;
        case 'vals': $('.fundtype td:not(.fundlabel, .first,.fundname,.vals), .fundtype th:not(.first,.fundname,.vals)').hide(); break;
        case 'performance': $('.fundtype td:not(.fundlabel, .first,.fundname,.performance), .fundtype th:not(.first,.fundname,.performance)').hide(); break;


    }
    // Redraw the screen options
    redrawScreen(tab);
}
// Filter rows against the various parameters
function filterRows(type, param) {
    // Absolute filters - these get the results via Ajax
    if (type) {
        // Show funds by individual isin
        if (type == 'isin') {
            ajaxLoad('', '', param);
        }
        // Show funds by fund name
        else if (type == 'text') {
            searchRows(true);
        }
        // Show featured only
        else if (type == 'featured') {
            ajaxLoad('', '', '', 1);
        }
        // Show watchlist only
        else if (type == 'watchlist') {
            isinList = [];
            updateWatchlistSharedCookies(watchList);

            for (i = 0; i < watchList.length; i++) {
                isinList.push(watchList[i].split(',')[0]);
            };
            ajaxLoad('', '', isinList);
        }
    }
    // Cumulative filters
    else {
        // Reductionist filtering - start with everything visible and hide rows with the incorrect attribute
        showAllRows();
        // Go through the menus, get column number and hide all isins with a different content - also factors in text
        $('#ie_filters select[name!=fundtype]').each(function () {
            sel = this[this.selectedIndex].value;
            text = $('#f_search').val().toLowerCase();
            if (sel != 'All') {
                $('#ie_content tbody tr[@' + $(this).attr('name') + '!=' + sel + ']').each(function () {
                    $(this).hide();
                });
            }
        });
        //Read slider positions and calculate items to hide
        $('.slider').each(function () {
            var s = $(this).parent();
            var o = $(this).children();
            var fromItem = s.find('.from').attr('value');
            var toItem = s.find('.to').attr('value');
            // Risk rating - filter by content
            if (s.is('#f_riskrating')) {
                riskRatingCol = $('#ie_content th:contains("Risk rating")');
                riskRatingCol = riskRatingCol.parent().children().index(riskRatingCol.eq(0)) + 1;
                $('#ie_content tbody td:nth-child(' + riskRatingCol + ')').each(function () {
                    f = $(this);
                    o.each(function (i) {
                        if (i >= fromItem && i <= toItem && f.text().trim().toLowerCase() == $(this).text().trim().toLowerCase()) {
                            f.attr('leave', 'true');
                        }
                    });
                    if (!f.attr('leave')) {
                        f.parent().hide();
                    }
                    else {
                        f.removeAttr('leave');
                    }
                });
            }
            // Launch date - filter by date range
            if (s.is('#f_launchdate')) {
                launchDateCol = $('#ie_content th:contains("Launch date")');
                launchDateCol = launchDateCol.parent().children().index(launchDateCol.eq(0)) + 1;
                startYear = o.eq(fromItem).text();
                endYear = o.eq(toItem).text() == '+' ? '' : o.eq(toItem).text();
                var now = Date.fromDDMMYYYY(new Date());
                var earliest = new Date();
                earliest.setDate(now.getDate() - startYear * 365);
                // Only calculate end year for the last marker
                if (endYear) {
                    var latest = new Date();
                    latest.setDate(now.getDate() - endYear * 365);
                }
                $('#ie_content tbody td:nth-child(' + launchDateCol + ')').each(function () {
                    var launch = Date.fromDDMMYYYY($(this).text());
                    if (launch >= earliest || (latest && launch <= latest)) {
                        $(this).parent().hide();
                    }
                });
            }
            // Morning Star - filter by star rating
            if (s.is('#f_stars')) {
                $('#ie_content div:not(#trusts) table').each(function () {
                    ratingCol = getColumnIndex('Morning Star Rating', $(this))
                    if (ratingCol) {
                        minStars = o.eq(fromItem).text().trim() == '-' ? 0 : o.eq(fromItem).text().trim().length;
                        maxStars = o.eq(toItem).text().trim().length;
                        $(this).find('td:nth-child(' + ratingCol + ')').each(function () {
                            if ($(this).find('img').length < minStars || $(this).find('img').length > maxStars) {
                                $(this).parent().hide();
                            }
                        });
                    }
                });
            }
        });
        // Reset filters
        resetFilters('select', true, true);
    }
    // Toggle fund-level rows
    $('#ie_content tr.fund').each(function () {
        // See if there are any share classes visible
        var fIndex = $(this).parent().children().index(this) + 1;
        var rows = $(this).parent().children();
        for (i = fIndex; i < rows.length; i++) {
            if (rows.eq(i).is(':visible')) {
                $(this).show(); break;
            }
            else {
                $(this).hide();
            }
            if (rows.eq(i + 1).is('.fund')) { break; }
        }
    });
    // Hide a table header if a fund type is blank
    $('#ie_content .fundtype table').each(function () {
        if ($(this).find('tbody tr:visible').length == 0) {
            if ($(this).find('caption').length == 0) { $(this).append('<caption>No funds selected</caption>'); }
            $(this).find('thead').hide();
            if (!$('#vals').is('.on')) { $(this).find('tfoot').hide(); }
            $(this).prev().addClass('disabled');
        }
        else {
            $(this).find('caption').remove();
            $(this).find('thead').show();
            if ($('#vals').is('.on')) { $(this).find('tfoot').show(); }
            $(this).prev().removeClass('disabled');
        }
    });
    //loadData();
}
// Show/hide loader for when things are calculated
// --------------------------------------------
function toggleLoader(d) {
    if (d == 'show') {
        $('.noresult').remove();
        $('#ie_buttons, #ie_buttons2').hide();
        $('#ie_content').addClass('loading');
    }
    else {
        if ($('.fundtype').length > 0) {
            $('#ie_buttons, #ie_buttons2').show();
        }
        $('#ie_content').removeClass('loading');
    }
}
// Marks all watchlist items with an icon
// --------------------------------------------
function markWatchlistItems() {
    // Fix - add watchlist icon span where missing
    $('td.fundname:not(:has(span.watchlistIcon))').prepend('<span class="watchlistIcon"></span>');
    $('tr .watchlistIcon.watched').removeClass('watched').removeAttr('title');
    for (i = 0; i < watchList.length; i++) {
        $('tr[@isin=' + watchList[i].split(',')[0] + '] .watchlistIcon').addClass('watched').attr('title', 'This item is in my watch list');
    }
}
// Reset all filters bar a given filter or filter type
// --------------------------------------------
function resetFilters(apart, ignoreTypeReset, ignoreSearchReset) {
    if ($(apart).is('.f_topbutton')) {
        $('#ie_mainfilters div:not(' + apart + ')').removeClass('on');
    }
    $('#ie_filters select:not(' + apart + ')').attr('selectedIndex', '0');
    if (!ignoreTypeReset) { $('#ie_content .fundtype').show(); }
    if (!ignoreSearchReset) { $('#ie_filters input[@type=text]:not(' + apart + ')').val(''); }
    // Place markers to starting position - not run for menu filters
    if ($('#f_advanced').is(':visible') && (!apart || !$(apart).is('select'))) {
        $('.marker').removeAttr('value').each(function () {
            var s = $(this).parent().find('.slider div');
            var t = $(this).parent().find('.sliderOn');
            if ($(this).is('.from')) {
                $(this).css('left', s.width() / 2 - $(this).width() / 2 + 'px');
                t.css('left', s.width() / 2 - $(this).width() / 2 + 'px');
                $(this).attr('value', '0');
            }
            else if ($(this).is('.to')) {
                $(this).css('left', s.length * s.width() - s.width() / 2 - $(this).width() / 2 + 'px');
                t.css('width', $(this).offset().left - $(this).parent().find('.from').offset().left + 'px');
                $(this).attr('value', s.length - 1);
            }
        });
    }
}
// Show everything
// --------------------------------------------
function showAllRows() {
    $('#ie_content tbody tr').show();
    //loadData();
}
// Load data to hidden form field for downloading
// --------------------------------------------
function loadData() {
    var sContent = '';
    $('body').append('<div id="temp"></div>');
    $('#ie_content .fundtype:visible').each(function () {
        $('#temp').append($(this).find('h2, table:visible').clone());
    });
    $('#temp').find('tr:hidden, input:checkbox, img, span, td:hidden, th:hidden, tfoot:hidden').remove();
    $('#temp').find('input').each(function () {
        $(this).parent().html($(this).val());
    });
    xlsCSS = '<style>body{font-family: arial;} thead td{background: #000; color: #fff;} table{width:100%} td{vertical-align: top; font-family: arial;} thead tr{ font-weight: bold; }</style>';
    $('#hdExcelData').val(xlsCSS + $('#temp').html().replace(/\u00A3/g, 'ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â£').replace(/\u20AC/g, 'ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬'));
    $('#temp').remove();
    $('#contentMiddleFull form').trigger('submit');
}
// Select and deselect rows
// --------------------------------------------
function selectRow(r) {
    var r = $(r);
    var myISIN = $(r).parents('tr').attr('isin');
    if (r.is(':checked')) {
        // Highlight row
        r.parents('tr').addClass('selected');
        // Check if the isin is in the watchlist
        isWatched = false;
        for (i = 0; i < watchList.length; i++) {
            if (myISIN == watchList[i].split(',')[0]) {
                isWatched = true;
            }
        }
        // Rename and fix the button as needed
        if (isWatched && $('.buttonWatchlist').attr('action') != 'add') {
            $('.buttonWatchlist').attr('action', 'remove').val('Remove from my watchlist').removeAttr('disabled');
        }
        else if (!isWatched && $('.buttonWatchlist').attr('action') != 'remove') {
            $('.buttonWatchlist').attr('action', 'add').val('Add to my watchlist').removeAttr('disabled');
        }
        else {
            alertUser('Please only select items to add or remove from the watchlist');
            $('#ie_content tbody tr[@isin=' + myISIN + ']').removeClass('selected').find('input:checkbox').removeAttr('checked');
        }
    }
    else {
        // Lowlight rows with the same isin
        r.parents('tr').removeClass('selected');
        // If nothing is selected, disable the watchlist button
        if ($('#ie_content tbody tr.selected').length == 0) {
            $('.buttonWatchlist').val('My watchlist').attr('disabled', 'true').removeAttr('action');
        }
    }
}
// Toggle advanced filters
// --------------------------------------------
function toggleAdvanced(d) {
    if (d != 'show') {
        $('#f_advanced').slideUp();
    }
    else {
        $('#f_advanced').slideDown();
        // Arrange labels across the length
        $('.slider').each(function () {
            $(this).find('div').css('width', $(this).width() / $(this).children().length + 'px');
        });
    }
}
// Check valuation units value, store and calculate
// --------------------------------------------
function insertUnits(u, ft) {
    if (u.value != '') {
        if (!IsNumeric(u.value)) {
            alertUser('Please only use numbers in this field');
            u.value = $(u).attr('oldVal') ? $(u).attr('oldVal') : '';
            u.focus();
        }
        else {
            calculateVal(u, ft);
            // Store values in cookie, if the fund is in the watchlist
            if (watchList) {
                var thisISIN = $(u).parents('tr').attr('isin');
                for (i = 0; i < watchList.length; i++) {
                    if (thisISIN == watchList[i].split(',')[0]) {
                        watchList[i] = (thisISIN + ',' + u.value);
                    }
                }
                $.cookie(siteName, watchList.join(';'), { expires: 90 });
            }
        }
    }
}
// Calculate valuation totals
// --------------------------------------------
function calculateVal(i, ft) {
    if (!ft) var ft = $(i).parents('.fundtype');
    var price = $(i).parents('tr').find('.price').text().replace(/p|£/g, '').trim();
    if (!price) {
        alertUser('There is no price data for this fund');
        i.value = '0';
        return false;
    }
    var iValue = ft.is('#oeics') || ft.is('#trusts') ? i.value * price / 100 : i.value * price;
    $(i).parent().next().find('input').val(CurrencyFormatted(iValue)).attr('raw', iValue);
    // Append totals
    var subTotalValue = 0;
    var totalValue = 0;
    var grandTotal = 0;
    ft.find('.inputValue[raw]').each(function () {
        subTotalValue = (subTotalValue + parseFloat($(this).attr('raw')));
    });
    ft.find('.inputTotalValue').val(CurrencyFormatted(subTotalValue)).attr('raw', subTotalValue)
    $('#ie_content .inputTotalValue[raw]').each(function () {
        grandTotal = (grandTotal + parseFloat($(this).attr('raw')));
    });
    $('#ie_content #inputGrandTotal').val(CurrencyFormatted(grandTotal));
}
// Group share classes according to funds
// --------------------------------------------
function groupShareClasses() {
    $('.fundtype:visible').each(function () {
        $(this).find('tr.fund').remove();
        colspan = $(this).find('th:visible').length;
        // Save fundtype
        var ft = $(this).attr('id');
        $(this).find('tr[@isin]').each(function () {
            var s = $(this);
            var f = $(this).attr('fund');
	    var dis = $(this).attr('Disclaimers');
	
            // Fix ampersand on the fund name link
            var fsLink = s.find('.fundname a');
            if (fsLink.length > 0) {
                fsLink.attr('href', fsLink.attr('href').replace(' &', ' and'));
            }
            // Hide link to techrules ffs if a flag is set
            s.find('a[nolink="True"]').each(function () {
                $(this).parent().html($(this).text()).parents('tr').find('.docs:first img, .documents:first img').remove();
            });
            // Change link to techrules ffs if there's a manual PDF attribute
            s.find('a[ManualPDF!=""]').each(function () {
                $(this).attr('href', '../GetFile.aspx?File=' + $(this).attr('ManualPDF'));
            });
            // Mark prices as pence for IT and OEICs
            if (ft == 'trusts' || ft == 'oeics') { $('.price', s).append('p'); }
            else { $('.price', s).prepend('£'); }
            // Add fund rows, with optional homepage icons
            if (f && (!s.prev() || !s.prev().attr('fund') || s.prev().attr('fund') != f)) {

		if(dis == undefined ) {dis=''} else {f = f + ' ' + dis;}

                c = typeof featuredFunds != 'undefined' && featuredFunds.indexOf(s.attr('isin')) != -1 ? 'featured' : '';
                link = s.attr('homepage') ? '<a href="' + siteRoot + s.attr('homepage') + '">' + f + '</a>' : f;
                s.before('<tr class="fund ' + c + '"><td class="fundlabel" colspan="' + colspan + '">' + link + '</td></tr>');
            }
        });
    });
    // Prepopulate cookies value
    if ($('#ie_tabs #vals').is('.on') && watchList) {
        for (i = 0; i < watchList.length; i++) {
            var units = $('#ie_content tr[isin=' + watchList[i].split(',')[0] + '] .inputUnits');
            if (units.length > 0 && watchList[i].split(',')[1] > 0) {
                units.val(watchList[i].split(',')[1]);
                calculateVal(units[0]);
            }
        }
    }
    // Add featured icons
    $('.featured td').append('<img src= "' + siteRoot + '/_images/icon_star.Gif" class="icon_featured" alt="Featured fund" />');
}
// Load external data
// --------------------------------------------
function ajaxLoad(fundtype, tab, isinList, featured) {
    if (!fundtype && $('#f_ranges li.on').length > 0) { fundtype = $('#f_ranges li.on').attr('class').split(' on')[0].split(' hover')[0]; }
    if (!tab) { tab = $('#ie_tabs .on').length > 0 ? $('#ie_tabs .on').attr('id') : $('#ie_tabs div:first').addClass('on').attr('id'); }
	currTab = tab;
   var dataUrl = siteRoot + '/data/';
    if (isinList) { dataUrl += "_dynamic.aspx?featured=false&isinlist=" + isinList + "&x=y"; }


    else if (featured) { dataUrl += "_dynamic.aspx?featured=false&isinlist=" + featuredFunds + "&x=y"; 
				currArea = 'featuredfunds'
						}
    else { dataUrl += '_' + fundtype + '_' + tab + '.aspx'; 
				currArea= fundtype;
		}
    /*  Added by Shrikant under CAS-06848-5YWZ  */
    document.getElementById("inputGrandTotal").value = "0.00";
    $.ajax({
        type: 'GET',
        url: dataUrl,
        beforeSend: function () {
            toggleLoader('show');
        },
        success: function (msg) {
            $('.fundtype').remove();
            if (msg.indexOf('fundtype') != -1) {
                $('#quickValsTotal').before(msg);
                // Custom table sorting for risk rating and launchdate
                $.tablesorter.addParser({
                    id: 'riskrating',
                    is: function (s) { return false; },
                    format: function (s) {
                        return s.trim().toLowerCase().replace(/very low/, 0).replace(/low/, 1).replace(/medium/, 2).replace(/high/, 3).replace(/very high/, 4);
                    },
                    type: 'numeric'
                });
                $.tablesorter.addParser({
                    id: 'launchdate',
                    is: function (s) { return false; },
                    format: function (s) {
                        return Date.fromDDMMYYYY(s.trim());
                    },
                    type: 'numeric'
                });

                var args = tab == 'keyfacts' || isinList || featured ? { headers: { 4: { sorter: 'riskrating' }, 7: { sorter: 'launchdate'}}} : '';

/*added by Shrikant under CAS-08218*/

                var args = tab == 'keyfacts' ? { headers: { 6: { sorter: 'launchdate'}}} : '';

                $('#ie_content table').tablesorter(args);
                // Get investment trust data
                var t = $('#ie_content div[id=trusts] table');
                if (t.length > 0) {
                    $.ajax({
                        type: 'GET',
                        cache: false,
                        url: siteRoot + '/Proxy.aspx?Location=http://jpmf.screenfinance.com/create-xml.asp',
                        success: function (data) {
                            var data = ensureXML(data);
                            $('SHARECLASS', data).each(function () {
                                t.find('tr[@isin=' + $(this).find('ALT_CODE_ISIN').text() + '] td._nav').text($(this).find('PRICE_NAV_AM').text());
                                t.find('tr[@isin=' + $(this).find('ALT_CODE_ISIN').text() + '] td._currentprice').text($(this).find('CURRENT_PRICE').text());
                                t.find('tr[@isin=' + $(this).find('ALT_CODE_ISIN').text() + '] td._change').text(($(this).find('CURRENT_PRICE').text() - $(this).find('CLOSING_MID_PRICE').text()).toFixed(2));
                                t.find('tr[@isin=' + $(this).find('ALT_CODE_ISIN').text() + '] td._midprice').text($(this).find('CLOSING_MID_PRICE').text());
                                t.find('tr[@isin=' + $(this).find('ALT_CODE_ISIN').text() + '] td._discount').text($(this).find('DISCOUNT_PREMIUM').text());
                            });
                            var chCol = getColumnIndex('Price change', t);
                            t.find('tr td:nth-child(' + chCol + ')').each(function () {
                                if (parseFloat($(this).text()) > 0) {
                                    $(this).addClass('up');
                                }
                                else if (parseFloat($(this).text()) < 0) {
                                    $(this).addClass('down');
                                }
                                else {
                                    $(this).addClass('same');
                                }
                            });
                            t.find('tr.fund').remove();
                            t.trigger('update');
                            toggleLoader('hide');
                            groupShareClasses();
                        }
                    });
                }
                // Fund type toggles
                if ($('#ie_content h2').length > 1) {
                    $('#ie_content h2').click(function () {
                        if (!$(this).is('.disabled')) {
                            if ($(this).find('.toggle').is('.collapse')) {
                                $(this).parent().find('table').hide();
                                $(this).find('.toggle').removeClass('collapse').addClass('expand');
                            }
                            else {
                                $(this).parent().find('table').show();
                                $(this).find('.toggle').removeClass('expand').addClass('collapse');
                            }
                        }
                    });
                }
                else {
                    $('#ie_content h2').css('cursor', 'default').find('.toggle').remove();
                }
                // Arrange mouseover behaviour for IE6
                $('#ie_content table th').mouseover(function () {
                    $(this).addClass('hover');
                }).mouseout(function () {
                    $(this).removeClass('hover');
                });
                // If a fundtype has changed, populate dropdown menus from filters
                if ($('#f_advanced').is(':visible')) {
                    if ($('#ie_filters select option[value!=All]').length == 0 || fundtype != currFundType) {
                        $('#ie_filters select').each(function () {
                            $(this).find('option[value!=All]').remove();
                            var aryOptions = [];
                            var menu = $(this);
                            var filter = $(this).attr('name');
                            // Run through the rows and get unique list of options
                            $('#ie_content tbody tr[@' + filter + ']').each(function () {
                                if ($(this).attr(filter).trim() != '' && $.inArray($(this).attr(filter).trim(), aryOptions) == -1) {
                                    aryOptions.push($(this).attr(filter).trim());
                                }
                            });
                            // Populate the fiter with options
                            for (i = 0; i < aryOptions.length; i++) {
                                $(this).append('<option value="' + aryOptions[i] + '">' + aryOptions[i] + '</option>');
                            }
                        });
                        // Reset all filters and remember the last fundtype
                        currFundType = fundtype;
                        resetFilters('#f_all');
                    }
                    // If it hasn't, apply all the filters
                    else {
                        filterRows();
                    }
                }
                // Draw screen options depending on the tab
                if (isinList || featured) {
                    $('#' + tab).addClass('on');
                    filterColumns(tab);
                }
                else {
                    redrawScreen(tab);
                }
                // Group share classes if there's no IT
                if (t.length == 0) { groupShareClasses(); }
                // Switch watchlist items
                markWatchlistItems();
            }
            else {
                $('#ie_buttons2').before('<div class="noresult">No funds were found.</div>');
            }
            toggleLoader('hide');
        }
    });
}
// Initiate screen after new data is loaded
// --------------------------------------------
function redrawScreen(tab) {

	FundXplorerTabRecord(tab,currArea);
	
    // Rearrange fund-level colspan 
    $('.fundtype').each(function () {
        colspan = $(this).find('th:visible').length;
        $(this).find('tr.fund td').attr('colSpan', colspan).attr('colspan', colspan);
        $(this).find('tfoot td:first').attr('colSpan', colspan - 1).attr('colspan', colspan - 1);
    });
    // Set default tab options
    $('#ie_content tfoot, .smallPrint:visible').hide();
    $('thead, .buttonDownload, .buttonPrint, .highbridge').show();
    $('tr.temphide').show();
    // Draw options depending on selected tab
    switch (tab) {
        case 'vals':
            $('.fundtype').each(function () {
                var ft = $(this);
                // Initiate valuations boxes
                ft.find('.inputUnits').focus(function () {
                    if (this.value != '0') { $(this).attr('title', this.value); }
                    else { this.value = ''; }
                }).blur(function () {
                    insertUnits(this, ft);
                });
            });
            $('#ie_content tfoot, #ie_content tfoot *').show();
            $('.fundname').css('width', '450px');
            if ($('#trusts').length > 0) {
                $('.ITsmallPrint').show();
            }
            if ($('.fundtype:not(#trusts)').length > 0) {
                $('.smallPrint').eq(1).show();
            }
            $('.smallPrint').eq(2).insertBefore($('.smallPrint').eq(1)).show();
            break;
        case 'keyfacts':
            $('#ie_content table').each(function () {
                // Find Morning Star column and substitute contents
                var msCol = getColumnIndex('Morning Star Rating', $(this));
                if (msCol) {
                    $(this).find('tbody tr td:nth-child(' + msCol + ')').each(function () {
                        r = $(this).text().trim().length;
                        $(this).empty();
                        for (i = 0; i < r; i++) {
                            $(this).append('<img src="' + siteRoot + '/_images/micropal_star.gif" alt="Star rating" />')
                        }
                    });
                }
            });
            $('#ie_content #trusts .morningstar').hide();
            $('.smallPrint').eq(0).show();
            $('.fundname').css('width', '210px');
            break;
        case 'prices':
            // Draw ticks and icons
            $('#ie_content table').each(function () {
                // Find XD column and substitute contents
                var xdCol = getColumnIndex('XD', $(this));
                if (xdCol) {
                    $(this).find('tbody tr td:nth-child(' + xdCol + ')').each(function () {
                        if ($(this).text() == '' || $(this).text().trim() == '0') { $(this).text(''); }
                        else { $(this).text('').addClass('tick').attr('title', 'Fund in accounting period'); }
                    });
                }
                // Add arrows for price change
                var chCol = getColumnIndex('Change', $(this));
                if (chCol) {
                    $(this).find('tbody tr td:nth-child(' + chCol + ')').each(function () {
                        if (parseFloat($(this).text()) > 0) { $(this).addClass('up'); }
                        else if (parseFloat($(this).text()) < 0) { $(this).addClass('down'); }
                        else { $(this).addClass('same'); }
                    });
                }
            });
            if ($('#trusts').length > 0) {
                $('.ITsmallPrint').show();
            }
            if ($('.fundtype:not(#trusts)').length > 0) {
                $('.smallPrint').eq(1).show();
            }
            $('.fundname').css('width', '370px');
            break;
        case 'docs':
            $('.fundname').css('width', '690px');
            $('#ie_content table tbody').find('a[href$="}"], a[href$="="]').remove();
            $('.buttonDownload, .buttonPrint').hide();
            break;
        case 'objectives':
            $('#ie_content').find('thead, .first, .fundname').hide();
            // As objectives are fund-specific, filter out rows with the same fund name
            $('#ie_content table tbody tr:not(.fund)').each(function () {
                if ($(this).next() && $(this).next().attr('fund') == $(this).attr('fund')) {
                    $(this).addClass('temphide').hide();
                }
            });
            break;
    }
}
// Find column index
// --------------------------------------------
function getColumnIndex(header, table) {
    var colIndex = '';
    table.find('th').each(function () {
        if ($(this).text().trim().toLowerCase() == header.trim().toLowerCase()) {
            colIndex = ($(this).parent().children().index(this) + 1);
        }
    });
    return colIndex;
}
// Display alert for user
// --------------------------------------------
function alertUser(msg) {
    $('#ie_msg .msg').hide();
    $('#ie_msg .msg').text(msg).fadeIn(2000, function () {
        v = setTimeout('$(\'#ie_msg .msg\').fadeOut(200)', 2000);
    });
}
// Check if a value is numeric
// --------------------------------------------
function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}
// Format number for currency
// --------------------------------------------
function CurrencyFormatted(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '\u00A3' + num + '.' + cents);
}
// Date parsers
// --------------------------------------------
Date.prototype.toDDMMYYYYString = function () {
    return isNaN(this) ? 'NaN' : [this.getDate() > 9 ? this.getDate() : '0' + this.getDate(), this.getMonth() > 8 ? this.getMonth() + 1 : '0' + (this.getMonth() + 1), this.getFullYear()].join('/');
}
Date.fromDDMMYYYY = function (s) {
    return (/^(\d\d?)\D(\d\d?)\D(\d{4})$/).test(s) ? new Date(RegExp.$3, RegExp.$2 - 1, RegExp.$1) : new Date(s);
}
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }
// Make sure that data returned is in XML content type
function ensureXML(data) {
    var xml;
    if (typeof data == "string") {
        xml = new ActiveXObject("Microsoft.XMLDOM");
        xml.async = false;
        xml.loadXML(data);
    }
    else {
        xml = data;
    }
    return xml;
}






function updateWatchlistSharedCookies(thisWatchList)
{

		var sharedcookies;
        sharedcookies = siteName+'watchlist';
        sharedcookies = sharedcookies.toLowerCase();
        if(thisWatchList.length>0) {
			$.cookie(sharedcookies, thisWatchList.join(';'), { expires: 90 , path: '/' });
        }
        else
        {

			
			$.cookie(sharedcookies, '', { expires: 90 , path: '/' });

			sharedcookies = siteName+'fundvisits';
sharedcookies  = sharedcookies.toLowerCase();
			
$.cookie(sharedcookies, '', { expires: 90 , path: '/' });

        }
        
}

