$(document).ready(function()
{
    // DOM is ready

    $(function()
    {
        var conEmailMarketingFeeCampaign = 8;
        var conEmailMarketingFeeRecipient = .08;

        function isNumber(v)
        {
            var regex=/[0-9]/g;
            return regex.test(v);
        }

        function Currency(dblValue)
        {
            nStr = dblValue.toFixed(2);
            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 "&pound;" + x1 + x2;
        }

        function PanelShow()
        {
            $('.panel').animate({ height: "220px" }, 500, 'swing', function () { $('#username').focus(); } );
        }
        function PanelHide()
        {
            $('.panel').animate({ height: "0" }, 500, 'swing', function () { $('.panel').css('display', 'none'); } );
        }
        /*var items = $('.billboard ul li').size();
        for (i=1;i<=items;i++)
        {
            $('.billboard ul li:nth-child(' + i + ')').hide();
            $('.billboard ul li:nth-child(' + i + ')').fadeOut();
        }
        var timer;
        var billboardItem = 0;
		var donext = function (x)
		{
            if (billboardItem != 0)
            {
                $('.billboard ul li:nth-child(' + billboardItem + ')').fadeOut();
                //$('.billboard ul li:nth-child(' + billboardItem + ')').hide();
            }
            billboardItem++;
            if (billboardItem > items)
            {
                billboardItem = 1;
            }
            //show next billboard item
            
            //$('.billboard ul li:nth-child(' + billboardItem + ')').show();
            $('.billboard ul li:nth-child(' + billboardItem + ')').fadeIn('slow');

			if(timer != null)
			{
                clearInterval(timer);
            }
			timer = setInterval(function() { donext(); }, 5000);
		}
		donext();
		*/

        //check the current url and update the navigation if it matches
        var url = window.location.pathname.split('/');
        var strURL = "/";
        var strFolder = window.location.pathname;
        if (url.length >= 3)
        {
            strURL = "/" + url[1] + "/";
        }
        if (url.length >= 4)
        {
            strFolder = "/" + url[1] + "/" + url[2] + "/";
        }
        $(".menu ul li a[href='" + strURL + "']").parent('li').addClass('selected');
        $(".side ul li a[href='" + strFolder + "']").parent('li').addClass('selected');

        //swap the border outline on focus and blur
        $('.content input,.content textarea,.panel input,.panel textarea').focus(function() { $(this).addClass('selected'); });
        $('.content input,.content textarea,.panel input,.panel textarea').blur(function() { $(this).removeClass('selected'); });
        $('.panel input,.panel textarea').focus(function() { $(this).addClass('selected'); });
        $('.panel input,.panel textarea').blur(function() { $(this).removeClass('selected'); });
        switch (window.location.pathname)
        {
            case "/login.asp":
            case "/password-reminder.asp":
                $('#txtemail').focus();
                break;
            default:
                $('#txtfirstname').focus();
        }
        $('#btnlogin').click(function ()
        {
            if ($('.panel').css('display') == 'none')
            {
                PanelShow();
            } else {
                PanelHide();
            }
            return false;
        });
        
        $('#username').focus(function ()
        {
            if ($('#username').attr('defaultValue') == $('#username').val())
            {
                $('#username').val("");
            } else {
                $('#username').select();
            }
        });
        $('#username').blur(function ()
        {
            if ($('#username').val() == "")
            {
                $('#username').val($('#username').attr('defaultValue'));
            }
        });

        $("#editable").dblclick( function()
        {
            document.getElementById('editable').designMode = 'On'; 		// Moz, Op, Saf
            document.getElementById('editable').contentEditable = true;	// Op, IE, Saf
            $("#editable").focus();
            return false;
        });
        $(document).keydown( function(e)
        {
            switch(e.keyCode)
            {
                // user presses the "a"
                case 27:
                    if ($('.overlay').css('display') == 'none')
                    {
                        if ($('.panel').css('display') == 'none')
                        {
                            $('.panel').css('display', 'block');
                            
                            var st = Number(parseInt($(window).scrollTop()));
                            if (st > 0)
                            {
                                $('html, body').animate({scrollTop: (0) }, 500, 'swing', function () { PanelShow() } );
                            } else {
                                PanelShow();
                            }                            
                        } else {
                            PanelHide();
                        }
                    } else {
                        $('.overlay .close').click();
                    }
                    break;	
                default:
                    break;	
            }
        });
        
        /* overlay panel */
        $('.gallery a.thumb').click(function ()
        {
            $('.overlay').html("<div class='large'></div><div class='choice'></div><div class='close' title='Close [esc]'></div>");
            $('.overlay').css(
            {
                top: parseInt($(window).scrollTop() + (($(window).height() - $('.overlay').height())/2)) + 'px',
                left: parseInt($(window).scrollLeft() + (($(window).width() - $('.overlay').width())/2)) + 'px'
            });
            $('.gallery a.thumb').removeClass('selected');
            $(this).addClass('selected');
            $('.overlay .choice').html($(this).parent().html());
            if($.browser.msie)
            {
                $('.overlay').show();
            } else {
                $('.overlay').fadeIn(500);
            }
            $('.overlay .large').html("<img src='" + $(this).attr("href") + "' />");
            return false;
        });
        
        $('.overlay .close').live('click', function ()
        {
            if($.browser.msie)
            {
                $('.overlay').hide();
                $('.overlay').html("");
            } else {
                $('.overlay').fadeOut(500, function () { $('.overlay').html(""); } );
            }
        });

        $('.overlay .choice a').live('click', function ()
        {
            $('.overlay .large img').attr('src', $(this).attr('href'));
            $('.overlay .choice a').removeClass('selected');
            $(this).addClass('selected');
            return false;
        });
        
        /* automatic tab creation */
        var tabHeaders = $('.tabx h2');
        if (tabHeaders.length>0)
        {
            $('.tabx h2').remove();
            $('.tabx').prepend(tabHeaders);
            $('.tabx').addClass('tabs');
            $('.tabs').addClass('tabx');
            $('.tabs h2').wrapAll("<div class='tabstrip'><\/div>");
            $('.tabs h2').live('click', function ()
            {
                var i = $('.tabs h2').index(this);
                $('.tabs .tab').hide();
                $('.tabs .tab:eq(' + i + ')').show();
                $('.tabs h2').removeClass('selected');
                $('.tabs h2:eq(' + i + ')').addClass('selected');
            });
            $('.tabs .tab').hide();
            $('.tabs .tab:eq(0)').show();
            $('.tabs h2').removeClass('selected');
            $('.tabs h2:eq(0)').addClass('selected');
            console.log(url);
        }

        $('#txtsearch').focus( function()
        {
            $('#txtsearch').removeClass('inactive');
            if ($('#txtsearch').val() == "search this site")
            {
                $('#txtsearch').val("");
            }
            return false;
        });
        $('#txtsearch').blur( function()
        {
            $('#txtsearch').addClass('inactive');
            if ($('#txtsearch').val() == "")
            {
                $('#txtsearch').val("search this site");
            }
            return false;
        });
        $('.noautocomplete').attr('autocomplete', 'off');
        
        if ($('h1').text() == "Environment")
        {
            $('.container').addClass('eco');
            $('.panel').addClass('panel_eco');
            $('#btnlogin').attr('src', '/_images/login3_eco.gif');
        }
        
        $('blockquote.bubble').append('<span class="arrow" />');
        
        if ($('#map').length>0)
        {
            GoogleMap();
            $('#mapzoomin').click( function()
            {
                map.setCenter(new GLatLng(52.89258226860718, -1.2604424357414246), 17);return false;
                return false;
            });
            $('#mapzoomout').click( function()
            {
                map.setCenter(new GLatLng(52.89258226860718, -1.2604424357414246), 11);return false;
                return false;
            });
            $('#showaddress').click( function()
            {
                showAddress($('#addresstosearch').val());
                return false;
            });
            $('#showaddressfull').click( function()
            {
                showLocation($('#addresstosearch').val());
                return false;
            });

        }
        if ($('.calculator').length>0)
        {
            $('.calculator #frmcalc').submit(function ()
            {
                $('.alert').hide();
                var lngRecipients = $('#txtrecipients').val();
                if (isNaN(lngRecipients) == true)
                {
                    lngRecipients = 100;
                    $('#txtrecipients').val(100);
                    $('.alert').html("<div class='warning'><p>Sorry but as you entered characters other than numbers I was not able to work out what you wanted, could you try just using the number this time please.<\/p><\/div>");
                    $('.alert').fadeIn(500);
                }
                if (lngRecipients.length>=5)
                {
                    lngRecipients = 100;
                    $('#txtrecipients').val(100);
                    $('.alert').html("<div class='warning'><p>Sorry but you entered a number larger than I wanted to try and work out, could you try a smaller one below 10,000 please.<\/p><\/div>");
                    $('.alert').fadeIn(500);
                }
                var dblAnswer = 0;
                if (lngRecipients > 5)
                {
                    $('#lblrecipients').text(lngRecipients);
                    dblAnswer = dblAnswer + (lngRecipients * conEmailMarketingFeeRecipient);
                    $('#lbltotal').html(Currency(dblAnswer));
                    dblAnswer = dblAnswer + (conEmailMarketingFeeCampaign);
                    $('#lblanswer').html("<b>" + Currency(dblAnswer) + "<\/b>");
                    $('#lblgrandtotal').html(Currency(dblAnswer));
                    $('#txtrecipients').select();
                } else {
                    $('.answer').html("No Charge");
                }
                return false;
            });
            $('#txtrecipients').focus(function ()
            {
                $('#txtrecipients').select();
            });
            $('#txtrecipients').keydown(function (e)
            {
            });
            $('#txtrecipients').focus();
            $('#lblchalkboard').fadeIn();
            $('#lblchalkboard').click(function ()
            {
                $('.chalkboard').fadeIn();
                $('#lblchalkboard').fadeOut();
                $('#lblanswer').fadeOut();
                $('#txtrecipients').focus();
                return false;
            });
        }
        $('dfn').mouseenter(function ()
        {
            $(this).attr('title', '');
            var lngID = $(this).attr('id');
            var dfnLeft = parseInt($(this).position().left);
            var dfnTop = parseInt($(this).position().top);
            var dfnWidth = parseInt($(this).width());
            var dfnHeight = parseInt($(this).height());
            
            /*
            $.ajax(
            {
                url: "/_api/glossary.asp",
                global: false,
                type: "json",
                data: (
                {
                    id : lngID
                }),
                dataType: "html",
                success: function(obj)
                {
                    alert(obj.term);
                    alert(obj.definition);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { },
                complete: function (XMLHttpRequest, textStatus) { }
            });
            */
            $.getJSON('/_api/glossary.asp', { id: lngID }, function(json)
            {
                $('.popup').remove();
                $('body').append("<div class='popup'><div class='top'>" + json.definition + "<\/div><div class='bottom'><\/div><\/div>");
                var popWidth = parseInt($('.popup').width());
                var popHeight = parseInt($('.popup').height());
                $('.popup').css( { 'top': (dfnTop-popHeight) + 'px', 'left': (dfnLeft - ((popWidth-dfnWidth)/2)) + 'px' } );
                if ($.browser.msie)  
                {
                    $('.popup').show();
                } else {
                    $('.popup').fadeIn(200);
                }
            });
        });
        $('dfn').mouseleave(function ()
        {
            $('.popup').remove();
        });
        $('.search').mouseenter(function ()
        {
            $('.search').fadeTo('fast', 1);
        });
        $('.search').mouseleave(function ()
        {
            $('.search').fadeTo('slow', .4);
        });
        $('.search').fadeTo('fast', .4);
        
        /* highlights all title tags where the title tag is empty */
        $('a[title=""]').addClass('missing_title');
        $('img[alt=""]').wrap("<div class='missing_alt_wrapper'></div>");
        $('img[alt=""]').after('<span class="missing_alt">&nbsp;</span>');
        if ($('#cu3er-container').length > 0)
        {
            var flashvars = {};
            flashvars.xml = "/_data/config.xml";
            flashvars.font = "/_images/blank.gif";
            var attributes = {};
            attributes.wmode = "transparent";
            attributes.id = "slider";
            swfobject.embedSWF("/_flash/cu3er.swf", "cu3er-container", "960", "300", "9", "expressInstall.swf", flashvars, attributes);
        }
        
    });
});

