var chartSongId = 0;
var renderTimer = 0;
var tEmbed = 0;
var loading = "<img src=\"/styles/fb_loading.gif\">";
var appMode = 'default';
var fb_scope = 'offline_access,publish_stream,user_location,email,user_birthday';

if (document.domain.indexOf("local") == -1)
{
	document.domain = 'breakoutband.com';
} else {
	document.domain = 'breakoutband.local';
}

jQuery.fx.interval = 33;

var BB = {};
BB.window = window;
BB.response = {};
BB.response.prompt_login = -1;

/*Shadowbox.init({players:['iframe','html'], modal:true, handleOversize:"none"});
(function() {
	  Shadowbox.__isLoaded = false;
	  Shadowbox.__onLoad = function() {};
	  var load = Shadowbox.load;
	  Shadowbox.load = function() {
	    load();
	    Shadowbox.__isLoaded = true;
	    Shadowbox.__onLoad();
	  };
	  var open = Shadowbox.open;
	  Shadowbox.open = function(options) {
	    Shadowbox.__isLoaded ? open(options) : Shadowbox.__onLoad = function() { open(options) };
	  }
	})()*/

$(document).ready(function()
{
	// Buttons
	jQuery.ready(function() {
	  jQuery('a.minibutton').bind({
	    mousedown: function() {
	      jQuery(this).addClass('mousedown');
	    },
	    blur: function() {
	      jQuery(this).removeClass('mousedown');
	    },
	    mouseup: function() {
	      jQuery(this).removeClass('mousedown');
	    }
	  });
	});
	
	// Bucket pagination
    /**
	$('.paginatedLink').live('click',(function(){
		$(this).closest('.pageable-container').load(this.href);
		return false;
	}));
    **/
	
	// Single link pagination
	$('.paginated-single-link').live('click', function()
	{
        if(appMode != "default"){
            return false;
        }
        
		var pageableContainer = $(this).closest('.pageable-container');

		if (pageableContainer.attr('id') != undefined)
		{
			c = " #" + pageableContainer.attr('id');
		} else {
			c = "";
		}
		
		pageableContainer.find('.pageable-wrapper-single:last').slideUp().load(this.href + c, null, function()
		{
			if (pageableContainer.hasClass('irateable') || pageableContainer.hasClass('irateable-container'))
			{
				initRating();
			}
		}).slideDown();
		return false;
	});
	
	// Star rating
	initRating();
	
	// Filtering
	$('.filter-container a').live('click', function()
	{
		if ($(this).data('dir') == undefined)
		{
			$(this).data('dir', 'DESC');
		}
		
		$('.filter-container a').css('text-decoration','');
		$(this).css('text-decoration','underline');
		$('#songs_list, #pack_list').html(loading).load(this.href + "&dir=" + $(this).data('dir'));
		
		if ($(this).data('dir') == 'ASC')
		{
			$(this).data('dir', 'DESC');
		} else {
			$(this).data('dir', 'ASC');
		}
		
		return false;
	});

	// Navigation
	if ($("#navigation").length == 1)
	{
		$("#navigation li a").each(function()
		{
			$(this).prepend("<div class=\"nav-drop nav-drop-left\"></div>");
			$(this).append("<div class=\"nav-drop nav-drop-right\"></div>");
			$(this).find(".nav-drop").css("background", "#FFFFFF");
		});
		
		$("#navigation li").hover(function()
		{
			var contentContainer = $(this).find("div.nav-content-container");

            if($(this).hasClass("dead")){
                return false;
            }
			
			$(this).find(".nav-drop").css("visibility", "visible");
            $(this).css("background","#239DEA");
			
			if (contentContainer.length == 0)
			{
				var url = $(this).find('a:first').attr('href');
				var c = $("<div class=\"nav-content-container\"><div style=\"height: 3px; background-color: #239DEA; margin: 0px -20px 20px -20px;\"></div><div class=\"nav-content-loader\">"+loading+"</div></div>");
				
				$(this).append(c).find('.nav-content-loader:first').load(url, null, function(response)
				{
					// Calculate width and display flush right or left
					if ($(this).closest('li').attr('offset') != undefined)
					{
						c.css('marginLeft', '-' + $(this).closest('li').attr('offset') + 'px');
					}
					/*var offset = $(this).offset().left;
					var width = $(this).width();
					var navWidth = $('#main_container').width();
					var btnWidth = $(this).closest('li').width();

					$(this).hide();
					
					if ((offset + width) >= navWidth)
					{
						c.css('marginLeft', '-' + (width - (btnWidth - 78)) + 'px');
					}
					
					$(this).show();*/
				});
			} else {
				contentContainer.removeClass('hidden');
			}

            if(!$(this).hasClass("dead")){
                $(this).attr("z-index","9999");
            }
		}, function()
		{
			$(this).find(".nav-drop").css("visibility", "hidden");
			$(this).find("div.nav-content-container").addClass('hidden');

            $(this).css("background","#FFFFFF");
		});
		
		$("#navigation li > div > a").click(function()
		{
			return false;
		});
	}
	
    $(".notification_icon").click(function(){
        var childContainer = $(this).children(".notifications");
        var countContainer = $(this).children("#count_display");
        if(!$(this).hasClass("active")){
            $(this).parent().parent().find(".notifications").hide();
            $(this).parent().parent().find(".notification_icon").removeClass("active");
            $(this).parent().parent().find(".notifications").html('<img class="ajax_loader" src="/styles/fb_loading.gif">');

            $(this).children().show();
            $.get(childContainer.attr('rel'),
                function(response){
                    childContainer.html(response);
                    if(countContainer.is(":visible")){
                        countContainer.hide();
                    }
                }
            );
            $(this).addClass("active");
        }else{
            childContainer.hide();
            $(this).removeClass("active");
        }
    });

	// Clickable Avatars
	$('.avatar-clickable').live('click', function()
	{
		var href = $(this).find('a:first').attr('href');

		if (href != undefined)
			window.location = href;
	});
	
	// UI
	$('.default-text').live('click', function()
	{
		$(this).removeClass('gray').removeClass('pink').removeClass('green');
        $(this).removeClass("default-text");
		
		if ($(this).data('clicked') == undefined)
			$(this).val('');
			
		$(this).data('clicked', true);
	});
	
	$('.de-fan').live('click', function()
	{
		if (confirm('De-fan this artist?'))
		{
			var sc = $(this);
			
			$.post(
				'/fans/de-fan-user',
				{
					id:sc.attr('rel')
				}, function(response)
				{
					if (response > 0)
					{
						if ($('#see_all_favs').length == 0)
						{
							$('.de-fan').addClass('hidden');
							$('#fan_user').removeClass('hidden');
						}
						
						sc.closest('.fan').hide('slow');
					}
				}
			);
		}
	});
	
	$('.delete-image').live('click',function()
	{
		if (confirm('Delete this image?'))
		{
			var imageId = $(this).attr('rel');
			
			$.post('/user/delete-image',{imageId:imageId});
			
			$(this).closest('.user-image-listing').hide('slow');
		}
	});
	
	$('.release-to-competition').live('click', function(e)
	{
		$(this).html(loading);
		
		$.post('/competitions/submit/commit', {competition_id:$(this).attr('rel')}, function(response)
		{
            if(appMode == "default"){
                if (response == 1)
                {
                    alert('Sorry, but an error occured and we cannot submit your song into this competition, please try again!');
                } else {
                    window.location = response;
                }
            }else{
                openShareWindow();
            }
		});
	});
	
	// Charts
	$('.release-link').live('click', function(e)
	{
		var context = $(this);
		var parts = context.attr('rel').split(':');
		
		var songId = parts[0];
		var token = parts[1];
		
		promptRelease(songId, token);
		
		return false;
	});

	$('.unrelease-link').live('click', function(e)
	{
		if (confirm('Unrelease this song?\n\nYour song may still be visible in search for up to 24 hours before being removed.'))
		{
			var context = $(this);
			
			//container.html(loading + '&nbsp;Unreleasing...');
			var parentContainer = context.parents(".song.chart_detail");
			
			$.post('/song/unrelease', {song_id:context.attr('rel')}, function(response){
				context.closest('.ipostable').hide();
			});
		}
		return false;
	});
	
	$('.view-thread-replies').live('click', function()
	{
        if(appMode != "default"){
            return;
        }
        
		$(this).closest('.icountable, .ipostable').find('.thread-reply').show('slow');
	});
	
	$('.post-reply').live('click', function()
	{
        if(appMode != "default"){
            return;
        }
        
		var pnr = $(this);
		var numReplies = pnr.closest('.postable-container').find('.detail-thread').length;
		var body = pnr.closest('.thread-reply').find('textarea:first').val();
		var oHtml = pnr.html();

		if (body.length > 0)
		{
			pnr.html(loading);

			$.post(pnr.attr('href'),
			{
				note_body:escape(body)
			},
			function(response)
			{
				pnr.html(oHtml);
				
				if (response != BB.response.prompt_login)
				{
					pnr.closest('.thread-wrapper').find('.threads').append(response);
					pnr.closest('.icountable').find('.view-thread-replies:first').text('Reply ('+(numReplies + 1)+')');
					pnr.closest('.thread-reply').find('textarea:first').val('').blur().trigger('change');
				} else {
					BbPopUp.promptLogin();
				}
			});
		}
		
		return false;
	});
	
	$('.playSong').live('click', function(e)
	{
		var parent = $(this).parents('.song:first');
		var rel = $(this).attr('rel').split(':');
		var songId = rel[0];

		if (songId != chartSongId)
			stopSong();
		
		if (parent.hasClass('chart-detail-on'))
		{
			_defaultState(parent, $(this));
		} else {
			closeAll();
			_openState(parent, $(this));
		}

		tEmbed = rel[1];
		chartSongId = songId;
	});
	
	$('.song-delete').live('click', function(e)
	{
		if (confirm('Delete this song?\n\nThis will remove your song from the charts and radio, and cannot be undone!'))
		{
			var context = $(this).parents('.song:first');
			var songId = $(this).attr('rel');
			
			$.post(
				'/song/delete',
				{
					song_id:songId
				},
				function(response)
				{
					if (response > 0)
						context.hide('slow');
				}
			);
		}
	});
	
	$('.song-reviews-span').live('click', function()
	{
		$(this).closest('.ipostable').find('.show-posts:first').trigger('click');
	});
	
	$('.show-posts').live('click', function(e)
	{
        if(appMode != "default"){
            return;
        }

		var link = $(this);
		var reviews = link.closest('.ipostable').find('.posts-wrapper:first');

		if (link.data('open') == true)
		{
			reviews.slideUp(function()
					{
						link.text('See All');
						link.data('open', false);
					});
		} else {
			if (link.data('loaded') == false || link.data('loaded') == undefined)
			{
				link.text('Loading...');
				
				reviews.slideUp().load(link.attr('href'), null, function(response)
				{
				}).slideDown(function()
						{
							link.text('Minimize');
							link.data('open', true);
							link.data('loaded', true);
						});
			} else {
				reviews.slideDown(function()
						{
							link.text('Minimize');
							link.data('open', true);
						});
			}
		}
		
		return false;
	});
	
	$('.post-wrapper input, #review_wrapper textarea').live('click', function(e)
	{
		if ($(this).data('selected') == undefined)
		{
			$(this).val('');
		}
		
		$(this).data('selected', true);
	});
	
	$('.post').live('click', function()
	{
        if(appMode != "default"){
            return;
        }

		var btn = $(this);
		var oHtml = btn.html();
		var reviews = $(this).closest('.postable-container');
		var isong = $(this).closest('.ipostable');

		if (reviews.length == 0)
			return false;
		
		var reviewBox = reviews.find('input:first, textarea:first');
		var context = reviews.find('.posts-context:first');
		
        if (reviewBox.val().length > 0 && reviewBox.data('selected') != undefined)
		{
			$(this).html(loading);

			$.post(
				btn.attr('href'),
				{
					review:escape(reviewBox.val())
				}, 
				function(response)
				{
					btn.html(oHtml);

					if (response == BB.response.prompt_login)
					{
						BbPopUp.promptLogin();
					} else {

						if ($('.icountable').length == 0)
						{
							context.html(response);
						} else {
							context.prepend(response);
						}

						var txt = isong.find('.num-posts:first');
						var cNum = Number(txt.text());
						
						txt.text(cNum + 1);
						
						reviewBox.val('').blur();
					}
				}
			);
		}
		
		return false;
	});
	
	// Bands
	band_key_count_global=0;
	// Artists
	$('#band_name').live('keypress', function()
	{
		band_key_count_global++;
		
		setTimeout("band_name_lookup("+band_key_count_global+")",1000);
		
	});
	$('#band_name').live('blur', function()
	{
		var btn = $(this);
		var input = $('#band_name');
		var status_icon = $('#status_icon');
		var status = $('#band_name_status');
		var band_name = input.val();
		
		if (input.hasClass('default-text') && input.data('clicked') == undefined || band_name.length == 0)
		{
			alert('Please type a band name!');
			return;
		}
		
		btn.attr('disabled', true);
		input.attr('disabled', true);
		
		status.removeClass('hidden').html('<img src="/styles/fb_loading.gif">&nbsp;Checking for duplicate names...');
		
		$.post(
				'/band/index/check-name',
				{
					band_name:band_name
				}, function (response)
				{
					if (parseInt(response) == 1)
					{
						BandWizard.name = band_name;
						
						if (btn.attr('rel') == 'no-step')
							status.text("").addClass('hidden');
						else
							status.text("What a rad name and it's totally yours! Continue to the next step by clicking below!");
						
						input.addClass('green');
						input.data('changed', true);
						status_icon.removeClass('hidden').removeClass('error').addClass('success');
						status.removeClass('pink').addClass('green');
					} else {
						BandWizard.name = null;
						
						input.removeClass('green');
						input.data('changed', false);
						status_icon.removeClass('hidden').removeClass('success').addClass('error');
						status.removeClass('green').addClass('pink');
						
						status.text('Sorry, that name is unavailable. Please use another name and try again!');
					}
					
					btn.removeAttr('disabled');
					input.removeAttr('disabled');
				}
		);
	});
	$('#check_band_name').live('click', function()
	{
		var btn = $(this);
		var input = $('#band_name');
		var status_icon = $('#status_icon');
		var status = $('#band_name_status');
		var band_name = input.val();
		
		if (input.hasClass('default-text') && input.data('clicked') == undefined || band_name.length == 0)
		{
			alert('Please type a band name!');
			return;
		}
		
		btn.attr('disabled', true);
		input.attr('disabled', true);
		
		status.removeClass('hidden').html('<img src="/styles/fb_loading.gif">&nbsp;Checking for duplicate names...');
		
		$.post(
				'/band/index/check-name',
				{
					band_name:band_name
				}, function (response)
				{
					if (parseInt(response) == 1)
					{
						BandWizard.name = band_name;
						
						if (btn.attr('rel') == 'no-step')
							status.text("").addClass('hidden');
						else
							status.text("What a rad name and it's totally yours! Continue to the next step by clicking below!");
						
						input.addClass('green');
						input.data('changed', true);
						status_icon.removeClass('hidden').removeClass('error').addClass('success');
						status.removeClass('pink').addClass('green');
					} else {
						BandWizard.name = null;
						
						input.removeClass('green');
						input.data('changed', false);
						status_icon.removeClass('hidden').removeClass('success').addClass('error');
						status.removeClass('green').addClass('pink');
						
						status.text('Sorry, that name is unavailable. Please use another name and try again!');
					}
					
					btn.removeAttr('disabled');
					input.removeAttr('disabled');
				}
		);
	});
	
	$('.band_wizard_step_prev').live('click', function()
	{
		BandWizard.step = $(this).attr('rel');
		BandWizard.gotoPrevious();
		
		return false;
	});
	
	$('.band-wizard-step').live('click', function()
	{
		if (BandWizard.name == undefined)
		{
			alert("You mast have a unique band name to continue!");
		} 
		else if (BandWizard.id == undefined)
		{
			$('.band_wizard_step_next:eq(0)').trigger('click');
		} else {
			BandWizard.gotoStep($(this).index() + 1);
		}
	});
	
	$('.band_wizard_step_next:eq(0)').live('click', function()
	{
		var step = $(this).attr('rel');
		var available = $('.available');
		
		if (BandWizard.name != undefined)
		{
			if (BandWizard.id == undefined)
			{
				$.post('/band/create',{band_name:escape(BandWizard.name)}, function(id)
				{
					if (id > 0)
					{
						available.attr('disabled', true);
						
						BandWizard.id = id;
						BandWizard.step = step;
						BandWizard.stepComplete(1);
						BandWizard.gotoNext();
					}
				});
			} else {
				BandWizard.step = step;
				BandWizard.gotoNext();
			}
		} else {
			alert("You must have a unique band name before proceeding!");
		}
		
		return false;
	});
	
	$('.band_wizard_step_next:eq(1)').live('click', function()
	{
		var step = $(this).attr('rel');
		BandWizard.step = step;
		BandWizard.stepComplete(2);
		BandWizard.gotoNext();
	});
	
	$('.band_wizard_step_next:eq(2)').live('click', function()
	{
		if ($('.genre-cb:checked').val() == undefined)
		{
			alert('You must select at least 1 genre for '+ BandWizard.name +' before proceeding...');
			
			return false;
		}
		
		if ($('#create_profile_form input[name*=influences]').data('clicked') == undefined)
		{
			$('#create_profile_form input[name*=influences]').val('');
		}
		
		$('#create_profile_form').trigger('submit');
	});
	
	$('a#fbInvite').live('click', function()
	{
		var ele = $('#shareContainer')[0];
		var url = $(this).attr('href');
		
		$('#shareContainer').empty().html('<iframe src="'+url+'" width="100%" frameborder="0" height="100%"></iframe>');
		
		/*
		$.ajax({
			  type:"POST",
			  url: $(this).attr('href'),
			  datatype: 'text',
			  success: function(html) {
			    ele.innerHTML = html;
			    FB.XFBML.Host.parseDomElement(ele);
			  }
			});*/
		return false;
	});
	
	// Featured Packs
	var cOffset = 0;
	var responseTarget = $('#featured_packs');
	
	$('.scrubKit').live('click', function()
	{
		if ($(this).attr('title') == "Previous")
		{
			if (cOffset != 0)
			{
				cOffset -= 1;
			}
		} else {
			cOffset += 1;
		}
		
		$.post(
				'/charts/featured.packs',
				{
					offset : cOffset
				},
				function (response)
				{
					responseTarget.html(response);
				}
		);
	});
	
	
	//Friend selector
	$('.friend-select-box .friend-ck').live('click', function()
	{
		var ele = $(this).parents('.friend-select-box:first');
		
		if (! ele.hasClass('friend-selected'))
		{
			ele.addClass('friend-selected');
			ele.find(':checkbox:first').attr('checked', true);
		} else {
			ele.removeClass('friend-selected');
			ele.find(':checkbox:first').removeAttr('checked');
		}
	});
	
	//Profile editing
	$('#updateGenres').live('click', function()
	{
		var ids = "";
		var parent = $(this).parents('.genre-editor:first');
		var type = parent.attr('title').split(':')[0];
		var fk = parent.attr('title').split(':')[1];
		
		$('.genre-cb:checked').each(function()
		{
			ids += "&ids[]=" + $(this).val();
		});
		
		$('#genre_editor').css('display', 'none');
		$('#genre_editor_wrapper > div.loading').css('display', 'block');
		
		$.ajax({
			type:"POST",
			url:'/'+type+'/update-genres/id/'+fk,
			data:ids,
			success:function(response)
			{
				$('span#editGenres').css('display', 'block').text(response);
				$('#genre_editor').css('display', 'none');
				$('#genre_editor_wrapper > div.loading').css('display', 'none');
			}
		});
	});
	
	$('span#editGenres.editable').click(function()
    {
		$(this).css('display', 'none');
		$('#genre_editor').css('display', 'block');
    });
	
	$('h1#bandName.editable').click(function()
    {
		//$(this).css('display', 'none');
		//$(this).load('/band/create');
    });
	
	if(jQuery().jGrowl){
		$.jGrowl.defaults.position = 'bottom-right';
		$.jGrowl.defaults.closeTemplate = '&times;';
		$.jGrowl.defaults.life = 5000;
	}
	$("img.add-as-a-friend").click(function(){
		///friends/send-friend-request/user/<?php echo $this->profile_user_id ?>/sb/1
		var profile_id=$("#add-friend-profile-id").val();
		$.ajax({
			type:"GET",
			url:'/friends/send-friend-request/user/'+profile_id,
			beforeSend:function(response){
				$("img.add-as-a-friend").html(loading);
				$.jGrowl("Sent",{header:"Friend Request", sticky:false, life:5000});
			},
			success:function(response)
			{
//				$.jGrowl(response,{header:"Friend Request", sticky:false, life:5000});
			},
			error:function(response)
			{
				$.jGrowl("Add friend failure!",{header:"Friend Request Error"});
			}
		});
	});
	
	$('.limit_chars').livequery(function()
	{
		$(this).each(function(){
			
			var limit = $(this).attr('alt') || 140;
			var length = $(this).val().length;

			$(this).parent().find('.char_remaining').text('Remaining Chars: '+ (limit - length));
			
			$(this).change(function(){
				if ($(this).val().length == 0)
				{
					$(this).parent().find('.char_remaining').text('Remaining Chars: '+ limit);
				}
			});
			
			$(this).keyup(function(){
				
				var remaining = limit - $(this).val().length;
				
				if (remaining > 1){
					//
				} else {
					remaining = 0;
					$(this).val($(this).val().substring(0, limit));
				}
				
				$(this).parent().find('.char_remaining').text('Remaining Chars: '+ remaining);
			});
				
		});
	});
	
	$('#signup-form .signup-button').click(function(){
		if($('#signup-form #first_name').val()==""){
			$.jGrowl("Please enter first name");
			return false;
		}
		if($('#signup-form #last_name').val()==""){
			$.jGrowl("Please enter last name");
			return false;
		}
		if($('#signup-form #email').val()==""){
			$.jGrowl("Please enter your email address");
			return false;
		}
		if($('#signup-form #password').val()==""){
			$.jGrowl("Please enter password");
			return false;
		}
		if (!$('#signup-form #agree').attr('checked')){
			$.jGrowl("You must agree to the Terms and Conditions to continue!");
			return false;
		}
        if($('#signup-form #location').hasClass("default-text")){
            $('#signup-form #location').val("");
            return true;
        }
		$('#signup-form').submit();
	});
	
	$("#panel_login_button").live('click',function(){
		if($('#email.panel-textbox').val()==""){
			$.jGrowl("Please enter email");
			return false;
		}
		if($('#password.panel-textbox').val()==""){
			$.jGrowl("Please enter password");
			return false;
		}
		$("#panel-login-form").submit();
	});
	
	$("input#email.panel-textbox").keypress(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 13){
			$("input#password.panel-textbox").focus();
			e.preventDefault();
		}
	});
	
	$("input#password.panel-textbox").keypress(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 13){
			if($('input#email.panel-textbox').val()==""){
				$.jGrowl("Please enter email");
				return false;
			}
			if($('input#password.panel-textbox').val()==""){
				$.jGrowl("Please enter password");
				return false;
			}
			$("#panel-login-form").submit();
			
			e.preventDefault();
		}
	}); 
		
	 $("fb-login").click(function(){
		FB.login(function(response) {
		    if (response.session) {
		      document.getElementById('fb-login').innerHTML = "<span id='fb_login_text' class='fb_button_text'>Logout</span>";
		    } else {
		      document.getElementById('fb-login').innerHTML = "<span id='fb_login_text' class='fb_button_text'>Connect with Facebook</span>";
		    }
		  });
	});

	if(window.location.hostname=="dev.breakoutband.com"){
	 api_key = "0a01fdebd506bf99aef1b6886e8778df";
	}else if(window.location.hostname=="alpha.breakoutband.com"){
	 api_key = "7ecf0782e38ce619ccb8777c40a66708";
	}else if(window.location.hostname=="stage.breakoutband.com"){
	 api_key = "36724f53d89ea4eb03731d6a451ab1c1";
	}else if(window.location.hostname=="www.breakoutband.com"){
	 api_key = "846c40ad8d82b9158e2f44e76d6bab34";
	}else if(window.location.hostname=="world.breakoutband.com"){
	 api_key = "00be216feb9c1b40228b3fd7854806d7";
	}else if(window.location.hostname=="www.breakoutband.local"){
	 api_key = "d44381b367f39c72692bd802c405e2ff";
	}else if(window.location.hostname=="localhost"){
	 api_key = "aa494829038a7c9aaf6ec176f0faa028";
	}
	
	try {
		FB_RequireFeatures(["XFBML"], function(){
			FB.Facebook.init(api_key, "/xd_receiver.htm");
		});
	} catch(err)
	{
		//
	}

	$('#green_fan_button').live('click', function()
	{
		var userId = $(this).attr('rel');
		var context = $(this).parent();
		var ogHtml = context.html();

		if (userId > 0)
		{
			context.html('<img src="/styles/fb_loading.gif">');
			
			$.post(
				'/fans/fan-user/', {id:userId}, function(r)
				{
					context.html(ogHtml);
					
					if (r == BB.response.prompt_login)
					{
						BbPopUp.promptLogin();
					} else if (r == 0) {
						context.children("#green_fan_button").addClass('hidden');
						context.children("#ditch_fan_button").removeClass('hidden');
                        context.parent("#friend_container").children(".fanned").hide();
					} else {
						context.children("#green_fan_button").addClass('hidden');
						context.children("#ditch_fan_button").removeClass('hidden');
                        context.parent("#friend_container").children(".fanned").show();
						
						var num_fans = Number($('#num_fans').text()) + 1;
						var num_fans_this_week = Number($('.num_fans:first').text()) + 1;
						
						$('#num_fans').text(Number(num_fans));
						$('.num_fans').text(Number(num_fans_this_week));
						$('#num_fans_tab').text(Number(num_fans) + " Fans");
					}
				}
			);
		}
		
		return false;
	});
	
	$('#ditch_fan_button').live('click', function()
	{
		var context = $(this).parent();
		var userId = context.children('#green_fan_button').attr('rel');
		var ogHtml = context.html();

		var num_fans = Number($('#num_fans').text()) - 1;
		var num_fans_this_week = Number($('.num_fans:first').text()) - 1;

		$('#num_fans').text(Number(num_fans));
		$('.num_fans').text(Number(num_fans_this_week));
		$('#num_fans_tab').text(Number(num_fans) + " Fans");
		
		context.html('<img src="/styles/fb_loading.gif">');

		$.post(
			'/fans/de-fan-user',
			{
				id:userId
			},
			function(){
				context.html(ogHtml);
				context.children("#green_fan_button").removeClass('hidden');
				context.children("#ditch_fan_button").addClass('hidden');
                context.parent("#friend_container").children(".fanned").hide();
			}
		);
	});

    if(jQuery().qtip){
        $("div.breakout-bucks-figure[title]").qtip({
            position: {
              my: 'bottom left',  // Position my top left...
              at: 'top center'  // Position my top left...
            }
        });
        $("div.breakout-pro-bucks-figure[title]").qtip({
            position: {
              my: 'bottom left',  // Position my top left...
              at: 'top center'  // Position my top left...
            }
        });
        $("div.vote-section[title]").qtip({
            position: {
              my: 'top center',  // Position my top left...
              at: 'bottom center'  // Position my top left...
        }});

        $("div.url-icons[title]").qtip({
            position: {
              my: 'bottom left',  // Position my top left...
              at: 'top left'  // Position my top left...
        }});

        $("div.competition-image-container[title]").qtip({
            position: {
              my: 'bottom center',  // Position my top left...
              at: 'top center'  // Position my top left...
            }
        });
    }

    $(".alert-menu").toggle(function(){
        var spinner = $(this).children(".spinner");
        spinner.show();
        $(this).addClass("expanded");
        $(this).parent().children(".display-container").load($(this).children("a").attr("href"), function(){
            $(this).parent().children(".display-container").show("fast");
            spinner.hide();
        });
    }, function(){
        var spinner = $(this).children(".spinner");
        spinner.hide();
        $(this).parent().children(".display-container").hide("fast", function(){
            $(this).parent().children(".display-container").html("");
        });
        $(this).removeClass("expanded");
    });

    $(".alert-menu > a").click(function(event){
        event.preventDefault();
    });
});

