var currentPlaylistID = '';var lastPlaylist = '';var lastComment = '';var lastSearchResult = '';var playlistSort = '';var playlistPage = 1;var friend_activity_title = '';var friend_activity_id = '';var observeRowHighlightingRunOnce = false;var searchDefaultText = 'Share a song now';var FBSearchDefaultText = "Start typing a friend's name";var FBFriendGetRunOnce = false;var FB_user_data = [];var FB_UID_list = [];var FB_name_list = [];var selected_uid = [];function preload(src) { //preload an image	heavyImage = new Image(); 		heavyImage.src = src;}function changeImage(target, newImage) {	if ($(target).src != newImage) {		$(target).src = newImage;	}	}function bubble_up(event, item) {	var relatedTarget = $(event.relatedTarget || event.fromElement);	var target = Event.element(event);	if (target == null || relatedTarget == null) return false;	if ((target == item || Element.descendantOf(target, item)) && !((relatedTarget == item) || Element.descendantOf(relatedTarget, item))) {		return true;	}	return false;}function observe_links() {        document.observe("dom:loaded", function() {                $$('a.store_link').each(function(item) {                        item.observe('click', function(event) {				record_link(item.href, item.readAttribute('link_section'));                        });                });        });}function record_link(link, section) {	var record_req = new Ajax.Request('/links.php', {  		method: 'post',  		parameters: {'link': link, 'section': section}	});}function showMore(type, mobile) {	if (type == 'recent' && lastPlaylist != '') {		//show the loading div		var old_stuff = $('show_more').innerHTML;		if (old_stuff.search(/loading/) > -1) return;		$('show_more').update("<div style='padding: 6px 0;'><img src='/images/loading_24.gif'></div>");		var cmd = "getRecentPlaylists";		if (mobile) cmd = "getRecentPlaylistsMobile";		if (playlistSort == 'popular') playlistPage++;	//increment the page counter if sorting by popular		var req = new Ajax.Updater('playlists_container', '/most_recent.php', {			method: 'get',			parameters: {'cmd': cmd, 'last': lastPlaylist, 'sort': playlistSort, 'page': playlistPage},			evalScripts: true,			insertion: 'bottom',			onSuccess: function(response) {				//hide the loading div				$('show_more').update(old_stuff);				if (response.responseText == '') $('show_more').hide();			}		});	} else if (type == 'friend_activity' && lastPlaylist != '') {                //show the loading div                var old_stuff = $('show_more').innerHTML;		if (old_stuff.search(/loading/) > -1) return;                $('show_more').update("<div style='padding: 6px 0;'><img src='/images/loading_24.gif'></div>");		var cmd = "getMore";		if (mobile) cmd = "getMoreMobile";                var req = new Ajax.Updater('playlist_search_data', '/friend_activity.php', {                        method: 'get',                        parameters: {'cmd': cmd, 'last': lastPlaylist, 'title': friend_activity_title, 'id': friend_activity_id},                        evalScripts: true,                        insertion: 'bottom',                        onSuccess: function(response) {				//hide the loading div                                $('show_more').update(old_stuff);				if (response.responseText == '') $('show_more').hide();                        }                });        } else if (type == 'comments' && lastComment != '') {		//show the loading div		var old_stuff = $('show_more').innerHTML;		if (old_stuff.search(/loading/) > -1) return;		$('show_more').update("<div style='padding: 6px 0;'><img src='/images/loading_24.gif'></div>");		var cmd = "more";		//if (mobile) cmd = "getMoreMobile";		var req = new Ajax.Updater('comments_container', '/do_comments.php', {                        method: 'post',                        parameters: {'function': cmd, 'playlist': currentPlaylistID, 'lastComment': lastComment},                        evalScripts: true,                        insertion: 'bottom',                        onSuccess: function(response) {				//hide the loading div                                $('show_more').update(old_stuff);				if (response.responseText == '') $('show_more').hide();                        }                });        }}function showMoreSearch(term, container) {	if (term != '' && lastSearchResult != '' && container != '') {		//show the loading div		var old_stuff = $('show_more').innerHTML;		if (old_stuff.search(/loading/) > -1) return;		$('show_more').update("<div style='padding: 6px 0; text-align: center;'><img src='/images/loading_24.gif'></div>");		var req = new Ajax.Updater(container, '/search', {			method: 'get',			parameters: {'q': term, 'last': lastSearchResult, 'ajax': '1'},			evalScripts: true,			insertion: 'bottom',			onSuccess: function(response) {				//hide the loading div				$('show_more').update(old_stuff);				if (response.responseText == '') $('show_more').hide();			}		});	}}function addComment() {	var textarea = $('comment_text');	var comment_text = textarea.value;	if (comment_text != '' && currentPlaylistID != '') {		$('comment_submit').disable();		$('comment_spinner').show();		var req = new Ajax.Updater('comments_container', '/do_comments.php', {			method: 'post',			parameters: {'function': 'add', 'playlist': currentPlaylistID, 'text': comment_text, 'ajax': 1},			evalScripts: false,			insertion: 'top',			onSuccess: function(response) {				$('comment_text').value = '';	//clear out their comment								$('comment_spinner').hide();				$('comment_submit').enable();								if ($('comment_counter')) {					updateCounter();				}			}		});	}	}function updateCounter(counter, textarea, maxCommentLength, np_hashtag) {	if (!(textarea && counter)) return;		if (np_hashtag) {		if ($(np_hashtag).checked) maxCommentLength -= 12;		if (maxCommentLength < 0) maxCommentLength = 0;	}		var t = $(textarea);	var text = t.value;	var textlength = text.length; 		var new_value = maxCommentLength - textlength;	var comment_counter = $(counter);	comment_counter.update(new_value);		if(new_value < 0) {		comment_counter.style.color = 'red';	} else {		comment_counter.style.color = '#CCCCCC';	}}function updateShareCounter(number, maxCommentLength) {	updateCounter('comment_counter_' + number, 'status_message_' + number, maxCommentLength, 'add_np_hashtag_' + number);}function insertUserName(textarea, user) {	if (!textarea) return;		var t = $(textarea);		insertAtCursor(t, user + ' ');	//updateCounter(counter, textarea, maxCommentLength);		//textarea.focus();	var newlength = t.value.length;	setSelRange(t, newlength, newlength);		}function setSelRange(inputEl, selStart, selend) { 	if (inputEl.setSelectionRange) { 		inputEl.focus(); 		inputEl.setSelectionRange(selStart, selend); 	} else if (inputEl.createTextRange) { 		var range = inputEl.createTextRange(); 		range.collapse(true); 		range.moveEnd('character', selend); 		range.moveStart('character', selStart); 		range.select(); 	} }function insertAtCursor(element, text) {	if (document.selection) {		element.focus();		sel = document.selection.createRange();		sel.text = text;	} else if (element.selectionStart || element.selectionStart == '0') {		var startPos = element.selectionStart;		var endPos = element.selectionEnd;		element.value = element.value.substring(0, startPos) + text + element.value.substring(endPos, element.value.length);	} else {		element.value += text;	}}function showShareBox(shareDiv, commentBox) {	var shareDivElem = $(shareDiv);	var commentBoxElem = $(commentBox);	//first hide all other open share boxes	$$('div.share_box').each(function(item) {		if (item != shareDivElem && item.visible()) {	//don't touch the one we just clicked			item.hide();			//Effect.SlideUp(item, { duration: 0.2 });		}	});                	if (shareDivElem != undefined) {  		shareDivElem.toggle();		/*		if (shareDivElem.visible()) {			Effect.SlideUp(shareDivElem, { duration: 0.2 });		} else {			Effect.SlideDown(shareDivElem, { duration: 0.2, afterFinish:function(){				if (commentBoxElem != undefined) {					try {						commentBoxElem.focus();					} catch(err) {										}				}			} });		}		*/	}		if (commentBoxElem != undefined) {		try {			commentBoxElem.focus();		} catch(err) {				}	}			return false;}function shareSong(submit_button, trackId, status_textarea, loading_element, update_container, source, friendSearchBoxDiv, number, np_hashtag_checkbox) {	if (!(trackId && status_textarea && loading_element && update_container)) return false;	if (friendSearchBoxDiv && $(friendSearchBoxDiv) != undefined) {		if ($(friendSearchBoxDiv).visible() && (selected_uid[number] == undefined || selected_uid[number] == null || selected_uid[number] == '' || selected_uid[number] == 0)) return false;	}		var np_hashtag = 0;	if (np_hashtag_checkbox) {		if ($(np_hashtag_checkbox).checked) np_hashtag = 1;	}		var status_message;	try {		if (encodeURIComponent) {			status_message = encodeURIComponent($(status_textarea).value);		} else {			status_message = escape($(status_textarea).value);		}	} catch(err) {		status_message = escape($(status_textarea).value);	}		//if (!status_message || status_message == '') return false;		$(submit_button).disable();	$(loading_element).show();	var req = new Ajax.Request('/share', {  		method: 'post',  		parameters: {'songs': trackId, 'description': status_message, 'nowplaying': np_hashtag, 'source': source, 'target_id': selected_uid[number]},  		onSuccess: function(transport) {  			$(loading_element).hide();  			$(submit_button).enable();			var div = $(update_container);			var data = transport.responseText.evalJSON(true);						if (data.status == 'ok') {				div.update(data.html);			} else if (data.status == 'fail') {				div.update("<div class='error'>" + data.errorDescription + "</div>");			} else {				div.update("<div class='error'>There was an error while trying to share this song: " + transport.responseText + "</div>");			}		}	});}function onSearchFocus() {	var s = $('search_textbox');	if (s.value == searchDefaultText) {		s.value = '';		s.addClassName('search-highlighted');	}	$('search_container').addClassName('search_container-highlighted');}function onSearchBlur() {		var s = $('search_textbox');		if (s.value == '') {		s.value = searchDefaultText;		s.removeClassName('search-highlighted');	}	$('search_container').removeClassName('search_container-highlighted');}function observeRowHighlighting() {	if (observeRowHighlightingRunOnce) {		observeRowHighlightingWorker();	} else {		document.observe("dom:loaded", function() {observeRowHighlightingWorker()});		observeRowHighlightingRunOnce = true;	}	}function observeRowHighlightingWorker() {		var outer_selector = 'div.main_song_row';		var inner_selector = 'div.buy_row';				$$(outer_selector).each(function(item) {			item.stopObserving();	//clear any observers already in place			item.observe('mouseover', function(event) {				if (bubble_up(event, item)) {					item.addClassName('main_song_row_highlighted');					item.select(inner_selector).each(function(item2) {						item2.addClassName('vis');					});				};			});			item.observe('mouseout', function(event) {				if (bubble_up(event, item)) {					item.removeClassName('main_song_row_highlighted');					item.select(inner_selector).each(function(item2) {						item2.removeClassName('vis');					});				};			});					});}typeahead.prototype.AddEvent = function (element, eventType, functionName){	Event.observe(element, eventType, functionName);	return true;};typeahead.prototype.RemoveEvent = function(element, eventType, functionName){	Event.stopObserving(element, eventType, functionName);	return true;	};// A very basic typeahead objectfunction typeahead(number) {  if (!FBFriendGetRunOnce) {  	FBFriendGetRunOnce = true;	ajaxGetFriendInfo();	//get their friends list if we haven't already  }    var options = FB_name_list;    this.number = number;    this.obj = $('typeahead_' + this.number);  this.obj.onfocus = null;  //this.RemoveEvent(this.obj,'focus', arguments.callee.caller);  this.AddEvent(this.obj,'focus', this.onfocus.bind(this));  this.AddEvent(this.obj,'blur', this.onblur.bind(this));  this.AddEvent(this.obj,'keyup', this.onkeyup.bind(this));  this.AddEvent(this.obj,'keydown', this.onkeydown.bind(this));  this.AddEvent(this.obj,'keypress', this.onkeypress.bind(this));   this.results = [];   // Create the dropdown list that contains our suggestions  this.list = document.createElement('div');  //this.list.setClassName('th_list')  this.list.className = 'th_list';  this.list.style.width = this.obj.offsetWidth - 2;  this.list.style.display = 'none';//           .setStyle({width: this.obj.getOffsetWidth()-2+'px',//                      display: 'none'});  this.obj.parentNode.insertBefore(this.list, this.obj.nextSibling);  // Various flags  this.focused = true;  this.options = options;  this.selectedindex = -1;  // Styling foo  //this.obj.removeClassName('th_placeholder')  //        .setValue('');  this.obj.removeClassName('th_placeholder');  this.obj.value = '';   //this.update_results();  //this.show();  this.hide();}typeahead.prototype.max_results = 5;// Show suggestions when the user focuses the text fieldtypeahead.prototype.onfocus = function(event) {  this.focused = true;  if (this.obj.value == FBSearchDefaultText) {	this.obj.removeClassName('th_placeholder');	this.obj.value = '';  }	  if (this.obj.value.length > 0) { //only display if they've started typing something in  this.update_results();  this.obj.removeClassName('th_found');  this.show();  }}// ...and hide it when they leave the text fieldtypeahead.prototype.onblur = function() {  this.focused = true;  this.hide();  if (selected_uid[this.number] == undefined || selected_uid[this.number] == null || selected_uid[this.number] == 0) {  	this.obj.value = '';	//if no valid user is selected, delete what they typed in  }  if (this.obj.value == '') {	this.obj.addClassName('th_placeholder');	this.obj.value = FBSearchDefaultText;  }}// Every keypress updates the suggestionstypeahead.prototype.onkeyup = function(event) {  switch (event.keyCode) {    case 27: // escape      this.hide();      this.obj.removeClassName('th_found');      break;    case 0:    case 13: // enter    case 37: // left    case 38: // up    case 39: // right    case 40: // down      break;    default:      this.update_results();      this.show();      this.obj.removeClassName('th_found');      if (this.obj.value == '' || this.selectedindex == -1) { //if they clear out the text field and/or there is no valid user selected      	selected_uid[this.number] = null;	//doPlaylistSearch();      }      break;  }}// We want interactive stuff to happen on keydown to make it feel snappytypeahead.prototype.onkeydown = function(event) {  switch (event.keyCode) {    case 9: // tab      if (this.results[this.selectedindex]) {        //this.obj.addClassName('th_found')        //        .setValue(this.results[this.selectedindex]);        this.obj.addClassName('th_found');	this.obj.value = this.results[this.selectedindex];	this.done();	this.hide();        //event.preventDefault();        //Event.stop(event);      } else {	this.hide();	//doTitleSearch(this.obj.value);      }      break;    case 13: // enter      if (this.results[this.selectedindex]) {        //this.obj.addClassName('th_found')        //        .setValue(this.results[this.selectedindex]);        this.obj.addClassName('th_found');	this.obj.value = this.results[this.selectedindex];	this.done();	this.hide();        //event.preventDefault();        Event.stop(event);      } else {	this.hide();	//doTitleSearch(this.obj.value);      }      break;    case 38: // up      this.select(this.selectedindex - 1);      //event.preventDefault();      Event.stop(event);      break;    case 40: // down      this.select(this.selectedindex + 1);      //event.preventDefault();      Event.stop(event);      break;  }}// Override these events so they don't actually do anythingtypeahead.prototype.onkeypress = function(event) {  switch (event.keyCode) {    case 13: // return    case 38: // up    case 40: // down      //event.preventDefault();      Event.stop(event);      break;  }}// This gets called from our code to select a given index... this is where we would do something interesting like fire off some AJAX or somethingtypeahead.prototype.select = function(index) {  var children = this.list.childNodes;  var found = false;  for (var i = 0; i < children.length; i++) {    if (i == index) {      children[i].addClassName('th_selected');      this.selectedindex = index;      found = true;    } else {      children[i].removeClassName('th_selected');    }  }  if (!found && children[this.selectedindex]) {    children[this.selectedindex].addClassName('th_selected');  }}//call this to actually do some work when we select something and hit enter or click ittypeahead.prototype.done = function() {	selected_uid[this.number] = this.results_uids[this.selectedindex];}// This is called every keypress to update the suggestionstypeahead.prototype.update_results = function() {  // Search the list of potential results and find ones that match what we have so far  var results = [];  var results_uids = [];  //var found_at = []; //the character position for each result where the found text begins     //var val = this.obj.getValue().toLowerCase();  var val = this.obj.value.toLowerCase();    //var reg = new RegExp('/[^A-Za-z ]*/');  //var reg = /([^a-z] )+/g;  //var reg = /^[a-z]+$/g;  //val = val.replace(reg,'');  val = val.replace(/[^a-z\s]/g,'');  this.selectedindex = -1;   var done = false;	var parts = val.split(" ");		for (var i = 0; i < this.options.length; i++) {		if (done) { break };		var temp_name = this.options[i].toLowerCase();		temp_name = temp_name.replace(/[^a-z\s]/g,'');		var good = true;		for (var j = 0; j < parts.length; j++) {			var part = parts[j];			if (part != '' && part != null) {				var reg1 = new RegExp('^'+part);				var reg2 = new RegExp(' '+part);				if (!temp_name.match(reg1) && !temp_name.match(reg2)) {					good = false;				}			}		}		if (good) {			results.push(this.options[i]);			results_uids.push(FB_UID_list[i]);			if (results.length >= this.max_results) {				done = true;			}		}	}  // Generate a list to display the elements to the user  //this.list.setTextValue('');  //remove all child nodes  if ( this.list.hasChildNodes() )  {      while ( this.list.childNodes.length >= 1 )      {          this.list.removeChild( this.list.firstChild );             }   }  this.list.innerText = '';  if (this.obj.value.length == 0) { //if nothing is typed in, results should be null        results = null;	results_uids = null;	this.hide();        return;  }   for (var i = 0; i < results.length; i++) {    var temp = document.createElement('div');    temp.className = 'th_suggestion';    this.AddEvent(temp,'mouseover', function() {this[0].select(this[1]);}.bind([this, i]));    this.AddEvent(temp,'mousedown', function(event) {this.obj.addClassName('th_found');; this.obj.value = this.results[this.selectedindex]; this.done(); this.hide();}.bind(this));    var img = document.createElement('img');    if (FB_user_data[results_uids[i]].pic_square == '') {    	img.src = 'http://www.songshare.fm/images/q_silhouette.gif';    } else {        img.src = FB_user_data[results_uids[i]].pic_square;    }    temp.appendChild(img);    var inner_div = document.createElement('div');    $(inner_div).addClassName('with_pic');       var span = document.createElement('span');	var bold_chars = [];	var temp_name = results[i].toLowerCase();	for (var j = 0; j < parts.length; j++) {		var part = parts[j];		if (part != '' && part != null) {			var reg1 = new RegExp('^'+part);			var reg2 = new RegExp('[ \']'+part);						if (temp_name.match(reg1)) {				for (var k = 0; k < part.length; k++) {					bold_chars[k] = true;				}			}						if (temp_name.match(reg2)) {				var mymatch = reg2.exec(temp_name);				for (var k = mymatch.index + 1; k < mymatch.index + part.length + 1; k++) {					bold_chars[k] = true;				}			}		}		}	var started = false;	var text = '';	for (var j = 0; j < results[i].length; j++) {		if (bold_chars[j]) {			if (!started) {				text += '<em>';				started = true;			}			text += results[i].substring(j, j + 1);		} else {			if (started) {				text += '</em>';				started = false;			}			text += results[i].substring(j, j + 1);		}	}    span.innerHTML = text;        inner_div.appendChild(span);    var user_location = document.createElement('small');    user_location.innerHTML = FB_user_data[results_uids[i]].affiliation;    inner_div.appendChild(user_location);          temp.appendChild(inner_div);    this.list.appendChild(temp);  }  this.results = results;  this.results_uids = results_uids;    if (this.results.length > 0 && this.selectedindex == -1) this.select(0);	//automatically select the first result  //if (this.results.length == 0) {  	//alert('results = 0');	  //this.selectedindex = -1;  //}  //this.found_at = found_at;}typeahead.prototype.show = function() {  //this.list.setStyle('display', 'block');  this.list.style.display = 'block';}typeahead.prototype.hide = function() {  //this.list.setStyle('display', 'none');  this.list.style.display = 'none';}function ajaxGetFriendInfo() {	var req = new Ajax.Request('/getuserdata', {  		method: 'get',  		onSuccess: function(transport) {			var r = transport.responseText.evalJSON(true);						if (r != null && r.users.length > 0) {				for (i=0; i < r.users.length; i++) {					FB_user_data[r.users[i].uid] = r.users[i];					FB_UID_list.push(r.users[i].uid);					FB_name_list.push(r.users[i].name);				}				} else {			}		}	});}function toggleFriendSearchBox(text, friendSearchBoxDiv, typeaheadBox, commentBox, number) {	var originalText = "Post to a Friend's Wall instead";	var alternateText = 'Post to Profile instead';		text = $(text);	var friendSearchBoxElem = $(friendSearchBoxDiv);	var typeaheadBoxElem = $(typeaheadBox);	var commentBoxElem = $(commentBox);		if (text.innerHTML.search(alternateText) > -1) {		friendSearchBoxElem.hide();		selected_uid[number] = '';	//unset the selected friend		$(typeaheadBox).value = FBSearchDefaultText;	//reset the box		typeaheadBoxElem.removeClassName('th_found');		typeaheadBoxElem.addClassName('th_placeholder');		text.update(originalText);	} else {		if (!FBFriendGetRunOnce) {			FBFriendGetRunOnce = true;			ajaxGetFriendInfo();	//get their friends list if we haven't already		}		friendSearchBoxElem.show();		text.update(alternateText);	}		if (commentBoxElem != undefined) {		try {			commentBoxElem.focus();		} catch(err) {				}	}}
