var jQueryScriptOutputted = false;


function initJQuery() {
    
    //if the jQuery object isn't available
    if (typeof (jQuery) == 'undefined') {

        if (!jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;

            //output the script (load it from google api)
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {

        $(function () {
            enhancedUI();
        });
    }

}
initJQuery();

// check if current site should have 
function siteReady() {
    if (location.href.toLowerCase().indexOf('/new/it/') > -1) {
        return true;
    } else {
        return false;
    }
}

// temporarily hide the libary to avoid flicker
//if (siteReady()) { document.getElementById('frmLiterature').style.display = 'none'; }


function enhancedUI() {

    // ----------------- Clean-up document library ---------------------

    if ($('#frmLiterature').length && siteReady()) {

        // swap class for new style
        $('#contentcontainer').addClass('library').addClass('rounded').attr('id', '');
        var $l = $('.library');
        
        // remove redundant tables
        $('> table, br', $l).remove();
        $('#tblLiteratureAreas').css('width', '100%');

        $('.library > div > table').each(function () {

            // add header
            $(this).parent().before('<h3>' + $('tr:first td:nth-child(2)', this).text() + '</h3>');

            // cleaup
            $('tr:first, tr td:first, img', this).addClass('toRemove');
            $('*', this).removeAttr('style');
            $('td[colspan=3]').addClass('toRemove');
            $('td', this).attr('colspan', 1);

            // show all
            $('tr', this).show();

            // add icon
            $('a', this).addClass('pdf');

            // clean up header
            $(this).prepend('<thead><tr><th>Download</th><th>Order copies</th></tr></thead>');

        })

        $('.toRemove').remove();
        $l.show();
    }

    //  ---------------- Alternating rows --------------------
    //$('.library tbody tr:even td').addClass('alt');
    $('.library tr').each(function () {
        if (!$(this).parents('#tblLiteratureAreas').length)
            $('td:first,th:first', this).addClass('first');
    });

    $('.library h3:first, .library tr:last td').css('border', '0px');
    $('.library h3')
        .hover(function () {
            $(this).toggleClass('over');
        })
        .click(function () {

            var openNew = $(this).is('.open') ? false : true;
            $('.library div.open').slideToggle(600).removeClass('open');
            $('.library h3.open').removeClass('open');

            if (openNew) {
                $(this).next().slideToggle(600).addClass('open');
                $(this).toggleClass('open');
            }
        });

    $('.library h3:first').trigger('click');

    //  ---------------- Tabs --------------------
    // Fade tabs and buttons on mouseover
    $('#tabs li').hover(
        function () {
            if (!$(this).is('.tabOn')) $(this).fadeTo(200, 0.5);
        },
        function () {
            if (!$(this).is('.tabOn')) $(this).fadeTo(10, 1);
        })
		.click(function () {
		    $(this).fadeTo(10, 1);
		});


    //  ---------------- jCarousel --------------------
    if ($('#carousel').length) {

        // Append next / prev buttons
        $('#carousel').prepend('<div class="slidenav prev disabled"><a href="#"></a></div>');
        $('#carousel').append('<div class="slidenav next"><a href="#"></a></div>');

        var currSlide = 0,
            totalSlides = $('#carousel li').length,
            slideW = $('#carousel li:first').width();

        // Set carousel with to the sum of its slides
        $('#carousel ul').css('width', totalSlides * slideW + 'px');

        // Move slides as per user click
        $('#carousel .slidenav a').click(function () {
            if (!$(this).parent().is('.disabled')) {
                var newSlide = $(this).parent().is('.prev') ? currSlide - 2 : currSlide + 2;

                // Toggle buttons on start / end
                if (newSlide > 0) $('#carousel .slidenav.prev').removeClass('disabled');
                else $('#carousel .slidenav.prev').addClass('disabled');

                if (newSlide < totalSlides - 2) $('#carousel .slidenav.next').removeClass('disabled');
                else $('#carousel .slidenav.next').addClass('disabled')

                currSlide = newSlide;
                $('#carousel ul').animate({ left: -slideW * currSlide + 'px' }, 1000);
            }
            return false;
        });

    }


    //  ---------------- News scroller --------------------

    if ($('#newsticker').length) {
        var $n = $('#newsticker ul');
        var newsW = $n.width();
        
        // Duplicate the scroller to remove any blank views 
        $n.append($n.html()).css('width', newsW * 2 + 'px');

        // Do animation
        function scrollStory() {
            pos = $n.position();
            // Start again if we reach the original width
            if (Math.abs(pos.left) > newsW) {
                $n.css('left', 0 + 'px');
                scrollStory();
                return;
            }
            $n.animate({ left: (pos.left - 1) + 'px' }, 1, function () {
                if (!pauseScroll) scrollStory();
            });
        }

        // Pause when mouse goes over a lunk
        var pauseScroll = false;
        $('#newsticker a')
		    .mouseover(function () {
		        pauseScroll = true;
		    })
		    .mouseout(function () {
		        pauseScroll = false;
		        scrollStory();
		    });

        scrollStory();
    }

    // Minified jQuery cookie plugin
    eval(function (p, a, c, k, e, d) { e = function (c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) { d[e(c)] = k[c] || e(c) } k = [function (e) { return d[e] } ]; e = function () { return '\\w+' }; c = 1 }; while (c--) { if (k[c]) { p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]) } } return p } ('m.b=i(c,3,0){7(p.v>1&&(3===6||d 3!=="q")){0=m.u({},0);7(3===6){0.2=-1}7(d 0.2===\'o\'){g e=0.2,t=0.2=l r();t.z(t.C()+e)}4(n.b=[9(c),\'=\',0.j?h(3):9(h(3)),0.2?\'; 2=\'+0.2.A():\'\',0.5?\'; 5=\'+0.5:\'\',0.8?\'; 8=\'+0.8:\'\',0.f?\'; f\':\'\'].w(\'\'))}0=3||{};g a,k=0.j?i(s){4 s}:x;4(a=l y(\'(?:^|; )\'+9(c)+\'=([^;]*)\').B(n.b))?k(a[1]):6};', 39, 39, 'options||expires|value|return|path|null|if|domain|encodeURIComponent|result|cookie|key|typeof|days|secure|var|String|function|raw|decode|new|jQuery|document|number|arguments|object|Date|||extend|length|join|decodeURIComponent|RegExp|setDate|toUTCString|exec|getDate'.split('|'), 0, {}))
    
    
    //  ---------------- Breadcrumbs and social bookmarking tools --------------------
    if (siteReady() && !$('#navigation li:first').is('.navOn') && !$('#quicklinks_home:visible').length) {
        if (!$('#breadcrumbs').length)
            $('#content').before('<div id="breadcrumbs"></div>');

        var $b = $('#breadcrumbs'),
            $li = $('li.navOn, li.subnavOn, li.lastnavOn', $('#navigation'));

        if ($li.length) {
            $b.append('<a href="./">Home</a>');
            $li.each(function (i, item) {
                $b.append(' / <a href="' + $('> a', this).attr('href') + '">' + $('> a', this).text().concat($(this).is('.lastnavOn') ? 26 : 40) + '</a>');
            });
        }

        var toolHTML = '<script language="javascript" type="text/javascript">var addthis_config = {"data_track_clickback":true}; </script>'
                        + '<div id="social-bookmarks"><a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=fcam1868"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>';

        var fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", "http://s7.addthis.com/js/250/addthis_widget.js#username=fcam1868");
        $b.after(toolHTML);
        setTimeout(function () {
            document.getElementsByTagName("head")[0].appendChild(fileref);    
        }, 10);
    }

    //  ---------------- RSS reader --------------------

    if ($('.rssFeed').length) {
        // Minified jFeed
        eval(function (p, a, c, k, e, d) { e = function (c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } ('3.X=a(h){h=3.J({v:D,C:D,u:D},h);k(h.v){$.W({t:\'V\',v:h.v,C:h.C,U:\'4\',u:a(4){d f=j B(4);k(3.T(h.u))h.u(f)}})}};a B(4){k(4)2.K(4)};B.r={t:\'\',l:\'\',c:\'\',b:\'\',g:\'\',K:a(4){k(3(\'8\',4).y==1){2.t=\'x\';d s=j z(4)}H k(3(\'f\',4).y==1){2.t=\'S\';d s=j A(4)}k(s)3.J(2,s)}};a o(){};o.r={c:\'\',b:\'\',g:\'\',i:\'\',n:\'\'};a A(4){2.q(4)};A.r={q:a(4){d 8=3(\'f\',4).9(0);2.l=\'1.0\';2.c=3(8).5(\'c:e\').6();2.b=3(8).5(\'b:e\').p(\'I\');2.g=3(8).5(\'R:e\').6();2.w=3(8).p(\'4:Q\');2.i=3(8).5(\'i:e\').6();2.m=j G();d f=2;3(\'P\',4).F(a(){d 7=j o();7.c=3(2).5(\'c\').9(0).6();7.b=3(2).5(\'b\').9(0).p(\'I\');7.g=3(2).5(\'O\').9(0).6();7.i=3(2).5(\'i\').9(0).6();7.n=3(2).5(\'n\').9(0).6();f.m.E(7)})}};a z(4){2.q(4)};z.r={q:a(4){k(3(\'x\',4).y==0)2.l=\'1.0\';H 2.l=3(\'x\',4).9(0).p(\'l\');d 8=3(\'8\',4).9(0);2.c=3(8).5(\'c:e\').6();2.b=3(8).5(\'b:e\').6();2.g=3(8).5(\'g:e\').6();2.w=3(8).5(\'w:e\').6();2.i=3(8).5(\'N:e\').6();2.m=j G();d f=2;3(\'7\',4).F(a(){d 7=j o();7.c=3(2).5(\'c\').9(0).6();7.b=3(2).5(\'b\').9(0).6();7.g=3(2).5(\'g\').9(0).6();7.i=3(2).5(\'M\').9(0).6();7.n=3(2).5(\'L\').9(0).6();f.m.E(7)})}};', 60, 60, '||this|jQuery|xml|find|text|item|channel|eq|function|link|title|var|first|feed|description|options|updated|new|if|version|items|id|JFeedItem|attr|_parse|prototype|feedClass|type|success|url|language|rss|length|JRss|JAtom|JFeed|data|null|push|each|Array|else|href|extend|parse|guid|pubDate|lastBuildDate|content|entry|lang|subtitle|atom|isFunction|dataType|GET|ajax|getFeed'.split('|')))

        $.getFeed({
            url: 'blog.xml',
            success: function (feed) {
                var rssItems = [];
                for (i = 0; i < 6; i++) {
                    rssItems.push('<li>' + feed.items[i].title + '</li>');
                }
                $('.rssFeed ul').html(rssItems.join(''));
            }
        });
    }

    //  ---------------- Savings calculator--------------------

    if ($('#iCalc').length) {
        var seenCalcAlert = false,
            iCalc = function () {
                var lumpCalc = function (amount, term, rate) {
                    return (amount * (Math.pow((1 + rate), term))).toFixed(2);
                };
                var monthlyCalc = function (amount, term, rate) {
                    return ((amount / rate) * (Math.pow((1 + rate), term) - 1)).toFixed(2);
                }
                var iTerm = +$('#iTerm').val(),
				iMonthly = +$('#iMonthly').val(),
				iLumpSum = +$('#iLumpSum').val(),
				iGrowth = +$('#iGrowth').val() / 100,
				rMonthly = +monthlyCalc(iMonthly, iTerm * 12, iGrowth / 12),
				rLumpSum = +lumpCalc(iLumpSum, iTerm, iGrowth);

                if (iLumpSum > 1000000) {
                    alert('ERROR\nSorry, the maximum lump sum investment amount is &pound;1m. Please enter another amount.');
                } else if (iMonthly > 10000) {
                    alert('ERROR\nSorry, the maximum monthly investment amount is &pound;1m. Please enter another amount.');
                } else {
                    if (!seenCalcAlert) alert('IMPORTANT\nThese figures are only examples and are not guaranteed - they are not minimum or maximum amounts. They are examples of the effect of 4%, 6% and 8% growth on a lump sum investment and/or monthly savings. What you will get back depends on how your investment grows and on the tax treatment of the investment - the level of any tax benefits and liabilities will depend on individual circumstances and may change in the future. You could get back more or less than this. Don\'t forget that inflation would reduce what you could buy in the future with the amounts shown. The value of investments and the income from them may fall as well as rise and investors may not get back the full amount invested. Past performance is not a guide to the future.');
                    seenCalcAlert = true;
                    $('#rMonthly').text(String(rMonthly).addCommas());
                    $('#rLumpSum').text(String(rLumpSum).addCommas());
                    $('#rTotal').text(String((rMonthly + rLumpSum).toFixed(2)).addCommas());
                }
                return false;
            };

        $('#iCalc input')
            .focus(function () {
                $(this).data('oldVal', this.value);
            })
            .blur(function () {
                if (!$(this).val().isNumber()) {
                    $(this).val($(this).data('oldVal'));
                    return false;
                }
            });

        $('#iCalc').submit(function () {
            if (!$('#iCalc input[value=0]').length) { iCalc(); }
            return false;
        });
    }

    //  ---------------------- How to invest widget -----------------

    if ($('#how-wrapper').length) {

        // add step labelling 
        $('#how').prepend('<div id="how-panel"><a href="#reset" id="reset">Restart</a><a href="#back" id="how-back">Back one step</a><a href="#myshortslist" id="how-viewshortlist" disabled="disabled">My shortlist (<span>0</span> items)</a><a href="#clear" id="how-clear" disabled="disabled"">Remove all</a></div>');
        $('#how-panel').append('<div id="how-page"><ul><li>1</li><li>2</li><li>3</li><li>4</li></div>');

        // add shortlist buttons
        $('#trustlist div').append('<a href="#" class="how-add"><span>Add to</span> shortlist</a>');

        // user interaction
        $('#how button.more').click(function () {
            howto.move($(this).attr('rel'));
            return false;
        });

        $('#how button.save').click(function () {
            howto.save($(this).attr('rel'));
            return false;
        });

        $('#how-back').click(function () {
            howto.prev();
            return false;
        });

        $('#how-viewshortlist').click(function () {
            howto.shortlist();
            return false;
        });

        $('#how #reset').click(function () {
            howto.reset(true).move('how-1');
            return false;
        });

        $('#how-clear').click(function () {
            howto.empty();
            return false;
        });

        $('a.how-add').live('click', function () {
            howto.addtrust($('#trustlist div').index($(this).parent()));
            return false;
        });


        // app internals
        var howto = {

            // current screen id
            step: 'how-1',
            page: 1,

            // user selection - todo: save in cookie
            userObj: '',
            userTrusts: [],
            userTrustType: '',
            userPlan: '',

            // cookie options
            cookieOptions: {
                expires: 7
            },

            // move to specifc step
            move: function (id) {
                // toggle views
                //$('#' + this.step).hide();
                //$('#' + id).show();

                $('#' + this.step).fadeOut(200, function () {
                    $('#' + id).fadeIn(400);
                });
                /*var idx = $('#how .how-step').index($('#' + id));
                $('#how').animate({'margin-left': '-' + idx * 775 + 'px'}, 1000);*/

                // move paging            
                this.page = $('#' + id).is('.how-page') ? $('.how-page').index($('#' + id)) : $('.how-page').index($('#' + id).prevAll('.how-page'));
                if (!$('li:nth-child(' + this.page + ')', $('#how-page')).is('.on'))
                    $('li.on, li:nth-child(' + this.page + ')', $('#how-page')).toggleClass('on');

                // store new id
                this.step = id;
                $.cookie('userStep', id, this.cookieOptions);
                $.cookie('userPage', this.page, this.cookieOptions);
                this.fixUI();
            },

            // move to next page - not step
            next: function () {
                var nextid = $('#' + this.step).nextAll('.how-page').attr('id');
                this.move(nextid);
            },

            // move one step back - to the step which links to this one
            prev: function () {
                var prevStep = $('button[rel=' + this.step + ']').parents('.how-step'),
                previd = prevStep.length ? prevStep.attr('id') : $('#' + this.step).prevAll('.how-page').attr('id');
                this.move(previd);
            },

            // save user choice
            save: function (val) {
                switch (this.page) {
                    case 1:
                        this.userObj = val;
                        $.cookie('userObj', val, this.cookieOptions);
                        this.next();
                        break;
                    case 2:
                        this.userPlan = val;
                        $.cookie('userPlan', val, this.cookieOptions);
                        this.next();
                        break;
                    case 3:
                        this.userTrustType = val;
                        $.cookie('userTrustType', val, this.cookieOptions);
                        this.filter();
                        break;
                }
                return this;
            },

            // filter trusts by objective and trust type
            filter: function (stop) {
                $('#trustlist div').hide();
                $('#trustlist h2').text($('#how-4 button[rel=' + this.userTrustType + ']').siblings('h3').text());
                $('#trustlist div.' + this.userObj + ' h3' + (this.userTrustType == 'combination' ? '' : '.' + this.userTrustType)).parent().show();
                this.move('trustlist');
            },

            // clear shortlist
            empty: function () {
                this.userTrusts.length = 0;
                $.cookie('userTrusts', null);
                $('#trustlist div.how-shortlisted').removeClass('how-shortlisted').removeClass('how-shortlisted').find('a span').text('Add to');
                this.move('how-4');
            },

            // reset all values and start again,
            reset: function (check) {
                if (check && confirm('This will reset all your choices. Are you sure?')) {
                    this.userObj = this.userPlan = this.userTrustType = '';
                    this.userTrusts = [];
                    $.cookie('userObj', null);
                    $.cookie('userPlan', null);
                    $.cookie('userTrustType', null);
                    $.cookie('userTrusts', null);
                    $.cookie('userStep', null);
                    $.cookie('userPage', null);
                    return this;
                }
            },

            //shortlist functions
            shortlist: function () {
                $('#trustlist div').hide();
                $('#trustlist h2').text('My shortlist');
                $('#trustlist div.how-shortlisted').show();
                if (this.page != 'trustlist')
                    this.move('trustlist');
            },

            addtrust: function (idx) {
                // add or remove items and change the button label
                var arrayIdx = $.inArray(idx, this.userTrusts);
                if (arrayIdx == -1) {
                    this.userTrusts.push(idx);
                    $('#trustlist div').eq(idx).addClass('how-shortlisted').find('a span').text('Remove from');
                } else {
                    this.userTrusts.splice(arrayIdx, 1);
                    $('#trustlist div').eq(idx).removeClass('how-shortlisted').find('a span').text('Add to');
                    if ($('#trustlist h2').text() == 'My shortlist') {
                        if (this.userTrusts.length)
                            $('#trustlist div').eq(idx).fadeOut(400);
                        else
                            this.move('how-4');
                    }
                }
                $.cookie('userTrusts', this.userTrusts.join(','), this.cookieOptions);
                this.fixUI();
            },

            // arrange interaction controls
            fixUI: function () {
                if (this.step != 'how-1')
                    $('#how-panel').slideDown();
                else
                    $('#how-panel').slideUp();

                if (this.step != 'how-2')
                    $('#reset').show();
                else
                    $('#reset').hide();

                if (this.userTrusts.length)
                    $('#how-viewshortlist, #how-clear').removeAttr('disabled').find('span').text(this.userTrusts.length);
                else
                    $('#how-viewshortlist, #how-clear').attr('disabled', 'disabled').find('span').text(this.userTrusts.length);

            },

            // redraw from saved state
            init: function () {
                if ($.cookie('userStep') && $.cookie('userStep') != 'how-1') {
                    if (confirm('We see that you have used this tool before; would you like to continue from where you left off?')) {
                        this.userObj = $.cookie('userObj') || '';
                        this.userPlan = $.cookie('userPlan') || '';
                        this.userTrustType = $.cookie('userTrustType') || '';

                        // arrange trusts - need numbers
                        if ($.cookie('userTrusts')) {
                            var trusts = $.cookie('userTrusts').split(',');
                            $.each(trusts, function (i, trust) {
                                howto.userTrusts.push(+trust);
                            });
                        }

                        // show selected type
                        if (this.userTrusts.length) {
                            $.each(this.userTrusts, function (i, idx) {
                                $('#trustlist div').eq(idx).addClass('how-shortlisted').find('a span').text('Remove from');
                            });
                            this.shortlist();
                            // show shortlist
                        } else if (this.userTrustType) {
                            this.filter();
                            // redirect to saved step
                        } else {
                            this.move($.cookie('userStep') || '');
                        }
                        //this.fixUI();
                    } else {
                        this.reset(false);
                    }
                }
            }

        }

        // start'er up - delay if the cookie is not loaded yet
        if (typeof $.cookie == 'undefined') {
            setTimeout(function () { howto.init() }, 50);
        } else {
            howto.init();
        }
    }

};

String.prototype.addCommas = function () {
    var nStr = this;
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
String.prototype.isNumber = function () {
    var rgx = /^[1-9][0-9]*$/; // checks natural numbers (positive integers)
    return rgx.test(this);
}
String.prototype.concat = function (length) {
    var nStr = this,
        oStr = nStr.length < (+length) ? nStr.toString() : nStr.substring((+length - 3), 0) + '...';
    return oStr;
}
