(function ($) {
    // prototype functions
    String.prototype.replaceAll = function (find, replace) {
        var self = this;

        while (self.indexOf(find) != -1) {
            self = self.replace(find, replace);
        }
        return self;
    }

    // log plugin
    $.fn.log = function () {
        $.log(this);

        return this;
    }
    $.log = function (args) {
        if (window.console) {
            console.log(arguments.length > 1 ? Array.prototype.slice.call(arguments) : arguments[0]);
        }
    }

    // konami plugin
    $.fn.konami = function (options) {
        var enterKey = 13;

        if (typeof options == 'function') {
            options = { callback: options };
        }

        options = options || {};

        options = $.extend({
            callback: false,
            keyCode: [38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
            reqEnter: true, //13,
            enterTime: false
        }, options);


        if (options.callback == false) return;

        if (options.reqEnter && options.keyCode[options.keyCode.length] != enterKey) {
            options.keyCode.push(enterKey);
        }

        return this.each(function () {
            var seq = [];
            $(this).keyup(function (e) {
                if (e.keyCode == options.keyCode[seq.length]) {
                    seq.push(e.keyCode);
                } else {
                    seq = [];
                }

                if (options.keyCode.length == seq.length) {
                    seq = [];
                    options.callback();
                }
            });
        });
    }

    // custom label hover functionality for forms
    $.fn.labelIt = function () {
        $(this)
		.focus(function () {
		    $(this).prev('label').hide();
		})
		.blur(function () {
		    if ($(this).val() == '') {
		        $(this).prev('label').show();
		    }
		})
		.filter(':text, select, :password').each(function () {
		    if ($(this).val() != '') {
		        $(this).prev('label').hide();
		    }
		});
        return this;
    }
})(jQuery);

/**
* Pause execution of javascript for x amount of seconds
*/
function wait(milliseconds) {
    var date = new Date();
    var curDate = null;

    do {
        curDate = new Date();
    } while (curDate - date < milliseconds);
}

function showWelcomeBox() {
    $('#first-timers').show();
    $('#first-timers p.hide a').click(function () {
        $.fn.colorbox.close();
        return false;
    })
    $(document).colorbox({
        width: '800px',
        inline: true,
        href: '#first-timers',
        open: true,
        opacity: .7,
        title: ' ',
        transition: 'none',
        onClosed: function () {
            $('#first-timers').remove();
        }
    });
    $.cookie('welcome', 'true', { expires: 90, path: '/' });
}

/**
* Check to see if this browser supports html5 placeholder support
*/
function supports_input_placeholder() {
    var i = document.createElement('input');
    return 'placeholder' in i;
}

function fixPlaceholderInputs() {

    // find each input with placeholder attribute
    $('input[placeholder!=""]').each(function () {
        var $ref = $(this);
        var options = {
            cls: 'ph-active',
            phStyle: {
                color: '#CCC'
            }
        };

        // get ph text
        var phText = $(this).attr('placeholder');

        $(this).bind('blur focus', function (e) {
            updatePlaceholder(e.type)
        });

        updatePlaceholder('blur');

        function updatePlaceholder(type) {
            if (type == 'blur') {
                if ($.trim($ref.val()) == '' || $.trim($ref.val()) == phText) {
                    $ref
						.addClass(options.cls)
						.css(options.phStyle)
						.val(phText);

                }
            } else if (type == 'focus' && $ref.hasClass(options.cls)) {
                $ref
					.removeClass(options.cls)
					.val('');
                // reset the styles
                for (var name in options.phStyle) {
                    $ref.css(name, '');
                }
            }
        }

    });
}

/**
* The join form object
* handles the opening, closing & additional functionality of the join form that
* appears at the top of the page
*/

function joinForm(options) {
    options = options || {};

    options = $.extend({
        openSpeed: 500,
        fadeSpeed: 125,
        formId: 'join-form'
    }, options);

    // the open state of the form
    // = closed/opened
    var self = this;
    var openState = 'closed';
    var openWhat = '';
    var $form;
    var stateHtml = {};

    /**
    * Constructor
    * Builds initial dom structure needed for this component
    *
    */
    this.init = function () {
        $form = $('#join-form');

        // join form
        $('#join-form a.signup-btn').click(function () {
            self.open('signup-radar');
            return false;
        });

        // signup
        $('#signup-radar label').click(function () {
            if ($(this).css('position') == 'absolute') {
                // find associated input element
                $(this).next().focus();
            }
        });
        $('input[type=text], input[type=password], input[type=email], select', '#signup-radar').labelIt();

        $('form', '#signup-radar').submit(function () {
            self.open('signup-success');
            return false;
        });

        // login
        $('#login-radar label').click(function () {
            if ($(this).css('position') == 'absolute') {
                // find associated input element
                $(this).next().focus();
            }
        })
        $('input[type=text], input[type=password], input[type=email], select', '#login-radar').labelIt();
    }

    /**
    * Toggle the forms opened/closed state
    */
    this.toggle = function (what) {
        if (this.getOpenState() == 'closed' || openWhat != what) {
            this.open(what);
        } else {
            this.close();
        }
    }

    /**
    * Close the form
    */
    this.open = function (what) {
        var whatStates = {
            'join-radar': '180px',
            'login-radar': '200px',
            'signup-radar': '350px',
            'signup-success': '220px'
        };
        if (openState == 'opened' && openWhat == what) return;

        var speed = openState == 'opened' ? 0 : options.fadeSpeed;

        if (openWhat != '') {
            $('#' + openWhat).hide();
        }

        openState = 'opened';
        openWhat = what;

        $form.fadeIn(speed, function () {

            $(this).animate({
                height: whatStates[what]
            }, {
                duration: options.openSpeed,
                easing: 'easeOutBack',
                complete: function () {
                    $('#' + what).show();
                }
            });
        })
    }

    /**
    * Open the form
    */
    this.close = function () {
        if (openState == 'closed') return;

        $('#' + openWhat).hide();

        openState = 'closed';
        openWhat = '';

        $form.animate({
            height: '50px'
        }, {
            duration: options.openSpeed,
            easing: 'easeOutBack',
            complete: function () {
                $(this).fadeOut(options.fadeSpeed);
            }
        });
    }

    /**
    * The open state of the form
    */
    this.getOpenState = function () {
        return openState;
    }


    this.init();
}

/**
* article comment functionality
*/
function Comments(options) {
    options = options || {};
    options = $.extend({
        baseSelector: '#comments',
        initDisplay: 5,
        itemsPerPage: 5,
        showMoreClass: 'show-more'
    }, options);

    var $c = $(options.baseSelector);
    var totalComments;

    function _init() {
        if ($c.length == 0) return; // no comments

        totalComments = $('>div', $c).length;

        _addPagination();
        _addMissingClasses();
        _addBodyArrows();
        _addFormPlaceholders();

    }

    function _addFormPlaceholders() {
        var $fieldsDiv = $('.frm-name, .frm-email, .frm-suburb, .frm-mobile', '#comment-form');
        $fieldsDiv.find('input')
			.focus(function () {
			    $(this).prev('label').hide();
			})
			.blur(function () {
			    if ($(this).val() == '') {
			        $(this).prev('label').show();
			    } else {

			    }
			});
    }


    function _addPagination() {
        if (totalComments > options.initDisplay) {
            var gt = options.initDisplay - 1;
            $('>div:gt(' + gt + ')', $c).hide();
            $('<button>Show More</button>')
				.addClass(options.showMoreClass)
				.click(_showMorePagination)
				.appendTo($c);

        }
    }

    function _showMorePagination() {
        $('>div:hidden:lt(' + options.initDisplay + ')', $c).slideDown();
        var btn = $('button.' + options.showMoreClass)
						.text('Show Even More');
        if ($('>div:hidden', $c).length == 0) {
            btn.remove();
        }
    }

    function _addMissingClasses() {
        $c.children('div:even').addClass('even');
        $c.children('div:odd').addClass('odd');
        $('.body p:first-child').addClass('first');
        $('.body p:last-child').addClass('last');
    }

    function _addBodyArrows() {
        if (!$.browser.msie || $.browser.version >= 7) {
            var $body = $('.body', $c);
            $('<span />').addClass('arrow-border').appendTo($body);
            $('<span />').addClass('arrow').appendTo($body);

            $('<span />').addClass('arrow').appendTo('#comment-form .login-message');

        }
    }

    // run constructor
    _init();
}

/**
* Handles the mini player & the open/expanding of the player
*
*/
function miniPlayer(options) {
    // private variables
    var self = this;
    var mpState = 'closed'; //closed,open,opening,closing
    var mpOffset = $('#mini-play').offset();
    var _playlist;
    //var cpIndex = 0;
    //var items = [];

    // options
    options = options || {};
    options = $.extend({
        cookieName: 'player-expand',
        defaultImageSrc: '/Layout/Skins/Default/images/default-album.jpg'
    }, options);

    this.init = function () {
        // expandable background
        $('<div id="player-bg"></div>').appendTo('.content-wrap');

        $('<span />')
			.addClass('arrow')
			.appendTo('#player');

        if ($.cookie(options.cookieName) == 'open') {
            self.expand(false);
        }

        $('#mini-play>.arrow').click(function () {
            self.expand();
        });
        $('#player>.arrow').click(function () {
            self.contract();
        })

        $('img', '#mini-play').error(function () {

            var $img = $(this);

            $img.attr('alt', '');

            if ($img.attr('src').indexOf(options.defaultImageSrc) == -1) {
                $img.attr('src', defaultImg);
            }

        });

        // trackCache/like functionality
        $('#mini-play .like a').click(function (ev) {
            // stop .net from sending ajax request
            ev.preventDefault();

            if ($(this).is('[disabled]')) {
                return false;
            }

            // let's get the track id!
            var $parent = $(this).parents('div[data-track-id]');
            if ($parent.length == 0 && $(this).parents('.more-info').length == 1) {
                $parent = $('.current-text');
            }
            //			if($parent.length == 0 && $(this).parents('.more-info-pane').length == 1) {
            //				$parent = $('.current-text');
            //			}
            var trackId = parseInt($parent.attr('data-track-id'));
            if (trackId > 0) {
                
                _incrementTrack(trackId);
            }

            return false;
        });
    }

    function _incrementTrack(trackId) {
        $.ajax({
            url: '/Handlers/LikeHelperHandler.ashx',
            data: 'trackId=' + trackId + '&increment=true',
            dataType: 'text',
            success: function () {
                var newLike = _playlist.getByTrackId(trackId).likeCount + 1;
                if ($('#mini-play div[data-track-id=' + trackId + '] .like a').length > 0) {
                    //                    $('div[data-track-id=' + trackId + '] .like a').text('Like (' + newLike + ')').attr('disabled', 'disabled');
                    $('#mini-play div[data-track-id=' + trackId + '] .like a').text('Like (' + newLike + ') People').attr('disabled', 'disabled');
                } else {
                    $('.more-info .like a').text('Like (' + newLike + ')').attr('disabled', 'disabled');
                }
            },
            error: function () {
                
            }
        });
    }

    this.setPlaylist = function (playlist) {
        _playlist = playlist;
        _redraw();
    }

    this.getPlaylist = function () {
        return _playlist;
    }

    /**
    * Stores the current open state within a cookie
    */
    this._storeState = function () {
        $.cookie(options.cookieName, mpState, { expires: 90, path: '/' });
    }

    this.expand = function (animate) {
        if (mpState == 'open') return;

        if (animate == undefined) {
            animate = true;
        }
        mpState = 'opening';
        var contentCss = { marginTop: '380px' };
        var miniplayCss = { visibility: 'hidden' };

        if (animate) {
            $('#content').animate(contentCss, { duration: 300, easing: 'easeInOutSine' });
            $('#mini-play>div').fadeOut(200, function () {

                $('#mini-play .arrow').hide();
                $('#player-bg').show().animate({
                    width: '960px'
                }, {
                    duration: 420,
                    easing: 'easeInOutSine'
                });
                $('#player')
					.css({
					    height: $('#mini-play').height(),
					    left: mpOffset.left,
					    top: '12px',
					    width: $('#mini-play').width()

					})
					.show()
					.animate({
					    width: '960px',
					    left: '7px',
					    top: '5px',
					    height: '350px'
					}, {
					    duration: 500,
					    easing: 'easeInOutSine',
					    complete: function () {
					        $('#mini-play').css(miniplayCss);
					        mpState = 'open';
					        self._storeState();
					    }
					});
            });
        } else {
            $('#content').css(contentCss);
            $('#player-bg').show().css({ width: '960px' });
            $('#player').css({ height: '350px', left: '7px', top: '5px', width: '960px' }).show();
            $('#mini-play').css(miniplayCss);
            mpState = 'open';
            this._storeState();
        }

    }



    this.contract = function () {
        mpState = 'closing';

        $('#player-bg').animate({
            width: '1px'
        }, {
            duration: 420,
            easing: 'easeInOutSine',
            complete: function () {
                $(this).hide();
            }
        });
        $('#player').animate({
            width: $('#mini-play').width(),
            left: mpOffset.left
        }, {
            duration: 500,
            easing: 'easeInOutSine',
            complete: function () {
                $('#content').animate({
                    marginTop: '0'
                }, {
                    duration: 300,
                    easing: 'easeInOutSine'
                });
                $('#mini-play .arrow').show();
                $('#mini-play').css({ visibility: 'visible' });
                $('#player').hide();
                $('#mini-play>div').fadeIn(100);
            }
        })


        mpState = 'closed';
        this._storeState();
    }

    this.redraw = function () {
        _redraw();
    }

    // PRIVATE METHODS
    function _redraw() {
        var pl = self.getPlaylist(), prev = pl.getPrevious(), next = pl.getNext();

        setTimeout(function () {
            _updateItem($('#mini-play .current'), pl.getCurrent());
            setTimeout(function () {
                _updateItem($('#mini-play .next'), next[0]);
            }, 60);
            setTimeout(function () {
                _updateItem($('#mini-play .last'), prev[0]);
            }, 120);
        }, 300);

    }

    function _urlNormalise(string) {
        string = string.toLowerCase().replace(/([\.\+\?]+)/, '');
        string = string.replaceAll('&', '_and_');
        string = string.replaceAll(' ', '-').replaceAll('--', '-');
        return string;
    }

    function _updateItem($itmRef, data) {
        var 
			bgColor = $itmRef.css('backgroundColor'),
			url = '/artists/';
        if (data.artist.length > 0) {
            url += _urlNormalise(data.artist) + '/';
        }

        $itmRef.attr('data-track-id', data.trackId);

        $itmRef
			.attr('data-artist', data.artist)
			.attr('data-track', data.name)
			.find('img')
				.attr('src', data.image)
				.attr('alt', '')
				.attr('title', data.artist + ' - ' + data.name)
			.end()
			.find('.artist-name')
				.text(data.artist)
			.end()
			.find('.track-name')
				.text(data.name)
			.end()
			.find('.description')
				.text('')
			.end()
			.find('a.more-info')
				.attr('href', url)
			.end()

        recycleString($itmRef.find('.artist-name'), 30);
        recycleString($itmRef.find('.track-name'), 50);

        if (data.buyurl1 != '') {
            $itmRef.find('.buy-now a').attr('href', data.buyurl1).removeClass('disabled').end();
        } else {
            $itmRef.find('.buy-now a').attr('href', '#').addClass('disabled').end();
        }
        if (data.status == 'playing') {
            $itmRef.find('.like a').removeAttr('disabled').removeClass('disabled');
        }
        $('#mini-play .current .like a').removeAttr('disabled').removeClass('disabled');
        $itmRef.find('.share a').attr('href', 'http://' + location.host + url).attr('title', data.artist + ' on Radar Music');
    }

    function recycleString($element, maxHeight, append) {
        append = append || '&hellip;';
        var origHtml = $element.html(), max = 200, i = 0;
        $element.html('<span id="ellip">' + origHtml + '</span>');
        var ellip = $('#ellip');
        if (ellip.height() > maxHeight) {
            $element.attr('title', ellip.text());
            while (ellip.height() > maxHeight && i < max) {
                i++;
                origHtml = origHtml.substr(0, origHtml.length - 1);
                ellip.html(origHtml + append);
            }
            $element.html(ellip.text());
        } else {
            $element.html(origHtml);
        }
    }
    this.init();
}
