


$(document).ready(function(){

	
	$('.rollout_link').click(function() {
		var low = $(this).attr('low') + 'px';
		var hi = $(this).attr('hi') + 'px';
		
		if($('#' + $(this).attr('rel')).css('top') === low) {
			$('#' + $(this).attr('rel')).animate({"top": hi}, "slow");
			if($(this).attr('rel') === 'login_rollout') {
				$('#forgot_rollout').animate({"top": -93}, "slow");
			} else {
				$('#login_rollout').animate({"top": -72}, "slow");
			}
		} else {
			$('#' + $(this).attr('rel')).animate({"top": low}, "slow");	
		}				  
	});
	
	$('.ezpz_input').ezpz_hint();
	$('.datepicker').datepicker();
	
	$('.top_list li:odd').addClass('alt');

	

	
 	DD_roundies.addRule('#content', '3px 3px 0 0', true);
	DD_roundies.addRule('.playlist', '5px', true);
 
	$('#dialog').dialog({
			autoOpen: false,
			modal:true,
			zIndex:20,
			title: " ",
			height: 600,
			width: 520
	});
	
	$('#add_section').click(function() {
		$('#dialog').dialog("option", "width", 650);
		$('#dialog').dialog("option", "height", 470);
		$('#dialog').dialog('open');
		
		loadNewSection($(this).attr('rel'));							 
	});
	
	$('.edit_section').click(function() {
		$('#dialog').dialog("option", "width", 650);
		$('#dialog').dialog("option", "height", 470);
		$('#dialog').dialog('open');
		
		loadSection($(this).attr('rel'));			
	});	
	
	
	loadStars();
	
	initTopDelete();
	initTopOrder();
	initSearchLinks();
	
	initPrivacyLinks();
	
	$('.edit_story').click(function() {
		loadEditStory($(this).attr('rel'));
	});
	
	$('.delete_story').click(function() {

		if(confirm('Do you want to delete this story?')) {
			var that = this;
			$.post(homeDir + 'stories/delete-story',
				   {'id': $(this).attr('rel')},
				   function(data) {
					   	if($(that).attr('pg') == 'sections') {
							window.location = homeDir + 'stories';	
						} else {
							$(that).parent().parent()
									.parent().parent().remove();
						}
				   });
		}
									  
	});
	
	initDeleteComments();
	
	
});

function initDeleteComments() {
	$('.delete_comment').click(function() {
			
			if(confirm('Do you want to delete this comment?')) {
				
				var that = this;
				$.post(homeDir + 'stories/delete-comment',
					{id: $(this).attr("rel")},
					function() {
						$(that).parent()
								.parent()
								.parent().remove();
					});
				
			}
	});	
}

function setBetaNotice() {
		return;
		$('#dialog').empty();
		$('#dialog').load(homeDir + 'index/beta-notice', {},
				function() {
					$('#dialog').dialog("option", "width", 600);
					$('#dialog').dialog("option", "height", 450);
					$('#dialog').dialog('option', 'buttons', { "Agree": function() {$(this).dialog('close');}});
					$('#dialog').dialog('open');
				});	
					
}
function initTopDelete() {
	
	$('.delete_top').unbind('click');
	$('.delete_top').click(function() {

		var type = $(this).attr('rel');
		var id = $(this).attr('t_id');
		
		var that = this;
		$.post(homeDir + 'users/delete-top/',
			   	{
				'type' : type,
				'id' : id
				},
				function() {
					$(that).parent().parent().siblings('form').show();
					$(that).parent().remove();
					
					$('.top_list li').removeClass('alt');
					$('.top_list li:odd').addClass('alt');
				
				});
	});	
	
	
}


function initTopOrder() {
		$('.top_list').sortable({
			
			update : function() {
				var order = $(this).sortable('serialize');
		
				var that = this;
				$.post(homeDir + 'users/order-top?' + order,
						{'type' : $(that).attr('rel')},
						function() {
							$(that).find('li').removeClass('alt');
							$(that).find('li:odd').addClass('alt');						
						});
				

			}		
		});	
}

