var artist_timer = null;
var playlist_timer = null;
var autoplay_timeout = null;
function add_artist_friend(P_ID)
{
	$$('#friend_artist_link_'+P_ID+' a').each(function(elm) { elm.innerHTML = 'Adding ... '; });
	new Ajax.Updater('friend_artist_link_'+P_ID,'/ajax/artist', {method:'post',parameters: {'a':'add_friend','P_ID' : P_ID }, onComplete:function() { 
																																					 if($('comment_table_form') != null)
																																					 {
																																						 $('comment_table_form').removeClassName('hide');
																																					 }
																																				  }});
	return false;
}
function remove_artist_friend(P_ID)
{
	$$('#friend_artist_link_'+P_ID+' a').each(function(elm) { elm.innerHTML = 'Removing ... '; });
	new Ajax.Updater('friend_artist_link_'+P_ID,'/ajax/artist', {method:'post',parameters: {'a':'remove_friend','P_ID' : P_ID }, onComplete:function() { 
																																					 if($('comment_table_form') != null)
																																					 {
																																						 $('comment_table_form').addClassName('hide');
																																					 }
																																					 }});
	return false;
}
function add_artist_friend2(P_ID)
{
	$$('#friend_artist_link_'+P_ID+' a').each(function(elm) { elm.innerHTML = 'Adding ... '; });
	new Ajax.Updater('friend_artist_link_'+P_ID,'/ajax/artist', {method:'post',parameters: {'a':'add_friend_small','P_ID' : P_ID }});
	return false;
}
function remove_artist_friend2(P_ID)
{
	$$('#friend_artist_link_'+P_ID+' a').each(function(elm) { elm.innerHTML = 'Removing ... '; });
	new Ajax.Updater('friend_artist_link_'+P_ID,'/ajax/artist', {method:'post',parameters: {'a':'remove_friend_small','P_ID' : P_ID }});
	return false;
}

function removeFriendSuggestion(userid)
{
	var url = "/action/remove_friend_suggestion/"+userid;
	new Ajax.Request(url, { method: 'get', parameters: null, onSuccess: function (resp) {
																				  $('friend_suggest_'+userid).remove();
																				  }});
}
function deleteRecentlyPlayed(tid)
{
	var url = "/action/remove_recently_played/"+tid;
	new Ajax.Request(url, { method: 'get', parameters: null, onSuccess: function (resp) {
																				  $('track_'+tid).remove();
																				  }});
}

function toggleBio()
{
	if($('long_bio').className == 'hide') 
	{
		$('long_bio').className = 'show';  
		$('short_bio').className = 'hide';
	}
	else if($('short_bio').className == 'hide')
	{
		$('long_bio').className = 'hide';
		$('short_bio').className = 'show';
	}
}
function ajax_submit_return(url, formid)
{
	var params = '';
	if(formid != '') params = $(formid).serialize();
	url = url.replace('index.php','load.php');
	new Ajax.Request(url, { method: 'post', parameters: params, onSuccess: function(response)
			{
				if(response.responseText.length > 100) process_returned_HTML(response.responseText);
				else location.href='#'+response.responseText;
			}});
	return false;
}
function load_js(file)
{
  var headID = document.getElementsByTagName('head')[0];
  var scripts = $(headID).select('script');
  var exist = false;
  scripts.each(function (elm)
	{
		if(elm.src == file) exist = true;
	});
  if(!exist)
  {
	var scriptelm = document.createElement('script');
	scriptelm.type= 'text/javascript';
	scriptelm.src= file;
	headID.appendChild(scriptelm);
  }
}
function openFeedbackWindow() 
{
	ol_open_tall('/feedback/',''); 
}

function searchAjax()
{
	if(!rsh_loaded) return true;
	var what = $('what').options[$('what').selectedIndex].value;
	var keyword = $('keyword').value;
	location.href = '#/search.php?what='+what+'&keyword='+keyword+'&ajax_loaded=1';
	return false; 
}

function submit_feedback()
{
	if(!isEmail($('email').value)) { alert("Please enter a valid email."); $('email').select(); return false; }
	if($('subject').value == '') { alert("Please enter a subject."); $('subject').select(); return false; }
	if($('feedback').value == '') { alert("Please enter your feedback."); $('feedback').select(); return false; }
	var params = 'email='+encodeURIComponent($('email').value)+'&subject='+encodeURIComponent($('subject').value)+'&feedback='+encodeURIComponent($('feedback').value)+'&captcha_code='+encodeURIComponent($('captcha_code').value)+'&bug_url='+encodeURIComponent($('bug_url').value);
	var url = '/feedback/submit/';
	new Ajax.Updater('overlay_content', url, { parameters: params, method: 'post' })
}
function open_overlay(url)
{
	$('overlay').className = 'show';
	var vp_width = document.viewport.getWidth();
	var vp_height = document.viewport.getHeight();
	var vp_scroll_offset = document.viewport.getScrollOffsets();
	var top = vp_scroll_offset+20;
	var left = (vp_width - 420) / 2;
	$('overlay').setStyle({top: top+"px", left: left+"px"});
	$('overlay').innerHTML = url;
	$('overlay').className = 'show';
}

function close_overlay()
{
	$('overlay').className = 'hide';
}

function trim(str)
{
 s = str.replace(/^(\s)*/, '');
 s = s.replace(/(\s)*$/, '');
 return s;
}

function isEmail(str){
  if(str == '') return false;
  var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
  return re.test(str);
}

function copytext(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range && BodyLoaded==1)
      range.execCommand('Copy');
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
	document.getElementById('copycodetext').innerHTML = 'code copied';
	inElement.select(); 
  }
}

