
/////////////////////////////////////////////////////////////////////////////////////////////
// VARIABLES

var t;
var ticks_per_beat = 60;
var tick_count = ticks_per_beat;
var time_res = 40; // [ms]
var ticks_per_s = 1000/time_res;
var velocity = 0.5; // > 0.5

var running = false;
var shuffle = false;
var mute = false;
var cover_kb = true;
var repeat = true;

var chordbox_count = 20;
var old_chordbox = 0;
var current_chordbox = 0;

var band_count = 9;
var strings = Array(5,12,8,3,10,5); // En Bra Gitarr Drar Aldrig El

var soundroot = false;
var soundcount = 0;
var floating_chords = new Array();
var the_chord = new CM.Chord('C','');
var chordlist = new CM.Chordlist("noname");

var custom_list = '';

/////////////////////////////////////////////////////////////////////////////////////////////
// SOUNDMANAGER 2


soundManager.url = 'swf/';
// disable debug mode after development/testing..
soundManager.debugMode = false;

var snd_guitar = new Array();
var globalVolume = 40;

soundManager.onload = function(){
	for (var i = 1; i <= 24; ++i)
	{
		snd_guitar.push(soundManager.createSound('g'+i,'audio/g'+i+'.mp3'));
	}
	init();
}

function play_root()
{
	if (mute) return; //Mute
	snd_guitar[the_chord.tones[0]-1].play({volume: globalVolume});
}

function play_tonic(index)
{
	if (mute) return; //Mute
	snd_guitar[the_chord.wrapped_tones[index]+11].play({volume: globalVolume});
}

function play_chord()
{
	if (mute) return; //Mute
	
	snd_guitar[the_chord.tones[0]-1].play({volume: globalVolume});
	var i = the_chord.wrapped_tones.length;
	if (i > 0) 
	do
	{
		snd_guitar[the_chord.wrapped_tones[i-1]+11].play({volume: globalVolume});
	}
	while (--i);
}

/////////////////////////////////////////////////////////////////////////////////////////////
// LIST HANDLING

function set_preset(code)
{
	if (code == 'custom')
	{
		chordlist = CM.parseChords(custom_list);
		$("#chordlist").html(chordlist.get_html());
	}
	else
	{
		chordlist.make_from_code(code);
		$("#chordlist").html(chordlist.get_html());
	}
	//$("#chordlist2").html(chordlist.get_html());
}

function add_chord()
{
	var index = document.getElementById('chordlist').selectedIndex;
	if (index == -1)
	{
		chordlist.add(the_chord.clone(),chordlist.list.length);
		$("#chordlist option:last").before("<option>" + the_chord.root_name + the_chord.chord_name + "</option>");
	}
	else
	{
		chordlist.add(the_chord.clone(),index);
		$("#chordlist option:selected").before("<option>" + the_chord.root_name + the_chord.chord_name + "</option>");
	}
	//$("#chordlist2").html(chordlist.get_html());
}

function remove_chord()
{
	var index = document.getElementById('chordlist').selectedIndex;
	//$("#app_shadow_top").html(index);
	if (index >= chordlist.list.length || index == -1) return;
	if ($("#chordlist option:selected"))
	{
		chordlist.remove(index);
		$("#chordlist option:selected").remove();
	}
	//$("#chordlist2").html(chordlist.get_html());
}

function switch_items(offset)
{
	var index = document.getElementById('chordlist').selectedIndex + offset;
	if (index >= chordlist.list.length || index < 1) return;
	if (offset)
	{
		var prev = $("#chordlist option:selected").next();
		$("#chordlist option:selected").before(prev);
	}
	else
	{
		var prev = $("#chordlist option:selected").prev();
		$("#chordlist option:selected").after(prev);
	}
	chordlist.switch_items(index);
	//$("#chordlist2").html(chordlist.get_html());
}

function transpose(step)
{
	chordlist.transpose(step);
	$("#chordlist").html(chordlist.get_html());
}