function promptRelease(songId, token, supress)
{
	var s = supress || 0;
	
    if(appMode == "facebook"){
        var facebook_app_id = $("#app_id").attr("rel");
        BbPopUp.open('/song/prompt-release/song_id/' + songId + '/token/' + token + '/s/' + s + '/facebook_app_id/' + facebook_app_id);
    }else if(appMode == "satellite"){
        var app_id = $("#app_id").attr("rel");
        BbPopUp.open('/song/prompt-release/song_id/' + songId + '/token/' + token + '/s/' + s + '/app_id/' + app_id);
    }else{
        BbPopUp.open('/song/prompt-release/song_id/' + songId + '/token/' + token + '/s/' + s);
    }
}

function openLoveCrushCrushedFB()
{
	window.open('http://www.facebook.com/breakoutband?v=app_4949752878');
}

function signupFacebook(){
    $('#fb_connect_btn_small').toggle();
    $('#fb_connect_loader_small').toggle();
    FB.getLoginStatus(function(response) {
        if (response.authResponse) {
            signupRedirect(response.authResponse.accessToken)
        } else {
            FB.login(function(response) {
                if (response.authResponse) {
                    signupRedirect(response.authResponse.accessToken)
                } else { }
                }, {scope: fb_scope});
            }
        });
}

