
	/* ------------------------------------------
	*  INDEX PAGE
	* ---------------------------------------- */
	
	function indexPage() {
		// Submit the comment via ajax
		$('.add-comment').submit(ajaxAddComment);
		
		
	/* ------------------------------------------
	*  GROUP PLAYLISTS
	* ---------------------------------------- */

		// Show/hide comments on actionstream items
		$('.comment-add').click(function(){
	        var comment_form = $(this).parents('li:first').find('.comment_form:first');
			comment_form.toggle();
	        comment_form.find('input[type=text]').focus();
			return false;
		});
	
		// Hide default comment input text on focus
		$('.add-comment input[type=text]').focus(function() {
			if (/^Add your comment/.test(this.value)) {
				this.value = "";
			}
			$(this).addClass("focus");
		});
	
		$('.add-comment input[type=text]').blur(function() {
			if ($.trim(this.value) == '') {
				this.value = 'Add your comment';
				$(this).removeClass('focus');
			}
		});
	
		// Select share url when input is in focus
		$('.invite_field').focus(function(){
			this.select();
		});
		
		// Using jScrollpane on the playlist users box
		if ($('#playlist_users').height() > '350'){
			$('#playlist_users').css('height','350px');
			$('.jscroll').jScrollPane();
		}
		
		// Playlist user's remove button
		$('#playlist_users li .closesmall').css('display','none'); // Hide via js so non-js will see the link
		$('#playlist_users li').mouseover(function(){
			$('.closesmall',this).css('display','block');
		}).mouseout(function(){
			$('.closesmall',this).css('display','none');
		});
		
		$('#playlist_users .closesmall').each(function(i) {
	        // When you click on the close button...
			$(this).bind('click', function(e) {
	            // If the viewer doesn't want to remove the user, shortcircuit
				if (!confirm("Are you sure you want to remove this user? Their existing tracks will stay on this playlist but they will not be able to add any more.")) {
					return false;
				}
	            var el = this;
	            // Make the removal call
	        	$.ajax({
	            	url: $(el).attr('href') + '&ajax=1',
		            global: false,
	    	        type: "GET",
	                dataType: 'json',
	                success: function(msg) { // If the function returned successfully...
						// If the back end was successful...
						if (!msg.header.code) {
	                        $('#content .contributor_count').each(function(i) {
								$(this).text($(this).text() - 1);
	                        }); // Decrement the total contributor count
	                        $(el).parent().remove(); // Remove the parent element
		                    alert("This user was successfully removed");
						}
	                },
				    error: function(msg) {
					    alert("There was a problem removing this user. Please try again later.");
	                }
	            });
	            return false;
	        });
	    });

		// Create group settings modal
		$('#lnkGroupSettings').bind('click', function(e) {

			var content = '<div class="boxy_content">'
				+ '<form id="frmSettings" action="' + DOMAIN_ASYNC + '/entity/permissions/' + playlist_enid + '/setgroupprivs" accept-charset="utf-8">'
				+ '<fieldset><legend>Who can contribute to this playlist?</legend>'
				+ '<label for="rdoInviteMe"><input type="radio" name="privs" id="rdoInviteMe" value="1" />Only people invited by me can contribute</label>'
				+ '<label for="rdoInviteContrib"><input type="radio" name="privs" id="rdoInviteContrib" value="2" />Any contributor can invite contributors</label>'
				+ '<label for="rdoInviteAll"><input type="radio" name="privs" id="rdoInviteAll" value="3" />Anyone can contribute (no invites needed)</label>'
				+ '</fieldset>'
				+ '<button id="btnFrmSettingsSubmit" type="submit" class="green"><span>Save</span></button>'
				+ '</form>'
				+ '</div>';

			jQuery('.boxy-wrapper').remove(); // Remove all existing lightboxes
			var lightbox = new Boxy(content,{
				//title: 'Group Settings',
				closeable: true,
				closeText: 'X',
				center: true,
				fixed: false,
				modal:true,
				hideFade: true,
				hideShrink: false,
				unloadOnHide:true,
				afterShow: function () {
                    var invite_fields = $('#frmSettings input');
                    invite_fields.each(function() {
                        if ($(this).attr('value') == invite_privs) {
							$(this).attr('checked', true);
						}
                    });

					$('#btnFrmSettingsSubmit').bind('click', function(e) {
						$.ajax({
							url: $('#frmSettings').attr('action') + '?ajax=1',
							type: 'POST',
							data: $('#frmSettings').serialize(),
							complete: function() {
                                invite_fields.each(function() {
									if ($(this).attr('checked')) {
										invite_privs = $(this).attr('value');
                                    }
                                });
                                lightbox.hideAndUnload();
                                return true;
                            }
						});
						return false;
                    });
					return false;
				}
			});
			return false;
		});

		
	}
	
	
  /* ------------------------------------------
  *  MANAGE PAGE
  * ---------------------------------------- */
  var savedPlaylist = true;
  var playlistTracks;
  var tl, dl_input, ul_input, nojs=false;
  var update_linkids = [];
  var delete_linkids = [];
  
  function managePage(){
	//if the "nojs" URL param is set, then don't init any of the drag&drop javascript frou-frou 
	if(document.location.href.indexOf('nojs') !== -1) {
		return false;
	}
	
	playlistTracks = $('#playlistTracks');
	tl = document.getElementById('playlistTracks');
	dl_input = document.getElementById('deletelinks');
	ul_input = document.getElementById('updatelinks');
	refreshLinks();   
	savedPlaylist = true;
	
	// SAVE CHANGES BEFORE LEAVING --------------------------
	window.onbeforeunload = function() {
		if (!savedPlaylist) {
			if (confirm("Do you want to save the changes made to your playlist?")) {
				$.ajax({
					url: $('#frmManageSongs').attr('action'),
					type: 'POST',
					data: $('#frmManageSongs').serialize(),
					complete: function() { savedPlaylist = true; }
				});
			}
		}
	};
	
	// SAVE BUTTONS -----------------------------------------
	$('button.save').click(function(){
		savedPlaylist = true;
	});
	
	// CANCEL BUTTONS -----------------------------------------
	$('a.button.cancel').click(function(){
		savedPlaylist = true;
	});
	
	// UP BUTTONS -------------------------------------------
	$('a.move_up', playlistTracks).each(function(index, item){
		var li = $(item).parents('li');
		$(item).click(function(){
			if (li.get(0) != $(playlistTracks).children('li:first-child').get(0)) {
				highlightTrack(li);
				li.prev().before(li);
				refreshLinks();
			}
			return false;
		});
	});
	
	// DOWN BUTTONS -------------------------------------------
	$('a.move_down', playlistTracks).each(function(index, item){
		var li = $(item).parents('li');
		$(item).click(function(){
			if (li.get(0) != $(playlistTracks).children('li:last-child').get(0)) {
				highlightTrack(li);
				li.next().after(li);
				refreshLinks();
			}
			return false;
		});
	});
	
	// DELETE BUTTONS -------------------------------------------
	$('a.delete', playlistTracks).click(function(){
		$(this).parents('li').hide(
			'drop', 
			{direction:'down'},
			500,
			function() {
				$(this).addClass('deleted');
				markLinkDeleted($(this).attr('id'));
				refreshLinks();
			}
		);
		refreshLinks();
		return false;
	});
	
	// DRAG & DROP -------------------------------------------
	playlistTracks.sortable({
		opacity: 0.7,
		revert: true,
		scroll: true,
		axis: 'y',
		tolerance: 'pointer',
		stop: refreshLinks
	});
	
	// ADD A SONG BY URL --------------------------------------
	$('#btnAddSongURL').click(function(){
		Window.create({
			url: $('#btnAddSongURL').attr('href'),
			specs: {
				width: 600,
				height: 600
			}
		});
		return false;
	});
  }
  
  function highlightTrack(li){
	li.css('color',(($('#playlistTracks>li').get().indexOf(li.get(0)) % 2 != 0) ? '#738eb0' : '#99b0cc'));
	li.effect(
		"highlight", {color:'#ffee55'}, 1000,
		function(){ $(this).removeAttr('style'); }.bind(li)
	);
  }