/////////////////////////////////////////////////////////////////////////////////////////////
// DISPLAY CHORDELEMENT


function update_keyboard(w_color,b_color)
{
	if (b_color == '#000' || cover_kb)
	{
		var jj = the_chord.wrapped_tones.length;
		if (jj > 0) 
		do
		{
			var j = jj-1;
			var tone = the_chord.wrapped_tones[j];
			var el = $("#key"+tone);
			if (el.css('width') == '19px') // white key
			{
				el.css('background-color',w_color);
				document.getElementById('key'+(tone+12)).style.backgroundColor = w_color;
				document.getElementById('key'+(tone+24)).style.backgroundColor = w_color;
			}
			else // black key
			{
				el.css('background-color',b_color);
				document.getElementById('key'+(tone+12)).style.backgroundColor = b_color;
				document.getElementById('key'+(tone+24)).style.backgroundColor = b_color;
			}
		}
		while (--jj);
	}
	else
	{
		var adder = 0;
		if (the_chord.tones[0] < 8) adder = 12;
		
		var jj = the_chord.tones.length;
		if (jj > 0) do
		{
			var j = jj-1;
			var tone = the_chord.tones[j]+adder;
			var el = $("#key"+tone);
			if (el.css('width') == '19px')
				el.css('background-color',w_color);
			else
				el.css('background-color',b_color);
		}
		while (--jj);
	}
}

function display_keyboard()
{
	update_keyboard('#FFBD70','#824600');
}

function clear_keyboard()
{
	update_keyboard('#FFF','#000');
}

function display_guitar()
{
	var the_tones = the_chord.wrapped_tones;
	var s = 6;
	do 
	{
        var submarker = false;
        for (var b = 0; b <= band_count; ++b)
        {
			var cur_marker = document.getElementById('mark'+b+s);
			
            if (b) { cur_marker.style.display = 'none'; } //erase prev
			
			var jj = the_tones.length;
			if (jj > 0) 
			do
            {
				var j = jj-1;
				var temp_tone = strings[s-1]+b;
                if ((temp_tone == the_tones[j]) || (temp_tone == the_tones[j]+12))
                {
					// hit!
                    if (b)
                    {
						if (submarker) cur_marker.style.backgroundPosition = 'bottom right';
						else cur_marker.style.backgroundPosition = 'bottom left';
						
						cur_marker.style.display = '';
						submarker = true;
                    }
					else submarker = true;
                }
            }
			while (--jj);
        }
	} 
	while (--s); // i must be greater than 0 here
}

function clear_buttons()
{
	// turn off last root and chord
	var tone = CM.translate(the_chord.root_name);
	document.getElementById('b'+tone).style.backgroundImage = 'url(img/button_right.png)';
	//$("#b"+tone).css('background-image','url(img/button_right.png)');
	$("#b"+tone+" span").css('background-image','url(img/button_left.png)');
	
	tone = CM.translate(the_chord.chord_name)
	document.getElementById('b'+tone).style.backgroundImage = 'url(img/button_right.png)';
	//$("#b"+tone).css('background-image','url(img/button_right.png)');
	$("#b"+tone+" span").css('background-image','url(img/button_left.png)');
}

function display_buttons()
{
	// highlight new root and chord
	var tone = CM.translate(the_chord.root_name);
	document.getElementById('b'+tone).style.backgroundImage = 'url(img/button_active_right.png)';
	//$("#b"+tone).css('background-image','url(img/button_active_right.png)');
	$("#b"+tone+" span").css('background-image','url(img/button_active_left.png)');
	
	tone = CM.translate(the_chord.chord_name);
	document.getElementById('b'+tone).style.backgroundImage = 'url(img/button_active_right.png)';
	//$("#b"+tone).css('background-image','url(img/button_active_right.png)');
	$("#b"+tone+" span").css('background-image','url(img/button_active_left.png)');
}                        

