/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/AwesomePager/UI_AwesomePager.js ======== */

var Amie = Amie || {};

Amie.UI = window.Amie.UI || {};

Amie.UI.AwesomePager = (function () {
    function loadWithScope(contentId, url, scope, stateful) {
        var s = scope || 'global';
        var options = { url: url, type: "GET", success: handleSuccess(contentId), scope: s};
        if(stateful){
			var path = $.history_manager.getPathName();
        	var params = url.split('?')[1];
        	$.history_manager.load_inner_ajax(options,path + '?' + params);
        }
        else{
        	$.ajax(options);
        }
    }

    function handleSuccess(contentId) {
        return function(data) {
            $("#" + contentId).empty().html(data);
        };
    }

    return function (pagerId, contentId, url, currentPage, scope, stateful) {
        $("#" + pagerId + " .num").click(function() {
            loadWithScope(contentId, url + $(this).text(), scope, stateful);
            $("#"+contentId).trigger('ui_awesomepager.page_changing', {page: $(this).text()});
        });
        $("#" + pagerId + " .prev").click(function() {
            loadWithScope(contentId, url + (currentPage - 1), scope, stateful);
            $("#"+contentId).trigger('ui_awesomepager.page_changing', {page: (currentPage - 1)});
        });
        $("#" + pagerId + " .next").click(function() {
            loadWithScope(contentId, url + (currentPage + 1), scope, stateful);
            $("#"+contentId).trigger('ui_awesomepager.page_changing', {page: (currentPage + 1)});
        });
    };
})();/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Carousel/UI_Carousel.js ======== */

(function () {
/**
*   A javascript API for the UI_Carousel component
*   4 panes per tab
*/

Amie.UI.carousel = function (wrapper) {
        var self = this;
        this.wrapper = wrapper;
        this.scrollElement = wrapper.find('.ui-carousel-scroller')[0];
        this.currentSection = wrapper.find('.ui-carousel-section:first');
        this.locationSet = wrapper.find('.ui-carousel-location');
        //this.tabSet = wrapper.find('.ui-tab-collection');
        
        wrapper.find('.ui-carousel-arrow-left').click(function() {self.scrollPrev();});
        wrapper.find('.ui-carousel-arrow-right').click(function() {self.scrollNext();});
        /*wrapper.find('.ui-tab').(function (e) {
            var elem = $(e.target);
            var tab = elem.hasClass('ui-tab') ? elem : elem.parents('.ui-tab');
            var section = tab.parents('ul').children('.ui-tab').index(tab);
            self.scrollTo(section);
            return false;
        });*/
};
Amie.UI.carousel.prototype = {
    scrollAnimation: {time:0, begin:0, end:0, change:0.0, duration:0.0, timer:null},
    scrollNext: function () {
        var next = this.currentSection.next('.ui-carousel-section');
        //var tab = this.tabSet.find('.ui-tab.selected').next();
        var currentLocation = this.locationSet.find('.selected').next();
        if (!next.is('*')) {
            next = this.wrapper.find('.ui-carousel-section:first');
            //tab = this.tabSet.find('.ui-tab:first');
            currentLocation = this.locationSet.find('div:first');
            //console.debug('currentLocation is *');
        }
        //console.debug(currentLocation);
        //Amie.UI.tab.select(tab);
        this.locationSet.children('div').removeClass('selected');
        currentLocation.addClass('selected');
        this._scrollTo(next);
        return false;
    },
    scrollPrev: function () {
        var prev = this.currentSection.prev('.ui-carousel-section');
        //var tab = this.tabSet.find('.ui-tab.selected').prev();
        var currentLocation = this.locationSet.find('.selected').prev();
        if (!prev.is('*')) {
            prev = this.wrapper.find('.ui-carousel-section:last');
            //tab = this.tabSet.find('.ui-tab:last');
            currentLocation = this.locationSet.find('div:last');
        }
        //Amie.UI.tab.select(tab);
        this.locationSet.children('div').removeClass('selected');
        currentLocation.addClass('selected');
        this._scrollTo(prev);
        return false;
    },
    scrollTo: function (section) {
        var next = this.wrapper.find('.ui-carousel-section').eq(section);
        this._scrollTo(next);
    },
    loadFrom: function(url){
        var self = this;
        self.wrapper.find('.ui-carousel-long').html('');
        this.wrapper.find('.ui-loader').show();
        $.ajax({
            type: "GET",
            url: url,
            data: {},
            success:
            function(data){
               self.wrapper.find('.ui-loader').hide();
               var a = 1;
               var newLoc = '';
               while(a <= ($(data).find('div.ui-carousel-section').length)){
                  newLoc += '<div class="location-'+a+'">&nbsp;</div>';
                  a++;
               }
               self.wrapper.find('.ui-carousel-long').html(data);
               self.locationSet.children().removeClass('selected');
               self.wrapper.find('div.ui-carousel-location').html(newLoc);
               self.locationSet.find('.location-1').addClass('selected');
            }
        });
        
        
        this.wrapper.find('.ui-carousel-long').show();
    },
    _scrollTo: function (next) {
        var anim = this.scrollAnimation;
        if (anim.timer) {
            clearInterval(anim.timer);
            anim.timer = null;
        }
        anim.time = 0;
        anim.duration = 30;
        anim.begin = this.scrollElement.scrollLeft;
        anim.end = next.attr('offsetLeft');
        anim.change = anim.end - anim.begin;
        this.currentSection = next;
        
        var self = this;
        anim.timer = setInterval(function() {self._scroll();}, 15);
    },
    _scroll: function () {
        var anim = this.scrollAnimation;
        if (anim.time > anim.duration) {
            clearInterval(anim.timer);
            anim.timer = null;
        }
        else {
            var move = sineInOut(anim.time, anim.begin, anim.change, anim.duration);
            this.scrollElement.scrollLeft = move;   // Avoid using jquery attr method for speed
            anim.time++;
        }
    }
};

$(document).bind('amie.ready', function() {
    $('.ui-carousel').each(function(){
        if(!$(this).data('carousel')){
        	$(this).data('carousel', new Amie.UI.carousel($(this)));
            $('.location-1').addClass('selected');
            $(this).find('.ui-carousel-location > div').click(function(){
            	var page = $(this).attr('class').replace(' selected', '').replace('location-', '');
            	$(this).siblings().removeClass('selected');
            	var w = $(this).parents('.ui-carousel');
            	w.data('carousel')._scrollTo(w.find('.section-'+page));
            	$(this).addClass('selected');
            });
        }
    });
});

function sineInOut(t, b, c, d) {
    return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
}

})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/ContextualHelp/UI_ContextualHelp.js ======== */

