var DA = function () {

    //    var embedAudioPlayer = function (e) {

    //        var anchor = $(this);

    //        anchor
    //            .parent()
    //                .click(function (e) {
    //                    e.stopPropagation();
    //                    return false;
    //                })
    //                .end()
    //            .hide()
    //            .after($('<div />', { 'id': this.id + '_player' }))

    //        AudioPlayer.embed(
    //            this.id + '_player', {
    //                titles: "",
    //                soundFile: this.href
    //            });
    //        ;
    //        e.stopPropagation();
    //        return false;
    //    }

    return {
        Init: function () {

            $('.audioplayer').bind('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            });

            if ($.browser.msie) {
                $('#archive-tab').find('a').corner('5px top cc:#2d282b');
                //$('#DA.todays-da #content, #DA.printable-view #content').find('> .content-wrap').corner('right bl 5px');
                $('#DA.celebrity-guests  #content').find('> .content-wrap').corner('bottom 5px');
                // $('#DA.celebrity-guests #celebrities .info .name').corner('top 5px');
                // $('#DA.celebrity-guests #celebrities .info').corner('5px cc:#ffffff');
                // $('#channels').find('.channel').find('a').corner('5px cc:#fff');
                // $('#channels').find('.channel').find('strong').corner('right 5px cc:#fff');
                // $('#channels').find('.show').find('h4').find('a').corner('5px cc:#fff');
                // $('#channels').find('.show').find('h4').find('strong').corner('right 5px cc:#fff');
                // $('#channels').find('.show').find('h5').corner('3px');
                // $('#channels').find('.show').find('.meta-info').find('>li > div').corner('3px');
                $('#DA.simple-view .inner-wrap').corner('5px');
                // $('#DA.printable-view .meta-info, #DA.search-archive #searchResults .meta-info').corner('5px');
                $('#DA.search-archive #content, #DA.search-archive #content .criteria, #DA.search-archive #content .filter, #DA.suggestion #content, #DA.home #content, #DA.suggestion #content, #DA.error #content').corner('6px');
                //$('#DA.printable-view #shows h5, #DA.search-archive #searchResults h5').corner('5px');
            }
        },
        DASimpleViewInit: function () {
            //$('> ul', '#channels').StudentQueueUp(3, { 'class': 'simple-view', css: { width: '275px', float: 'left', overflow: 'hidden', padding: '0px 13px'} });

            if (soundManager) {
                soundManager.url = '/js/soundmanager/swf';
                soundManager.flashVersion = 9;
                soundManager.useFlashBlock = false;
                soundManager.useHTML5Audio = true;
                soundManager.debugMode = false;
            }

            var channels = $('#channels');

            channels.find('a.play-video').bind('click', function () {

                var link = $(this),
                    id = link.attr('data-vid');

                if (currentSong) {
                    if (currentSong.sID == id) {
                        // is Paused?
                        if (currentSong.paused) {
                            currentSong.resume();
                            link.children('.icon').addClass('playing');
                            link.find('#backToStart').show();
                            return false;
                        }

                        // is playing or buffering
                        if (currentSong.playState) {
                            currentSong.pause();
                            link.children('.icon').removeClass('playing');
                            link.find('#backToStart').hide();
                            return false;
                        } else {
                            currentSong.play();
                            link.children('.icon').addClass('playing');
                            link.find('#backToStart').show();
                            return false;
                        }
                    } else {
                        window.currentSong.unload().destruct();

                    }
                }

                currentSong = soundManager.createSound({
                    id: id,
                    url: this.href
                });
                currentSong.play();
                currentSong._onfinish = function () {

                    var l = link;

                    soundManager.setPosition(id, 0);
                    currentSong.pause();
                    l.children('.icon').removeClass('playing');
                    link.find('#backToStart').hide();
                }
                channels.find('.playing').removeClass('playing');
                link.children('.icon').addClass('playing');

                var backToStart = $('#backToStart');
                   
                if (!backToStart.length) {
                    backToStart = $('<a />', {
                        id: 'backToStart',
                        click: function (e) {

                            var c = channels,
                                btslink = $(this);

                            currentSong.setPosition(0).pause();
                            c.find('.playing').removeClass('playing');

                            btslink.hide();

                            e.stopPropagation();
                            return false;
                        }
                    });
                }

                backToStart.appendTo(link).show();
                return false;
            });
            this.Init();
        },
        DADetailViewInit: function () {
            this.Init();
            //            var embedplayer = embedAudioPlayer;

            //            AudioPlayer.setup("/js/audio-player/player.swf", {
            //                width: 150,
            //                initialvolume: 100,
            //                transparentpagebg: "yes",
            //                left: "000000",
            //                bg: "CA1F32",
            //                leftbg: "CA1F32",
            //                rightbg: "CA1F32",
            //                lefticon: "FFFFFF",
            //                animation: "no",
            //                noinfo: "yes",
            //                tracker: "AFAFAF",
            //                autostart: "yes"
            //            });

            //            $('.audioplayer a')
            //                .bind('click', embedplayer);
            //            $('.audioplayer').click(function (e) {
            //                e.stopPropagation();
            //                return false;
            //            });
            //            
            // Center align list expand cursor
            this.CenterAlign('.icon', $('.header', $('.show', $('#channels .shows'))));
            this.CenterAlign('.icon', $('#channels .channel'));

            var DAExpands = [];
            DAExpands.push(this.Expand('.channel', $('#channels')));
            DAExpands.push(this.Expand('.header', $('.show', $('#channels .shows'))));

            $('#expand-all').bind('click.DAExpand', function (e) {
                if (!$.isArray(DAExpands)) return false;

                var len = DAExpands.length, i;
                for (i = len - 1; i >= 0; i--) {
                    DAExpands[i].ExpandAll();
                }

                $(this).addClass('checked');
                $('#collapse-all').removeClass('checked');

                return false;
            }).trigger('click.DAExpand');
            $('#collapse-all').bind('click.DAExpand', function () {

                if (!$.isArray(DAExpands)) return false;

                var len = DAExpands.length, i;
                for (i = len - 1; i >= 0; i--) {
                    DAExpands[i].CollapseAll();
                }

                $(this).addClass('checked');
                $('#expand-all').removeClass('checked');

                return false;

            });

            // Rating Widget
            $('.rating').WBMVotty('.ratebox', '.overall', '.ratebar', ['.r1', '.r2', '.r3', '.r4', '.r5']);
        },
        SuggestionInit: function () {
            this.Init();

            var formEls = $("#content .callLetter, #content .email, #content .suggestion");

            $("#content .submit a").click(function (e) {

                var els = formEls,
                    emailRegex = /\w+([.-_]\w+)*@\w+([.-_]\w+)*\.\w{2,4}/,
                    emptyEl = $.grep(els, function (n, i) {
                        var $this = $(n),
                            val = $.trim($this.val()),
                            ori = $this.data('default'),
                            isEmpty = false;

                        isEmpty = val == '';
                        if (!isEmpty) isEmpty = val == ori;
                        return isEmpty;
                    }),
                    emailValid = false,
                    emailEl = $('#content .email')

                if (emailEl.val() !== '' || emailEl.val() !== emailEl.data('default')) {
                    emailValid = emailRegex.test(emailEl.val())
                }

                if (emptyEl.length > 0) {
                    var errMsg;

                    if (emptyEl.length === els.length)
                        errMsg = "You haven't written anything! \nPlease include your call letters, email address, and suggestion. \nThank you!";
                    else {
                        errMsg = "Please include ";

                        var len = emptyEl.length, i = 0;
                        for (; i < len; i++) {
                            if (len === 2 && i === len - 1) {
                                errMsg += ' and ';
                            } else if (len > 2) {
                                errMsg += ', ';
                                if (i === len - 1) {
                                    errMsg += 'and ';
                                }
                            }
                            errMsg += $(emptyEl[i]).attr('data-title');
                        }

                        errMsg += ". \nThank you!";
                    }

                    alert(errMsg)
                    return false;
                }

                if (!emailValid) {
                    alert("Invalid email address. \nPlease double check if you miss out something. \nThank you!")
                    emailEl.focus();
                    return false;
                }

                return true;
            });

            formEls
                .each(function () {
                    var $this = $(this);
                    $this.data('default', $this.attr('data-default'));
                })
                .bind('focusin focusout', function (e) {
                    var $this = $(this),
                        val = $this.val(),
                        ori = $this.data('default');

                    if (e.type === 'focusin') {
                        if (val === ori) $this.val('');
                    } else {
                        if (val == '') $this.val(ori);
                    }
                });
        },
        Expand: function (selector, context, options) {

            if (undefined === selector) throw new Error('Must specify a selector');
            if (undefined === context) context = $('body');

            var els = $(selector, context),
				options = $.extend({
				    ExpandedCls: 'expanded',
				    CollapseCls: 'collapse'
				}, options);

            var expand = function (el, open) {
                var parent = el.parent(),
					opt = options;

                if (open) {
                    parent
						.removeClass(opt.CollapseCls)
						.addClass(opt.ExpandedCls)
						.find('.tools .button')
							.removeClass('checked')
							.filter('.expand').addClass('checked');
                }
                else {
                    parent
						.removeClass(opt.ExpandedCls)
						.addClass(opt.CollapseCls)
						.find('.tools .button')
							.removeClass('checked')
							.filter('.collapse').addClass('checked');
                }
            };

            els.bind('click.DAExpand', function (e, open) {
                var $this = $(this),
					open = open !== undefined ?
						open :
						$this.parent().hasClass(options.CollapseCls);

                open ?
					expand($this, true) :
					expand($this, false);

                $this
					.find('.tools .button')
						.bind('click', function (e) {
						    var that = $this,
								parent = that.parent(),
								button = $(this),
								isExpand = button.is('.expand'),
								opt = options;

						    if (isExpand) expand(that, isExpand)
						    else expand(that, isExpand);

						    return false;
						});

                $('#expand-all, #collapse-all').removeClass('checked');

                //e.preventDefault();
                return false;
            });

            return {
                Expand: function (index) {
                    $(els[index]).trigger('click.DAExpand', true);
                },
                Collapse: function (index) {
                    $(els[index]).trigger('click.DAExpand', false);
                },
                ExpandAll: function () {
                    els.trigger('click.DAExpand', true);
                },
                CollapseAll: function () {
                    els.trigger('click.DAExpand', false);
                }
            }

        },
        CenterAlign: function (selector, context) {
            var icons = $(selector, context);

            icons.each(function () {
                var $this = $(this),
			        myHeight = $this.outerHeight(true),
			        height = $this.parent().outerHeight(true),
			        top = (height / 2 - myHeight / 2) + 'px';

                $this.css('top', top);

            });
        }
    }
};