function roll_in_new_chord()
{
    // show new chord, with animation (-40, 60, 140)
	$("div.chord:eq("+current_chordbox+")").animate({top: "-40px", opacity: 0, fontSize: "15pt"}, 3500);
	current_chordbox = (current_chordbox + 1) % chordbox_count;
	$("div.chord:eq("+current_chordbox+")").css({top: "140px", opacity: 1, fontSize: "56pt"})
		.html(the_chord.root_name + the_chord.chord_name)
		.animate({top: "60px", opacity: 0.8, fontSize: "42pt"}, 2000);
}

function clear_chord()
{
	if (the_chord.is_undefined()) return;
	clear_keyboard();
	clear_buttons();
}

function display_chord()
{
	if (the_chord.is_undefined()) return;
    $("#chord_hold .panel_inner").html(the_chord.str());
	display_buttons();
	display_guitar();
	display_keyboard();
}

/////////////////////////////////////////////////////////////////////////////////////////////
// CHANGE CHORD

function change_tonic(tonic_nr, tonic_symb)
// when pressing a root button
{
	if (the_chord.root_name == tonic_symb) { return; }
	clear_chord();
	the_chord.set_root(tonic_nr, tonic_symb);
    display_chord();
}

function change_chord(chord_symb)
// when pressing a chord button
{
	if (the_chord.chord_name == chord_symb) { return; }
	clear_chord();
    the_chord.set_chord(chord_symb);
    display_chord();
}

function show_chord_in_list(index)
// when selecting a chord in the list
{
	tonic_symb = chordlist.list[index].root_name;
	chord_symb = chordlist.list[index].chord_name;
	if (the_chord.root_name == tonic_symb && the_chord.chord_name == chord_symb) { return; }
	clear_chord();
	the_chord.set_root(chordlist.list[index].root_nr, tonic_symb);
    the_chord.set_chord(chord_symb);
    display_chord();
}

/////////////////////////////////////////////////////////////////////////////////////////////
// MAIN LOOP CONTROL AND INIT

function playpause(ee)
{
    if (running)
    {
		running = false;
		clearInterval(t);
    }
	else
	{
        running = true;
        t = setInterval("main_loop()",time_res);
	}
	button_up(ee,running);
}

function stop()
{
	clearInterval(t);
	tick_count = ticks_per_beat;
	running = false;
	chordlist.current_index = -1;
	for (var i = 0; i < floating_chords.length; ++i)
		floating_chords[i].box.hide();
	floating_chords = new Array();
	$("#activation_line").css('opacity',0.0);
	button_up($("#startbutton"));
}

function update_speed(bpm)
{
	if (bpm)
	{
		if (isNaN(bpm)) return;
		if (bpm > 1000 || bpm < 10) return;
	}
	else
		bpm = $("#speedselect option:selected").val();
	ticks_per_beat = Math.floor(240/bpm * ticks_per_s);
	velocity = (time_res/25)*(0.4+bpm/600);
	if (tick_count > ticks_per_beat)
		tick_count = ticks_per_beat;
	$("#customspeed").val(bpm);
}

function custom_speed(ms)
{
	if (isNaN(ms)) return;
	if (ms < 100) return;
	delay = ms;
}

function add_floating_chord()
{
	var new_chord;
	if (shuffle)
		new_chord = chordlist.step_random();
	else
	{
		if (!repeat && chordlist.current_index == chordlist.list.length-1) return;
		new_chord = chordlist.step_one();
	}
	if (!repeat && chordlist.current_index == chordlist.list.length-1)
		new_chord.last = true;
	new_chord.top = 5;
	new_chord.fsize = 5;
	new_chord.active = 0;
	new_chord.opacity = 1.0;
	new_chord.box = $("div.chord:eq("+current_chordbox+")");
	current_chordbox = (current_chordbox + 1) % chordbox_count;
	new_chord.box.html(new_chord.str());
	new_chord.box.css({'color':'#000','opacity':new_chord.opacity,'font-size':new_chord.fsize+'pt'}).show();
	floating_chords.push(new_chord);
}