/**
 * Update the order of the "updatelinks" form element with a comma-separated list of link ids,
 * in the order of the links in the DOM
 */
function refreshLinks() {
	var tli = tl.getElementsByTagName('li');
	var linkid;
	savedPlaylist = false;
	//reset the update list
	update_linkids = [];
	//and refill with the current state of links in the DOM
	for(var i=0;i<tli.length;i++) {
		if(!/deleted/.test(tli[i].className)) { //if the link hasn't been marked as deleted, add it to the update list
			linkid = tli[i].id.match(/\d+/);
			update_linkids[update_linkids.length] = linkid;
			document.getElementById('trackOrder-' + linkid).innerHTML = i + 1;
		}
	}
	//and copy the links into the hidden input for updates
	ul_input.value = update_linkids.join(',');
}
/**
 * Marka link as deleted by adding it to the "deletelinks" form element
 * @param int linkDomId
 */
function markLinkDeleted(linkDomId) {
	//extract the link id from the element's DOM id and add it to the list to delete
	var linkid = linkDomId.match(/\d+/ );
	if(linkid !== null) {
		delete_linkids[delete_linkids.length] = linkid;
	}
	//and copy the links into the hidden input for deletes
	dl_input.value = delete_linkids.join(',');
}

	/* ------------------------------------------
	*  LOGIN / SIGN UP MODALS
	* ---------------------------------------- */
