/////////////////////////////////////////////////
// connect to websocket

var socket = io.connect();
function initPage() { socket.emit("initPage");  
		      console.log("init.client.log")
		    }

//socket.on("metroPulse", metronomeTick);
/////////////////////////////////////////////////

socket.on("metroPulse", pulseInClient);
function pulseInClient(pulse,groupID,metrobeat){
    var groupPage=document.getElementById('group').value
    if (groupID == groupPage) {
	metronomeTick(1000, groupID, metrobeat);
    }
}

//////////////////////////////////////////////////
// AUDIO SCORE CUES

var audioUnit1 = new Audio('audio/testfile.ogg');
var audioUnit49 = new Audio('audio/testfile.ogg');
var audioUnit3 = new Audio('audio/testfile.ogg');
var audioUnit4 = new Audio('audio/testfile.ogg');

function playAudio(a) {
    a.play();
}

//playAudio(audio_unit_1);


/////////////////////////////////////////////////
function  metroCss(beat, beatcolor,text){
    var color = beatcolor;
    $(".metrocase > div").each(function(){$(this).stop()});
    $(".metrocase > div").each(function(){$(this).css('background-color', beatcolor)});
    $(".metrocase > div").each(function(){$(this).text(" ")});
}

function metronomeTick(pulse, voice,metrobeat) {
    var color = "gray"
    metroCss(0, "red", "4")
    setTimeout(function(){metroCss(0, "black", "4")},150);
};

/////////////////////////////////////////////////
// update the stopwatch value on the client page in line with server
socket.on("chronFromServer", function(chron) { $("div#client_chronometer").text(chron); });

// server time
    socket.on("dateTime", function(datetime) {
	$("div#datetime").text("" +datetime);
    });

/////////////////////////////////////////////////

// countin (solo part)

socket.on("countinFromServer", countinClient);
function countinClient(groupID, currentseconds,mm,text,colour,background,unit){
    var groupPage=document.getElementById('group').value
    if (groupID == groupPage) {
	$("#counttitle").css('color','black');
	$("#counttitle").text(text);
	$("#count").text(currentseconds);
	document.getElementById("count").style.color=colour;
 }}

/////////////////////////////////////////////////

// countdown to change (solo)

socket.on("counterText", cText);
function cText(groupID, currentseconds,text){
    $("#totalcountdown"+groupID).text(text);	
    var groupPage=document.getElementById('group').value
    if (groupID == groupPage) {
	//console.log(text)
	$("#totalcountdown").text(text);	
    }}

// when voice is changed in UI grab and update from server

function changeSoloVoice(v) { socket.emit("changeSoloVoice", v); }

// makes sure page is loaded if not it grabs svg etc

socket.on("pageIni", pageIni);
function pageIni (group,unit,time,mm,seqcounter,nextunit) { 
    //console.log(unit + " ---> " + nextunit)
    var soloist = $("#group").attr('value'); //4//$("#group").value;
    if (group==1){
	var n1 = $("#previewbox-1").html().indexOf("svg"); 
	//console.log(n1)
	if (n1 == -1){
	    //console.log("n1 == -1 so load svg:")
	    $("#previewbox-1").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
	}
    }
    
    if (group==2){
	var n2 = $("#previewbox-2").html().indexOf("svg"); 
	if (n2 == -1){ 
	    $("#previewbox-2").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
	}
    }

    if (group==3){
	var n3 = $("#previewbox-3").html().indexOf("svg"); 
	if (n3 == -1){ 
	    $("#previewbox-3").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
	}
    }

    if (group==4){
	var n4 = $("#previewbox-4").html().indexOf("svg"); 
	if (n4 == -1){ 
	    $("#previewbox-4").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
	}
    }


    if (group==soloist) { 	
	//console.log("INI sooolooooist=: ---------------------- : " + soloist)
	var n = $("#previewbox-solo").html().indexOf("svg"); 
	if (n == -1){ 
            $("#previewbox-solo").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
    	    $("#previewbox-solo-next").html("<img src='svg/"+(nextunit) + ".svg" + "' width='100%'>")
	}   
    }


}   