function initPrivacyLinks() {
	$('.terms_link').click(function() {
		$('#dialog').empty();
		$('#dialog').load(homeDir + 'legal/terms-of-use', {},
				function() {
					$('#dialog').dialog("option", "width", 600);
					$('#dialog').dialog("option", "height", 450);
					$('#dialog').dialog('option', 'buttons', { "Close": function() {$(this).dialog('close');}});
					$('#dialog').dialog('open');
				});		
	});
	
	$('.privacy_link').click(function() {
		$('#dialog').empty();
		$('#dialog').load(homeDir + 'legal/privacy', {},
				function() {
					$('#dialog').dialog("option", "width", 600);
					$('#dialog').dialog("option", "height", 550);
					$('#dialog').dialog('option', 'buttons', { "Close": function() {$(this).dialog('close');}});
					$('#dialog').dialog('open');
				});			
	});
	
	
}
function loadStars() {
	$('.stars').each(function() {
		var that = this;
		$(this).load(homeDir  + 'ratings/stars/',
					 {'id': $(this).attr('rel'),
					 'u': $(this).attr('u')},
					 function() {
						 
						$(that).find('.star_link').click(function() {
	
							$.post(homeDir + 'ratings/rate', 
								{'rank': $(this).find('.star').attr('rel'), 
								 'story_id':  $(that).attr('rel')},
								function() {
									loadStars();
								}
							);
						});
						
						$(that).find('.star_link').hover(function() {
							var parent = $(this).parent();
							var pos = $(this).find('.star').attr('rel');
							$(parent).find('.star:lt('+ pos + ')')
									.css('background-position', '0px -15px');
						}, function() {
							$(this).parent().find('.star').css('background-position', '0px 0px');
						});
						
						$(that).find('.star').each(function() {
							var avgVal = $('#avgRank_' + $(that).attr('rel')).val();
							if($(this).attr('rel') > avgVal) {
								
								var val = parseInt($(this).attr('rel')) - 0.5;
								if(val <= avgVal) {
									$(this).addClass('half');
								} else {
									$(this).addClass('off');
								}
								
							}
						});
					 });			
	});	
}
function loadSection(section_id) {
	$('#dialog').empty();
	$('#dialog').load(homeDir + 'stories/edit-section/', 
			{'id': section_id}, 
			function() {	
				$('#dialog').bgiframe();
				$('#add_photos').click(function() {
					openPhotosDialog(story_id);		
				});
				
				setValidate();
				
				$('.section_save').click(function() {
					tinyMCE.get("desc").save();
					$('#section_form').submit()							 
				});
				
				var that = this;
				$('.dialog_cancel').click(function() {
					$(that).dialog('close');							
				});
			});		
}

function loadNewSection(story_id) {
	$('#dialog').unbind('dialogbeforeclose');
	$('#dialog').empty().dialog("option", "width", 630);
	$('#dialog').empty().dialog("option", "height", 500);
	$('#dialog').load(homeDir + 'stories/new-section/', 
			{'story_id': story_id}, 
			function() {	
				$('#dialog').bgiframe();
				
				setValidate();
				
				$('#add_photos').click(function() {
					openPhotosDialog(story_id);		
				});
				
				$('#section_msg').hide();
				
				$('.section_save').click(function() {
					tinyMCE.get("desc").save();

					if($(this).hasClass('btn_new_section')) {
						$('#redirect').val(0);
						$('#section_form').ajaxSubmit(function() {
							$('#section_form').resetForm();
							$('#section_msg').show();
							$('#section_msg').fadeOut('slow');
							
						});
						
					} else {
						var title = $('#story_title').val();
						var image = $('#album_art').val();
						var song = $('#song').val();
						var artist = $('#artist').val();
						var story_id = $('#story_id').val();
						publishNewStory(title, image, song, artist, story_id);						
						$('#redirect').val(1);
						$('#section_form').submit();
					}
					
					//publishNewSection($('#title').val(), $('#story_id').val());
				});
				
				var that = this;
				$('.dialog_cancel').click(function() {
					//$(that).dialog('close');			
					window.location = homeDir + 'stories/story/id/' + $('#story_id').val();			
				});
			});	
}

