/* 
	Copyright 2011 Patrick Mounteney
    Kaleidoscopic Creation
    www.kaleidoscopiccreation.co.uk
	
*/

var picker2 = (function() {
					
var api=[]; // make object to attach methods to
var topPos0 = [16, -20, -56, -91, -133, -170]; // top css position of picker column 0 (Channels)
var topPos1 = [16, -20, -56, -96, -133, -170]; // top css position of picker column 1 (Streams)
var selectedChannelRowKey = 2;
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 picker2_whatsplayingTimer;
var streamErrorMessageIsDisplayed = false;


var streamObj = [
				 
{
	isCurrentlySelectedChannel: false,
	streamName: "WDJ - Retro",
	streamShortName: "retro",
	streamColor: "green", 
	streamValues: ["-","-","96k mp3","-","-","-"],
	streamUrls: ["-","-","http://78.129.163.140:8030","-","-","-"],
	currentMp3Stream: "96k mp3",
	currentAACStream: false,
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=retro"
	
},				 
	 
{
	isCurrentlySelectedChannel: true,
	streamName: "WDJ - Gold",
	streamShortName: "gold",
	streamColor: "#95774c",
	streamValues: ["-","-","96k mp3","-","-","-"],
	streamUrls: ["-","-","http://78.129.163.140:8110","-","-","-"],
	currentMp3Stream: "96k mp3",
	currentAACStream: false,
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=gold"
},

	
{
	isCurrentlySelectedChannel: false,
	streamName: "WDJ - Now",
	streamShortName: "now",
	streamColor: "#ffc82e",
	streamValues: ["-","-","96k mp3","-","-","-"],
	streamUrls: ["-","-","http://78.129.163.140:8000","-","-","-"],
	currentMp3Stream: "96k mp3",
	currentAACStream: false,
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=now"
},

{
	isCurrentlySelectedChannel: false,
	streamName: "WDJ - Rocky",
	streamShortName: "rocky", 
	streamColor: "purple",
	streamValues: ["128k AAC","64k AAC","32k AAC","128k mp3","96k mp3","48k mp3"],
	streamUrls: ["http://78.129.163.140:8228",
				 "http://78.129.163.140:8060",
				 "http://78.129.163.140:8010",
				 "http://78.129.163.140:8220",
				 "http://78.129.163.140:8080",
				 "http://78.129.163.140:8205"
				 ],
	currentMp3Stream: "64k mp3",
	currentAACStream: "64k AAC",
	nowPlayingUrl: "http://lazygit.org/ekr/sc_now_playing.php?stream=rocky"
}
	 
	 ];

/*
api.remove_AAC_from_dataset = function(){
return;
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_2");
// 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"); // for ruddy IE
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);

$(pickerCol0).draggable({ axis: "y",  start: function(event, ui) { draggingInProgress = true }, stop: function(event, ui) { col0FinishedDrag(ui) } });
$(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; right: 100px;";
	messageDiv.innerHTML = "Drag with your mouse above or below the bar to scroll - then click 'Start'";
	$(messageDiv).fadeIn();
	setTimeout(function(){ $(messageDiv).fadeOut(); }, 10000);
	});
 
 

selectedChannelRowKey = findCurrentSelectedChannel();


buildCol0(); 



autoSelectStream(); // select current stream


// embed 'click' sound FX
var flashvars = {};
var params = {loop: "false"};
var attributes = {};

swfobject.embedSWF("swf/picker_sound.swf", "clickFX2", "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]);

/*
// listen for 'pause' event
jwplayer("flashPlayer").onPause(
function(event) {
	return;
flashPlayerIsPlaying = false;
flashPlayerInitialised = false;
jwplayer("flashPlayer").remove(); // stop streams and clean up
stopButtonTwo.style.display = "none";
playButtonTwo.style.display = "block";
});

// listen for 'error' event
jwplayer("flashPlayer").onError(
function(e) {
document.getElementById("whatsPlaying2").innerHTML = e.message;
// stop everything
flashPlayerIsPlaying = false;
flashPlayerInitialised = false;
jwplayer("flashPlayer").remove(); // stop streams and clean up
stopButtonTwo.style.display = "none";
playButtonTwo.style.display = "block";
});
*/

stopButtonTwo.style.display = "block";
playButtonTwo.style.display = "none";
flashPlayerIsPlaying = true;
}

api.stopFlashPlayer = function(){
//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
stopButtonTwo.style.display = "none";
playButtonTwo.style.display = "block";
}


// Picker Control for Column 0 - hardwired for four channels
function col0FinishedDrag(e){
if(flashPlayerIsPlaying) api.stopFlashPlayer();
if(clickFX) clickFX.triggerStart(); 

var currentPos = e.position.top;
//write_log("currentPos: "+e.position.top);

	if(currentPos > -7){
	animateToNewPickerPosition(pickerCol0, 0);
	selectedChannelRowKey = 0;
	}

	if(currentPos > -37 && currentPos < -6 ){
	animateToNewPickerPosition(pickerCol0, 1);;
	selectedChannelRowKey = 1;
	}
	
	if(currentPos > -78 && currentPos < -36){
	animateToNewPickerPosition(pickerCol0, 2);
	selectedChannelRowKey = 2;
	}
	
	if(currentPos < -78){
	animateToNewPickerPosition(pickerCol0, 3);
	selectedChannelRowKey = 3;
	}
	
	
	//document.getElementById("picker2Col0Log").innerHTML = streamObj[selectedChannelRowKey].streamName;
	
	
	
	logCurrentChannel();
	autoSelectStream();
	deletePreviouswhatsPlaying(); // good idea to do it here as the new stream may not immediately produce a usable replacement
	getWhatsPlaying();
	
	
}

// 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 > -7){
	animateToNewPickerPosition(pickerCol1, 0);
	selectedStreamRowKey = 0;
	}
	
	if(numOfStreams > 1 && currentPos > -40 && currentPos < -4){
	selectedStreamRowKey = 1;
	}
	
	if(numOfStreams > 2 && currentPos > -81 && currentPos < -39){
	selectedStreamRowKey = 2;
	}
	
	if(numOfStreams > 3 && currentPos > -120 && currentPos < -80){
	selectedStreamRowKey = 3;
	}
	
	if(numOfStreams > 4 && currentPos > -200 && currentPos < - 119){
	selectedStreamRowKey = 4;
	}
	
	if(numOfStreams > 5 && currentPos < -151){
	selectedStreamRowKey = 5;
	}
	
	
	$(pickerCol1).css("top",topPos1[selectedStreamRowKey]);
	
	
	logCurrentStream(adjustedStreamValues[selectedStreamRowKey]); // keep track of current stream
	
	if(canPlayAAC) changeHTML5PlayerStream();
	
	setPrefs();
}

