var RFM = RFM || {};
jQuery(function () {
    RFM.utr.initialize();
});

RFM.utr = (function ($) {
    var that = {};

    /* public functions */
    that.initialize = function () {
        setupPrintLink();
        setupAudioPlayer();
        setupVideoPlayer();
        setupPopupPlayer();
        addUnloadAlertIfPlaying();
        setupTwitterSidebar();
        setupFacebookSidebar();
        setupSongSuggestionValidation();
        $('abbr.timeago').timeago();
        logRegisterReferrer();
        popupLoginWindow();
        redirectActivatedUser();
        setupShare();
        $('input.search-site-form').hint('Search this site');
    };

    that.isPlaying = function() {
        var isPlaying = false
        $('.swf-player').each(function() {
            if (this.getConfig && (
                    this.getConfig().state == 'PLAYING' ||
                    this.getConfig().state == 'BUFFERING')) {
                isPlaying = true;
            }
        });
        return isPlaying;
    };

    /* private functions */
    function setupShare() {
      $('a.subscribe').click(function () {
        $.post("/inc/interaction_request", {
            js: "1", ctype: "subscribe"
        } );
        return true;
      });
      $('a.download').click(function () {
        $.post("/inc/interaction_request", {
            js: "1", ctype: "download"
        } );
        return true;
      });
      $('a.retweet').click(function () {
        $.post("/inc/interaction_request", {
            js: "1", ctype: "retweet"
        } );
        return true;
      });
    }
    // show login lightbox if requested
    function popupLoginWindow() {
        if (location.hash == '#login-popup') {
            $('a.open-popup[href=#login-popup]').click();
        }
    };

    /*
        if this is the register page and the referrer is for some other page
        on this domain, then log the referrer in a cookie.
        This cookie will be used to redirect the user from the activation page
        to where they last left off.
    */
    function logRegisterReferrer() {
        if (location.pathname.indexOf('/members/register/') !== -1) {
            var proto_domain = location.protocol + '//' + location.hostname;
            if (document.referrer !== location.href &&
                document.referrer.indexOf(proto_domain) === 0) {
                $.cookie('registerReferrer', document.referrer, {'path': '/', 'expires': .25});
            }
        }
    };

    /*
        If this user has a registerReferrer cookie and we're on the account
        activation page, then redirect the user to the page they were on when
        the clicked the "Register" link and show the login lightbox.
    */
    function redirectActivatedUser() {
        if (location.search.indexOf('ACT=77') === -1) { return; }
        if ($("p:contains('Your account has been activated')").length == 0) {
            return;
        }
        var proto_domain = location.protocol + '//' + location.hostname;
        var referrer = $.cookie('registerReferrer');
        if (referrer && referrer.indexOf(proto_domain) === 0) {
            $.cookie('registerReferrer', null);
            location.href = referrer + '#login-popup';
        }
    };

    function setupSongSuggestionValidation() {
        $('#contact_form').submit(function() {
            var error = false;
            if ($('#song').attr('value') == '' && $('#artist').attr('value') == '') {
                error = 'Please submit a song and artist.';
            }
            else if ($('#song').attr('value') == '') {
                error = 'Please submit a song.';
            }
            else if ($('#artist').attr('value') == '') {
                error = 'Please submit an artist.';
            }

            if (error) { alert(error); return false; }
        });
    };

    function setupTwitterSidebar() {
        if (!$('#twitterSidebarContent').length > 0) { return; }
        google.load("feeds", "1", {"nocss" : true, "callback" : function() {
            var feed = new google.feeds.Feed("http://twitter.com/statuses/user_timeline/26902447.rss");
            feed.load(function(result) {
                if (result.feed.entries.length > 0) {
                    var content = result.feed.entries[0].content;
                    content = content.replace(/^radarradio: /, '');
                    $('#twitterSidebarContent').html(content).autolink().twitterautolink();
                }
                else {
                    $('#twitterSidebar').hide();
                }
            });
        }});
    };

    function setupFacebookSidebar() {
        if (!$('#facebookSidebarContent').length > 0) { return; }
        google.load("feeds", "1", {"nocss" : true, "callback" : function() {
            var feed = new google.feeds.Feed("http://twitter.com/statuses/user_timeline/97019224.rss");
            feed.load(function(result) {
                if (result.feed.entries.length > 0) {
                    var content = result.feed.entries[0].content;
                    content = content.replace(/^radarradiofb: /, '');
                    $('#facebookSidebarContent').html(content).autolink();
                }
                else {
                    $('#facebookSidebar').hide();
                }
            });
        }});
    };

    function addUnloadAlertIfPlaying() {
        if ($('.swf-player').length > 0) {
            window.onbeforeunload = function () {
                if (RFM.utr.isPlaying()) {
                    return"Your player will be stopped if you leave this page.";
                }
            };
        }
    };

    function setupPopupPlayer() {
        $('a.popup-player').click(function() {
            var newwindow = window.open(this.href,'',
                'resizable=1,toolbar=0,location=0,status=0,menubar=0,scrollbars=1,width=515,height=390');
            newwindow.focus();
            return false;
        });
    };

    function setupPrintLink() {
        $('a.print-page').click(function() {
            $('link[media=screen]').attr('disabled', 'disabled');
            $('link[media=print]').attr('media', 'screen');
            window.print();
            return false;
        });
    };

    function setupAudioPlayer() {
        $('a.panel-player').each(function(i) {
            var $this = $(this);
            var width = $(this).width();
            width = (width < 200) ? '200' : '' + width;
            $this.replaceWith("<div class='panel-player' id='panel-player-" + i + "'></div>");
            var so = new SWFObject('/js/player.swf', 'swf-player-'+i, width, '24', '9');
            so.addParam('allowfullscreen','true');
            so.addParam('allowscriptaccess','always');
            so.addParam('wmode','opaque');
            so.addParam('class','swf-player');
            if (location.href.indexOf('popup-player') !== -1) {
                so.addVariable('autostart', 'true');
            }
            so.addVariable('id', 'swf-player-'+i);
            //so.addVariable('duration','3123');
            so.addVariable('file',$this.attr('href'));
            so.addVariable('backcolor','5d502d');
            so.addVariable('frontcolor','FFFFFF');
            so.addVariable('plugins','gapro-1');
						so.addVariable('gapro.accountid','UA-948741-14');
						so.addVariable('gapro.trackstarts','true');
						so.addVariable('gapro.trackpercentage','true');
						so.addVariable('gapro.tracktime','true');
            so.write('panel-player-' + i);
        });
    };

    function setupVideoPlayer() {
        $('a.video-player-link').each(function(i) {
            var $this = $(this);
            var width = '453';
            $this.replaceWith("<div class='panel-player' id='panel-player-" + i + "'></div>");
            var so = new SWFObject('/js/player.swf', 'swf-player-'+i, width, '281', '9');
            so.addParam('allowfullscreen','true');
            so.addParam('allowscriptaccess','always');
            so.addParam('wmode','opaque');
            so.addParam('class','swf-player');
            so.addVariable('id', 'swf-player-'+i);
            so.addVariable('file',$this.attr('href'));
            so.addVariable('backcolor','5d502d');
            so.addVariable('frontcolor','FFFFFF');
            so.addVariable('plugins','gapro-1');
						so.addVariable('gapro.accountid','UA-948741-14');
						so.addVariable('gapro.trackstarts','true');
						so.addVariable('gapro.trackpercentage','true');
						so.addVariable('gapro.tracktime','true');
            so.write('panel-player-' + i);
        });
    };

    return that;
}(jQuery));