socket.on("pageFlip", pageFlip);

//  some if logic to check if file is already displayed
// if not load it - client doesnt need to be present at start

function pageFlip (group,unit,time,mm,seqcounter,nextunit) { 
    var soloist = $("#group").attr('value');

    if (group==1){
	$("#previewbox-1").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>") 
    }
    
    if (group==2){
	$("#previewbox-2").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
    }
    
    if (group==3){
	
	$("#previewbox-3").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
    }
    
    if (group==4){
	$("#previewbox-4").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
    }
    

    // page flip for solo part section
    
    if (group==soloist) {

	// changes the svg and preview images
	$("#previewbox-solo").html("<img src='svg/"+(unit) + ".svg" + "' width='100%'>")
	$("#previewbox-solo-next").html("<img src='svg/"+(nextunit) + ".svg" + "' width='100%'>")

	// check for audio assets to play
	// audio assets should have a value attribute which should be compared with the unit
	// if the unit has an associated audio attribute it should play
	
	if ( window["audioUnit"+unit] ){
	    console.log("audio asset detected for this unit... playing now...")
	    playAudio(window["audioUnit"+unit]);
	} else { console.log("no audio for this unit.."); }
    }

    // check for effect associated with unit
    // maybe in future we could use the webAudio API?

}



////////////////////////////////////////////////

/* commented out for now as interferes with chat
need to introduce metakey...manyana... not so usefull anyway really... 

keyboard controls 
+++++++++++++++++++++++++

SPACE to toggle visibilty of preview
m to toggle visibilty of metronome
s to toggle visibilty of stopwatch
h to hide all above


*/

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'block')
        e.style.display = 'none';
       else
           e.style.display = 'block';
}

$(document).keypress(function(e){
//    console.log(e.which);
  // "0" button for hide chat
    var hcheckWebkitandIE=(e.which==48 ? 1 : 0);
    var hcheckMoz=(e.which==48 ? 1 : 0);
    if (hcheckWebkitandIE || hcheckMoz) { 
	toggle_visibility('comms') 
}
    });

//*/

////////////////////////////////////////////////
// this needs to have a variable to define the websocket
// otherwise we will pings from all sockets connected
// no! the server broadcasts the ping and the clients emit the pong!
// ah but then the time reported back from the server needs to be targeted
// to specific client..

//////////////////////////////////////////////
// Latency "Pong"

socket.on("timeFromServer", function(n) { 
    socket.emit("clientTimeResponse",n); });

socket.on("latencyFromServer", function(latency) {
    $("#client_latency").text("Latency: "+latency+"ms.")
});

function getLatencies(x) { socket.emit("getLatencies", x); }

//////////////////////////////////////////////


socket.on('connect', function () {
    $('#chat').addClass('connected');
});

socket.on('announcement', function (msg) {
    $('#Lines').append($('<p>').append($('<em>').text(msg)));
});

socket.on('nicknames', function (nicknames) {
    $('#nicknames').empty().append($('<span>Online: </span>'));
    for (var i in nicknames) {
	$('#nicknames').append($('<b>').text(nicknames[i]));
    }
});

socket.on('user message', message);
socket.on('reconnect', function () {
    $('#lines').remove();
    message('System', 'Reconnected to the server');
});

socket.on('reconnecting', function () {
    message('System', 'Attempting to re-connect to the server');
});

socket.on('error', function (e) {
    message('System', e ? e : 'A unknown error occurred');
});

function message (from, msg) {
    $('#lines').prepend($('<p>').prepend($('<b>').text(from), msg));
}

// dom manipulation
$(function () {
    $('#set-nickname').submit(function (ev) {
	socket.emit('nickname', $('#nick').val(), function (set) {
	    if (!set) {
		clear();
		return $('#chat').addClass('nickname-set');
	    }
	    $('#nickname-err').css('visibility', 'visible');
	});
	return false;
    });

    $('#send-message').submit(function () {
	message('me', $('#message').val());
	socket.emit('user message', $('#message').val());
	clear();
	$('#lines').get(0).scrollTop = 10000000;
	return false;
    });

    function clear () {
	$('#message').val('').focus();
    };
});