function animateToNewPickerPosition(column, key){
$(column).animate({"top":topPos0[key]}, 100, "swing");
}


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.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);
$(pickerCol0).css("top", topPos0[selectedChannelRowKey]); // set channel according to prefs
}


// 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();
	
	$(pickerCol1).css("top", topPos1[selectedStreamRowKey]); 
	$(pickerCol1).show(10);
	
	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(html5Player2) html5Player2.pause(); // don't just pull the rug out
var canPlay = false;
html5Player2 = new Audio(url); // make new HTML5 'audio' object
html5Player2.addEventListener('playing', isPlaying2, false);
html5Player2.addEventListener('pause', hasStopped2, false);
html5Player2.preload = "auto";
html5Player2.src = url;
var theType = (streamText.indexOf("AAC") > -1)? "audio/mp4" : "audio/mp3";
html5Player2.type = theType;
}


function changeHTML5PlayerStream(){
if(html5Player2 == null) return;
if(html5Player2) html5Player2.pause(); // don't just pull the rug out
var streamText = streamObj[selectedChannelRowKey].streamValues[selectedStreamRowKey];
var theType = (streamText.indexOf("AAC") > -1)? "audio/mp4" : "audio/mp3";
html5Player2.type = theType;
var url = streamObj[selectedChannelRowKey].streamUrls[selectedStreamRowKey];
if(url == "-"){
streamErrorMessageIsDisplayed = true;
document.getElementById("whatsPlayingArea2").innerHTML = "Stream is not playable";
return;
}
if(streamErrorMessageIsDisplayed == true){
document.getElementById("whatsPlayingArea2").innerHTML = "";
previous_artist = "";
previous_title = "";
streamErrorMessageIsDisplayed = false;
getWhatsPlaying();
}
setTimeout(function(){ html5Player2.setAttribute("src", url); }, 250); // change to new stream but set delay or 'pause' event won't fire
}

function isPlaying2(e){html5PlayerIsPlaying = true; stopButtonTwo.style.display = "block"; playButtonTwo.style.display = "none"; };
function hasStopped2(e){ html5PlayerIsPlaying = false; stopButtonTwo.style.display = "none"; playButtonTwo.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 findCurrentSelectedChannel(){
var n = false;
for (var i=0; i< streamObj.length; i++) {
if(streamObj[i].isCurrentlySelectedChannel == true){
n = i;
break;
}
}
return n;	
}

function logCurrentChannel(){
for (var i=0; i< streamObj.length; i++) {
if(selectedChannelRowKey == i){
streamObj[i].isCurrentlySelectedChannel = true;	
}else{
streamObj[i].isCurrentlySelectedChannel = false;	
}
}
}

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_2");

if(store != null){
	
	streamObj = $.evalJSON(store);
	
}

}else{
var data = $.cookie('ekr_picker_2');
if(data != null) streamObj = $.evalJSON(data);
}
}


function setPrefs(){
if( supports_local_storage() ){
localStorage.setItem("ekr_picker_2", $.toJSON(streamObj)); // now save to local storage
}
$.cookie('ekr_picker_2', $.toJSON(streamObj));
}


api.startWhatPlayingTimer = function(){
getWhatsPlaying(); // get it immediately then hand over to timer
picker2_whatsplayingTimer = setInterval(getWhatsPlaying, 15000);
}


api.stopWhatPlayingTimer = function(){
clearInterval(picker2_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("-");
	var artist = splits[0];
	var title = splits[1];
	if(artist.startsWith("Show Promo - ") || artist.startsWith("Jingle - ")) return;
	if(artist.startsWith("Ad - ")){
	artist = "Break"; // could also remove instances of "Promo", "Jingle" or anything really	
	title = "";
	}
	var data = "<p class='whatsPlayingTextFirstLine'>"+artist+"</p><p>"+title+"</p>";
	}
	if(data.indexOf("undefined") != -1) return;
    if(artist != previous_artist && title != previous_title){
		$("#whatsPlayingArea2").html(data);
		previous_artist = artist;
		previous_title = title;
	}
  }
});

}



function supports_local_storage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch(e){
    return false;
  }
}


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;
	  
}());