(function () {
    
    /**
    *   A javascript API for the UI_ContextualHelp component
    */
    Amie.UI.ContextualHelp = function() {
        
        var showTooltip = function(e) {
            var self = this;
            $(self).children().show();
            $.log("help is on the way!");
        };
        
        var hideTooltip = function(e) {
            var self = this;
            $(self).children().hide();
           $.log("help is on the way out");
        };
        
        $('.ui-contextual-help').hover(showTooltip,hideTooltip);
    };
    
    var help = new Amie.UI.ContextualHelp();
    
    
})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/CountdownTimer/UI_CountdownTimer.js ======== */

$(function() {

      Amie.UI.CountdownTimer = function(options) {
          this.options = options;
          this.elem = options.elem;
          this.init();
      };

      Amie.UI.CountdownTimer.prototype = {
          init: function() {
              $.log("countdown timer init");
              this.endTime = new Date().getTime() + 1000*(this.options.startSeconds);
              this.endTime -= 1000; // because if we start at exactly 10 minutes, it'll show 11 minutes for a second
              this.options.startCallback();
              this.tick();
              var self = this;
              this.ticker = setInterval(function() { self.tick(); }, 1000);
          },

          update: function() {
              this.elem.html(this.format(this.seconds));
          },

          tick: function() {
              this.seconds = Math.round((this.endTime - new Date().getTime())/1000);
              this.update();
              if (this.seconds <= 0) {
                  clearInterval(this.ticker);
                  this.options.endCallback();
              }
          },

          format: function(secs) {
              var min = Math.floor(secs / 60);
              var sec = String(secs % 60);

              if (min >= 1) {
                return (min + 1) + ' minutes';
              }
              if (sec.length == 1) { sec = "0" + sec; }
              return min + ':' + sec;
          }

      };
});
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Cropper/UI_Cropper.js ======== */

(function () {

Amie.UI.Cropper = function(selection_div, img_div, wrapper_div, options) {
    this.selection_div = selection_div;
    this.img_div = img_div;
    this.wrapper_div = wrapper_div;

    var self = this;

    selection_div.css('top', '0');
    selection_div.css('left', '0');

    self.options = options;

    var img = $(img_div).find("img");
    var imgsrc = img.attr("src");

    var loader_img = wrapper_div.find('.ui-cropper-loader-image');

    img_div.css({ opacity: 0.5 });

    // We have to wait until the img is loaded before we try to get its size.
    // Otherwise, we'll think it's 0x0 and all hell will break loose.
    // We also have to use this loader_img rather than using the actual image,
    // since the actual image starts off display:hidden and therefore has 0 width
    // and height on some browsers.
    loader_img.bind(
        'load',
        function() {
            self.orig_size = [loader_img.get(0).width, loader_img.get(0).height];
            size = self.orig_size;

            outerWidth = wrapper_div.get(0).offsetWidth - 10;
            self.scaleFactor = outerWidth / size[0];

            scaledSize = [size[0] * self.scaleFactor, size[1] * self.scaleFactor];

            $(selection_div).resizable({
                        containment: wrapper_div,
                        handles: 'se',
                        knobHandles: true,
                        autohide: false,
                        minWidth: self.options.minWidth * self.scaleFactor,
                        minHeight: self.options.minHeight * self.scaleFactor,
                        resize: function (e, ui) { return self.resize(e, ui); },
                        stop: function(e, ui) { return self.stop(e, ui); }
                }).
            draggable({
                        cursor: 'move',
                        containment: wrapper_div,
                        drag: function(e, ui) { return self.drag(e, ui); },
                        stop: function(e, ui) { return self.stop(e, ui); }
                });


            img_div.css( { position: 'relative' } );

            img_div.css( { width: scaledSize[0] + "px",
                           height: scaledSize[1] + "px",
                                 display: 'block' } );

            img.css(  { width: scaledSize[0],
                        height: scaledSize[1] } );


            img2 = img.clone();
            img2.css( { position: 'absolute', top: 0, left: 0} );
            img2.appendTo(selection_div);

            self.img2 = img2;

            wrapper_div.css( {  position: 'relative' } );
            selection_div.css('position', 'absolute');
            selection_div.position.top = 0;
            selection_div.position.left = 0;

            if (options) {
                if (options.defaultTop) {
                    selection_div.css({'top': options.defaultTop * self.scaleFactor});
                    img2.css({top: -1 * options.defaultTop * self.scaleFactor});
                }
                if (options.defaultLeft) {
                    selection_div.css({'left': options.defaultLeft * self.scaleFactor});
                    img2.css({left: -1 * options.defaultLeft * self.scaleFactor});
                }
                if (options.defaultWidth) {
                    selection_div.css('width', options.defaultWidth * self.scaleFactor);
                }
                if (options.defaultHeight) {
                    selection_div.css('height', options.defaultHeight * self.scaleFactor);
                }
            }

            // Update form to defaults
            var form = document.forms[options.formName];
            form.x.value = options.defaultLeft;
            form.y.value = options.defaultTop;
            form.width.value = options.defaultWidth;
            form.height.value = options.defaultHeight;

            if (options.onReady) { options.onReady(); }
        });
    // Because the image might be cached or have loaded super fast, we check
    // if it's already complete and trigger the load() function manually
    if (loader_img[0].complete) {
        loader_img.load();
    }
};


Amie.UI.Cropper.prototype = {

    resize: function(e, ui) {
        var data = this.selection_div.data("resizable");
        var ar = (data.size.width) / (data.size.height);
        
        if (this.options.maxRatio && ar > this.options.maxRatio) {
            data.size.width = data.size.height * this.options.maxRatio;
        } else if (this.options.minRatio && ar < this.options.minRatio) {
            data.size.height = data.size.width / this.options.minRatio;
        }
    },

    stop: function(e, ui) {
//        $.log("stop");
        this.updateForm();
    },

    drag: function(e, ui) {
        if (ui.position.left < 0) {
            ui.position.left = 0;
        }
        if (ui.position.top < 0) {
            ui.position.top = 0;
        }
        this.img2.css({left: -1 * ui.position.left, top: -1 * ui.position.top});
//        $.log("left: " + ui.position.left + " top: " + ui.position.top);
    },

    updateForm: function() {
        var form = document.forms[this.options.formName];

//        $.log('selection width, height: ' + [this.selection_div.width(), this.selection_div.height()]);
        form.width.value = Math.round(this.selection_div.width() / this.scaleFactor);
        form.height.value = Math.round(this.selection_div.height() / this.scaleFactor);

        var pos = this.selection_div.data("draggable").position;
        if (pos) {
            form.x.value = Math.floor(pos.left / this.scaleFactor);
            form.y.value = Math.floor(pos.top / this.scaleFactor);
        }
    }
};


})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/FlashMessage/UI_FlashMessage.js ======== */