function signupRedirect(access_token){
    window.location = '/login/facebook/async/false?access_token='+access_token;
}

// Mail
var composeMessage = function(user_id)
{
	if (user_id > 0)
	{
		BbPopUp.open('/messaging/compose/index/m/1/recipientid/' + user_id);
	}else{
		BbPopUp.open('/messaging/compose/index/m/1/');
    }
}

var acceptFriendRequest = function(mail_id, friend_id)
{
	if (confirm('Accept this friend request?'))
	{
		if (mail_id > 0 && friend_id > 0)
		{
			$.post(
				'/friends/become-friend',
				{
					user:friend_id
				},
				function (response)
				{
					$('#requestContent').html(response);
					_deleteActionConfirm(mail_id);
				}
			);
		} else {
			alert('An error occured while trying to process this request, sorry!');
		}
	}
}

var denyFriendRequest = function(mail_id)
{
	if (confirm('Deny this friend request?'))
	{
		if (mail_id > 0)
		{
			_deleteActionConfirm(mail_id);
		}
	}
}

var replyToMessage = function(mail_id, writer)
{
	var body = $('#replyText').val();
	
	if (body.length > 0)
	{
		$.post(
			'/mail/reply',
			{
				mail_id : mail_id,
				writer_id : writer,
				body : body
			},
			function (response)
			{
				$('#replyText').val('');
				$('#thread_container').append(response);
			}
		);
	}
	
	return false;
}