function switchTableTab(tableid,tab_prefix)
{
	// remove all selected classes from tabs
	$$('#'+tableid+' .tab').each(function (elm) { elm.removeClassName('selected'); });
	// select the correct tab
	$(tab_prefix+'_tab').addClassName('selected');
	// hide all the tab contents
	$$('#'+tableid+' .tabcontent').each(function (elm) { elm.removeClassName('hide'); elm.addClassName('hide'); });
	// show the correct tab content
	$(tab_prefix+'_tabcontent').removeClassName('hide');
}

/*
HTMLEncode - Encode HTML special characters.
Copyright (c) 2006 Thomas Peri, http://www.tumuski.com/

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The Software shall be used for Good, not Evil.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 * HTML-Encode the supplied input
 * 
 * Parameters:
 *
 * (String)  source    The text to be encoded.
 * 
 * (boolean) display   The output is intended for display.
 *
 *                     If true:
 *                     * Tabs will be expanded to the number of spaces 
 *                       indicated by the 'tabs' argument.
 *                     * Line breaks will be converted to <br />.
 *
 *                     If false:
 *                     * Tabs and linebreaks get turned into &#____;
 *                       entities just like all other control characters.
 *
 * (integer) tabs      The number of spaces to expand tabs to.  (Ignored 
 *                     when the 'display' parameter evaluates to false.)
 *
 * v 0.3 - January 4, 2006
 */
function htmlEncode(source, display, tabs)
{
	function special(source)
	{
		var result = '';
		for (var i = 0; i < source.length; i++)
		{
			var c = source.charAt(i);
			if (c < ' ' || c > '~')
			{
				c = '&#' + c.charCodeAt() + ';';
			}
			result += c;
		}
		return result;
	}
	
	function format(source)
	{
		// Use only integer part of tabs, and default to 4
		tabs = (tabs >= 0) ? Math.floor(tabs) : 4;
		
		// split along line breaks
		var lines = source.split(/\r\n|\r|\n/);
		
		// expand tabs
		for (var i = 0; i < lines.length; i++)
		{
			var line = lines[i];
			var newLine = '';
			for (var p = 0; p < line.length; p++)
			{
				var c = line.charAt(p);
				if (c === '\t')
				{
					var spaces = tabs - (newLine.length % tabs);
					for (var s = 0; s < spaces; s++)
					{
						newLine += ' ';
					}
				}
				else
				{
					newLine += c;
				}
			}
			// If a line starts or ends with a space, it evaporates in html
			// unless it's an nbsp.
			newLine = newLine.replace(/(^ )|( $)/g, '&nbsp;');
			lines[i] = newLine;
		}
		
		// re-join lines
		var result = lines.join('<br />');
		
		// break up contiguous blocks of spaces with non-breaking spaces
		result = result.replace(/  /g, ' &nbsp;');
		
		// tada!
		return result;
	}

	var result = source;
	
	// ampersands (&)
	result = result.replace(/\&/g,'&amp;');

	// less-thans (<)
	result = result.replace(/\</g,'&lt;');

	// greater-thans (>)
	result = result.replace(/\>/g,'&gt;');
	
	if (display)
	{
		// format for display
		result = format(result);
	}
	else
	{
		// Replace quotes if it isn't for display,
		// since it's probably going in an html attribute.
		result = result.replace(new RegExp('"','g'), '&quot;');
	}

	// special characters
	result = special(result);
	
	// tada!
	return result;
}
function show_music_stock_form(id)
{
	ol_open_tall('/account/stock/form/'+id, {  });
}

function music_stock_process(maxbuy,maxsell,pid)
{
	var action = $('action').options[$('action').selectedIndex].value;
	var qty = parseInt($('qty').value);
	if(qty <= 0) { alert("Please enter a valid quantity."); return false; }
	if(action == 'sell')
	{
		if(qty > maxsell)
		{
			alert("Sorry, you can only sell up to a maximum of "+maxsell+" stocks.");
			return false;
		}
		var url = '/account/stock/sell/'+pid;
		var params = { 'sell_total' : qty };
	}
	else
	{
		if(qty > maxbuy)
		{
			alert("Sorry, you can only buy up to a maximum of "+maxbuy+" stocks.");
			return false;
		}
		var url = '/account/stock/buy/'+pid;
		var params = { 'buy_total' : qty };
	}
	new Ajax.Updater('overlay_content',url,{ method : 'post', parameters: params });
	return false;
}
function togglePopupTab(type)
{
	$$('.popup a.tab').each(function(elm) { $(elm).removeClassName('selected'); });
	$(type+'_tab').addClassName('selected');
	$$('.popup_tab_content').each(function(elm) { $(elm).addClassName('hide'); });
	$(type+'_tab_content').removeClassName('hide');
	$(type+'_tab_content').descendants().each(function(elm)
														{
															if($(elm).hasClassName('hide'))
															{
																$(elm).addClassName('hide');
															}
															else
															{
																$(elm).removeClassName('hide');
															}
														});
}

function send_dedication()
{
	var email = trim($('emails').value);
	var from = trim($('from').value);
	var message = trim($('message').value);
	var tid = trim($('dedicated_T_ID').value);
	// check emails
	var emails = email.split(','); var curemail = '';
	for(var i = 0; i < emails.length; i++)
	{
		curemail = trim(emails[i]);
		if(!isEmail(curemail))
		{
			alert("There is an invalid email address in the 'To Email'.");
			return false;
		}
	}
	// check from
	if(from == "") { alert("Please enter your name."); return false; }
	var params = { 'tid' : tid, 'email' : email, 'message' : message, 'from' : from };
	new Ajax.Request('/ajax/dedicate/', { method: 'post', parameters: params, onComplete: function(resp)
																								   {
																									   $('email_tab_content').innerHTML = resp.responseText;
																								   }});
	return false;
}