$(function () {
/**
*    A javascript API for UI_FlashMessage
*/

Amie.UI.flashMessage = function (message, typeParam, optionsParam) {
    var type = typeParam || 'explanation';
    var options = optionsParam || {};
    var timeout = options.timeout || 5000;
    var container = $(options.container || $('#ajax-flash-message'));
    clearTimeout(container.data('timeout'));
    
    container.html(message);
    container.show();
    
    var self = this;
    container.data('timeout', setTimeout(function(){
        container.fadeOut('slow');
        delete self;
    }, timeout));
};
Amie.UI.flashMessage.prototype = {
    
};

$(document).bind('amie.ready',
                 function() {
                     $('.ui-flashmessage .close-button').click(
                         function() { $(this).parent('.ui-flashmessage').remove(); return false; }
                         ).show();
                 });
    
});
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Form/UI_Form.js ======== */

	Amie.UI.validateForm = function(formEl, action, additionalPosts){
		var form = $(formEl);
		var outgoing = {};
		$(form).find('input[type!=submit]').each(function(){
		    if (!$(this).attr('disabled')) {
		        outgoing[this.id] = $(this).val();
		    }
		});
		$(form).find('select').each(function(){
	        outgoing[this.id] = $(this).val();
	    });
	    if(typeof additionalPosts != "undefined" && additionalPosts.length > 0){
		    $.each(additionalPosts, function(){
		        outgoing[this] = $('#'+this).val();
		    });
	    }
	    var doServer = true;
	    
	    $('.as-input-required').each(function(){
          if ((this.type == 'checkbox') && (!this.checked)) {
              Amie.UI.raiseValidationError($(this), 'You must check this box to continue.');
              doServer = false;
          }
	    });

        var successFn =
            function(data) {
                if(data.success){
		            $(form).get(0).submit();
		        }
		        else{
		            $.each(data.messages, function(i, n) {
                        Amie.UI.raiseValidationError($('#'+this[0]), this[1][0]);
		            });
		        }
            };

        var submitAnywayFn =
        function(XMLHttpRequest, textStatus, errorThrown) {
                $(form).get(0).submit();
            };

	    if(doServer){
		    $.ajax({
                  url: action,
                  data: outgoing,
                  type: 'POST',
                  dataType: 'json',
                  error: submitAnywayFn,
                  success: successFn,
                  timeout: 3000
                });
	    }
	};
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/HuluThing/UI_HuluThing.js ======== */

Amie.UI.HuluThing = function(elem) {
    var self = this;
    this.elem = elem;
    this.selected = $(elem).find('li.selected').prevAll().length;
    this.fading = false;
    this.resetTimeout();
    if ($(elem).data('tor')) {
        this.TIMEOUT_LEN = $(elem).data('tor');
    }
    $(elem).find('.ui-tab a').click(function (e) { self.handleClick(this); });
};

Amie.UI.HuluThing.prototype = {
    TIMEOUT_LEN: 15000,

    handleClick: function(link) {
        var newPos = $(link).parents('.ui-tab').prevAll().length;
        this.rotateTo(newPos);
    },

    resetTimeout: function() {
        var self = this;
        if (this.timeout) { clearTimeout(this.timeout); }
        this.timeout = setTimeout(function() { self.rotateNext(); }, this.TIMEOUT_LEN);
    },

    rotateNext: function() {
        if ($(this.elem).data('ui-huluthing') != this) {
            return;
        }

        var count = $(this.elem).find('.ui-huluthing-entry').length;
        var nextP = (this.selected + 1 ) % count;
        var tab = $(this.elem).find('li.ui-tab-huluthing').eq(nextP);

        Amie.UI.selectTab(tab.attr('id'));
        this.rotateTo(nextP);
    },

    rotateTo: function(newPos) {
        var self = this;
        var oldPos = this.selected;
        if (oldPos == newPos) { return; }

        var current = $(this.elem).find('.ui-huluthing-entry').eq(oldPos);
        var next    = $(this.elem).find('.ui-huluthing-entry').eq(newPos);

        if (this.fading) {
            this.postFade = function() { self.rotateTo(newPos); };
            return;
        }

        this.resetTimeout();
        this.selected = newPos;
        this.fading = true;

        current.fadeOut(150, function() {
                            next.fadeIn(250, function() {
                                            var pf = self.postFade;
                                            self.fading = false;
                                            if (pf) {
                                                self.postFade = undefined;
                                                pf();
                                            }
                                        });
                        });
    }
};

$(document).bind('amie.ready',
                 function() {
                     $('.ui-huluthing').each(
                         function() {
                             if (! $(this).data('ui-huluthing')) {
                                 $(this).data('ui-huluthing', new Amie.UI.HuluThing('#' + $(this).attr('id')));
                             }
                         });
                 });
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Image/UI_Image.js ======== */

// http://images.amiestreet.com/album-art/Big-Bang-Theory-Theme-by-Barenaked-Ladies_25975_full.jpg
    
