
var drg = {
    isIe: function () { return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4); },

    // Function to add rounded corners
    round: function (els)
    {
        // Loop through passed in elements
        els.each(function (i, el)
        {
            $(el).css('position', 'relative');

            // Get width and heights to calculate positions due to IE6 bug
            var height = $(el).height();
            var width = $(el).width();

            $(el).css({ width: width, height: height });

            var size = '';
            var mod = 15;

            // Inject our corner elements
            $(el).prepend(
				$('<span class="ctl"></span>'),
				$('<span class="ctr"></span>').css('left', width - mod),
				$('<span class="cbr"></span>').css({ left: width - mod, top: height - mod }),
				$('<span class="cbl"></span>').css('top', height - mod)
			);
        });
    },

    // Used to split single paragraph into multiple on <br>'s
    pSplit: function (els, charLimit)
    {
        charLimit = charLimit || 50;
        $(els).each(function (i, el)
        {
            var fntS = parseInt($(el).css('font-size'));
            var html = $(el).text();
            var newHtml = '';
            var words = html.split(' ');

            var targ = $(el).children();
            targ = (targ.length > 0) ? targ[targ.length - 1] : el;

            $(targ).html('');

            var text = '';
            for (var i = 0; i < words.length; i++)
            {
                var word = words[i];

                if ((text.length + word.length) < charLimit && i !== words.length - 1)
                {
                    text += word + ' ';
                } else
                {
                    if (i == words.length - 1)
                    {
                        text += word;
                    }
                    newHtml += '<span class="pSplit">' + text + '</span>';
                    text = word + ' ';
                }
            }

            $(targ).html(newHtml);
        });
    },

    // Method to animate overlay content
    slideCont: function (els)
    {
        $(els).each(function (i, el)
        {
            var copy = $(el).children('.copy');
            var items = $(copy).children('*');

            $(items).css('margin-left', -2000);

            $(window).load(function ()
            {
                $(copy).css('top', Math.floor(($(el).height() - $(copy).height()) / 2));
                $(items).delay(i * 200).each(function (j, el)
                {
                    el = $(el);

                    el.delay(j * 100).animate({ marginLeft: 0 }, { duration: 1000, easing: 'easeOutExpo' });
                });
            });
        });
    },

    addHover: function (els, link)
    {
        $(els).mouseover(function () { $(this).addClass('hover'); });
        $(els).mouseout(function () { $(this).removeClass('hover'); });

        if (link)
        {
            $(els).click(function ()
            {
                var a = $(this).find('a');

                if (a)
                {
                    window.location = a[0].href;
                }
            });
        }
    },

    orders: function ()
    {
        $('.detailList').each(function (i, list)
        {
            var items = $(list).children('li');
            items.each(function (i, el)
            {

            });
        });

        // Report page
        if ($.inArray('report', drg.classes) !== -1)
        {
            var filter = $('.tools .filter');
            var cont = $(filter).children('div');

            $(cont).find('.opener').click(function () { $(this).parent().toggleClass('open'); });

            // Setup datepicker
            $("#datefrom").datepicker({ 'dateFormat': 'dd-mm-yy' });
            $("#dateto").datepicker({ 'dateFormat': 'dd-mm-yy' });

            // Add js class to container
            $(cont).addClass('js');

            // Hide
            cont.css('display', 'none');
            var isOpen = false;

            $(filter).children('a').click(function (e)
            {
                e.preventDefault();

                if (isOpen)
                {
                    close();
                } else
                {
                    open();
                }
            });

            $(filter).find('a.btn.close').click(function ()
            {
                if (isOpen)
                {
                    close();
                }
                return false;
            });

            $(cont).find('.form-input-wrap input').each(function (i, inp)
            {
                var value = $(inp).attr('value');

                $(this).focus(function ()
                {
                    $(inp).attr('value', '');
                });

                $(this).blur(function ()
                {
                    if ($(inp).attr('value') === '')
                        $(inp).attr('value', value);
                });
            });

            $(cont).find('.checks ul li').each(function (i, li)
            {
                var check = $(li).find('input')[0];
                var label = $(li).find('label')[0];

                $(label).mouseover(function () { $(this).addClass('hover'); });
                $(label).mouseout(function () { $(this).removeClass('hover'); });
                $(label).mousedown(function () { return false; })

            });

            function open()
            {
                cont.css({
                    left: $(filter).position().left,
                    top: $(filter).position().top + 34,
                    display: 'block'
                });
                filter.addClass('open');
                isOpen = true;
            };

            function close()
            {
                cont.css('display', 'none');
                filter.removeClass('open');
                isOpen = false;
            }
        }
    },

    toolTip: function (els, opts)
    {
        opts = opts || {};

        $(els).each(function (i, el)
        {
            var tool = $('<div class="tooltip"><div><a href="#" class="close" title="Close this message">Close</a>' + opts.html + '</div></div>');
            $(document.body).append(tool);
            var shown = false;
            var pos = $(el).offset();

            tool.css({
                display: 'none',
                top: pos.top + $(el).height(),
                left: pos.left + ((opts.over) ? 0 : -($(el).width() / 2))
            });

            var close = function ()
            {
                tool.css('display', 'none');
                shown = false;
            };

            tool.find('a.close').click(close);

            if (opts.after)
            {
                opts.after({ tool: tool, close: close });
            }

            if (!opts.over)
            {
                $(el).click(function ()
                {
                    tool.css('display', 'block');
                    shown = true;

                    if (opts.cancel)
                        return false;
                });
            } else
            {
                tool.addClass('over');
                tool.find('.close').remove();
                $(el).mouseover(function ()
                {
                    tool.css('display', 'block');
                    show = true;
                });

                $(el).mouseout(function ()
                {
                    close();
                });
            }
        });
    },

    playlistNav: function ()
    {
        var nav = $('#navPlaylists');
        var opener = $(nav).find('a').first();
        var div = $(nav).find('div');
        div.bgiframe();

        var isOver = false;
        var timer = null;

        var checkState = function ()
        {
            $(nav)[((isOver) ? 'add' : 'remove') + 'Class']('open');
        };

        $(opener).mouseover(function ()
        {
            isOver = true;
            checkState();
        });

        $(opener).mouseout(function ()
        {
            clearTimeout(timer);
            isOver = false;
            timer = setTimeout(checkState, 50);
        });

        $(div).mouseover(function ()
        {
            clearTimeout(timer);
            isOver = true;
        });

        $(div).mouseout(function ()
        {
            clearTimeout(timer);
            isOver = false;
            timer = setTimeout(checkState, 50);
        });
    },

    salesreportNav: function ()
    {
        var nav = $('#navSales');
        var opener = $(nav).find('a').first();
        var div = $(nav).find('div');
        div.bgiframe();

        var isOver = false;
        var timer = null;

        var checkState = function ()
        {
            $(nav)[((isOver) ? 'add' : 'remove') + 'Class']('open');
        };

        $(opener).mouseover(function ()
        {
            isOver = true;
            checkState();
        });

        $(opener).mouseout(function ()
        {
            clearTimeout(timer);
            isOver = false;
            timer = setTimeout(checkState, 50);
        });

        $(div).mouseover(function ()
        {
            clearTimeout(timer);
            isOver = true;
        });

        $(div).mouseout(function ()
        {
            clearTimeout(timer);
            isOver = false;
            timer = setTimeout(checkState, 50);
        });
    },

    formSelect: function (el)
    {
        var isOpen = false; // Set inital status to closed
        var opts = $(el).find('option'); // Get select options
        var self = this;

        var selected = false;
        $(opts).each(function (i, el)
        {
            if ($(el).attr('selected'))
            {
                selected = i;
            }
        });

        // Create drop down html
        var html = $('<div class="form-select"><span class="text">' + $(opts[selected]).attr('text') + '</span><div class="opener"></div></div>');
        $(el).before(html);
        $(el).css({ position: 'absolute', left: '-1000em' });

        var pos = $(html).position(); // Get html position

        var text = $(html).find('.text'); // Get text area
        var opener = $(html).find('.opener'); // Get opener

        $(el).keyup(function (e)
        {
            var i = selected;

            if (e.which === 13)
            {
                select(selected);
                close();
                return false;
            }

            if (e.which == 38)
            {
                i--;

                if (i < 0)
                {
                    i = opts.length - 1;
                }
            }

            if (e.which == 40)
            {
                i++;

                if (i > opts.length - 1)
                {
                    i = 0;
                }
            }

            select(i);
        });

        // Attach opener click event
        $(html).click(function ()
        {
            toggle();
            return false;
        });


        // Create dropdown
        var drop = $('<div class="form-select-drop"><div><div><div><div><ul></ul></div></div></div></div></div>');
        var dropList = $(drop).find('ul').first();

        var lis = [];
        // Loop through options and append list items to drop down
        $(opts).each(function (i, el)
        {
            lis[i] = $('<li style=width:150px;' + ((selected === i) ? ' class="selected"' : '') + '><a href="#">' + $(el).attr('text') + '</a>');
            var li = lis[i];

            // Attach click event for drop down item
            $(li).find('a').click(function ()
            {
                select(i);
                close();
                return false;
            });

            $(dropList).append(li);
        });
        $(html).after(drop);

        if ($(drop).height() >= 150)
        {
            $(dropList).css({
                'overflow-x': 'hidden',
                'overflow-y': 'auto',
                'height': 150
            });
        }

        close();

        function toggle()
        {
            if (isOpen)
            {
                close();
            } else
            {
                open();
            }
        };

        function close()
        {
            if (self.isIe() === 4)
            {
                $('select, .form-textarea').css('visibility', 'visible');
            }
            $(drop).css('display', 'none'); isOpen = false;
            $(opener).removeClass('open');
        };
        function open()
        {
            if (self.isIe() === 4)
            {
                $('select, .form-textarea').css('visibility', 'hidden');
            }

            var pos = $(html).position();
            isOpen = true;
            $(opener).addClass('open');
            el.focus();

            $(drop).css({
                display: 'block',
                position: 'absolute',
                left: pos.left,
                top: pos.top + $(html).height(),
                width: $(text).width() + 35
            });
        };
        function select(i)
        {
            $(opts[selected]).removeAttr('selected');
            $(lis[selected]).removeClass('selected');
            selected = i;

            $(opts[selected]).attr('selected', 'selected');
            $(lis[selected]).addClass('selected');

            $(text).html($(opts[selected]).attr('text'));
        };
    },

    archive: function ()
    {
        $('.listing').each(function (i, el)
        {
            var openers = $(el).find('a.opener');

            $(openers).each(function (j, o)
            {
                o = $(o);
                var p = o.parent();

                p.addClass('close');

                o.click(function ()
                {
                    o.toggleClass('current');
                    p.toggleClass('close');

                    return false;
                });
            });
        });
    },

    overlayFuncs: function (el)
    {
        $(el).find('.recommended ul').jcarousel();

        var ctrls = $(el).find('.controls .btns ul li');

        $(ctrls).each(function (i, el)
        {
            var drop = $(el).find('.drop');

            $(el).mouseover(function ()
            {
                $(el).addClass('open');
            });

            // We want the email box to stay open till user clicks on email icon to close it,
            // so we don't have mouseout event on the email button
            if (el.className != "email")
            {
                $(el).mouseout(function ()
                {
                    $(el).removeClass('open');
                });
            }

        });

        // Added to put the email dropdown in the right hand column of the programme details page
        $('#supCol2 .email').each(function ()
        {
            $(this).mouseover(function ()
            {
                $(this).addClass('open');
            });
        });

        $('#lb-cont input, #lb-cont textarea').each(function (i, inp)
        {
            var value = $(inp).attr('value');

            $(this).focus(function ()
            {
                $(inp).attr('value', '');
            });

            $(this).blur(function ()
            {
                if ($(inp).attr('value') === '')
                    $(inp).attr('value', value);
            });
        });

        // ProgramDetails.aspxWhen user clicks in the Send to or messsage area the text will disappear or reappear
        // when clicking away. Watermarking.
        $('#supCol2 input, #supCol2 textarea').each(function (i, inp)
        {
            var value = $(inp).attr('value');

            $(this).focus(function ()
            {
                $(inp).attr('value', '');
            });

            $(this).blur(function ()
            {
                if ($(inp).attr('value') === '')
                    $(inp).attr('value', value);
            });
        });
    },

    //    screenerReport: function ()
    //    {
    //        if (!$(document.body).hasClass('sales'))
    //        {
    //            var newRow = '<tr class="expanded"><td colspan="6" class="comment">'
    //            newRow += '<label for="comment">Comment:</label>';
    //            newRow += '<div class="form-textarea"><textarea name=""></textarea></div>';
    //            newRow += '<div class="form-sep optin"><input type="checkbox" name="hide" class="checkbox" /> <label for="hide">Hide comments on producer report.</label></div>';
    //            newRow += '<div class="form-sep buttons"><a href="#" class="close">Cancel</a> <span>or</span> <input type="image" src="' + drg.BASE + 'assets/img/form/buttons/save.png" name="save" class="btn" /></div>'
    //            newRow += '</td></tr>';
    //            newRow = $(newRow);

    //            var salesEx = '<div class="form-input-wrap"><input type="text" name="salesexec" /></div>';
    //            salesEx = $(salesEx);

    //            var status = function (opts)
    //            {
    //                var html = '<select name="">';

    //                for (var i = 0; i < opts.length; i++)
    //                {
    //                    html += '<option value="' + opts[i].value + '">' + opts[i].text + '</option>';
    //                }

    //                html += '</select>';

    //                return $(html);
    //            };

    //            var table = $('.mainCol table:not(.extra)');

    //            $('.mainCol table tbody tr').each(function (i, row)
    //            {
    //                var open = false, rowHtml = null, salesHtml = null, statusHtml = null, close = null;
    //                var cols = $(row).find('td'); // Get row columns

    //                var oriSales = $(cols[1]).html();
    //                var oriStatus = $(cols[5]).html();

    //                $(row).click(function ()
    //                {
    //                    if (!open)
    //                    {
    //                        // get the existing sales exec name
    //                        var execName = $(this).find('td')[1].innerHTML;

    //                        rowHtml = newRow.clone(); // Clone row html
    //                        salesHtml = $(salesEx).clone(); // Clone sales exec html
    //                        salesHtml.find('input').attr('value', execName);
    //                        close = $(rowHtml).find('.close');

    //                        // Generate status select html
    //                        statusHtml = status([
    //							{ value: 'flange', text: 'Flange' },
    //							{ value: 'flange', text: 'Flange2' },
    //							{ value: 'flange', text: 'Flange3' },
    //							{ value: 'flange', text: 'Flange' },
    //							{ value: 'flange', text: 'Flange2' },
    //							{ value: 'flange', text: 'Flange' },
    //							{ value: 'flange', text: 'Flange2' },
    //							{ value: 'flange', text: 'Flange' },
    //							{ value: 'flange', text: 'Flange2' },
    //							{ value: 'flange', text: 'Flange' },
    //							{ value: 'flange', text: 'Flange2' },
    //							{ value: 'flange', text: 'Flange' },
    //							{ value: 'flange', text: 'Flange2' }
    //						]);

    //                        $(table).first().addClass('commentOpen');
    //                        $(row).addClass('expanded');
    //                        // Inject html
    //                        $(row).after(rowHtml);

    //                        $(cols[1]).html(salesHtml);

    //                        $(cols[5]).html(statusHtml);
    //                        drg.formSelect(statusHtml);

    //                        $(window).scrollTop($(row).position().top - 20);

    //                        open = true;

    //                        $(close).click(function ()
    //                        {
    //                            $(rowHtml).remove();
    //                            $(table).first().removeClass('commentOpen');

    //                            $(cols[1]).html(oriSales);

    //                            $(cols[5]).html(oriStatus);

    //                            open = false;
    //                            $(row).removeClass('expanded');

    //                            return false;
    //                        });
    //                    }
    //                });
    //            });
    //        }
    //    },

    // homepage carousel?

    jsShow: function ()
    {
        var currentSlide = 0;
        var jsShow = $('#jsShow');
        var main = jsShow.find('.main');
        var copy = jsShow.find('.copy');
        var lis = jsShow.find('li');
        var hiddenCatalogue = $("input[id*=CatalogueMode]");
        var heroLink = $("#jsShow a[id*=heroLink]");

        $('<div class="wipe"></div>').appendTo([lis, main, copy]);
        var mainWipe = main.find('.wipe');
        var copyWipe = main.find('.copy');
        $('<img id="frontImg">').appendTo(main);
        var frontImg = $('#frontImg');
        frontImg.attr('src', $('.main img.large').attr('src'));
        frontImg.attr("style", "position: absolute; top: 0; left: 0;");
        frontImg.css('display', 'none');

        // add a small frontImg to each of the lis
        for (var i = 0; i < lis.length; i++)
        {
            var sfi = $('<img class="smallFront">').appendTo(lis[i]);
            sfi.attr('src', $(lis[i]).find('img.small').attr('src'));
            sfi.attr("style", "position: absolute; top: 0; left: 0;");
        }

        lis.bind('click', function (e)
        {
            var li = $(e.target).parents('li').first();
            change(li);
            clearInterval(autoInt);
            autoInt = setInterval(autoChange, 5000);
            return false;
        });

        var autoChange = function ()
        {
            if (currentSlide > 3) currentSlide = 0;
            var img = $(lis[currentSlide]).find('img');
            var catalogue = $(lis[currentSlide]).find('input');
            img.trigger('click');

            currentSlide++;

            if (currentSlide >= 4) return;


            return false;
        };

        function CheckIfCat()
        {
            var cat = copy.html().indexOf("hypViewCatalogueMainLink");
            var cat2 = copy.html().indexOf("hypViewCatalogue");

            // Find hidden field within the li's and using the current slide number determine if this slide
            // object is a hero or catalogue object.
            //if (catalogue[0].value == 'False')
            if (cat == -1 && cat2 == -1)
            {
                var testje = jsShow.find(".Dave");
                if (testje[0] != undefined)
                {
                    testje[0].className = "playOver";
                }
                else
                {
                    testje = jsShow.find(".playOver");
                    if (testje[0] != undefined)
                    {
                        testje[0].className = "playOver";
                    }
                }
            }
            else
            {
                var testje = jsShow.find(".playOver");
                if (testje[0] != undefined)
                {
                    testje[0].className = "Dave";
                }
                else
                {
                    testje = jsShow.find(".Dave");
                    if (testje[0] != undefined)
                    {
                        testje[0].className = "Dave";
                    }
                }

                heroLink.removeAttr("href");

            }

        }

        autoInt = setInterval(autoChange, 5000);

        var change = function (cont)
        {
            heroLink.attr('href', cont.find('.cta').find('a').attr('href'));
            // swap and fade the large images
            var mainImg = main.find('img.large');
            var contImg = cont.find('img.large');
            frontImg.attr('src', mainImg.attr('src'));
            frontImg.css('display', 'block');
            mainImg.attr('src', contImg.attr('src'));
            contImg.attr('src', frontImg.attr('src'));
            frontImg.fadeOut();
            mainImg.fadeIn();
            // swap and fade the small versions
            var mainImg = main.find('img.small');
            var contImg = cont.find('img.small');
            var smallBack = cont.find('img.small'); // duplicate for readability
            var smallFront = cont.find('img.smallFront');
            smallFront.attr('src', smallBack.attr('src'));
            smallBack.attr('src', mainImg.attr('src'));
            smallFront.css('display', 'block');
            // put the small image into the hero's small image
            mainImg.attr('src', smallFront.attr('src'));
            smallFront.fadeOut();
            smallBack.fadeIn();

            // swap the HTML
            var contText = cont.find('.text');
            var contHtml = contText.html();
            var copyHtml = copy.html();
            contText.html(copyHtml);
            copy.html(contHtml);
            CheckIfCat();

        };

    },

    programmes: function ()
    {
        var opener = $('.extra li.add a').first();
        var drop = $('.extra li.add .drop');
        drop.hide();

        opener.click(function ()
        {
            drop.toggle();
            return false;
        });
    },


    news: function ()
    {
        if ($(document.body).hasClass('markets'))
        {
            this.addHover($('.hero .item .image'), true);
            this.round($('.hero .item'));
        }
    },

    address: function ()
    {
        $('.address input').each(function (i, inp)
        {
            var value = $(inp).attr('value');

            $(this).focus(function ()
            {
                $(inp).attr('value', '');
            });

            $(this).blur(function ()
            {
                if ($(inp).attr('value') === '')
                    $(inp).attr('value', value);
            });
        });
    }
};