var createMessage = function ()
{
	var to = $('#to').val();
	var subject = $('#subject').val();
	var body = $('#body').val();
	
	if (subject.length > 1 && body.length > 1)
	{
		$.post(
			'/mail/send',
			{
				to:to,
				subject:subject,
				body:body
			},
			function (response)
			{
				$('#composeForm').html(response);
			}
		);
	}
}

var deleteMessage = function(id)
{
	if (confirm('Delete this message thread?'))
	{
		_deleteActionConfirm(id);
	}
}

var _deleteActionConfirm = function(id)
{
	$.post(
			'/mail/delete',
			{
				id:id
			},
			function(response)
			{
				$('#message_'+id).hide('slow');
			}
		);
}

var BandWizard = new function() {
	var id;
	var name;
	var step;
	var cWidth = 905;
	
	this.gotoPrevious = function()
	{
		if (parseInt(this.step) > 0)
		{
			this.move($('#wizard_content'), "+="+cWidth+"px");
		}
	};
	this.gotoNext = function()
	{
		if (parseInt(this.step) > 0 && this.id != undefined)
		{
			this.move($('#wizard_content'), "-="+cWidth+"px");
		}
	};
	this.gotoStep = function(_step)
	{
		if (this.id != undefined)
		{
			var xPos = Math.abs((this.step - _step) * cWidth);
			var cStep = this.step;
			
			this.step = _step;
			
			if (_step > cStep)
			{
				if (_step != cStep)
					this.move($('#wizard_content'), "-="+xPos+"px");
			} else if (_step != cStep) {
				this.move($('#wizard_content'), "+="+xPos+"px");
			}
		}
	}
	this.stepComplete = function(cStep)
	{
		$('#band_wizard_step_'+cStep).data('complete', true);
	};
	this.loadWizardSection = function(cStep)
	{
		var cUrl;
		
		if (cStep != undefined)
			this.step = cStep;
		
		switch(parseInt(this.step))
		{
			case 1 :
				cUrl = '/band/wizard/name-band';
				break;
			case 2 :
				this.stepComplete(2);
				cUrl = '/band/wizard/logo/id/'+this.id+'/name/'+escape(this.name);
				break;
			case 3 : 
				cUrl = '/band/wizard/setup-profile/id/'+this.id;
				break;
		}
		
		this.updateStepTabs();
		
		this.stretch(String($('#step_'+this.step).attr('stretch')+'px'));
		
		if ((cUrl != undefined) && ($('#step_'+this.step).data('loaded') == undefined))
		{
			var pCon = $('#step_'+this.step);
			
			$('#step_'+this.step+' .content').load(cUrl, function()
			{ 
				pCon.data('loaded', true);
				BandWizard.unlockNavigation();
			});
		}
	};
	this.lockNavigation = function()
	{
		$('.band_wizard_step_prev').attr('disabled', true);
		$('.band_wizard_step_next').attr('disabled', true);
	};
	this.unlockNavigation = function()
	{
		$('.band_wizard_step_prev').removeAttr('disabled');
		$('.band_wizard_step_next').removeAttr('disabled');
	}
	this.updateStepTabs = function()
	{
		//Update step tabs
		$('.band-wizard-step').each(function()
		{
			$(this).removeClass('current');
			
			if ($(this).data('complete') != undefined)
			{
				$(this).addClass('complete');
			}
		});
		
		$('#band_wizard_step_'+this.step).removeClass('complete').addClass('current');
	}
	this.move = function(elem, pos)
	{
		elem.animate({left: pos},{complete: this.loadWizardSection()});
	};
	this.stretch = function(num)
	{
		$('#band_wizard, #band_wizard_wrapper, .wizard-content-wrapper').animate({height: num});
		$('.band_wizard_navigation').animate({top: String(parseInt(num) - 180)});
		$('#footer').animate({top: String(parseInt(num) - 180)});
	}
};

