/* Music Player */

function trim(str){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function myrand( min, max ) {
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: missing parameter');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


/* roundIt Rounded corners */
function roundIt(which,outside,inside,border){
	which = which=="top"?"top":"btm";
	var outsideR = border===(undefined || "")?"r":"ar"; 
	var insideR = border===(undefined || "")?"r":"re";
	var insideStyle = 'background-color: '+inside+';';
	var outsideStyle = 'background-color: '+outside+';';
	var borderStyle = border===(undefined || "") ? "" : 'border-color: '+border+';';
	var html="";
	var x=null;
	
	html += '<b class="'+outsideR+which+'" style="'+outsideStyle+'">';
	if(which=="top"){
		for(x=1;x<=4;x++){
			html += '<b class="'+insideR+x+'" style="'+borderStyle+insideStyle+'"><\/b>';
		}
	}else{
		for(x=4;x>=1;x--){
			html += '<b class="'+insideR+x+'" style="'+borderStyle+insideStyle+'"><\/b>';
		}	
	}
	html += '<\/b>';
	return html;
}

function placeIt(placeThis,nearThis,placement){
	nearThis = $(nearThis);
	placeThis = $(placeThis);
	var pos = Element.cumulativeOffset(nearThis);
	var elDim = Element.getDimensions(nearThis);
	var midPoint = pos['left'] + (elDim['width']/2);
	var p = placement.split(/ /);

	ttDim = Element.getDimensions(placeThis);

	if(p[0].match(/top/)){
		placeThis.style.top = (pos['top'] - ttDim['height']) + 'px';
	}
	else if(p[0].match(/bottom/)){
		placeThis.style.top = (pos['top'] + elDim['height']) + 'px';
	}
	else if(p[0].match(/right/)){
		placeThis.style.left = (pos['left'] + elDim['width']) + 'px';
	}
	else if(p[0].match(/left/)){
		placeThis.style.left = (pos['left'] - ttDim['width']) + 'px';
	}

	if(p[1].match(/middle/)){
		placeThis.style.left = (midPoint - ( ttDim['width']/2 )) +'px';
	}
	else if(p[1].match(/topToTop/)){
		placeThis.style.top = pos['top'] +'px';
	}
	else if(p[1].match(/topToBottom/)){
		placeThis.style.top = pos['top'] + elDim['height'] +'px';
	}
	else if(p[1].match(/bottomToTop/)){
		placeThis.style.top = pos['top'] - ttDim['height'] +'px';
	}
	else if(p[1].match(/alignLeft/)){
		placeThis.style.left = pos['left'] +'px';
	}
	
	//console.log(placeThis.id+'-'+nearThis.id+'-'+placement);
	
}

/* Tooltips */
function iwaTooltip(){
	var ttElement = null;
	var ttContent = '';
	var ttHide = null;
	var viewsLeft = {};
	var x_allowed = 5;
	
	this.showTip = function(elem,placement){
		if(placement == (undefined || "" || null) ){ placement = 'top middle'; }
		if(ttElement!=null && elem!=ttElement){ clearTimeout(ttHide); this.hideMe(); }
		else if(elem==ttElement && ttHide!==null){ clearTimeout(ttHide); return false; }
		
		myid = elem.id;
		viewsLeft.init="the object";
		if(typeof viewsLeft[myid]=="undefined"){ viewsLeft[myid] = x_allowed; }
		if(elem.title!=""){
			ttContent = elem.title;
			ttElement = elem;
			elem.title = '';
		}else{
			ttContent = $('prompt_'+elem.id).innerHTML;
			//console.log(ttContent);
		}
		if(viewsLeft[elem.id] > 0){
			viewsLeft[myid] = viewsLeft[myid] - 1;
			
			var html="";
			if(placement.match(/bottom/)){ html +=  '<div id="ttTopNotch"><\/div>'; }
			html += roundIt('top','transparent','#FFFFFF','#CCCCCC');
			html += '<div id="ttmiddle">'+ttContent+'<\/div>';
			html += roundIt('btm','transparent','#FFFFFF','#CCCCCC');
			if(placement.match(/top/)){ html +=  '<div id="ttBottomNotch"><\/div>'; }
			
			$('tooltip').innerHTML = html;
			placeIt('tooltip',elem,placement);
			$('tooltip').appear({duration:'.5'});
		}
	};
	this.hideTip = function(){
		ttHide = setTimeout("tooltip.hideMe()",100);
	};
	this.hideMe = function(){
		ttHide = null;
		if(typeof ttElement == "undefined"){ return false; }
		ttElement.title = ttContent;
		$('tooltip').hide();
		ttElement=null;
	};
	this.clearHide = function(){
		clearTimeout(ttHide);
	};
}

tooltip = new iwaTooltip();

/* Tracking */
function adTrack(account_id){
	var zipcode = $('zipcode').value;
	var clubstr_session = $('session').value;
	
	new Ajax.Request('adTrack.php?account_id='+account_id+'&zipcode='+zipcode+'&clubstr_session='+clubstr_session+'', {
	  method: 'get'
	});	
	return true;
}

/* Ajax Search Fields */

function getSelectionId(searchField,li) {
	var idField = searchField.id + '_id';
    $(idField).value = li.id;
    stopMusic();
}

/* Show Editing */

function editEvent(id){
	$('hour').value=$('event_hour'+id).value;
	$('minute').value=$('event_minute'+id).value;
	$('ampm').value=$('event_ampm'+id).value;
	$('artist_searchfield_id').value=$('eventArtist_id'+id).value;
	$('artist_searchfield').value=$('eventArtist_name'+id).value;
	$('event'+id).update();
	$('event'+id).hide();	
}
function deleteEvent(id){
	$('event'+id).update();
	$('event'+id).hide();
}
function openShowEdit(show_id){
	new Ajax.Updater('showInfo','showInfo.php?show_id='+ show_id +'&ajax=1&showForm=1', {
		method: 'get',
		evalScripts:true
		});
}
function closeShowEdit(show_id){
	new Ajax.Updater('showInfo','showInfo.php?show_id='+ show_id, {
		method: 'get',
		evalScripts:true
		});	
}
function switchContent(elem,url){
	new Ajax.Updater(elem,url, {
		method: 'get',
		evalScripts:true
		});
}
function submitShowEditForm(show_id){
	var params = $('showEditForm').serialize(true);
	new Ajax.Request('showInfo?ajax=1&editShowInfo=1', {
		method: 'post',
		evalScripts:true,
		parameters: params,
		onSuccess: function(transport){
		    var msg = $('showEdit_msg');
    		if (transport.responseText.match(/good/)){
    		  //msg.update('Saving...').setStyle({ background: '#dfd' });
			  new Ajax.Updater('showInfo','showInfo.php?show_id='+ show_id, {
						method: 'get',
						evalScripts:true
						});	
    		}else{
    		  msg.update(transport.responseText).setStyle({ background: '#fdd' });
  			}
		}
	});
}


var newShows={};
var allShows={};

function Clubstr(){

	this.showindex = 0; // current top show
	this.fetchShows_lookahead = 9;
	this.prune_below = 10;
	this.prune_above = 20;
	this.returnScrollPosition = 0;

	this.playerMode = "stopped";
	this.playMode = "noIntro"; // noIntro, addIntro, addAdvert  
	this.playing = 0;
	this.playingIndex = '';
	this.soundcode = 0;
	this.prevcode = 0;

	this.playingSST = '0';

	this.playlist = { "size" : 0, "lastplayerid" :0,  "playerids" : { }, 
					"naturalQueuePosition" : 0 };

	this.mapExists=false;


	/* LAYOUT *****************************************************************/
	/* Rounded html bits */
	this.dateHeaderTop='<b class="rtop" style="background-color: #FFFFFF;"><b class="r1" style="background-color: #8F8F8F;"><\/b><b class="r2" style="background-color: #8F8F8F;"><\/b><b class="r3" style="background-color: #8F8F8F;"><\/b><b class="r4" style="background-color: #8F8F8F;"><\/b><\/b>';
	this.dateHeaderBtm='<b class="rbtm" style="background-color: #FFFFFF;"><b class="r4" style="background-color: #8F8F8F;"><\/b><b class="r3" style="background-color: #8F8F8F;"><\/b><b class="r2" style="background-color: #8F8F8F;"><\/b><b class="r1" style="background-color: #8F8F8F;"><\/b><\/b>';

	this.grayRoundBorderTop = '<b class="artop" style="background-color: #8F8F8F;"><b class="re1" style="border-color: #CCCCCC; background-color: #CCCCCC;"><\/b><b class="re2" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><b class="re3" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><b class="re4" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><\/b>';

	this.grayRoundBorderMiddle = 'style="border-left: 1px solid #CCCCCC; border-right: 1px solid #CCCCCC;"';

	this.grayRoundBorderBottom = '<b class="arbtm" style="background-color: #FFFFFF;"><b class="re4" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><b class="re3" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><b class="re2" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><b class="re1" style="border-color: #CCCCCC; background-color: #FFFFFF;"><\/b><\/b>';

	this.searchFormRoundedTop = '<b class="artop" style="background-color: #FFFFFF;"><b class="re1" style="border-color: #CCCCCC; background-color: #545751;"><\/b><b class="re2" style="border-color: #CCCCCC; background-color: #545751;"><\/b><b class="re3" style="border-color: #CCCCCC; background-color: #545751;"><\/b><b class="re4" style="border-color: #CCCCCC; background-color: #545751;"><\/b><\/b>';

	this.emptyEvent = '<tr><td colspan=3 class="dottedDivider" style="height:1px;"><\/td><\/tr>';

}


/* make html bits */
Clubstr.prototype.makeStars = function(e){ return ""; }
Clubstr.prototype.makeArtistWebsiteLink = function(website){ 
	return '<a href="http:\/\/'+website+'" target="_blank" class="websiteLink">website<\/a>'; 
}
Clubstr.prototype.makeVenueWebsiteLink = function(website){
	if(website==""){return "";}
	return ' • <a href="http:\/\/'+website+'" target="_blank">'+website+'<\/a>'; 
}

Clubstr.prototype.makeArtistCalLink = function(clubstr_url){ 
	return '<span class="small_artist_info"><a class="artist_cal" target="_blank" href="\/'+clubstr_url+'">artist cal<\/a><\/span>  &nbsp;';
}
Clubstr.prototype.makeClaimArtistLink = function(event){
	if(event.showClaimLink!=1){ return ""; }
	return '<span class="small_artist_info"><a target="_blank" href="\/create_account?type=artist&artist='+event.artist_id+'" class="claimLink">claim this artist and upload tracks<\/a><\/span>';
}
Clubstr.prototype.smallLightText = function (txt){
	if(txt==''){ return ""; }
	return ' <span class="small_light">'+txt+'<\/span>';
}
Clubstr.prototype.makeTrackList = function (myindex,myset){
	var artist_tracks = allShows[myindex].events[myset].artist_tracks;
	if(artist_tracks==""){ return ""; }
	var tracks = artist_tracks.split("_|_");
	var trackList='';
	var trackInfo;
	var x;
	for(x=0;x<tracks.length;x++){
	
		trackInfo = tracks[x].split("_,_");
		if(this.playingSST == trackInfo[0]){
			var playButtonStyle = 'style="display:none;"';
			var stopButtonStyle = '';
		}else{
			var stopButtonStyle = 'style="display:none;"';
			var playButtonStyle = '';		
		}
		trackList += '<span id="playButton'+trackInfo[0]+'" class="playButton" onClick="clubstr.playTrack(\''+trackInfo[0]+'\',\''+trackInfo[1]+'\'); return false" '+playButtonStyle+'>'+trackInfo[2]+'<\/span><span id="stopButton'+trackInfo[0]+'" class="stopButton" onClick="clubstr.stopMusic(); return false" '+stopButtonStyle+'>'+trackInfo[2]+'<\/span>';
	}
	return trackList;
}

Clubstr.prototype.makeSets = function(myindex){
	var events = allShows[myindex].events;
	var showEvents='';	
	var divider='';
	
	var SSTa = this.playingSST.split(/-/);
	
	for(x in events){
		if(x==2){ 
		divider='<tr><td style="height: 1px;" class="dottedDivider" colspan="3"><\/td><\/tr>'; 
		}
		if((myindex+'-'+x) == (SSTa[0]+'-'+SSTa[1])){
			var setClass='class="playingSet"';
		}else{ setClass=''; }
		
		showEvents += divider;	
		showEvents += '<tr id="showSet'+myindex+'-'+x+'" '+setClass+'><td width=70><div class="eventTimeDiv">';		
		showEvents += '<span class="showTime">'+events[x].showTime+'<\/span>';
		showEvents += '<span class="show_ampm">'+events[x].ampm+'<\/span><\/div><\/td>';
		showEvents += '<td width=56 style="padding:3px;">';
		showEvents += '<img src="'+events[x].artist_photo+'" class="artist_thumb"><\/td>';
		showEvents += '<td class="showInfoTD" width="*" style="padding:3px; 0 0 0">';
		showEvents += '<div class="artist_name" style="overflow:hidden"><nobr>';
		showEvents += events[x].artist_name;
		showEvents += ' '+this.makeStars()+' ';
		showEvents += '<span class="small_artist_info">'+events[x].artist_location;
		showEvents += this.makeArtistCalLink(events[x].artist_clubstr_url);
		showEvents += this.makeArtistWebsiteLink(events[x].artist_website);
		showEvents += '<\/span>';
		showEvents += '<\/nobr><\/div>';
		showEvents += '<div id="artistTracks'+events[x].artist_id+'" class="artistTracks" ';
		showEvents += 'style="overflow:hidden"><nobr>';
		showEvents += this.makeClaimArtistLink(events[x]);
		showEvents += this.makeTrackList(myindex,x);
		showEvents += '<\/nobr><\/div>';
		showEvents += '<\/td><\/tr>';
	}	
	return '<div class="showEventsWrapper"><table class="artistList">'+showEvents+'<\/table><\/div>';
}

Clubstr.prototype.makeShows = function(shows){
	var s;
	var showList = '';
	if(shows.no_shows_found && !no_shows_found){
		no_shows_found=1;
		showList += '<div class="dateHeader blueRound" id="showEnd">';
		showList +=  this.dateHeaderTop;
		showList += '<h2 class="dateH2" style="margin:5px 10px; padding:0;">'+shows.no_shows_found+'<\/h2>';
		showList += this.dateHeaderBtm;
		showList += '<\/div>';
		return showList;
	}
	for(x in shows){
		s=shows[x];
		showList += '<div class="dateHeader blueRound" id="showDate'+x+'">';
		showList += this.dateHeaderTop;
		showList += '<div style="float: right;margin-right:20px;" onClick="clubstr.scrollToShow('+x+');">';
		showList += 'Send to top</div>';

		showList += '<h2 class="dateH2">'+s.showLongDate;
		//showList += '<span class="light">|<\/span>'+s.venue_location;
		showList += '<\/h2>';
		
		//showList += this.dateHeaderBtm;
		showList += '<\/div>';
		showList += '<div id="showBox'+x+'" class="show grayRoundBorder">';
		showList += this.makeShowBox(x);
		showList += '<\/div><br>';
	}
	return showList;
}	

Clubstr.prototype.makeShowBox = function(myindex){
	//console.log("in makeShowBox = "+myindex);
	var s = allShows[myindex];
	var showList = '';
	showList += this.grayRoundBorderTop;
	showList += '<h2 class="venue_name"><span class="show_title">';
	if(s.cal_type=="general"){
		showList += '<a href="#" title="Show on map"';
		showList += 'onClick="clubstr.showVenueOnMap('+s.venue_id+');return false;" ';
		showList += 'onMouseover="tooltip.showTip(this);"';
		showList += 'onMouseout="tooltip.hideTip();"';
		showList += '>'+s.venue_name+'</a><span class="light">&nbsp;|&nbsp;<\/span>';
	}
	showList += s.showTitleText;
	
	showList += '<span class="light">&nbsp;|&nbsp;<\/span>'+s.priceText+s.soldOutText;
	showList += this.smallLightText(s.distanceText)+this.smallLightText(s.editLink)+'<\/span>';
	showList += '<span class="tiny_nohover" id="venue_address_showlink'+s.show_id+'">';
	showList += '<a href="#" onClick="clubstr.showVenueAddress('+s.show_id+'); return false">';
	showList += ' more<sub style="position: relative; left: -15px;top:3px">v<\/sub>';
	showList += '<\/a><\/span>';
	
	showList += '<span class="tiny_nohover" id="venue_address_hidelink'+s.show_id+'"';
	showList += 'style="display:none;"><a href="#" ';
	showList += 'onClick="clubstr.hideVenueAddress('+s.show_id+'); return false">';
	showList += ' less<sub style="position: relative; left: -12px; top: 4px;">^<\/sub><\/a>';
	showList += '<\/span><\/nobr>';
	showList += '<\/h2>';

	showList += '<div id="venue_address'+s.show_id+'" class="small_venue_info" ';
	showList += 'style="display:none;">'+s.venue_location;
	showList += this.makeVenueWebsiteLink(s.venue_website);
	showList += ' • ';
	showList += s.venue_phone+' &nbsp;<a href="?venue='+s.venue_id+'">';
	showList += '<img src="\/images\/calendar_icon_gray.gif" border=0 ';
	showList += 'style="position:relative;top:3px;"\/><\/a>&nbsp;';
	showList += '<span class="small_venue_info"><a href="'+s.clubstr_url+'">';
	showList += 'venue cal<\/a><\/span><\/div>';
	
	showList += '<div class="show_description" id="show_description'+s.show_id+'">';
	showList += s.show_description+'<\/div>';
	if(s.events){ showList += this.makeSets(myindex); }
	showList += this.grayRoundBorderBottom;
	return showList;
}

/* Map stuff ***************************************************************************/
Clubstr.prototype.showVenueOnMap = function(id){
	if(!this.mapExists){ return false; }
	parent.frames['mapFrame'].showVenueOnMap(id);
}

Clubstr.prototype.fillMapPoints = function(){
	// this is only called by the mapFrame anyway...
	if(!$('mapFrame')){ return false; }
	var s=null;
	for(x in allShows){
		s=allShows[x]; 
		var mapFrame = parent.frames['mapFrame'];
		mapFrame.addVenueToMap(s.venue_id,s.venue_name,
								s.venue_lat,s.venue_lon,s.venue_location);
	}
	this.mapExists=true;
	//console.log("set mapExists to true");
}

/* FETCHING DATA AND NAVIGATION *****************************************************/

Clubstr.prototype.showVenueAddress = function (show_id){
	$('venue_address_showlink'+show_id).hide();
	$('venue_address_hidelink'+show_id).show();
	$('venue_address'+show_id).show();
}

Clubstr.prototype.hideVenueAddress = function (show_id){
	$('venue_address_hidelink'+show_id).hide();
	$('venue_address_showlink'+show_id).show();
	$('venue_address'+show_id).hide();
}

/* Scrolling Navigation */
Clubstr.prototype.scrollShows = function(numplaces){
	this.returnScrollPosition = document.viewport.getScrollOffsets()['top'];
	console.log(this.returnScrollPosition);
	var myindex = this.showindex + parseInt(numplaces);
	if(myindex > allShows.num_results){ myindex = allShows.num_results; }
	if(myindex < 1){ myindex = 1; }
	this.scrollToShow(myindex);
}

Clubstr.prototype.scrollToTop = function(){
	while(document.viewport.getScrollOffsets()['top'] > this.returnScrollPosition){ 
	    window.scrollTo(0, document.viewport.getScrollOffsets()['top']-40);
	}
}

Clubstr.prototype.scrollToShow = function(myindex){
	this.showindex = parseInt(myindex);
	if(myindex > allShows.num_results){ myindex = allShows.num_results; }
	if(myindex < 1){ myindex = 1; }
	var divPos = $('showlistDiv').cumulativeOffset();
	var absDest = divPos['top']+10;
	var liPos = $('showDate'+this.showindex).cumulativeOffset();
	var moveDist = absDest-liPos['top'];
	new Effect.Move($('showlist'),{x: 0, y: moveDist, duration: .5, mode:'relative'});

	while(document.viewport.getScrollOffsets()['top'] > this.returnScrollPosition){ 
	    window.scrollTo(0, document.viewport.getScrollOffsets()['top']-40);
	}

//	this.scrollToTop();

	this.updateVisual();
	this.restorePrunedShows(myindex);
	this.pruneUnseenShows(myindex);	
	
	if((this.showindex > (allShows.fetchedShows - this.fetchShows_lookahead)) && 
	   (allShows.num_results > allShows.fetchedShows)){
		this.getShows(allShows.fetchedPages + 1);
	}
}


Clubstr.prototype.getShows = function(pg){
	//console.log('getShows '+pg);
	if(pg==1){ 
		if($('main')){ clubstr.stopMusic(); } 
		allShows = {};
		this.playlist['naturalQueuePosition']=0;
		this.mapExists = false;
		playerReplace(); // this is in embed.php
		
	}

	var thisObj = this;
	new Ajax.Request('/get_shows_json', {
	  method:'get',
	  parameters: { event_date: $F('event_date'), 
					   zipcode: $F('zipcode'), 
					   maxdist: $F('maxdist'),
					   tags: $F('tags'),
					   future_dates: $F('future_dates'),
					   ratingThreshold: $F('ratingThreshold'),
					   useRatings: $F('useRatings'),
					   artist: $F('artist'),
					   venue: $F('venue'),
					   page: pg 
					   },
	  onSuccess: function(transport){
			newShows = transport.responseText.evalJSON();
									
			for(z in newShows){
				//console.log("start merge");
			
				allShows[z] = newShows[z];
				
				allShows['fetchedShows'] = newShows[z].result_num;
				allShows['fetchedPages'] = pg;
				allShows['got_all_rows'] = newShows[z].got_all_rows;
			
				if(pg==1){ 
					allShows['num_results'] = newShows[z].num_results;
				}

				if(thisObj.mapExists){
					//console.log("mapExists. Adding venue to map");
					var s = newShows[z];
					parent.frames['mapFrame'].addVenueToMap(s.venue_id,s.venue_name,
											s.venue_lat,s.venue_lon,s.venue_location);					
				}
			}

			try{
			var showHTML = thisObj.makeShows(newShows);
			if(pg==1){ 
				$('showlist').style.top='10px';
				$('showlistUL').innerHTML = showHTML;				

				if(newShows.no_shows_found==null){
					thisObj.showindex=1;
					thisObj.scrollToShow(thisObj.showindex);
					thisObj.assignSoundcode();
				}
			}else{ 
				$('showlistUL').insert({ bottom: showHTML });
			}

			}catch(e){
				console.log("Error: "+e);
			}

			if(!thisObj.mapExists){
				//console.log("no mapExists trying to create map frame.");
				if($('mapFrame')){
					$('mapFrame').src = '/map_frame_dev?zipcode='+$F('zipcode')+'&zoom=7';
				}
			}

	   }
	});
}


Clubstr.prototype.restorePrunedShows = function(myindex){
	var startrestore = myindex - this.prune_below;
	if(startrestore < 1){ startrestore = 1; }
	for(var x = startrestore; x <= myindex; x++){
		//if($('showBox'+x).innerHTML != ""){ break; }
		if($('showBox'+x).innerHTML == ""){
			$('showBox'+x).innerHTML = this.makeShowBox(x);
			$('showBox'+x).style.height = "";
			//console.log('Restored show '+x);
		}

	}

	startrestore = myindex + this.prune_above;
	if(startrestore > allShows.fetchedShows){ startrestore = allShows.fetchedShows; }
	for(x = startrestore; x >= myindex; x--){
		//if($('showBox'+x).innerHTML != ""){ break; }
		if($('showBox'+x).innerHTML == ""){
			$('showBox'+x).innerHTML = this.makeShowBox(x);
			$('showBox'+x).style.height = "";
			//console.log('Restored show '+x);
		}
		
	}
	return true;
}

Clubstr.prototype.pruneUnseenShows = function(myindex){
	if(myindex > 1){
		var startprune = myindex - this.prune_below - 1;
		//console.log(myindex+'|'+startprune);
		if(startprune > 1){
			for(var x = startprune; x>=1; x--){
				if($('showBox'+x).innerHTML == ""){ break; }
				$('showBox'+x).style.height = $('showBox'+x).getHeight() + 'px';
				$('showBox'+x).innerHTML = "";
				//console.log('Pruned show '+x);
			}
		}
	}
	
	startprune = myindex + this.prune_above + 1;
	//console.log(myindex+'|'+startprune);
	if(startprune < allShows.fetchedShows){
		for(x = startprune; x<=allShows.fetchedShows; x++){
			if($('showBox'+x).innerHTML == ""){ break; }
			$('showBox'+x).style.height = $('showBox'+x).getHeight() + 'px';
			$('showBox'+x).innerHTML = "";
			//console.log('Pruned show '+x);
		}
	}
	return true;
}


Clubstr.prototype.updateVisual = function(){
	return true;
	$('result_num').innerHTML= allShows.result_num;
	$('num_results').innerHTML = allShows[1].allShows.num_results;
}

/* Player ******************************************************************************/	

Clubstr.prototype.addTrackCallback = function(playlist_array_length,notice){
	console.log(playlist_array_length+'|'+notice);
}

Clubstr.prototype.stopTrackCallback = function(track_index,notice){
	console.log(track_index+'|'+notice);
	this.playMode = "addIntro";
	this.queueNextAndPlay();
}


Clubstr.prototype.queueNextAndPlay = function(){
	var SST = this.getNextFromNaturalQueue();
	this.playTrack(SST);
	this.playMode = "noIntro";
}
Clubstr.prototype.getPrevAndPlay = function(){
	var SST = this.getPrevFromNaturalQueue();
	this.playTrack(SST);
}


Clubstr.prototype.assignSoundcode = function (){
	// put the current soundcode into prevcode and get the next soundcode	
	this.prevcode = this.soundcode;
	
	var thisObj = this; 
	var r = Math.random();
	new Ajax.Request(
		'mp3init?r='+r+'&sessID='+sessID+'&source='+request_source+'&source_id='+owner_id, 
		{
		  method: 'get',
		  onSuccess: function(transport) {
			if(transport.responseText.match("expired")){
		  
			}else{
				thisObj.soundcode = trim(transport.responseText);
			}
		  }
		});
}

Clubstr.prototype.getPrevFromNaturalQueue = function(){
	
	if(this.playlist['naturalQueuePosition'] < 2){
		return false;
	}else{
		var SST = this.playlist['naturalQueuePosition'].split(/-/);
		var startingShow = parseInt(SST[0]);
		var tryShow = parseInt(SST[0]);
		var trySet = parseInt(SST[1])-1;
		if(trySet < 1){  tryShow--; trySet = allShows[tryShow].num_events; }
		
		console.log(tryShow+'-'+trySet);
	}
	var trySST = "";

	for(tryShow; tryShow > 0; tryShow--){
		if(tryShow < startingShow){ trySet = allShows[tryShow].num_events; }
		if(!allShows[tryShow].events){ continue; }
		for(trySet; trySet > 0; trySet--){
			var natord = allShows[tryShow].events[trySet].natural_order;
			if(natord.length < 1){ console.log(tryShow+'-'+trySet+'-'+natord.length);  continue; }
			for(x=0; x < natord.length; x++ ){
				trySST = tryShow+'-'+trySet+'-'+natord[x];
				if(!this.playlist[trySST]){ 					
					return trySST; 
				}
			}
			if(trySST!=""){ return trySST; }
		}
	}	
	return false;
}


Clubstr.prototype.getNextFromNaturalQueue = function(){
	
	if(this.playlist['naturalQueuePosition'] == 0){
		var startingShow = 1;
		var tryShow = 1;
		var trySet = 1;
	}else{
		var SST = this.playlist['naturalQueuePosition'].split(/-/);
		var startingShow = SST[0];
		var tryShow = SST[0];
		var trySet = parseInt(SST[1])+1;
		console.log(tryShow+'-'+trySet);
	}
	var trySST = "";

	for(tryShow; tryShow < allShows.num_results; tryShow++){
		if(tryShow > startingShow){ trySet = 1; }
		if(!allShows[tryShow].events){ continue; }
		for(trySet; trySet <= allShows[tryShow].num_events; trySet++){
			var natord = allShows[tryShow].events[trySet].natural_order;
			if(natord.length < 1){ console.log(tryShow+'-'+trySet+'-'+natord.length);  continue; }
			for(x=0; x < natord.length; x++ ){
				trySST = tryShow+'-'+trySet+'-'+natord[x];
				y = myrand(0,natord.length-1);
				var defaultSST = tryShow+'-'+trySet+'-'+natord[y];
				if(!this.playlist[trySST]){ 					
					return trySST; 
				}
			}
			if(defaultSST!=""){ return defaultSST; }
		}
	}	
	return false;
}

Clubstr.prototype.addToPlaylist = function (SST){
	this.playlist['size']++;
	this.playlist['lastplayerid']++;
	this.playlist[SST] = this.playlist['size'];    
	this.playlist[this.playlist['size']] = SST;
	
	this.playlist.naturalQueuePosition=SST;

	if(SST==0){
		console.log("addTrack dummy");
		var dummyfile = 'http:\/\/www.clubstr.com\/mp3server_dev?b=dummyfile.mp3';
		window.document.main.addTrack(
			this.playlist['lastplayerid'], dummyfile, "", "", "", "", "", "Dummy File");
		this.playlist['lastplayerid']++;
		return true;
	}
	var thisSST = SST.split(/-/);
	var s = allShows[thisSST[0]]; var e = thisSST[1]; var t = thisSST[2];
	
	var intro = s.events[e].tracks[t].intro ? s.events[e].tracks[t].intro : false;
	var outro = s.events[e].outro ? s.events[e].outro : false;
	
	var intro = 'sampleintro.mp3';
	var outro = 'sampleoutro.mp3';
	
	var track_id = s.events[e].tracks[t].id;
	var track_name = s.events[e].tracks[t].track_name;
	var artist_name = s.events[e].artist_name;
	var player_show_info = s.showLongDate +' at '+ s.venue_name;

	var introfile = 'http:\/\/www.clubstr.com\/mp3server_dev?b='+intro;
	var outrofile = 'http:\/\/www.clubstr.com\/mp3server_dev?b='+outro;
	var songfile = 'http:\/\/www.clubstr.com\/mp3server?t='+track_id+'-'+this.soundcode+'-'+this.prevcode;
	var annotation = "“"+track_name+"” by "+artist_name+" - See it live: "+player_show_info;

	// We have 3 possible playerids for each playlistid
	// if no intro or outro, all three will be the same.
	// We check the callback from the player if the id matches the outro playerid,
	// then we send the next group to the player
	
	this.playlist['current_intro_playerid'] = this.playlist['lastplayerid'];

	if(intro && intro!="" && this.playMode=="addIntro"){
		console.log("addTrack intro");
		window.document.main.addTrack(this.playlist['lastplayerid'], introfile, "", "", "", "", 
			"", annotation,"intro");
		this.playlist['lastplayerid']++;
	}

	this.playlist['current_song_playerid'] = this.playlist['lastplayerid'];
		console.log("assigning "+songfile);
		window.document.main.addTrack(this.playlist['lastplayerid'], songfile, "", "", "", "", 
			"", annotation, "song");

	if(outro && outro!=""){
		console.log("addTrack outro");
		this.playlist['lastplayerid']++;
		window.document.main.addTrack(this.playlist['lastplayerid'], outrofile, "", "", "", "", 
			"", annotation, "outro");
	}
	this.playMode = "noIntro";
	this.playlist['current_outro_playerid'] = this.playlist['lastplayerid'];
}



Clubstr.prototype.playTrack = function (SST,track){
	// if we are continuing a paused track, we pass playTrack() with no arguments
	if(!typeof SST == "undefined"){ 
		var thisSST = this.playingSST.split(/-/);
		var track = allShows[thisSST[0]].events[thisSST[1]].tracks[thisSST[2]].id;
	}
	
	if( typeof SST == "undefined" && this.playerMode == "paused" ){ 
		window.document.main.playTrack();
		var thisSST = this.playingSST.split(/-/);
		this.playerMode = "playing";
		
		$('showSet'+thisSST[0]+'-'+thisSST[1]).addClassName('playingSet'); 
		$('stopButton'+this.playingSST).show();
		$('playButton'+this.playingSST).hide();
		$('player_play_button').hide();
		$('player_pause_button').show();
		
		return true;
	}
	// if we are already playing this track, do nothing
	else if(this.playing==track+'_'+this.soundcode && this.playerMode=="playing"){ return false; }
	
	// if clicked from the player and we aren't in pause mode, get the next track and play it
	else if(typeof SST == "undefined"){ 
		SST = this.getNextFromNaturalQueue();
	}
	
	// get the currently playing track and remove the playing indication from it.
	if(this.playingSST!=""){ 
		var prevSST = this.playingSST.split(/-/);
		if($('showSet'+prevSST[0]+'-'+prevSST[1])){
			$('showSet'+prevSST[0]+'-'+prevSST[1]).removeClassName('playingSet'); 
		}
	}
	
	// now set the passed argument as the current track
	this.playing=track+'_'+code;
	this.playingSST=SST;
	var thisSST = this.playingSST.split(/-/);

	var s = allShows[thisSST[0]];

	if($('showSet'+thisSST[0]+'-'+thisSST[1])){
		$('showSet'+thisSST[0]+'-'+thisSST[1]).addClassName('playingSet'); 
	}
	$$('.stopButton').invoke('hide');
	$$('.playButton').invoke('show');
	if($('stopButton'+SST)){
		$('stopButton'+SST).show();
		$('playButton'+SST).hide();
	}

	var track_id = s.events[thisSST[1]].tracks[thisSST[2]].id;
	var track_name = s.events[thisSST[1]].tracks[thisSST[2]].track_name;
	var artist_id = s.events[thisSST[1]].artist_id;
	var artist_name = s.events[thisSST[1]].artist_name;
	

	var image = "http:\/\/www.clubstr.com"+s.events[thisSST[1]].artist_photo;
	var player_show_info = s.showLongDate +' at '+ s.venue_name;

	var info_url="";
	var purchase_url="";
	var annotation="";

	$('player_artist_name').innerHTML = artist_name;	
	$('player_track_picture').src = image;
	$('player_track_picture').show();
	$('player_play_button').hide();
	$('player_pause_button').show();

	
	// add to playlist and play
	this.addToPlaylist(this.playingSST);
	window.document.main.stopTrack();
	window.document.main.gotoTrack(this.playlist.current_intro_playerid);
	this.assignSoundcode();
	
	this.scrollToShow(thisSST[0]);
	
}

Clubstr.prototype.stopMusic = function (mode){
	if(!$('main')){ return false; }
	
	if(typeof mode=="undefined"){ var mode = ""; }
	
	$$('.stopButton').invoke('hide');
	$$('.playButton').invoke('show');

	$('player_pause_button').hide();
	$('player_play_button').show();
	

	if(this.playingSST!=""){
		var prevSST = this.playingSST.split(/-/);
		if($('showSet'+prevSST[0]+'-'+prevSST[1])){
			$('showSet'+prevSST[0]+'-'+prevSST[1]).removeClassName('playingSet'); 
		}
	}
	
	if(mode=="pause"){
		window.document.main.playTrack();
		this.playerMode = "paused";

	}else{
		this.playing = 0;
		this.playingSST = '';

		this.playerMode = "stopped";
		window.document.main.stopTrack();
	
		var thisObj = this;
		new Ajax.Request(
		'mp3init?p='+prevcode+'&sessID='+sessID+'&source='+request_source+'&source_id='+owner_id, 
		{
		  method: 'get',
		  onSuccess: function(transport) {
			thisObj.soundcode = trim(transport.responseText);
		  }
		});
	}
}