// Attach domready function
$(document).ready(function () {

    // Changes the style of the menu button to show it is selected
    $('.hd').addClass("menulinkhighlight");
    $('.3d').addClass("menulinkhighlight");
    $('.he').addClass("menulinkhighlight");

    // Get the body id for later use
    var bodyId = $(document.body).attr('id');

    drg.classes = $(document.body).attr('class').split(' ');

    // If drg namespace has function matching body id run it
    if (drg[bodyId])
    {
        drg[bodyId]();
    }

    $(window).load(function ()
    {
        // Elements to round
        drg.round($('.media, #freshProg .row .media, #programmes.list .mainCol .item'));
    });

    drg.isIE6 = $.browser.msie && /msie 6\.0/i.test(navigator.userAgent);

    drg.pSplit($('.to .copy > *:not(p.format)'));
    drg.slideCont($('.to'));

    drg.addHover($('#programmes.list .mainCol .item .copy, #programmes.list .mainCol .item .image'), true);
    drg.addHover($('#filterBox li div'));

    drg.playlistNav();
    drg.salesreportNav();

    // Setup any form select elements
    $('select').each(function (i, el)
    {
        drg.formSelect($(el));
    });

    // Setup overlay function to add drop down functionality
    drg.overlayFuncs($('#lb-cont'));
    drg.overlayFuncs($('#supCol2'));

    drg.archive();

    //drg.screenerReport();

    drg.jsShow();

    drg.address();

    // Sort tool tip
    drg.toolTip($('#orders.report table.extra th'), {
        cancel: false,
        over: true,
        html: '<h2>Click to sort</h2>',
        after: function (obj)
        {

        }
    });

    drg.toolTip($('#orders.report table th'), {
        cancel: false,
        over: true,
        html: '<h2>Click to sort</h2>',
        after: function (obj)
        {

        }
    });

    $(window).load(function ()
    {
        drg.toolTip($('.remove a, .delete'), {
            cancel: true,
            html: '<h2>Confirm Delete</h2><p>Are you sure you want to remove this programme from the playlist?</p> <p class="btns"><a href="#" class="yes">Yes</a> <a href="#" class="no">No</a></p>',
            after: function (obj)
            {
                $(obj.tool).find('a.yes').click(obj.close);
            }
        });

        // Cufon
        Cufon.replace('.h1_cufon');
        Cufon.replace('div.mainCol h2');
    });

});