/** commented out for now 


	var loginModalURL;
	var loginModalOptions;
	var signUpModalURL;  
	var signUpModalOptions;
	
  // Sign Up Modal Options
  //loginModalURL = DOMAIN_ASYNC + '/signup-modal';
  signUpModalURL = DOMAIN_ASYNC + '/searchbeta/signup';
  signUpModalOptions = {
		id: 'signUpModal',
		width: 756,
		height: 360,
		ajax: true,
		forwardURL: DOMAIN_ASYNC + '/dashboard',
		afterFinish: function(modal){
			$('#frmSignUpModal').submit(function(){
				// Forward the user to the appropriate URL after signing up
				location.href = signUpModalOptions.forwardURL;
				return false;
			});
		}
	};
	
  // Login Modal Options
  //loginModalURL = DOMAIN_ASYNC + '/login-modal';
  loginModalURL = DOMAIN_ASYNC + '/searchbeta/login';
  loginModalOptions = {
		id: 'loginModal',
		width: 756,
		height: 370,
		ajax: true,
		forwardURL: DOMAIN_ASYNC + '/dashboard',
		afterFinish: function(modal){
			//$('frmLogInModal').onsubmit = function(){
			$('#frmLogIn').submit(function(){
				// Forward the user to the appropriate URL after logging in
				location.href = loginModalOptions.forwardURL;
				return false;
			});
			
			$('#btnCreateAccount').click(function(){
				modal.update(signUpModalURL, signUpModalOptions);
				return false;
			});
			
			$('#btnCancel').click(function(){
				modal.destroy();
				return false;
			});
		}
	};
	
	function modalSignup(event){
		//if (event.memo.url) signUpModalOptions.forwardURL = event.memo.url;
		(new Modalog()).initialize(signUpModalURL, signUpModalOptions);
		return false;
	};
	
	function modalLogin(event){
		//if (event.memo.url) loginModalOptions.forwardURL = event.memo.url;
		(new Modalog()).initialize(loginModalURL, loginModalOptions);
		return false;
	};
	
	$(document).ready(function(){
		// Sign Up Modal ---------------------------------------------
		$('#navSignUp').click(modalSignup);
		// Login Modal -----------------------------------------------
		$('#navLogIn').click(modalLogin);
	});
	
*/

  /* ------------------------------------------
  *  EMAIL CAMPAIGN
  * ---------------------------------------- */

function campaignPage(){
	//alert(global_isLoggedIn);
	if (typeof(global_isLoggedIn) == "undefined") {
		$('#campaignPoints div.campaign_point:not([class*=last]) a').click(function(){
			signUpModalOptions.forwardURL = this.href;
			modalLogin({ url: this.href });
			return false;
		});
	}
}


if (!Array.indexOf) { // Extend Array object to support indexOf (for <=IE6)
	Array.prototype.indexOf = function(obj) {
		for(var i=0, j=this.length; i<j; i++)
			if (this[i] == obj)
				return i;
		return -1;
	}
}