function HScrollList()
{
	var sc = this;
	var mainWrapper;
	var listWrapper;
	var itemWrapper;
	var scrollLeftControl;
	var scrollRightControl;
	var maxNumVisible = 6;
	var wrapperSize;
	var scrollAmount;
	var numItems;
	var maxScroll;
	
	this.init = function(_mainWrapper, _listWrapper, _itemWrapper, _scrollLeftControl, _scrollRightControl)
	{
		this.mainWrapper = _mainWrapper;
		this.listWrapper = _listWrapper;
		this.itemWrapper = _itemWrapper;
		this.scrollLeftControl = _scrollLeftControl;
		this.scrollRightControl = _scrollRightControl;
		
		this.wrapperSize = this.mainWrapper.width() + 12;
		this.scrollAmount = parseInt(this.itemWrapper.width()) + parseInt(this.itemWrapper.css('margin-right').split("px")[0]);
		
		this.numItems = this.itemWrapper.size();
		this.calcCoords();
		
		if (this.numItems > maxNumVisible)
		{
			this.scrollRightControl.removeClass('hidden');
			
			this.scrollLeftControl.click(function()
			{
				$(this).addClass('hidden');
				sc.listWrapper.animate({marginLeft: "+="+sc.scrollAmount+"px"}, {complete: sc.refreshScrubControl});
			});
			
			this.scrollRightControl.click(function()
			{
				$(this).addClass('hidden');
				sc.listWrapper.animate({marginLeft: "-="+sc.scrollAmount+"px"}, {complete: sc.refreshScrubControl});
			});
		}
		
		this.listWrapper.bind('DOMNodeInserted', this.addItem);
		this.listWrapper.bind('DOMNodeRemoved', this.removeItem);
	};
	this.removeItem = function(e)
	{
		if ($.browser.msie)
			e.cancelBubble = true;
		else
			e.stopPropagation();
		
		sc.numItems--;
		sc.refreshScrubControl();
		
		return false;
	};
	this.addItem = function(e)
	{
		if ($.browser.msie)
			e.cancelBubble = true;
		else
			e.stopPropagation();
		
		sc.numItems++;
		sc.refreshScrubControl();
		
		return false;
	};
	this.calcCoords = function()
	{
		this.maxScroll = Math.floor((this.numItems * this.scrollAmount) - this.wrapperSize);
	};
	this.refreshScrubControl = function(e)
	{
		sc.calcCoords();
		
		var curPos = Math.abs(sc.listWrapper.css('margin-left').split("px")[0]);

		if (curPos == 0)
			sc.scrollLeftControl.addClass('hidden');
		else
			sc.scrollLeftControl.removeClass('hidden');
		
		if (curPos >= sc.maxScroll)
			sc.scrollRightControl.addClass('hidden');
		else
			sc.scrollRightControl.removeClass('hidden');
	}
}