$(document).bind('amie.ready', function () {
    var albumPic = '.ui-image-album-zoom-enabled,.ui-image-artist-zoom-enabled';
    $('.zoom-box').hide();
    
    $('#as-page-inner-content')
    .delegate('mouseover', albumPic, function () {
        var self = $(this);
        if (self.data('zoom-box')) {
            return;
        }

        $("div.zoom-box").remove();
        var zoombox;
        if (self.hasClass('ui-image-album-zoom-enabled')){
            zoomBox = $('<div class="zoom-box album-zoom"></div>');
        }
        else if (self.hasClass('ui-image-artist-zoom-enabled')){
            zoomBox = $('<div class="zoom-box artist-zoom"></div>');
        }
        self.data('zoom-box', zoomBox);
        var image = new Image();
        image.src = self.attr('href');
        var dimensions = {width: 500, height: 500};
        $(image).bind('load', function(){
        	var ratio = image.height/image.width;
        	if(ratio > 1){
              dimensions.height = 500;
              dimensions.width = 500 / ratio;
        	}
        	else if(ratio < 1){
              dimensions.width = 500;
              dimensions.height = 500 * ratio;
        	}
        	$(image).data('dimensions', dimensions);
        });
        
        $(image).width('100%');
        $(image).height('100%');
        zoomBox.append(image);
        zoomBox.hide();
        $('#as-page-inner-content').append(zoomBox);
    })
    .delegate('click', albumPic, function (e) {
        e.stopPropagation();
        var self = $(this);
        var zoomBox = self.data('zoom-box');
        var container = self.parents('div.ui-image');
        $('.zoom-box').show();
        position(zoomBox, container);
        
        zoomBox.one('click', function (event) {
            event.stopPropagation();
            var self = $(this);
            self.animate({
                width: container.width(),
                height: container.height()
            }, 500, 'swing', function () {self.hide();});
            return false;
        });
        var a_width = ($('div.zoom-box img').data('dimensions')) ? $('div.zoom-box img').data('dimensions').width : 500;
        var a_height = ($('div.zoom-box img').data('dimensions')) ? $('div.zoom-box img').data('dimensions').height : 500;
        zoomBox.animate({
            width:  a_width,
            height: a_height
        }, 500);
        return false;
    });
    
    var position = function (target, src) {
        var offset = src.offset();
        target.css('left', offset.left + 'px');
        target.css('top', offset.top + 'px');
        target.width(src.width());
        target.height(src.height());
    };
    
});
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/InlineEdit/UI_InlineEdit.js ======== */

$(function() {
/**
 * Javascript object for inline editing of fields on Profile, Playlist, etc
 */
      Amie.UI.InlineEdit = function(elem, options) {
          var self = this;
          this.elem = elem;
          this.elem.click(function() { self.click(); });
          this.elem.addClass('editable');
          this.options = options;
      };

      Amie.UI.InlineEdit.prototype = {
          click: function() {

              // Set up the input where the editing happens

              var input;
              if (this.options.tag == 'input') {
                  input = $('<input type="text">');
              } else {
                  input = $('<textarea>');
              }
              input.attr('value', this.elem.text());


              // Set up the save/cancel buttons
              var buttonDiv = $('<div class="edit-buttons">');

              var self = this;
              var saveButton = $('<input type="button" value="SAVE" class="save-button"/>');
              saveButton.click(function() { return self.saveChanges(input.attr('value')); });

              var cancelButton = $('<input type="button" value="CANCEL" class="cancel-button"/>');
              var oldHtml = this.elem.html();
              cancelButton.click(function() { return self.revertChanges(oldHtml); });

              buttonDiv.append(saveButton).append(cancelButton);
              this.elem.empty().addClass('editing').removeClass('editable').unbind('click');
              this.elem.append(input).append(buttonDiv);
          },

          saveChanges: function(text) {
              var self = this;
              $.post(this.options.action,
                     {content: text, field: this.options.field},
                     function (response) { self.response(response); });
              return false;
          },

          revertChanges: function(oldHtml) {
              return this.stopEditing(oldHtml);
          },

          response: function(response) {
              this.stopEditing(response);
              var update = this.options.update;
              var updateSpace = '#'+update;
              $(updateSpace).text("Your changes have been saved");
              $(updateSpace).show('slow');
              setTimeout(function() {
                             $(updateSpace).hide('slow');
                         }, 2000);
          },

          stopEditing: function(newHtml) {
              var self = this;
              this.elem.empty().addClass('editable').click(function() { self.click(); });

              this.elem.html(newHtml);
              return false;
          }
      };

  });
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/InlineHelp/UI_InlineHelp.js ======== */

(function() {
    function hideInlineHelp() {
        $(this).parent('.ui-inlinehelp-collapse').slideUp();
        return false;
    }

    $(document).bind('amie.ready', function() {
        $('.collapse-link').click(hideInlineHelp);
    });
})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Input/UI_Input.js ======== */