function main_loop()
{
	if (chordlist.list.length < 1)
	{
		stop();
		return;
	}
	if (tick_count == ticks_per_beat)
	{
		add_floating_chord();
		tick_count = 0;
	}
	++tick_count;
	
	if (soundcount)
	{
		--soundcount;
		play_tonic(soundcount);
	}
	if (soundroot)
	{
		soundroot = false;
		play_root();
		soundcount = the_chord.wrapped_tones.length;
	}
    // update chords
	for (var i = 0; i < floating_chords.length; ++i)
	{
		var cc = floating_chords[i];
		if (cc.top > 108 && cc.active == 0) // highlight
		{
			cc.box.css('color','#f80');
			clear_chord();
			the_chord = cc.clone();
			display_chord();
			soundroot = true;
			cc.active = 1;
		}
		if (cc.top > 220) // remove
		{
			cc.box.hide();
			floating_chords.shift();
			if (!repeat && cc.last && chordlist.current_index == chordlist.list.length-1 && floating_chords.length < 1)
			{
				stop();
				return;
			}
			continue;
		}
		if (cc.active)
		{
			cc.opacity -= 0.05;
			cc.box.css('opacity',cc.opacity);
			$("#activation_line").css('opacity',cc.opacity);
		}
		cc.top += velocity*cc.fsize/32;
		cc.box.css('top',cc.top+'px');
		cc.fsize += velocity*0.8*(0.2+cc.top/50);
		cc.box.css('font-size',cc.fsize);
	}
}

function init()
{
	// look at all checkboxes and lists
	update_speed();
	//change_speed($("#speedselect").children("option:selected").val());
	button_up($("#shuffle"),shuffle);
	button_up($("#mute"),mute);
	button_up($("#repeat"),repeat);
	$("#cb_cover_kb").attr('checked','checked');
	$("#cb_kb_labels").attr('checked','');
	$("#cb_g_labels").attr('checked','');
	// set up environment
	$("#activation_line").css('opacity',0.0);
	display_guitar_tuner();
	if ($("#presets option:selected").html() == 'Custom')
		set_preset('custom');
	else
		set_preset("Cb");
	// generate a chord
	the_chord = chordlist.step_random();
	chordlist.current_index = -1; // fix index after getting a random chord
	display_chord();
	play_chord();
}

function change_volume(e)
{
	var x = e.pageX - $("#volume").offset().left;
	var x = e.pageX - $("#volume").offset().left;
	$('#volume div').css('width', x+'px');
	globalVolume = (x*100)/70;
	if (globalVolume > 100) globalVolume = 100;
}

jQuery(document).ready(function(){
	$("#volume").mousedown(change_volume);
});

/////////////////////////////////////////////////////////////////////////////////////////////
// TOOLBOX

function display_guitar_tuner()
{
	for (var i = 1; i <= 6; ++i)
	{
		$("#tuner"+i).html(CM.root_symbol[strings[i-1]]);
	}
}

function change_g_tuning(string_nr,change)
{
	strings[string_nr-1] += change;
	if (strings[string_nr-1] <= 0) { strings[string_nr-1] += 12; }
	if (strings[string_nr-1] > 12) { strings[string_nr-1] -= 12; }
	display_guitar_tuner();
	
	// update lables
	if ($("#cb_g_labels").is(":checked"))
		toggle_g_lables(1);
}

/////////////////////////////////////////////////////////////////////////////////////////////
// TOGGLE

function slide(target_id, x1, y1, x2, y2)
{
	if ($("#"+target_id).css('top') != y1 + 'px')
	{
		$("#"+target_id).animate({left: x1}); //,{queue:false}
		$("#"+target_id).animate({top: y1});
	}
	else
	{
		$("#"+target_id).animate({top: y2});
		$("#"+target_id).animate({left: x2});
	}
}

