// Default page init
(function($) {
    window.CC = window.CC || {};
    window.CC.pages = window.CC.pages || {};

    window.CC.pages.header = {
        init: function(element) {
            var self = this;
            
            // And share form
            $('#shareDialog').dialog({
                autoOpen: false,
                zIndex: 200002,
                modal: true
            });

            // Bind to auth events
            $(document).bind('authenticated', function() {
                self.handleLogin();
            });
            $(document).bind('loggedout', function() {
                CC.pages.header.updateUI();
            });
            
            $(document).bind('framework.initialized', function() {
                var url = $.ccFramework.getPage();
                if(url != '/' && url != '') {
                    $('#page, #headerBg, #player').show();
                }
            });
            
            $(document).bind('framework.willloadpage', function(e) {
                var url = e.url;
                
                // Parse the url
                var parsed = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
                url = parsed[9];
                
                // Determine the url we are going to load
                if(url == '/' || url == '') {
                    e.preventDefault();
                    window.location.href = '/about/index.html';
                    //e.routed = 'index_content.html';
                    return;
                } else if(/\.html$/.test(url)) {
                    return;
                }
                
                if(url.indexOf('/') == 0) {
                    url = url.substring(1);
                }
                var tokens = url.split('/'),
                page = null,
                sections = ['login', 'song', 'studio', 'artist', 'search', 'create', 'discover', 'topcharts'],
                extrasIdx = 1;

                if($.inArray(tokens[0], sections) != -1) {
                    page = tokens[0].toLowerCase();
                    extrasIdx = 2;
                } else {
                    page = 'profile';
                }
                
                if(tokens.length > extrasIdx) {
                    for(var i = extrasIdx; i < tokens.length; ++i) {
                        page += '_' + tokens[i].toLowerCase();
                    }
                }
                
                e.routed = page + '.html';
            });

            // Update ourself
            this.updateUI();

            // attach to the click events of any login button
            $('a.cc-live-login').live('click', function() {
                CC.pages.header.login();
                return false;
            });
            $('a.cc-live-logout').live('click', function() {
                CC.pages.header.logout();
                return false;
            });

            $("#userStatusMenu li").live('hover', function(event){
                if('mouseenter' == event.type) {
                    $(this).find("a").addClass("ui-state-hover");
                } else {
                    $(this).find("a").removeClass("ui-state-hover");
                }
            });
            
            $(".cc-show-user-menu").live('click', function() {
                $("#userStatusMenu").toggle();
                $('body').bind('click', function(event) {
                    $('#userStatusMenu').hide();
                    $(this).unbind(event);
                });
                return false;
            });

            // Setup the display of the search options
            $("#siteSearchButton").click(function() {
                CC.pages.header.doSearch();
                return false;
            });
            $('#searchOptions').hide();
            $("#siteSearch").focus(function() {
                if($(this).val() == $(this).attr('default') ) {
                    $(this).val('');
                }
                CC.pages.header.showSearchOptions();
                $('body').bind('click', function(event) {
                    if( $(event.target).closest('#siteSearchWrapper').length == 0) {
                        CC.pages.header.hideSearchOptions();
                        $(this).unbind(event);
                    }
                });
            }).blur(function() {
                if($(this).val() == '') {
                    $(this).val($(this).attr('default'));
                }
            }).keyup(function(event) {
                if(event.keyCode == '13') {
                    CC.pages.header.doSearch();
                    return false;
                }
            });

            // add value change functions to the search options
            $('#searchAll').change(function(event) {
                if($(this).is(':checked')) {
                    $('#searchOptions input:not(#searchAll)').attr('checked', false);
                } else if($('#searchOptions input:not(#searchAll):checked').length == 0) {
                    $('#searchAll').attr('checked', true);
                }
            });
            $('#searchOptions input:not(#searchAll)').change(function(event) {
                if($(this).is(':checked')) {
                    $('#searchAll').attr('checked', false);
                }
                if($('#searchOptions input:not(#searchAll):checked').length == 0) {
                    $('#searchAll').attr('checked', true);
                }
            });

            // Common actions (should probably go somewhere else
            $('.cc-favorite-add').live('click', function() {
                var uuid = $(this).attr('uuid');
                if(!uuid) return;
                CC.api.user.addfavorite({
                    uuid: uuid
                }, function() {
                    $().message('Favorite Added!');
                    CC.analytics.song.favorite(uuid);
                }, function(res, code, message) {
                    if('user.already_a_favorite' == message) {
                        $().message('Already a Favorite');
                    }
                });
                return false;
            });
            $('.cc-favorite-remove').live('click', function() {
                CC.api.user.removefavorite({
                    uuid: $(this).attr('uuid')
                }, function() {
                    $().message('Favorite Removed!');
                });
                return false;
            });

            $('.cc-fan-add').live('click', function() {
                var username = $(this).attr('username');
                CC.api.user.addfan({
                    username: username
                }, function() {
                    $().message('Fan Added!');
                    CC.analytics.user.fan(username);
                }, function(xhr, status, message) {
                    if('user.already_a_fan' == message) {
                        $().message('You are already a fan of ' + username);
                    } else {
                        $().message('Oops.  Something didn\'t go as planned when adding you as a fan.');
                    }
                });
                return false;
            });
            $('.cc-fan-remove').live('click', function() {
                CC.api.user.removefan({
                    username: $(this).attr('username')
                }, function() {
                    $().message('Fan Removed!');
                });
                return false;
            });
            $('.cc-song-vote').live('click', function() {
                var $this = $(this);
                if(!$this.attr('uuid')) {
                    return false;
                }
                CC.api.song.vote({
                    uuid: $this.attr('uuid')
                }, function() {
                    $().message('Vote Cast!');
                }, function() {
                    $().message('Only one vote per day per song.')
                });
                return false;
            });

            $('.cc-user-view').live('click', function(e) {
                e.preventDefault();
                
                var $this = $(this),
                username = $this.attr('username') || $this.data('username');
                $.ccFramework.loadPage('/' + encodeURIComponent(username));
                
                return false;
            });
            
            $('.cc-song-view').live('click', function(e) {
                e.preventDefault();
                
                var $this = $(this),
                uuid = $this.attr('uuid') || $this.data('uuid');
                $.ccFramework.loadPage('/song/' + uuid);
                return false;
            });
            
            $('.cc-studio-view').live('click', function(e) {
                e.preventDefault();
                
                var $this = $(this),
                uuid = $this.attr('uuid') || $this.data('uuid');
                $.ccFramework.loadPage('/studio/' + uuid);
                return false;
            });
            
            $('.cc-hover-reveal').live('hover', function(event) {
                var $this = $(event.currentTarget),
                min = $this.attr('hover-min') || 0.01,
                max = $this.attr('hover-max') || 0.7,
                target = $this.find($this.attr('target'));
                if( 'mouseenter' == event.type ) {
                    target.fadeTo('fast', max);
                } else if( 'mouseleave' == event.type ) {
                    target.fadeTo('fast', min);
                }
            });

            $('.cc-share').live('click', function() {
                var uuid = $(this).attr('uuid');
                if(uuid) {
                    CC.Sharer.shareSong(uuid);
                }
                return false;
            });

            $('.cc-download').live('click', function() {
                var $this = $(this);
                var uuid = $this.attr('uuid');
                if(!uuid) return false;
                document.location.href = 'http://api.clubcreate.com/song/url/web/' + uuid + '/download/redirect.mp3';
                return false;
            });
            
            var $menuTemplate = $('#userHoverMenu');
            $('.cc-user-view').live('hover', function(e) {
                if(e.type == 'mouseenter') {
                    var $this = $(this);
                    if($this.closest('.userPlaque').size() > 0) {
                        return;
                    }
                    
                    var $menu = $menuTemplate.ccTemplate('appendTo', 'body', {
                        username: $this.attr('username'),
                        displayName: $this.attr('username')
                    });
                    $menu.css({
                        position: 'absolute',
                        top: $this.offset().top + $this.height() - 3,
                        left: $this.offset().left + $this.width() - 3
                    });
                    $menu.fadeIn();
                    var request = null,
                    infoTimeout = window.setTimeout(function() {
                        request = CC.api.user.info({
                            username: $this.attr('username')
                        }, function(res) {
                            var $user = $(res).find('user'),
                            $stats = $user.find('stats');
                            $menu.find('.songsStat').text($stats.attr('songs'));
                            $menu.find('.fansStat').text($stats.attr('likedby'));
                            $menu.find('.favoritesStat').text($stats.attr('favorites'));
                            
                            if($user.attr('isfan') == 1) {
                                $menu.find('.cc-fan-remove').show();
                            } else {
                                $menu.find('.cc-fan-add').show();
                            }
                            
                            $menu.find('.loader').remove();
                            $menu.find('.userDetail').fadeIn();
                        });
                    }, 150);
                    
                    var closeTimeout = null,
                    setCloseTimeout = function() {
                        closeTimeout = window.setTimeout(function() {
                            $menu.fadeOut(function() {
                                $menu.remove();
                            });
                        }, 50);
                    };
                    
                    $('body').bind('click', function(event) {
                        var $target = $(event.target);
                        
                        if($(event.target).closest('.userPlaque').length == 0) {
                            setCloseTimeout();
                            $(this).unbind(event);
                        }
                    });
                    
                    $this.mouseleave(function() {
                        setCloseTimeout();
                    });
                    $menu.mouseenter(function() {
                        if(closeTimeout) {
                            window.clearTimeout(closeTimeout);
                        }
                        $(this).mouseleave(function() {
                            setCloseTimeout();
                        });
                    });
                }
            });
        },
        destroy: function(element) {
            
        },
        login: function() {
            CCSocialAuth.authenticate2('clubcreate');
        },
        logout: function() {
            CC.auth.doLogout();
            $.ccFramework.reloadPage();
        },
        handleLogin: function() {
            this.updateUI();
            if(CC.data.returnTo) {
                $.ccFramework.loadPage(CC.data.returnTo);
                delete CC.data.returnTo;
            } else {
                var currentPage = $.ccFramework.getPage();
                if('/' == currentPage || '' == currentPage) {
                    $.ccFramework.loadPage('/' + CC.auth.getUsername());
                } else {
                    $.ccFramework.reloadPage();
                }
            }
        },
        updateUI: function() {
            if(CC.auth.authorized) {
                var tmplData = {
                    username: CC.auth.getUsername()
                };
                $("#userStatusSignedInTmpl").ccTemplate("replaceInto", '#userStatus', tmplData);
            } else {
                $("#userStatusSignedOutTmpl").ccTemplate("replaceInto", '#userStatus');
            }
        },
        showSearchOptions: function() {
            $('#searchOptions').fadeIn('normal');
        },
        hideSearchOptions: function() {
            $('#searchOptions').fadeOut('normal');
            $('#siteSearch').blur();
        },
        doSearch: function() {
            var scopes = []
            $('#searchOptions input:checked').each(function() {
                scopes.push($(this).attr('scope'));
            })

            $.ccFramework.loadPage('/search?pattern=' + encodeURIComponent($('#siteSearch').val()) + '&scope=' + scopes.join(','));
            this.hideSearchOptions();
        }
    };

    window.CC.pages.player = {
        currentTime: 0,
        init: function(element) {
            var ua = navigator.userAgent;
            var isiOS = /iPad/i.test(ua) || /iPhone/i.test(ua) || /iPod/i.test(ua);
            
            if(isiOS) {
                $('#player').css('position', 'static').css('margin-top', '20px');
                $('body').css('margin-bottom', 0);
                $('#playerOpen').hide();
                $('#playerClose').hide();
            }
            
            $("#jplayer_interface").jPlayer({
                ready: function (e) {
                },
                ended: function() {
                    CC.pages.player._nextItem();
                },
                /*
                timeupdate: function(e) {
                    console.log(e);
                    CC.pages.player.currentTime = e.jPlayer.status.currentTime;
                },*/
                solution: "html,flash",
                swfPath: "src/js/jquery/jplayer/",
                supplied: "mp3",
                cssSelectorAncestor: "",
                cssSelector: {
                    play: "#play",
                    pause: "#pause",
                    stop: "",
                    videoPlay: "",
                    seekBar: ".jp-seek-bar",
                    playBar: ".jp-play-bar",
                    mute: "",
                    unmute: "",
                    volumeBar: ".jp-volume-bar",
                    volumeBarValue: ".jp-volume-bar-value",
                    currentTime: "#playerPosition",
                    duration: "#playerDuration"
                }
            });

            $("#playerQueue").sortable({
                placeholder: "playerPlaceholder",
                update: function(event, ui) {
                // NO-Op for now
                }
            });
            $('#hudClearTmpl').ccTemplate('replaceInto', '#hud');

            $('#playerOpen').click(function() {
                $('#playerOpen').hide();
                $('#playerClose').show();
                $('#player').animate({
                    bottom: '0px'
                }, {
                    queue: false,
                    duration: 'normal'
                }, 'swing');
            });
            $('#playerClose').click(function() {
                $('#playerOpen').show();
                $('#playerClose').hide();
                $('#player').animate({
                    bottom: '-85px'
                }, {
                    queue: false,
                    duration: 'normal'
                }, 'swing');
            });
            $('div.jp-progress').hover(function() {
                $(this).animate({
                    height: '15px'
                }, {
                    queue: false,
                    duration: 'normal'
                }, 'swing');
            }, function() {
                $(this).animate({
                    height: '5px'
                }, {
                    queue: false,
                    duration: 'normal'
                }, 'swing');
            });
            
            $('#playerRemix').click(function(e) {
                if($(this).hasClass('disabled') || $(this).attr('href') == '#') {
                    return false;
                }
            });

            $('.cc-player-queue').live('click', function(e) {
                e.preventDefault();
                var $this = $(this);
                CC.pages.player.queueItem( $this.attr('username'), $this.attr('display-name'), $this.attr('song-name'), $this.attr('uuid'), false );
                return false;
            });
            $('.cc-player-queue-now').live('click', function(e) {
                e.preventDefault();
                var $this = $(this);
                CC.pages.player.queueItem( $this.attr('username'), $this.attr('display-name'), $this.attr('song-name'), $this.attr('uuid'), true );
                return false;
            });
            $('.cc-player-pause').live('click', function(e) {
                e.preventDefault();
                $('#jplayer_interface').jPlayer('pause');
                return false;
            });
            $('.cc-player-queue-item').live('click', function(e) {
                e.preventDefault();
                CC.pages.player._playQueueItem($(this));
                return false;
            });
            $('.cc-player-queue-remove').live('click', function(e) {
                e.preventDefault();
                CC.pages.player._removeQueueItem($(this).parent('.cc-player-queue-item'));
                return false;
            });
        },
        destroy: function(element) {
        // NO-OP for now but we should remove the live handlers
        },
        _addQueueItem: function(item, first) {
            if(first) {
                $('#playerQueueItemTmpl').ccTemplate('prependTo', '#playerQueue', item);
            } else {
                $('#playerQueueItemTmpl').ccTemplate('appendTo', '#playerQueue', item);
            }
        },
        _getCurrentItem: function() {
            return $('#playerQueue .cc-current-queue-item');
        },
        _playQueueItem: function(item) {
            if(item.length == 0) {
                return;
            }
            this._getCurrentItem().removeClass('cc-current-queue-item');
            $(item).addClass('cc-current-queue-item');
            this._updatePlayer();
        },
        _updatePlayer: function() {
            var item = this._getCurrentItem();
            if(item.length == 0) {
                return;
            }

            var tmplData = {
                uuid: item.attr('uuid'),
                name: item.attr('song-name'),
                username: item.attr('username'),
                displayName: item.attr('display-name')
            };
            
            // Get the song info
            CC.api.song.info({
                uuid: item.attr('uuid')
            }, function(res) {
                var $res = $(res),
                resUuid = $(res).find('song').attr('uuid'),
                remixable = $res.find('license[name=current] right[name=derivatives]').attr('value') == '1';
                
                if(resUuid.substring(0, 31) == item.attr('uuid').substring(0, 31)) {
                    if(!remixable) {
                        $('#playerRemix').addClass('disabled');
                    } else {
                        $('#playerRemix').removeClass('disabled');
                    }
                }
            }, function() {
                $('#playerRemix').addClass('disabled');
            });

            $('#jplayer_interface').jPlayer('setMedia', {
                mp3: 'http://api.clubcreate.com/song/url/web/' + item.attr('uuid') + '/play/redirect.mp3'
            });
            $('#jplayer_interface').jPlayer('play');
            $('#hudPlayingTmpl').ccTemplate('replaceInto', '#hud', tmplData);
            $('#playerCurrentlyPlayingUserLink').attr('username', item.attr('username'));
            $('#playerCurrentlyPlayingCover').attr('src', 'http://users.clubcreate.com/' + encodeURIComponent(item.attr('username')) + '/large.png');
            $('#playerFavorite').attr('uuid', item.attr('uuid'));
            $('#playerVote').attr('uuid', item.attr('uuid'));
            $('#playerShare').attr('uuid', item.attr('uuid'));
            $('#playerRemix').attr('href', 'http://api.clubcreate.com/song/url/web/' + tmplData.uuid + '/remix/redirect');

            if(!this.isVisible()) {
                this.show(true);
            }

            // Record the hit as well
            CC.analytics.song.play(item.attr('uuid'));

            // Trigger an event
            $(document).trigger('songchanged', tmplData);
        },
        _removeQueueItem: function(item) {
            next = $([]).add($(item).next()).add($(item).prev());
            current = $(item).is('.cc-current-queue-item');
            if(current && next.length == 0) {
                $('#jplayer_interface').jPlayer('clearMedia');
                $('#hudClearTmpl').ccTemplate('replaceInto', '#hud');
            } else if(current && this._isPlaying()) {
                this._playQueueItem(next.first());
            }
                
            $(item).remove();
        },
        _prevItem: function() {
            this._playQueueItem(this._getCurrentItem().prev());
        },
        _nextItem: function() {
            this._playQueueItem(this._getCurrentItem().next());
        },
        _isPlaying: function() {
            return !$("#jplayer_interface").data("jPlayer").status.paused;
        },
        play: function() {
            if($("#jplayer_interface").data("jPlayer").status.paused) {
                $('#jplayer_interface').jPlayer('play');
                $(document).trigger('songchanged', this.getCurrentItem());
            }
        },
        pause: function() {
            if(!$("#jplayer_interface").data("jPlayer").status.paused) {
                $('#jplayer_interface').jPlayer('pause');
                $(document).trigger('songchanged', null);
            }
        },
        queueItem: function(username, displayName, name, uuid, now) {
            var currentItem = this.getCurrentItem(),
            item = {
                username: username,
                displayName: displayName,
                name: name,
                uuid: uuid
            };
            
            if(currentItem && item.uuid.substring(0,31) == currentItem.uuid.substring(0,31)) {
                if($("#jplayer_interface").data("jPlayer").status.paused) {
                    this.play();
                } else {
                    this.pause();
                }
                return;
            }
            
            this._addQueueItem(item, now);

            if(now || $('#playerQueue').children().length == 1) {
                this._playQueueItem($('#playerQueue li').first());
            }
        },
        getCurrentItem: function() {
            var item = this._getCurrentItem();
            if(item.length == 0) {
                return null;
            }

            var result = {
                uuid: item.attr('uuid'),
                name: item.attr('song-name'),
                username: item.attr('username'),
                displayName: item.attr('display-name')
            };
            return result;
        },
        isInQueue: function(uuid) {
            return $('#playerQueue li[uuid="' + uuid + '"]').length > 0;
        },
        isPlaying: function(uuid) {
            return this._getCurrentItem().attr('uuid') == uuid && this._isPlaying();
        },
        hide: function(animate) {
            if(animate) {
                $('#player').animate({
                    bottom: '-175px'
                }, {
                    queue: false,
                    duration: 'normal'
                }, 'swing');
            } else {
                $('#player').css('bottom', '-175px');
            }
        },
        show: function(animate) {
            if(animate) {
                $('#player').animate({
                    bottom: '-85px'
                }, {
                    queue: false,
                    duration: 'normal'
                }, 'swing');
            } else {
                $('#player').css('bottom', '-85px');
            }
        },
        isVisible: function() {
            return parseInt($('#player').css('bottom')) > -175;
        }
    };
})(jQuery);