var postNote = function(post_to_id, _type)
{
	var type = _type || "user";
	
	var button_text = $(".post-a-note").html();
	$('.post-a-note').html(loading);
    var note_reply_textarea = $('input[name*=note_body]:first, textarea[name*=note_body]:first');
	var note_body_text = note_reply_textarea.val();

	if (note_body_text.length > 0){
		$.post(
				'/note/post/id/'+post_to_id,
				{
					type: type,
					note_body: note_body_text
				},
				function(response){
					$(".post-a-note").html(button_text);
                    note_reply_textarea.val("");
					
					if (response == BB.response.prompt_login)
					{
						BbPopUp.promptLogin();
						return false;
					}
					
					$('input[name*=note_body]:first').val('').blur().trigger('change');
					$('#notes').prepend(response);
				}
			);
	}else{
		$(".post-a-note").html(button_text);
	}
}

function updateNumListens(id)
{
	var numListens = $('.listens_'+id).text();
	numListens++;
	$('.listens_'+id).empty().text(numListens);
}

var BbPopUp = {
	open: function(url, options)
	{
		defaultOptions = {
			title: '',
			width: 535,
			height: 367,
			callback : null
		}
		
		if (typeof options == 'object') {
			options = $.extend(defaultOptions, options);
		} else {
			options = defaultOptions;
		}

		if (options.plugin == 'shadowbox')
		{
			options.width = 515;
			options.height = 347;
			
			Shadowbox.open(
			{
				content: url,
				player: 'iframe',
				title: options.title,
				width: options.width,
				height: options.height
			});
		} else {
			//tb_open_new(url + '?width=' + options.width + '&height=' + options.height);
            if(url.indexOf('?') == -1){
                tb_show('', url + '?width=' + options.width + '&height=' + options.height, null, options.callback);
            }else{
                tb_show('', url + '&width=' + options.width + '&height=' + options.height, null, options.callback);
            }
		}
	},
	promptLogin: function(title)
	{
        var app_id = $("#app_id").attr("rel");
        promptLoginDialog(title, app_id);
	}
}
function promptLoginDialog(title, app_id)
{
    tb_remove();

    if(title == undefined)
        title = "";
    
    if (window.location.href.indexOf('/sb/') == -1)
    {
        app_id = app_id || 1;
        if(appMode == "satellite"){
            tb_show('', '/login/app/app_id/'+app_id+'/title/'+title+'?width=420&height=495');
        }else{
            tb_show('', '/login/index/title/'+title+'?width=550&height=500');
        }
    } else {
        window.parent.tb_show('', '/login?width=900&height=350');
    }
}