/**
*   A javascript API for the auto complete option of the UI_Input component
*   use Amie.UI.input.register(callback) to recieve json when the input value changes
*/
Amie.UI.autocompleteInput = function (inputEl, url) {
    var self = this;
    var input = $(inputEl);
    this.input = input;
    this.xhr = null;
    this.url = url;
    this._listeners = [];
    this._cache = {};
    this.curTimeout = null;

    input.attr('autocomplete','off');
    input.data('autocomplete', true);
    input.keyup(function (e) {self.run(e, url);});
};
Amie.UI.autocompleteInput.prototype = {
    run: function (e, url) {
        if (!this.input.data('autocomplete')) {
            return;
        }
        var self = this;
        var input = this.input;
        var props = {};
        var value = input.attr('value');
        props[input.attr('name')] = value;
        
        if (value == this.oldValue && e.type == 'keyup') {
            return;
        }

        this.oldValue = value;
        
        if (value.length < 2) {
            this.results = false;
            this.update();
            return;
        }
        
        if (this.xhr) {
            this.xhr.abort();
        }
        // Check Cache
        if (this._cache[value]) {
            this.results = this._cache[value];
            this.update();
        } else {
            if (this.curTimeout) {
                clearTimeout(this.curTimeout);
            }
            this.curTimeout = setTimeout(
                function() {
                    this.xhr = $.get(
                        url, 
                        props, 
                        function(data, status){
                            self._cache[value] = data;
                            self.results = data;
                            self.update();
                        }
                    );
                },
                300);
        }
    },
    update: function () {
        for (var i = 0, length = this._listeners.length; i < length; i++) {
            this._listeners[i](this.results);
        }
    },
    register: function (callback) {
        this._listeners.push(callback);
    }
};
Amie.UI.validateInput = function(inputEl, action, additionalPosts){
        var input = $(inputEl);
        if (input.attr('disabled')) {
            return;
        }
        var outgoing = {};
        outgoing[input.get(0).id] = input.val();
        if(typeof additionalPosts != "undefined" && additionalPosts.length > 0){
            $.each(additionalPosts, function(){
                outgoing[this] = $('#'+this).val();
            });
        }
        $.post( action, 
                outgoing,
                function(data){
                    if(data.success){
                        Amie.UI.raiseValidationSuccess(input);
                    }
                    else{
                        $.each(data.messages, function(i, n) {
                            Amie.UI.raiseValidationError($('#'+this[0]), this[1][0]);
                        });
                    }
                },
                'json'
        );
    };
    
    Amie.UI.raiseValidationError = function(input, message){
        $(input).addClass('error').removeClass('valid');
        var el = $(input).get(0);
        $('#error-'+el.id).remove();
        $(input).after('<span class="errorWrapper" id="error-'+el.id+'"><div class="error">'+message+'</div></span>');
    };
    Amie.UI.raiseValidationSuccess = function(input){
        $(input).addClass('valid').removeClass('error');
        $('#error-'+$(input).get(0).id).remove();
    };
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Lightbox/UI_Lightbox.js ======== */

/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').uiLightbox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.uiLightbox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.uiLightbox(function($) { 
 *      $.get('blah.html', function(data) { $.uiLightbox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.uiLightbox({ ajax: 'remote.html' })
 *    jQuery.uiLightbox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.uiLightbox' document event:
 *
 *    jQuery(document).trigger('close.uiLightbox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.uiLightbox
 *    beforeReveal.uiLightbox
 *    reveal.uiLightbox (aliased as 'afterReveal.uiLightbox')
 *    init.uiLightbox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.uiLightbox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.uiLightbox = function(data, klass) {  
    $.uiLightbox.loading();

    if (data.ajax) { fillFaceboxFromAjax(data.ajax); }
    else if (data.image) { fillFaceboxFromImage(data.image); }
    else if (data.div) { fillFaceboxFromHref(data.div); }
    else if ($.isFunction(data)) { data.call($); }
    else { $.uiLightbox.reveal(data, klass); }
  };

  /*
   * Public, $.uiLightbox methods
   */

  $.extend($.uiLightbox, {
    settings: {
      opacity      : 0.4,
      overlay      : true,
      loadingImage : '/static/images/loading.gif',
      closeImage   : '/static/images/ui_lightbox_close.png',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ]
    },
    
    originalPageTitle: document.title,

    loading: function() {
      init();
      if ($('#ui-lightbox .loading').length == 1) return true
      showOverlay()

      $('#ui-lightbox .content').empty()
      $('#ui-lightbox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.uiLightbox.settings.loadingImage+'"/></div>')
		
      $('#ui-lightbox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	($(window).width()/2) - $('#ui-lightbox').width()/2
      }).show()

      $(document).bind('keydown.uiLightbox', function(e) {
        if (e.keyCode == 27) $.uiLightbox.close()
        return true
      })
      $(document).bind('beforeReveal.uiLightbox', function(){
          $.uiLightbox.originalPageTitle = document.title;
      });
      $(document).trigger('loading.uiLightbox');
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.uiLightbox')
      if (klass) $('#ui-lightbox .content').addClass(klass)
      $('#ui-lightbox .content').html(data)
      $('#ui-lightbox .loading').remove()
      $('#ui-lightbox .body').children().fadeIn('normal')
      $('#ui-lightbox').css('left', $(window).width() / 2 - ($('#ui-lightbox').width() / 2))
      $(document).trigger('reveal.uiLightbox').trigger('afterReveal.uiLightbox')
    },

    close: function() {
      $(document).trigger('close.uiLightbox')
      return false
    },
    
    makeUrl: function(url) {
       return "/lightbox/r?url=" + escape(url);
    },
    gracefulRedirect: function(message, url, timeout){
        if ($.player.isVisible()) {
            $.uiLightbox('<div class="page-redirect">'+message+'</div><div class="page-redirect-link spacer-top-2" style="text-align:center;"><a href="'+url+'" onclick="$.uiLightbox.close();">If a new window does not open in 5 seconds, please click here</a></div>');
        	fn = function(){
    	    	window.open(url);
        		$.uiLightbox.close();
    		};
        } else {
            $.uiLightbox('<div class="page-redirect">'+message+'</div><div class="page-redirect-link spacer-top-2" style="text-align:center;"><a href="'+url+'" onclick="$.uiLightbox.close();">If redirect does not happen in 5 seconds, please click here</a></div>');
            fn = function(){
                document.location.href = url;
            }
        }
        window.setTimeout(fn, timeout);
    },
    historyManagerRender: function(url, response){
        $.uiLightbox.reveal(response, null);
    },
    historyManagerError: function(url, opts, XMLHttpRequest, textStatus, errorThrown){
        $.uiLightbox.gracefulRedirect(url, "An error occurred while processing your request.  One second while we try to resolve it.", 1000);
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.uiLightbox = function(settings) {
    init(settings)

    function clickHandler() {
      $.uiLightbox.loading(true)
      var klass = this.rel.match(/ui-lightbox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]
      fillFaceboxFromHref(this.href, klass)
      return false
    }
    return this.click(clickHandler)
  }
  // called one time to setup facebox on this page
  function init(settings) {
    if ($.uiLightbox.settings.inited) return true
    else $.uiLightbox.settings.inited = true

    $(document).trigger('init.uiLightbox')
    makeCompatible()

    var imageTypes = $.uiLightbox.settings.imageTypes.join('|')
    $.uiLightbox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.uiLightbox.settings, settings)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.uiLightbox.settings.closeImage
    preload[1].src = $.uiLightbox.settings.loadingImage

    $('#ui-lightbox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#ui-lightbox .close').click($.uiLightbox.close)
    $('#ui-lightbox .close_image').attr('src', $.uiLightbox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.uiLightbox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.uiLightbox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.uiLightbox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.uiLightbox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
      if(href.indexOf('https') > -1){
          $.history_manager.navigate(href, $.uiLightbox.historyManagerRender, 1, $.uiLightbox.historyManagerError);
      }
      else{
          $.get(href, function(data) { $.uiLightbox.reveal(data, klass) })
      }
  }

  function skipOverlay() {
    return $.uiLightbox.settings.overlay == false || $.uiLightbox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('#ui-lightbox_overlay').length == 0) 
      $("body").append('<div id="ui-lightbox_overlay" class="ui-lightbox_hide"></div>')

    $('#ui-lightbox_overlay').hide().addClass("ui-lightbox_overlayBG")
      .css('opacity', $.uiLightbox.settings.opacity)
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#ui-lightbox_overlay').fadeOut(200, function(){
      $("#ui-lightbox_overlay").removeClass("ui-lightbox_overlayBG")
      $("#ui-lightbox_overlay").addClass("ui-lightbox_hide") 
      $("#ui-lightbox_overlay").remove()
    })
    
    return false
  }
  
  window.openLightbox = function(url, klass){
  	  $.uiLightbox.loading();
  	  init();
  	  fillFaceboxFromHref(url, klass);
  }

  /*
   * Bindings
   */

  $(document).bind('close.uiLightbox', function() {
    document.title = $.uiLightbox.originalPageTitle;
    $(document).unbind('keydown.uiLightbox');
    $('#ui-lightbox').fadeOut(function() {
      $('#ui-lightbox .content').removeClass().addClass('content');
      hideOverlay();
      $('#ui-lightbox .loading').remove();
    });
  });
  
  $('#ui-lightbox .close-on-click a').live('click', function(){
      $.uiLightbox.close();
  });
  

})(jQuery);
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Loader/UI_Loader.js ======== */