function toggle_cover_kb(state)
{
	if (state)
		cover_kb = true;
	else
		cover_kb = false;
}

function toggle_kb_lables(state)
{
    if (state)
		$(".key_label").show();
    else
		$(".key_label").hide();
}

function toggle_g_lables(state)
{
    if (state)
    {
		for (var s = 1; s <= 6; ++s)
		{
			for (var b = 0; b <= band_count; ++b)
			{
				$("#label"+b+s).html(CM.root_symbol[strings[s-1]+b]).show();
			}
		}
    }
    else
    {
		for (var s = 1; s <= 6; ++s)
		{
			for (var b = 0; b <= band_count; ++b)
			{
				$("#label"+b+s).hide();
			}
		}
    }
}

function toggle_mute()
{
	mute=!mute;
	if (mute)
	{
		$("#volume").css('background-image','url(img/volume_inactive.png)');
		$("#volume div").css('background-image','url(img/volume_inactive.png)');
	}
	else
	{
		$("#volume").css('background-image','url(img/volume_active.png)');
		$("#volume div").css('background-image','url(img/volume_active.png)');
	}
}

function shuffle_click(ee)
{
	shuffle =! shuffle;
	if (shuffle)
		repeat = true;
	button_up(ee,shuffle);
	button_up($("#repeat"),repeat);
}

function repeat_click(ee)
{
	if (shuffle) return;
	repeat = !repeat;
	button_up(ee,repeat);
}

function button_down(ee, state)
{
	if (state)
		$(ee).css('background-position','left bottom');
	else 
		$(ee).css('background-position','right bottom');
}

function button_up(ee, state)
{
	if (state)
		$(ee).css('background-position','left top');
	else
		$(ee).css('background-position','right top');
}

function generateSequence()
{
	if (chordlist.list.length < 1)
	{
		$("#sequence").html('Chordlist is empty!');
		return;
	}
	var nr = $("#seq_nr").children("option:selected").val(); //get number of chords to generate
	var s = '';
	for (var i = 0; i < nr; ++i)
	{
		temp_ref = chordlist.step_random();
		s += temp_ref.root_name + temp_ref.chord_name + ' ';
	}
	$("#sequence").html(s);
}

function show_list_link()
{
	$("#list_link_box").css({top: "450px", opacity: 0});
	$("#list_link_box").animate({opacity: 1}, 500);
	s = chordlist.get_liststring();
	$("#list_link").val('http://www.chordpractice.com?list=' + s);
	$("#list_link").select();
}
function hide_list_link()
{
	$("#list_link_box").animate({opacity: 0}, 500)
		.css({top: "650px"});
	$("#list_link").val('');
}

/////////////////////////////////////////////////////////////////////////////////////////////
// TOOLBOX MENU

var menu_active = 0;
function deactivate_menu()
{
	$("div.menubox").stop().hide();
	$(".menuitem").css({
		background: '',
		color: '#fff'
	});
	menu_active = 0;
}
function activate_menuitem(ee,target_name)
{
	$(ee).css({
		background: '#FEF6EC',
		color: '#000'
	});
	$("#"+target_name).show();
	menu_active = 1;
}
function menuitem_click(ee,target_name)
{
	if (menu_active) { deactivate_menu(); }
	else { activate_menuitem(ee,target_name); }
}
function menuitem_over(ee,target_name)
{
	if (menu_active)
	{
		if ($("#"+target_name).is(":visible"))
		{
			return;
		}
		deactivate_menu();
		activate_menuitem(ee,target_name);
	}
	else
	{
		$(ee).css({
			background: '#FEF6EC',
			color: '#8A4A00',
		});
	}
}
function menuitem_out(ee)
{
	if (!menu_active) 
		$(ee).css({
			background: '',
			color: '#fff'
		});
}