function addLogoToCue(html)
{
	$('#band_logos_hscroll ul').prepend("<li>"+html+"</li>");

	if ($('#artist_logos, #band_logos').find('img').length == 1)
	{
		var src = $(html).find('img:first').attr('src');
		$('#logged_in_user_thumb').attr('src', src);
		updateBandLogo(src);
	}
	
	if ($.browser.msie)
	{
		$('#band_logos_hscroll').trigger({type:'DOMNodeInserted'});
	}
}

function fanArtist(userId, e)
{
	var context = $(e);
	var ogHtml = context.html();
	context.html(loading);
	
	$.post(
		'/fans/fan-user/', {id:userId}, function(r)
		{
			context.html(ogHtml);
			
			if (r == BB.response.prompt_login)
			{
				BbPopUp.promptLogin();
			} else if (r == 0) {
				alert("Looks like you're already a fan!");
			} else {
				context.closest('div').parent().find('.de-fan-user-inline:first').removeClass('hidden');
				context.closest('div').addClass('hidden');
			}
		}
	);
}

function deFanArtist(userId, e)
{
	var context = $(e);
	var ogHtml = context.html();
	context.html(loading);
	
	$.post(
		'/fans/de-fan-user/', {id:userId}, function(r)
		{
			context.html(ogHtml);
			
			if (r == BB.response.prompt_login)
			{
				BbPopUp.promptLogin();
			} else {
				context.closest('div').parent().find('.fan-user-inline:first').removeClass('hidden');
				context.closest('div').addClass('hidden');
			}
		}
	);
}

function sizeContainer(container, size)
{
	$('#'+container).height(size);
}

function hPosition(container, amount, dir)
{
	if (dir == 'down')
		direction = "";
	else
		direction = "-";
	
	container.animate({marginTop: direction+amount+"px"}, 1000);
}

function log(v)
{
	console.log(v);
}