/*shows the loading div every time we have an Ajax call*/
(function () {
    function loaderOnSend(event, XMLHttpRequest, ajaxOptions) {
        var s = (ajaxOptions && ajaxOptions.scope) ? ajaxOptions.scope : 'global';
        if (s == $(this).data('scope')) {
            var r = $(this).data('replace');
            $('#'+r).hide();
            $(this).show();
        }
    }

    function loaderOnComplete(event, XMLHttpRequest, ajaxOptions) {
        var s = (ajaxOptions && ajaxOptions.scope) ? ajaxOptions.scope : 'global';
        if (s == $(this).data('scope')) {
            $(this).hide();
            $('#'+$(this).data('replace')).show();
        }
    }

    function loaderOnStop(event, XMLHttpRequest, ajaxOptions){
        var s = (ajaxOptions && ajaxOptions.scope) ? ajaxOptions.scope : 'global';
        if (s == $(this).data('scope')){
            $(this).hide();
            $('#'+$(this).data('replace')).show();
        }
    }

    $(document).bind('amie.ready', function () {
        $(".ui-loader")
            .ajaxSend(loaderOnSend)
            .ajaxComplete(loaderOnComplete)
            .ajaxStop(loaderOnStop);
    });
})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Pane/UI_Pane.js ======== */

(function (Amie) {
    Amie.UI.pane = {};
    Amie.UI.pane.load = function (id, urlParam, dataParam, scopeParam) {
        var pane = $('#'+id);
        var url = urlParam || pane.data('url');
        var draw = function () {    
            Amie.UI.pane.show(id);
        };
        var data = dataParam || {};

        var target = pane.find('.ui-pane-inner');
        if (target.length === 0) {
            alert('cant find target inner pane!');
        }
        if (url) {
            var options = { 
                url: url,
                type: "GET", 
                data: data,
                scope: scopeParam || 'global',
                success: function(data) { 
                    pane.find('.ui-pane-inner').empty().html(data);
                    draw();
                }
            };
            $.ajax(options);
        } else {
            draw();
        }
        if ($.pageTracker) {
            $.pageTracker._trackEvent('UI_Pane', 'Load', id);
        }
    };
    Amie.UI.pane.setUrl = function (id, url) {
        var pane = $('#'+id);
        pane.data('url', url);
    };
    Amie.UI.pane.show = function (id) {
        var pane = $('#'+id);
        pane.show().siblings('.ui-pane').hide();
    };
    $(function () {
        var hash = $.history_manager ? $.history_manager.getRealHash() : location.hash;
        if ( hash && $('#'+hash).is('.ui-pane') ) {
            Amie.UI.pane.load(hash);
            Amie.UI.tab.select($('a[href=#'+hash+']').parents('.ui-tab'));
        }
    });
})(Amie);
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Rating/UI_Rating.js ======== */

Amie.UI.Rating = (function () {
	return function(wrapperId){
		$('#'+wrapperId).find('a.star').click(function(){
		  	$.get($(this).attr('href'), function(data){
		  		$('#'+wrapperId).find('span.rating-feedback').html('<strong>Saved!</strong>');
		  		$('#'+wrapperId).find('li.current-rating').width(parseInt(data * 14, 10)+'px');
		  	});
		  	return false;
		  }
		);
	};
})();
$(document).bind('amie.ready',function() {
    $('.ui-rating ul.star-rating > li > a.star').each(function () {
        if($(this).data('js-reg')) {
            return;
        }

        $(this).data('js-reg', true);
        $(this).hover(function(){
            var msg = '';
            switch(parseInt($(this).attr('rel'), 10)){
                case 1:
                   msg = 'Hate It!';
                break;
                case 2:
                   msg = 'Don\'t Like It';
                break;
                case 3:
                    msg = 'Think It\'s OK';
                break;
                case 4:
                    msg = 'Like It';
                break;
                case 5:
                    msg = 'Love It!';
                break;
            }
            $(this).parents('.ui-rating').find('span.rating-feedback').html(msg);
          },function(){
              if ($(this).parents('.ui-rating').find('span.rating-feedback').html() != '<strong>Saved!</strong>') {
                  $(this).parents('.ui-rating').find('span.rating-feedback').html('Rate It');
              }
          });
    });
    $('.ui-rating ul.star-rating').each(function(){
         $(this).mouseout(function(){
             if($(this).data('js-reg')) {
                return;
           }

             $(this).data('js-reg', true);
             var fb =  $(this).parents('.ui-rating').find('span.rating-feedback');
             if(fb.html().indexOf('Saved')==-1){
                fb.html('Rate It');
             }
         });
    });
});/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/ReorderLI/UI_ReorderLI.js ======== */

