/* 
	Copyright 2011 Patrick Mounteney
    Kaleidoscopic Creation
    www.kaleidoscopiccreation.co.uk
	
*/

var picker1 = (function() {
					
var api=[]; // make object to attach methods to
var topPos = [16, -20, -56, -96, -133, -165]; // top css position of draggable layer containing stream names and streams
var selectedChannelRowKey = 2; // hardwired to the "Rock Stream" for this picker
var selectedStreamRowKey = 0;
var pickerDiv, pickerCol0, pickerCol1;
var clickFX = false;
var draggingInProgress = false;
var adjustedStreamValues = [];
var adjustedStreamUrls = [];
var flashPlayerIsPlaying = false;
var html5PlayerIsPlaying = false;
var previous_artist = "";
var previous_title = "";
var picker1_whatsplayingTimer
var streamErrorMessageIsDisplayed = false;

// this is only for the "Rock Stream" - the others are only up to date in 'Picker 2'
var streamObj = [
				 
{
	isCurrentlySelectedChannel: false,
	streamName: "-",
	streamShortName: "retro",
	streamColor: "green", 
	streamValues: ["-","-","96k Stereo","-","-","-"],
	streamUrls: ["-","-","http://78.129.163.140:8030","-","-","-"],
	currentMp3Stream: "96k Stereo",
	currentAACStream: false,
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=retro"
	
},				 
	 
{
	isCurrentlySelectedChannel: false,
	streamName: "-",
	streamShortName: "gold",
	streamColor: "#95774c",
	streamValues: ["-","-","96k Stereo","-","-","-"],
	streamUrls: ["-","-","http://78.129.163.140:8110","-","-","-"],
	currentMp3Stream: "96k Stereo",
	currentAACStream: false,
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=gold"
},


{
	isCurrentlySelectedChannel: true,
	streamName: "Rock Stream",
	streamShortName: "rock",
	streamColor: "red",
	streamValues: ["128k AAC","64k AAC","128k mp3","64k mp3","48k mp3","24k mp3"],
	streamUrls: ["http://78.129.163.140:8020",
				 "http://78.129.163.140:8100",
				 "http://78.129.163.140:8070",
				 "http://78.129.163.140:8040",
				 "http://78.129.163.140:8120",
				 "http://78.129.163.140:8050"
				 ],
	currentMp3Stream: "64k mp3",
	currentAACStream: "64k AAC",
	streamBackupUrls: ["http://70.38.11.232:8024","http://70.38.11.232:8064"," http://70.38.11.232:8096","http://70.38.11.232:8048"],
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php"
},

{
	isCurrentlySelectedChannel: false,
	streamName: "-",
	streamShortName: "now",
	streamColor: "#ffc82e",
	streamValues: ["-","-","96k Stereo","-","-","-"],
	streamUrls: ["-","-","http://78.129.163.140:8000","-","-","-"],
	currentMp3Stream: "96k Stereo",
	currentAACStream: false,
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=now"
},

{
	isCurrentlySelectedChannel: false,
	streamName: "-",
	streamShortName: "rocky", 
	streamColor: "purple",
	streamValues: ["128k AAC","64k AAC","32k AAC","64k Stereo","48k Mono","24k Mono"],
	streamUrls: ["http://78.129.163.140:8228",
				 "http://78.129.163.140:8010",
				 "http://78.129.163.140:8060",
				 "http://78.129.163.140:8080",
				 "http://78.129.163.140:8220",
				 "http://78.129.163.140:8205"
				 ],
	currentMp3Stream: "64k Stereo",
	currentAACStream: "64k AAC",
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=rocky"
}
	 
	 ];

/*
api.remove_AAC_from_dataset = function(){

for(var i=0; i< streamObj.length; i++){
	var tempStreamValues = [];
	var tempStreamUrls = [];
	for(var k=0; k< streamObj[i].streamValues.length; k++){
	
	if(streamObj[i].streamValues[k].indexOf("AAC") == -1){
	tempStreamValues.push(streamObj[i].streamValues[k]);
	tempStreamUrls.push(streamObj[i].streamUrls[k]);
	}
	}
	streamObj[i].streamValues = tempStreamValues;
	streamObj[i].streamUrls = tempStreamUrls;
}
}

*/

api.initPicker = function(){
getPrefs();


pickerDiv = document.getElementById("picker_1");
// create close button
var close_but = document.createElement("img");
close_but.src = "images/round_red_close_icon.png"
close_but.setAttribute("class", "round_red_close_button");
close_but.setAttribute("className", "round_red_close_button");
$(close_but).bind('click', function() {
	$(pickerDiv).fadeOut();
	api.stopWhatPlayingTimer();
});
pickerDiv.appendChild(close_but);
// create inner div which wraps the two columns
my_picker_inner = document.createElement("div");
my_picker_inner.setAttribute("class", "picker_inner");
my_picker_inner.setAttribute("className", "picker_inner");
// create two 'columns'
pickerCol0 = document.createElement("div");
pickerCol0.setAttribute("class", "pickerCol0"); // for css
pickerCol0.setAttribute("className", "pickerCol0");
pickerCol1 = document.createElement("div");
pickerCol1.setAttribute("class", "pickerCol1");
pickerCol1.setAttribute("className", "pickerCol1");

my_picker_inner.appendChild(pickerCol0);
my_picker_inner.appendChild(pickerCol1);
pickerDiv.appendChild(my_picker_inner);
// create 'bar'
var bar = document.createElement("img");
bar.src = "images/picker_bar.png";
bar.setAttribute("class", "picker_bar_image"); 
bar.setAttribute("className", "picker_bar_image");
my_picker_inner.appendChild(bar);



$(pickerCol1).draggable({ axis: "y", start: function(event, ui) { draggingInProgress = true }, stop: function(event, ui) { col1FinishedDrag(ui) } });


 
$(my_picker_inner).bind('mousedown', function(e) {
	e.preventDefault(); // prevent accidental highlight of elements
	});



 $(bar).bind('mousedown', function(e) {
	var messageDiv = document.getElementById("messageDiv");	
	messageDiv.onmouseover = function(){$(messageDiv).fadeOut();};
	messageDiv.style.cssText = "position: absolute; top: 40px; left: 100px;";
	messageDiv.innerHTML = "Drag with your mouse above or below the bar to scroll - then click 'Play'";
	$(messageDiv).fadeIn();
	
	e.preventDefault(); // prevent drag moving image
	});


buildCol0();
autoSelectStream();



$(pickerCol0).css("top", topPos[2]); // hardwired to show the "Rock Stream" for this picker
document.getElementById("pickerCol0Log").innerHTML = streamObj[2].streamName;

/*
if(canPlayAAC){
selectedStreamRowKey =	1; // default stream for AAC
}else{
selectedStreamRowKey = 1; // default stream for mp3 (coincidentally the same as AAC, but it may change of course)
}
*/

$(pickerCol1).css("top", topPos[selectedStreamRowKey]);
document.getElementById("pickerCol1Log").innerHTML = streamObj[2].streamValues[selectedStreamRowKey];


// embed 'click' sound FX
var flashvars = {};
var params = {loop: "false"};
var attributes = {};

swfobject.embedSWF("swf/picker_sound.swf", "clickFX1", "12", "12", "9.0.0", false, flashvars, params, attributes, hasLoadedSound); // load 'click' sound


}


function hasLoadedSound(e){
	if (e.success){
	setTimeout(function(){clickFX = e.ref; }, 500);
	
	}
	
}


// Player Control blocks

api.playFlashPlayer = function(){
if(adjustedStreamUrls[selectedStreamRowKey].indexOf("http") == -1){
document.getElementById("whatsPlaying2").innerHTML = "Stream is not playable";
return;
}


createJWplayer(adjustedStreamUrls[selectedStreamRowKey]);

stopButtonOne.style.display = "block";
playButtonOne.style.display = "none";

flashPlayerIsPlaying = true;
}


api.stopFlashPlayer = function(){
stopButtonOne.style.display = "none";
playButtonOne.style.display = "block";
//if(jwplayer) jwplayer("flashPlayer").pause(); // we use 'pause' and not 'stop' as we can pick up it's event
if(jwplayer) jwplayer.pause(); 
flashPlayerIsPlaying = false;
flashPlayerInitialised = false;
//jwplayer("flashPlayer").remove(); // stop streams and clean up

}



// Picker Control for Column 1 - Streams

function col1FinishedDrag(e){
if(flashPlayerIsPlaying) api.stopFlashPlayer();	
if(clickFX) clickFX.triggerStart(); 

var numOfStreams = adjustedStreamValues.length;

var currentPos = e.position.top; 

	if(currentPos > 16){
	selectedStreamRowKey = 0;
	}
	
	if(numOfStreams > 1 && currentPos > -40 && currentPos < -4){
	selectedStreamRowKey = 1;
	}
	
	if(numOfStreams > 2 && currentPos > -78 && currentPos < -39){
	selectedStreamRowKey = 2;
	}

	if(numOfStreams > 3 && currentPos > -120 && currentPos < -77){
	selectedStreamRowKey = 3;
	}
	
	if(numOfStreams > 4 && currentPos > -200 && currentPos < - 119){
	selectedStreamRowKey = 4;
	}

	if(numOfStreams > 5 && currentPos < -151){
	selectedStreamRowKey = 5;
	}
	
	/*
	document.getElementById("pickerCol0Log").innerHTML = streamObj[selectedChannelRowKey].streamName;
	document.getElementById("pickerCol1Log").innerHTML = streamObj[selectedChannelRowKey].streamValues[selectedStreamRowKey];
	*/
	
	document.getElementById("pickerCol1Log").innerHTML = currentPos;
	
	logCurrentStream(adjustedStreamValues[selectedStreamRowKey]); // keep track of current stream
	 $(pickerCol1).css("top",topPos[selectedStreamRowKey]);
	
	
	if(canPlayAAC) changeHTML5PlayerStream();
	setPrefs();
}


function buildCol0(){
var list = document.createElement("ul");
list.setAttribute("class","picker_ul");
list.setAttribute("className","picker_ul");
for (var k=0; k< streamObj.length; k++) {
var li = document.createElement("li");
var span = document.createElement("span");
//span.onclick = function(){alert("Boo")};
span.style.cssText = "color: "+streamObj[k].streamColor;
var text = document.createTextNode(streamObj[k].streamName);	
span.appendChild(text);
li.appendChild(span);
list.appendChild(li);
}
pickerCol0.appendChild(list);	
}



// activated when user selects a new channel from column 0 of the picker
function autoSelectStream(){
	deleteprior(pickerCol1);
	$(pickerCol1).hide();
	var list = document.createElement("ul");
	list.setAttribute("class","picker_ul");
	list.setAttribute("className","picker_ul");
	
	var number_streams = makeAdjustedStreamsArray();
	
	
	for (var k=0; k< number_streams; k++) {
	var li = document.createElement("li");
	var span = document.createElement("span");
	
	var thisStream = adjustedStreamValues[k];
	
	var text = document.createTextNode(thisStream);
	
	span.appendChild(text);
	li.appendChild(span);
	list.appendChild(li);
	}
	pickerCol1.appendChild(list);
	
	selectedStreamRowKey = findPosOfCurrentStream();
	
	/*
	if(canPlayAAC){
		document.getElementById("pickerCol1Log").innerHTML = streamObj[selectedChannelRowKey].streamValues[selectedStreamRowKey];
	}else{
		document.getElementById("pickerCol1Log").innerHTML = adjustedStreamValues[selectedStreamRowKey];
	}
	*/
	
	$(pickerCol1).css("top", topPos[selectedStreamRowKey]); 
	$(pickerCol1).show();
	

	if(canPlayAAC) changeHTML5PlayerStream();
	
	setPrefs();
}


// parse streams for ACC's if we can play them
function makeAdjustedStreamsArray(){
adjustedStreamValues = [];
adjustedStreamUrls = [];
for(var k=0; k< streamObj[selectedChannelRowKey].streamValues.length; k++){
	if(!canPlayAAC && streamObj[selectedChannelRowKey].streamValues[k].indexOf("AAC") == -1){
	adjustedStreamValues.push(streamObj[selectedChannelRowKey].streamValues[k]);
	adjustedStreamUrls.push(streamObj[selectedChannelRowKey].streamUrls[k]);
	}
	if(canPlayAAC){
	adjustedStreamValues.push(streamObj[selectedChannelRowKey].streamValues[k]);
	adjustedStreamUrls.push(streamObj[selectedChannelRowKey].streamUrls[k]);	
	}
}
return adjustedStreamValues.length;
}



api.createHTML5Player = function(){
var streamText = streamObj[selectedChannelRowKey].streamValues[selectedStreamRowKey];
var url = streamObj[selectedChannelRowKey].streamUrls[selectedStreamRowKey];
if( url == "_") return; // can't be played
if(html5Player1) html5Player1.pause(); // don't just pull the rug out
var canPlay = false;
html5Player1 = new Audio(url);
html5Player1.addEventListener('playing', isPlaying1, false);
html5Player1.addEventListener('pause', hasStopped1, false);
html5Player1.preload = "auto";
html5Player1.src = url;
var theType = (streamText.indexOf("AAC") > -1)? "audio/mp4" : "audio/mp3";
html5Player1.type = theType;
}

function changeHTML5PlayerStream(){
if(html5Player1 == null) return;
if(html5Player1) html5Player1.pause(); // don't just pull the rug out
var streamText = streamObj[selectedChannelRowKey].streamValues[selectedStreamRowKey];
var theType = (streamText.indexOf("AAC") > -1)? "audio/mp4" : "audio/mp3";
html5Player1.type = theType;
var url = streamObj[selectedChannelRowKey].streamUrls[selectedStreamRowKey];
if(url == "-"){
streamErrorMessageIsDisplayed = true;
document.getElementById("whatsPlayingArea1").innerHTML = "Stream is not playable";
return;
}
if(streamErrorMessageIsDisplayed == true){
document.getElementById("whatsPlayingArea1").innerHTML = "";
previous_artist = "";
previous_title = "";
streamErrorMessageIsDisplayed = false;
getWhatsPlaying();
}
setTimeout(function(){ html5Player1.setAttribute("src", url); }, 250); // change to new stream but set delay or 'pause' event won't fire
}



function isPlaying1(e){html5PlayerIsPlaying = true; stopButtonOne.style.display = "block"; playButtonOne.style.display = "none"; };
function hasStopped1(e){ html5PlayerIsPlaying = false; stopButtonOne.style.display = "none"; playButtonOne.style.display = "block"; };


function findPosOfCurrentStream(){
if(canPlayAAC){
var currentAAC = streamObj[selectedChannelRowKey].currentAACStream;
var currentMp3 = streamObj[selectedChannelRowKey].currentMp3Stream;
return (currentAAC)? streamObj[selectedChannelRowKey].streamValues.indexOf(currentAAC) : streamObj[selectedChannelRowKey].streamValues.indexOf(currentMp3); // if no AAC use mp3 one
}else{
return adjustedStreamValues.indexOf(streamObj[selectedChannelRowKey].currentMp3Stream);
}
}

function logCurrentStream(stream){
if(canPlayAAC){
streamObj[selectedChannelRowKey].currentAACStream = stream;
}else{
streamObj[selectedChannelRowKey].currentMp3Stream = stream;
}
}


function getPrefs(){
	return;
if( supports_local_storage() ){
var store = localStorage.getItem("ekr_picker_1");

if(store != null){
	
	streamObj = $.evalJSON(store);

}

}else{
var data = $.cookie('ekr_picker_1');
if(data != null) streamObj = $.evalJSON(data);
}
}


function setPrefs(){
if( supports_local_storage() ){

localStorage.setItem("ekr_picker_1", $.toJSON(streamObj)); // now save to local storage
}
$.cookie('ekr_picker_1', $.toJSON(streamObj));
}


api.startWhatPlayingTimer = function(){
getWhatsPlaying(); // get it immediately then hand over to timer
picker1_whatsplayingTimer = setInterval(getWhatsPlaying, 15000);
}


api.stopWhatPlayingTimer = function(){
clearInterval(picker1_whatsplayingTimer);
}

function deletePreviouswhatsPlaying(){
$("#whatsPlayingArea2").html("");	
}

function getWhatsPlaying(){
$.ajax({
   url: "php/whatsplaying.php?url="+ streamObj[selectedChannelRowKey].nowPlayingUrl,
   cache: false,
   success: function(data) {
	var data = data.replace(/(<([^>]+)>)/ig,""); // remove HTML tags
	if(data.charAt(data.length-1) == "-") data.slice(0, -1); // remove any extra "-" from end of text
	if(data.indexOf("-") != -1){
	var splits = data.split(" - "); // split at artist/title delimiter
	var artist = splits[0];
	var title = splits[1];
	if(artist.startsWith("Show Promo - ") || artist.startsWith("Jingle - ")) return;
	if(artist.startsWith("Ad - ")){
	artist = "Break"; 
	title = "";
	}
	var data = "<p class='whatsPlayingTextFirstLine'>"+artist+"</p><p>"+title+"</p>";
	}
	if(data.indexOf("undefined") != -1) return;
    if(artist != previous_artist && title != previous_title){
		$("#whatsPlayingArea1").html(data);
		previous_artist = artist;
		previous_title = title;
	}
  }
});

}



// helpers

function supports_local_storage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch(e){
    return false;
  }
}




function displayMessage(){
	var messageDiv = document.getElementById("messageDiv");	
	messageDiv.onmouseover = function(){$(messageDiv).fadeOut();};
	messageDiv.style.cssText = "position: absolute; top: 40px; left: 100px;";
	messageDiv.innerHTML = "Drag with your mouse above or below the bar to scroll - then click 'Start'";
	$(messageDiv).fadeIn();
	setTimeout(function(){ $(messageDiv).fadeOut(); }, 10000);
}

function write_log(text, overwrite){
	var logDiv = top.document.getElementById('logDiv');
	if(overwrite){
		logDiv.innerHTML = text;
		return;
	}
	var mytextnode = top.document.createTextNode(text);
	logDiv.appendChild(mytextnode);
	var mybr = top.document.createElement("br");
	logDiv.appendChild(mybr);
	};

function deleteprior(div){
	if(!div) return;
	while (div.firstChild){
    div.removeChild(div.firstChild);
 	}
	}


return api;
	  
}());