/* custom jQuery plugins */

// add a 'hint' to an input
jQuery.fn.hint = function (hint) {
    var $ = jQuery;

    // could be added to String.prototype, but this keeps the plugin
    // side-effect free
    function ucfirst(str) {
        return (str.slice(0, 1).toUpperCase() + str.slice(1));
    }

    // add a hint to the item
    function hintify() {
        if (!this.value || this.value == $(this).data('hint')) {
            $(this).addClass('hint').val($(this).data('hint'));
        }
    }

    // remove or select a hint'D input
    function dehintify() {
        var $this = $(this).removeClass('hint');
        if (this.value == $this.data('hint')) {
            $this.val('');
        }
        else {
            $this.select();
        }
    }

    // process the hint for each element
    return $(this).each(function () {
        $(this).data('hint', (hint || ucfirst($(this).attr('name'))));
    }).each(hintify).focus(dehintify).click(dehintify).blur(hintify);
};

/* taken from http://kawika.org/jquery/js/jquery.autolink.js */
jQuery.fn.autolink = function () {
    return this.each( function(){
        var re = /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;
        $(this).html( $(this).html().replace(re, '<a href="$1">$1</a> ') );
    });
}

jQuery.fn.twitterautolink = function () {
    return this.each( function(){
        // username
        var re = /([\.|\,|\:|\¡|\¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/ig;
        $(this).html( $(this).html().replace(re, '$1<a href=\"http://twitter.com/$2\" class=\"tweet-username\">@$2</a>$3 ') );

        // hash tag
        var re = /([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/ig;
        $(this).html( $(this).html().replace(re, '$1<a href=\"http://search.twitter.com/search?q=%23$2\" class=\"tweet-hashtag\">#$2</a>$3 ') );
    });
}