function makeSortable(id, opacity, update_f) {
    $('#'+id).sortable({
        opacity: opacity,
        axis: 'y',
        placeholder: 'sorting',
        update: update_f,
        sort: function(e,ui){
            $('#'+id+' .list-order').each(
                function(i) {
                    $(this).text(i+1);
                }
            );
            $('.ui-sortable-helper .list-order').text($('#'+id+' li:hidden .list-order').text());
        },
        handle: $('.draggable'),
        delay: 400
    });
}/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Spotlight/UI_Spotlight.js ======== */

(function () {
/**
 *  A javascript API for the UI_Spotlight component
 *  input:  required - the input text element with autocomplete attached
 *  output: required - the div to output the spotlight results into
 *  selectCallback: optional - a function which takes (selected_item) as an arg
 *                                             and is called when an item is selected. "this" is set to
 *                                             the UI.spotlight object
*/

Amie.UI.spotlight = function (input, selectCallback) {
    var self = this;
    
    this.ignoreKeys = 0;
    this.input = input;
    this.form = input.parents('form');
    var output = $('<div id="spotlight-output">').appendTo('body');
    this.output = output;
    
    this.selectCallback = selectCallback || defaultSelectCallback;
    
    positionBelow(input, output);
    $(window).resize(function(e){positionBelow(input, output);});
    
    input.keydown(function(e){return self.keydown(e);});
    $(window).click(function (e) {
        if (!($(e.target).index(input) > -1 || $(e.target).parents().index(self.output) > -1) && !self.lock) {
            self.hide();
        }
    });
    output.click(function (e) {
        var item = $(e.target).parents('.ui-spotlight-selectable.selected');
        if (item.is('*')) { 
            self.select(item);
            return false;
        }
    });
    
    $(window).bind('amie:inner_page_reload', function (url) {
        self.reset();
    });
    
    this.lock = false;
    
    input.data('autocomplete').register(function(r){ self.update(r); });
};

Amie.UI.spotlight.prototype = {
    update: function (results) {
        if (this.lock) { return; }
        if (!results) {
            this.hide();
        } else {
            this.output.html(results);
            this.addBehaviors();
            this.reposition();
            this.output.show();
        }
    },
    addBehaviors: function () {
        var self = this;
        this.output.find('.ui-spotlight-selectable').hover(function () {
            if(!self.lock) { highlight(this); }
        },function(){
            if(!self.lock) { $(this).removeClass('selected'); }
        });
    },
    keydown: function (e) {
        var selected = this.output.find('.ui-spotlight-selectable.selected');
        this.input.data('autocomplete',true);

        switch (e.which) {
            case 40:    // Down
                if (!selected.is('*')) {
                    selected = this.output.find('.ui-spotlight-selectable:first');
                } else {
                    var next = selected.next('.ui-spotlight-selectable:first');
                    if (next.is('*')) { selected = next; }
                }
                break;
            case 38:    // Up
                var prev = selected.prev('.ui-spotlight-selectable:last');
                if (prev.is('*')) { selected = prev; }
                break;
            case 13:    // Enter
                if (selected.is('*')) {
                    this.select(selected);
                    selected.siblings().remove();
                    this.input.data('autocomplete', false);
                    return false;
                }
                return true;
            case 27:    // ESC
                self.hide();
                return false;
            default:
                return true;
        }
        highlight(selected);
        return false;
    },
    hide: function () {
        this.output.find('.selected').removeClass('selected');
        this.output.hide();
    },
    select: function (item) {
        this.lock = true;
        this.selectCallback.call(this, item, this.input, this.output);
    },
    setInput: function(s) {
        this.input.attr('value', s);
    },
    reset: function() {
        this.lock = false;
        this.input.removeClass('spotlight-found').val('');
        this.hide();
    },
    reposition: function() {
        positionBelow(this.input, this.output);
    }
};

var highlight = function (elem) {
    elem = $(elem);
    elem.siblings('.ui-spotlight-selectable').removeClass('selected');
    elem.addClass('selected');
};

var positionBelow = function (src, dest) {
    var offset = src.offset();
    newOffset = offset.left-68;
    newTopOffset = offset.top+5;
    dest.css('left',newOffset+'px');
    dest.css('top', (newTopOffset + src.outerHeight({ margin: true }))+'px');
};

var defaultSelectCallback = function (item, input, output) {
    var link = item.find('a');
    input.addClass('spotlight-found');
    if(link.attr('rel')=='view-all'){
    	
    }
    else{
    input.attr('value', $.trim(link.text()));
    
    }
    $.history_manager.fakeLinkClick(link);
};

})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/SwitchList/UI_SwitchList.js ======== */

(function() {

Amie.UI.SwitchList = function(id, options) {
    var self = this;

    this.id = id;
    this.visibleIndex = 0;
    this.div = $('#' + id);

    if (options.prevButtonId) {
        this.prevLink = $('#' + options.prevButtonId);
    } else {
        this.prevLink = this.div.find('.ui-switchlist-prev');
    }

    if (options.nextButtonId) {
        this.nextLink = $('#' + options.nextButtonId);
    } else {
        this.nextLink = this.div.find('.ui-switchlist-next');
    }

    this.prevLink.click(function (e) { self.goRelative(-1); return false;});
    this.nextLink.click(function (e) { self.goRelative(1); return false;});

    this.update();
};

Amie.UI.SwitchList.prototype = {
    update: function() {
        this.getElems().hide();
        this.getElems().eq(this.visibleIndex).show();
        this.div.find('.ui-switchlist-index').text(this.visibleIndex + 1);
    },

    getElems: function() {
        return this.div.find('.ui-switchlist-elem');
    },

    goRelative: function(incr) {
        this.visibleIndex += incr;

        var count = this.getElems().length;

        if (this.visibleIndex < 0) {
            this.visibleIndex = count - 1;
        }
        if (this.visibleIndex >= count) {
            this.visibleIndex = this.visibleIndex % count;
        }
        this.update();
    }
};

})();
/* ======== /home/songza/sets/simpler_radio/code/acf/comps/UI/Tab/UI_Tab.js ======== */