function limitChars(textid, limit, infodiv)
{
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(textlength > limit)
	{
		 $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		 $('#'+textid).val(text.substr(0,limit));
		 return false;
	}
	else
	{
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}
function band_name_lookup(key_count){
	if(key_count == band_key_count_global) { // The control will reach this point 1 second after user stops typing.
		
	}
}

function enhanced_fb_share(songId, type) {
    if(appMode != "default"){
        if(appMode == 'facebook'){
            var app_id = $("#facebook_app_id").attr("rel");
        }else {
            var app_id = $("#app_id").attr("rel");
        }
        BbPopUp.open("/share/song/index/app_id/"+app_id+"/app_mode/"+appMode+"/id/"+songId+'/type/'+type, {width:400, height:500});
        if(appMode == "facebook"){
            FB.Canvas.scrollTo(0,0);
            $("#TB_window").css("top", "410px");
            $("#TB_window").css("margin-top", "0px");
        }
    }else{
        BbPopUp.open("/share/song/index/id/"+songId+'/type/'+type, {width:400, height:500});
    }
	return false;
}

function scrollIFrame(name, x, y)
{
    var frame = document.getElementById(name);        
    frame.contentWindow.scrollTo(x, y);         
}

function enhanced_award_share(id) {
	if ($('#tooltip').size() > 0)
	{
		$('#tooltip').empty();
	}
	BbPopUp.open("/share/award/index/id/"+id, {width:400, height:580});
	return false;
}

function enhanced_trophy_share(id) {
	if ($('#tooltip').size() > 0)
	{
		$('#tooltip').empty();
	}
	BbPopUp.open("/share/trophy/index/id/"+id, {width:400, height:580});
	return false;
}

function submitToItunesRequest(id){
    
}

function fbs_click(songId) {
	return enhanced_fb_share(songId);
}

function shareSong(id, type)
{	
    return enhanced_fb_share(id, type);
}

function promoteUser(userId, pro)
{	
	var pro = pro || 0;
	BbPopUp.open("/share/promote/index/id/"+userId+"/pro/"+pro+"/", {width:400, height:500});
	return false;
}

function promoteProducer(userId)
{	
	BbPopUp.open("/share/promote/index/id/"+userId+"/producer/1/", {width:400, height:500});
	return false;
}

function promoteCompetition(competitionId)
{	
	BbPopUp.open("/share/promote-competition/index/id/"+competitionId, {width:400, height:500});
	return false;
}

function sweetShareFbShare(u, t){
	window.open(u,'share','toolbar=0,status=0,width=626,height=436');
	return false;
}

function initRating()
{
	// Rating
	if ($('.auto-submit-star').length > 0)
	{
		$('.auto-submit-star').rating({ 
			required: true,
			callback: function(value, link)
			{
				var container = $(this).parent();
				var attr = $(this).attr('name').split(':');
				var id = attr[0];
				var type = attr[1] || 'song';
				var hash = attr[2] || '';
				var typeEncr = attr[3] || '';
				
				$.post(
					'/'+type+'/rate',
					{
						id:id,
						rating:value,
						typeEncr:typeEncr
					},
					function(response)
					{
						if (response == BB.response.prompt_login)
						{
							BbPopUp.promptLogin();
						} else {
							$('input',container).rating('disable');
							container.find(".rating-response:first").append("<span style=\"font-style: italic; font-weight: bold; margin-left: 5px; position: relative; top:6px;\" class=\"pink\"><small>You rated "+value+"</small></span>");
						}
					}
				);
			} 
		});
	}
}

function is_int(value)
{ 
	if ((parseFloat(value) == parseInt(value)) && !isNaN(value))
	{
		  return true;
	  } else { 
		  return false;
	} 
}

function showYtVid(vid)
{
	BbPopUp.open("/static/v/vid/" + vid, {width: 640, height: 386});
}

function stubSongShare(id, hash, xpos, ypos)
{
	$.post("/share/song/index/stub/1/", {id:id, type:hash, xpos:xpos, ypos:ypos}, function(response)
	{
		$('#stubShare').remove();
		$('body').append(response);
	});
}

function swapNodes(a, b) {
    var aparent= a.parentNode;
    var asibling= a.nextSibling===b? a : a.nextSibling;
    b.parentNode.insertBefore(a, b);
    aparent.insertBefore(b, asibling);
}

function vote(songEntryId)
{
   var button = $("#vote_button_"+songEntryId);
   var button_container = $("#vote_button_"+songEntryId).parent();
   var button_text = $("#vote_button_"+songEntryId).parent().prev();
   var spinner = $("#vote_button_"+songEntryId).parent().next();

   button.hide();
   spinner.show();

   $.post("/competitions/contest/vote",
   {song_entry_id:songEntryId},
   function(response){
       button_container.removeAttr("onclick");
       button.show();
       button.removeClass("vote-button").addClass("vote-disabled-button");
       spinner.hide();
       if(typeof(parseInt(response))=='number')
           $(button_text).html(response);
   });
   return false;
}

function submitLinksForm()
{
    document.editLinksForm.submit();
}

function equalHeights(element){
	$(element).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	});
}

function toggleShareEmail()
{
    var song_share_email_panel = document.getElementById("song_share_email_panel");
    var song_share_widget_large_bg = document.getElementById("song_share_widget_large_bg");
    if(song_share_email_panel.style.display != "block"){
        $("#song_share_widget_large_bg").animate({ height: "474px" }, 750, "swing", function(){
            $("#song_share_email_panel").show();	
        });
    }else{
        $("#song_share_email_panel").hide();	
        $("#song_share_widget_large_bg").animate({ height: "256px" }, 750, "swing");
    }
}

function shareLog(url, id, app_id, app_mode)
{
    $.post(url, {id:id, app_id:app_id, app_mode:app_mode});
}

function shareEmail(url, id, app_id, app_mode)
{
    var to = $("#song_share_email_input").val();	
    var body = $("#song_share_email_textbody").val();	

    if(to==""){
        $.jGrowl("Please enter an email address");
        return;
    }
    var thisvar = $("#song_share_email_invite_button");
    var ogHtml = $("#song_share_email_invite_button").html();

    $("#song_share_email_invite_loader").show();
    thisvar.hide();	
    $.post(url, {id:id, to:to, body:body, app_id:app_id, app_mode:app_mode},
        function(response){
            thisvar.show();
            $("#song_share_email_invite_loader").hide();
        }
    );
}

function shareFacebook(facebook_url, url, id, app_id, app_mode)
{
	var app_id = app_id || null;
	var app_mode = app_mode || "default";
	
    window.open(facebook_url, 'share', 'toolbar=0,status=0,width=626,height=436');

    shareLog(url, id, app_id, app_mode);
}

function redirectToProfile(userId)
{
    window.location.href = "/user/"+userId;
}