function publishNewSection(title, story_id) {
	var links = [{"text": "View Story", 
				 "href":"http://" + window.location.hostname + homeDir + "stories/story/id/" + story_id}]; 
	var msg = "New MyAudioBio Story: " + title;
	var attachment = {'name': "New MyAudioBio Story: " + title,
					   "href":"http://" + window.location.hostname + homeDir + "stories/story/id/" + story_id,
					   "caption": "This user posted a new MyAudioBio story",
					   "description": "This is the description about the post",
						'media':
						[{'type':'image','src':'http://userserve-ak.last.fm/serve/300x300/32349887.jpg','href':'http://userserve-ak.last.fm/serve/300x300/32349887.jpg'}]}; 
	
	//callPublish(msg,attachment,links, '');	
	return true;
}

function publishNewStory(title, image, song, artist, story_id) {
	
	var link = "http://" + window.location.hostname + homeDir + "stories/story/id/" + story_id;
	
	var links = [{"text": "View Story", 
				 "href":link}]; 
	var msg = "";

	var attachment = {'name': "New MyAudioBio Story: " + title,
					   "href": link,
					   "description": song + " by " + artist,
					   "caption": "{*actor*} posted a new story at MyAudioBio.com"}; 	
						   	
	if(image !== '') {
		attachment = {'name': "New MyAudioBio Story: " + title,
						   "href": link,
						   "description": song + " by " + artist,
						   "caption": "{*actor*} posted a new story at MyAudioBio.com",
							'media':
							[{'type':'image','src':image,'href':link}]}; 		
	}

		
	//var attachment = {'media':[{'type':'image','src':'http://userserve-ak.last.fm/serve/300x300/32349887.jpg','href':'http://userserve-ak.last.fm/serve/300x300/32349887.jpg'}]}; 
	callPublish(msg,attachment,links, '');	
	return true;	
}

function notifyFriendTagged(title, image, song, artist, story_id, friend_id) {
	var msg = "";

	var link = "http://" + window.location.hostname + homeDir + "stories/story/id/" + story_id;
	
	var links = [{"text": "View Story", 
				 "href":link}]; 
	
	var attachment = {'name': "You've been tagged in a MyAudioBio Story: " +  title,
					   "href": link,
					   "description": song + " by " + artist,
					   "caption": "{*actor*} tagged you in a story at MyAudioBio.com"}; 	
		
		
	if(image !== '') {
		attachment = {'name': "You've been tagged in a MyAudioBio Story: " + title,
						   "href": link,
						   "description": song + " by " + artist,
						   "caption": "{*actor*} tagged you in a story at MyAudioBio.com",
							'media':
							[{'type':'image','src':image,'href':link}]}; 		
	}
				   
	callPublish(msg,attachment,links, friend_id);	
	return true;		
}

function callPublish(msg, attachment, action_link, target_id) {
  FB.ensureInit(function () {
	FB.Connect.ifUserConnected(function() {					  
  		FB.Connect.streamPublish(msg, attachment, action_link, target_id, '', null, true);		
	});
	
	/*
	FB.Connect.ifUserConnected(function() {
		//publish without prompting user for permission.
		FB.Connect.streamPublish(msg, attachment, action_link, target_id, '', null, true);		
	}, function () {
		//prompt user if they would like to publish.
		FB.Connect.showPermissionDialog("publish_stream", function(x){
			FB.Connect.streamPublish(msg, attachment, action_link, target_id, '', null, true);	
		}, false);
	});*/
  });
}
	