/**
*   A javascript API for the UI_Tab component
*/

Amie.UI.tab = (function () {
    return {
        click: function (e) {
            var elem = $(e.target);
            var tab = elem.hasClass('ui-tab-enabled') ? elem : elem.parents('.ui-tab-enabled');
            this.select(tab);
            return false;
        },
        select: function (tab) {
          tab.siblings('.ui-tab').each(function () {
            Amie.UI.tab.unselect(this);
          });
          tab.addClass('selected');
        },
        unselect: function(tab) {
          // Find the UI Pane selector from our tab href and hide that pane
          var  paneSelector = $(tab).children('a').attr('href');
          var pane = $(paneSelector);
          if (pane && pane.hasClass('ui-pane')) { pane.hide(); }
  
          $(tab).removeClass('selected');
        }
    };
})();

Amie.UI.selectTab = function(id){
    if(id.indexOf(',')>-1){
        $.map(id.split(','), function(i){
            Amie.UI.selectTab(i);
        });
    }
    else{
        var tab = $('#'+id);
        tab.siblings('.ui-tab').each(function () {
          Amie.UI.tab.unselect(this);
        });
        tab.addClass('selected');

        // If this is a tab within a secondary nav tabset, hide the
        // other secondary nav tabsets
        if(tab.parent().parent().hasClass('secondary-nav-tabset')){
            var subNav = $(tab.parent().parent());
            subNav.siblings('.secondary-nav-tabset').hide();
            subNav.show();
        }

        // If this is a tab within global nav, unselect other nav sets
        if(tab.parents('#global-nav').length > 0){
            $('.secondary-nav-tabset li.ui-tab.selected').removeClass('selected');
            $('.secondary-nav-tabset').hide().eq(tab.prevAll().length).show();
        }
    }
};

Amie.UI.unselectAllTabs = function(){
  $('.ui-tab').each(function () {
    Amie.UI.tab.unselect(this);
  });
};

Amie.UI.NavTabRollover = {
    init: function() {
        var self=this;
        this.addHover($('#secondary-nav-left'));
        this.addHover($('#global-nav .ui-tab-enabled'));

        // this is important so during persistent play when we
        // click on a tab, it'll select while the page loads
        $('#global-nav .ui-tab').click(
            function() {
                Amie.UI.selectTab($(this).attr('id'));
                self.fadeToTab($(this).attr('id'));
            });
    },

    addHover: function(els) {
        var self = this;
        els.hover(function() {
            var tabLag = $('#global-nav .tab-hover-lag').length;
            self.setTimeout(tabLag ? 600 : 300);
            $(this).addClass('tab-hover');
        }, function() {
            var tab = this;
            $(tab).removeClass('tab-hover');
            // add a "lag" class that means that we've recently hovered over a
            // tab - this causes timeouts on hover-in to be longer so we don't
            // accidentally switch when moving from tab to secondary nav (see #2724)
            $(tab).addClass('tab-hover-lag');
            setTimeout(function() { $(tab).removeClass('tab-hover-lag'); }, 600);
            self.setTimeout(600);
        });
    },

    setTimeout: function(time) {
        var self = this;
        if (this.timeout) {
            clearTimeout(this.timeout);
        }
        this.timeout = 
            setTimeout(function() { self.update(); },
                       time);
    },

    update: function() {
        var hoverTab = $('#global-nav .ui-tab-enabled.tab-hover').attr('id');
        if (hoverTab) {
            this.fadeToTab(hoverTab);
        } else if ($('#secondary-nav-left.tab-hover').length) {
        } else {
            this.fadeToStatic();
        }
    },

    fadeToStatic: function() {
        var staticId = $('#global-nav .ui-tab-enabled.selected').attr('id');
        this.fadeToTab(staticId);
    },

    fadeToTab: function(tabId) {
        var navId = tabId + '-nav';
        var curDisp = $('#' + navId).css('display');

        // If we persistent-played and clicked on a tab, it becomes
        // selected while it's still nav-hover, but we don't want
        // that!
        $('#'+tabId+'.nav-hover.selected').removeClass('nav-hover');

        if (tabId === undefined || (curDisp && (curDisp == 'none'))) {
            $('#global-nav li').removeClass('nav-hover').addClass('no-hover');
            $('.secondary-nav-tabset').hide();

            if (tabId) {
                $('#' + tabId + ':not(.selected)').addClass('nav-hover');
                $('#' + tabId).removeClass('no-hover');
                $('#' + navId).show();
            }
        } else {
            $('#' + navId).removeClass('noHover');
        }
    }

};
    
$(document).bind('amie.ready', function() {
    $('.ui-tab-dropdown-link').removeAttr('onclick');
    // preload images
    $(['dropdown-top.png','dropdown-bottom.gif','selected-right.png']).each(function() {
        $('<img>').attr('src', '/static/acf/ui-tab/' + this);
    });

    $('.usejs .ui-tab-enabled').click(function (e) {
        return Amie.UI.tab.click(e) || $(this).parents('.load-pane').is('*');
    });

    $('.ui-tab-dropdown').hoverIntent(function() {
        genreDropdown();
    },
    function() {
        genreDropdown();
    });
    $('.ui-tab-dropdown-link').click(function(){
        return false;
    });

    Amie.UI.NavTabRollover.init();
});

function genreDropdown() {
    $('.ui-tab-dropdown-link').parent('li').toggleClass('dropped');
    $('.ui-tab-dropdown .ui-tab-dropdown-container').toggle();
    return false;
}