function loadFbFriends() {
		//var widget_div = document.getElementById("profile_pics");
		
			FB.ensureInit(function () {
			  FB.Facebook.get_sessionState().waitUntilReady(function() {
			  FB.Facebook.apiClient.friends_get(null, function(result) {
				var markup = "";
				var num_friends = result ? Math.min(5, result.length) : 0;

				if (num_friends > 0) {
				  for (var i=0; i<num_friends; i++) {
					
					markup = 
					  '<li>' +
					  '<input type="checkbox" name="fb_friends['+result[i]+']" />' + 
					  '<fb:name uid="'+result[i]+'" useyou="true" linked="true"></fb:profile-pic>' + 
					  '<fb:profile-pic size="square" uid="'+result[i]+'" facebook-logo="true"></fb:profile-pic></li>';
					$('#friends_check').append(markup);
				  }
				}
				//widget_div.innerHTML = markup;
				//FB.XFBML.Host.parseDomElement(widget_div);
			  });
			  });
			});	
		
}
function loadEditStory(story_id) {
	
	$('#dialog').empty();
	$('#dialog').load(homeDir + 'stories/edit-story/', 
			{'story_id': story_id}, 
			function() {	
				$('#dialog').bgiframe();

				$('.story_save').click(function() {
					$('#story_form').submit()							 
				});
				
				var that = this;
				$('.dialog_cancel').click(function() {
					$(that).dialog('close');							
				});
				
				$('.datepicker').mask("99/99");
				setValidate();
				
				$('#dialog').dialog("option", "width", 600);
				$('#dialog').dialog("option", "height", 550);
				$('#dialog').dialog('open');
			});		
	
}
function openPhotosDialog(story_id) {
	$('#dialog').dialog("option", "width", 600);
	$('#dialog').dialog("option", "height", 550);
	$('#dialog').dialog("option", "closeOnEscape", false);
	$('#dialog').dialog('open');
	
	$('#dialog').empty();
	$('#dialog').load(homeDir + 'media/add-images/', 
			{'story_id': story_id}, 
			function() {	
				$('#dialog').bgiframe();
				
				var that = this;
				$('#add_images').click(function() {
					window.location = homeDir + 'stories/story/id/' 
								+ $(that).find('#story_id').val() + '/t/1';
					//$(that).dialog('close');
					
				});
			});	
}
function openVideosDialog(story_id) {
	$('#dialog')
		.dialog("option", "width", 600)
		.dialog("option", "height", 550)
		.dialog("option", "closeOnEscape", false)
		.dialog('open')	
		.empty()
		.load(
			homeDir + 'media/add-videos/', 
			{'story_id': story_id}, 
			function() {	
				$('#dialog').bgiframe();
				
				var that = this;
				$('#add_images').click(function() {
					window.location = homeDir + 'stories/story/id/' 
								+ $(that).find('#story_id').val() + '/t/1';
					//$(that).dialog('close');
				});
				
				$('.dialog_cancel').click(function() {
					$(that).dialog('close');							
				});
			}
		);	
}

function initSearchLinks() {
	
	$('.search_link').click(function() {
		
		var pg = 1;
		var type = $(this).attr('rel');
		if(type === 'artist') {
			pg = 1;
		} else if(type === 'song') {
			pg = 2;
		} else if(type === 'album') {
			pg = 3;
		}
		
		var word = $(this).text().replace(/^\s+/g,'').replace(/\s+$/g,''); /* trim */
		//url encode
		word = escape(word).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
		//redirect
		window.location = homeDir + 'stories/search/t/' + pg + '/keyword/' + word;							 
	});
}
function formatItem(item, position, length) {

	var newItem = item.toString();
	newItem = newItem.replace('<span class="time">', "");
	newItem = newItem.replace('</span>', "");
	return newItem;

}

function checkRequired() {
	var good = true;
	$('.required').each(function() {
		if($(this).val() === ''
					  || $(this).val() == $(this).attr('title')) {
			good = false;
			alert($(this).attr('rel') + ' is required');	
			
		}
	});	
	return good;
}

function setValidate() {
	$('.validate').submit(function() {
		return checkRequired();
	});	
}
	