var SongProps = new Object;
var re = /iphone/i;

var jqt = new $.jQTouch({
	//useFastTouch: false,
	slideSelector: '#jqt ul li a, .header a', //, #tools a
	icon: 'images/gc-iphone-icon.png',
	startupScreen: 'images/gcstartup-2.png',
	addGlossToIcon: false,
	statusBar: 'black',
	//submitSelector: 'select',
	formSelector: false,
	preloadImages: [
		'images/arrow-down-active.png',
		'images/arrow-down.png',
		'images/arrow-up-active.png',
		'images/arrow-up.png',
		'images/back-active.png',
		'images/back.png',
		'images/chevron-sm.png',
		'images/chromode-fl-off.png',
		'images/chromode-fl-on.png',
		'images/chromode-sh-off.png',
		'images/chromode-sh-on.png',
		'images/close-btn.png',
		'images/console-pause.png',
		'images/console-play.png',
		'images/console-rewind.png',
		'images/console-stop.png',
		'images/flip.png',
		'images/footer-bg.png',
		'images/header-bg.png',
		'images/info-active.png',
		'images/info.png',
		'images/list-button-active.png',
		'images/list-button.png',
		'images/listback-active.png',
		'images/listback.png',
		'images/palette-btn-active.png',
		'images/palette-btn.png',
		'images/playbtn-active.png',
		'images/playbtn.png',
		'images/prompt-arrow.png',
		'images/prompt-close.png',
		'images/spacer.gif',
		'images/spinner-large.gif',
		'images/spinner-small.gif',
		'images/toolbtn-active.png',
		'images/toolbtn.png'
	]
});

var spinner = '<div class="spinner">';
spinner	   += '<img src="images/spinner-small.gif" alt="" width="16" height="16" border="0" align="top"> Loading Song...';
spinner	   += '</div>';

function login()
{
	if ($('#loginform input:text').val()=='') {
		alert('You must enter your email.');
		return false;
	}
	else if ($('#loginform input:password').val()=='') {
		alert('You must enter your password.');
		return false;
	}
	
	var memory = $('#loginform #memory').attr('checked');
	var email = $('#loginform #email').val();
	
	$.post('mod/auth.php', $('#loginform').serialize(), function(data){
		if (data.error==0) {
			localStorage.isloggedin = true;
			localStorage.uid = data.uid;
			localStorage.uidenc = data.uidenc;
			if (memory)
				localStorage.email = email;
			else
				localStorage.removeItem('email');
			jqt.goTo('#mysongs', 'pop');
			//return false;
			//alert('done');
		}
		else {
			alert('Your username and/or password were not recognized. \rPlease try again.');
			$('#loginform #username').focus();
		}
	}, 'json');
	
	return false;
}

function logout()
{
	localStorage.removeItem('isloggedin');
	localStorage.removeItem('uid');
	localStorage.removeItem('uidenc');
	jqt.goTo('#gate', 'fade');
}

function wc_prompt()
{
	return; /////////////////////////////////////////////// debug
	if (promptshowing) return;
	chk1 = sessionStorage.getItem('wcPrompted');
	if ( chk1=='false' && re.test(navigator.userAgent) && !navigator.standalone ) { // prompt for web clip
		setTimeout('wc_show_prompt()', 3000);
	}
}

$(function(){

	$('#mysongs').bind('pageAnimationStart', function(e, info){
		if (info.direction=='in') {
			$.get('mod/mysongs.php', {'uid': localStorage.uid}, function(data){
				$('#mysongs .content').html(data);
				wc_prompt();
			}, 'html');
			//alert( localStorage.uid ); // works.
		}
		else if (info.direction=='out') {
			dismiss_prompt();
		}
	});
	
	$('#shared').bind('pageAnimationStart', function(e, info){
		if (info.direction=='in') {
			$.get('mod/shared.php', {'uid': localStorage.uid}, function(data){
				$('#shared .content').html(data);
				wc_prompt();
			}, 'html');
		}
		else if (info.direction=='out') {
			dismiss_prompt();
		}
	});

	$('#info').bind('pageAnimationStart', function(e, info){
		if (info.direction=='in') {
			$('.content',this).load('mod/info.html');
		}
	});

	$('#gate').bind('pageAnimationStart', function(e, info){
		//alert('gate ani start');
		if (info.direction=='in') {
			if (localStorage.email) {
				$('#loginform #memory').attr('checked', 'checked');
				$('#loginform #email').val( localStorage.email );
			}
		}
	});

	$('#gate').bind('pageAnimationEnd', function(e, info){
		if (info.direction=='in') {
			$('#loginform #email').focus();
		}
		if (info.direction=='out') {
			$('#loginform #email').val('');
			$('#loginform #password').val('');
		}
	});

	$('#song').bind('pageAnimationStart', function(e, info){
		var qstr = $(e.target).data('referrer').attr('id');
		//$('#song .content').html(spinner);////////////////////////////////////////////////////////
		if (info.direction=='in') {
			$.get('mod/song.php', {'uid': localStorage.uid, 'sid': qstr}, function(data){
				SongProps = data.Props;
				SongProps.chordpatt = new RegExp(data.Props.chordpatt, "i");
				
				$('#song .content').html(data.htmlstr);

				$('.staff, .staff *').each(function(){
					left = parseInt( $(this).css('left') );
					top = parseInt( $(this).css('top') );
					w = ($(this).width()/2)+'px';
					h = ($(this).height()/2)+'px';
					$(this).css( {'width': w, 'height': h, 'left': (left/2), 'top': (top/2) } ); /// 
				});
				chk = sessionStorage.getItem('orientationPrompted');
				if ( !promptshowing && chk=='false' && window.orientation==0 ) {
					setTimeout('o_prompt()', 3000);
				}
			}, 'json');
		}
		else if (info.direction=='out') {
			$('#tools').css('display', 'none');
			dismiss_prompt();
		}
	});

	$('#song').bind('pageAnimationEnd', function(e, info){
		if (info.direction=='out') {
			$('#song .content').css({'-webkit-transform':'translateY(0px)'});
			resetscroll();
			$('#song .content').html(spinner); // reset
			$('#song .back').removeClass('active');
		}
	});

});

$(document).ready(function(){

	sessionStorage.wcPrompted = 'false';
	sessionStorage.orientationPrompted = 'false';
	$('#song .content').html(spinner); // init song display

	if (!navigator.standalone && re.test(navigator.userAgent)) {
		$('.vertical-scroll.use-bottom-toolbar').css('height', '346px !important'); // 424-34-44 
		$('.landscape .vertical-scroll.use-bottom-toolbar').css('height', '197px !important');
	}
	
	if (localStorage.isloggedin) {
		jqt.goTo('#mysongs', 'pop');
	}
	else {
		jqt.goTo('#gate', 'fade');
	}
});

////////////////////////////////////////////////////////////////////////////
// prompts

var promptshowing = false;

function wc_show_prompt()
{
	if (promptshowing) return;
	promptshowing = true;
	sessionStorage.wcPrompted = 'true';
	var dialog 	= '<div id="prompt">';
	dialog	   += '<div id="dismiss" onclick="dismiss_prompt();"><\/div>';
	dialog	   += 'To install this web app on&nbsp;your phone: tap&nbsp;<b style="font-size:14px;">+<\/b> and then <b>\'Add to Home Screen\'<\/b>';
	dialog	   += '<div align="center" style="padding-top: 5px; margin-bottom: -5px;"><img src="images/prompt-arrow.png" alt="" width="39" height="10" border="0"><\/div>';
	dialog	   += '<\/div>';
	$('body').append(dialog);
	var prompt = $('#prompt');
	var start = window.orientation==0 ? 416 : 268; // -- 480-20-44, 320-20-32
	promptheight = prompt.height()+20; // includes shadow???
	var end = start-promptheight-30;
	prompt.css({'top': start+'px', 'display': 'block', 'opacity': 0 });
	prompt.animate(
		{'top': end+'px', 'opacity': 1.0 }, 800, 'swing', 
		function(){
			setTimeout('dismiss_prompt()', 10000);
		}
	);
}

function dismiss_prompt()
{
	if (!promptshowing) return;
	promptshowing = false;
	$('#prompt').fadeOut(200, function(){
		$('#prompt').remove();
	});
}

function o_prompt()
{
	if (promptshowing) return;
	if (window.orientation==0) { // check first to see if window has been rotated
		promptshowing = true;
		sessionStorage.orientationPrompted = 'true';
		var dialog 	= '<div id="prompt">';
		dialog	   += '<div id="dismiss" onclick="dismiss_prompt();"><\/div>';
		dialog	   += '<b>Tip:</b> rotate your device horizontally for the best viewing experience.';
		dialog	   += '<div align="center" style="margin-top: 5px;"><img src="images/flip.png" alt="" width="76" height="47" border="0"><\/div>';
		dialog	   += '<\/div>';
		$('body').append(dialog);
		var prompt = $('#prompt');
		prompttop = (460-34-prompt.height())/2; // includes shadow???
		prompt.css({'top': prompttop+'px'});
		prompt.fadeIn();
		setTimeout('dismiss_prompt()', 8000);
	}
}

////////////////////////////////////////////////////////////////////////////
// effects

function toggle_tools()
{
	var state = $('#tools').css('display');
	if (state=='block') {
		$('#tools').fadeOut();
		$('#toolbtn').removeClass('active');
	}
	else {
		$('#toolbtn').addClass('active');
		$.get('mod/toolbar.inc.php', {'instrument': SongProps.instrument, 'chromode': SongProps.chromode}, function(data){
			$('#tools').html(data);
			$('#tools').fadeIn();
		}, 'html');
	}
}

function change_instrument(i)
{
	if (i==SongProps.instrument) return;
	$('#i_'+SongProps.instrument).removeClass('hilite');
	$('#i_'+i).addClass('hilite');
	var re = new RegExp("/"+SongProps.instrument+"/", "i");
	$('.tab_window > img').each(function(){
		oldimg = $(this).attr('src');
		if (oldimg.search(re) != -1) {
			newimg = oldimg.replace(re, '/'+i+'/');
			$(this).attr('src', newimg);
		}
	});
	SongProps.instrument = i;
}

var keyshift = 0;
var dirs = ['up','down'];

function change_key(d)
{
	shift = 0;
	for (var x=0; x<dirs.length; x++)
		$('#key-'+dirs[x]).attr('src', 'images/arrow-'+dirs[x]+(dirs[x]==d?'-active':'')+'.png');
	$('.tab_window > img').each(function(){
		oldimg = $(this).attr('src');
		pts = oldimg.match(SongProps.chordpatt);
		if (pts) {
			n = SongProps.famsequence[SongProps.chromode][pts[1]];
			if (d=='up')
				newkey = n==11 ? 0 : n+1; // up
			else
				newkey = n==0 ? 11 : n-1; // down
			newimg = oldimg.replace(SongProps.chordpatt, SongProps.families[SongProps.chromode][newkey]+'-'+pts[2]+pts[3]);
			$(this).attr('src', newimg);
			shift = d=='down' ? -1 : 1;
		}
	});
	keyshift += shift;
	if (keyshift == 12 || keyshift == -12) keyshift=0;
	poff = (keyshift>=0 ? '+' : '')+keyshift+((keyshift<10 && keyshift>-10) ? '&nbsp;':'');
	$('#pitch_offset').html(poff);
}

function chromatics_flip(mapto)
{
	if (mapto == SongProps.chromode) return;
	$('#i_'+SongProps.chromode).removeClass('hilite');
	$('#chromode-'+SongProps.chromode).attr('src', 'images/chromode-'+SongProps.chromode+'-off.png');
	$('#i_'+mapto).addClass('hilite');
	$('#chromode-'+mapto).attr('src', 'images/chromode-'+mapto+'-on.png');
	var map = SongProps.cmap[mapto];
	$('.tab_window > img').each(function(){
		oldimg = $(this).attr('src');
		pts = oldimg.match(SongProps.chordpatt);
		if (pts && pts.length>0) {
			if (map[pts[1]]) {
				newimg = oldimg.replace(SongProps.chordpatt, map[pts[1]]+'-'+pts[2]+pts[3]);
				$(this).attr('src', newimg);
			}
		}
	});
	SongProps.chromode = mapto;
}


////////////////////////////////////////////////////////////////////////////
// scroller feature

var timerID = null;
var timerrunning = false;
/* var scrollspeeds = {
					49 : [ 1, 'Very Slow'], // 1 - ppms = .00900
					50 : [ 2, 'Slow'], 		// 2 - ppms = .06720
					51 : [ 3, 'Medium'], 	// 3 - ppms = .12540
					52 : [ 4, 'Fast'],		// 4 - ppms = .18360
					53 : [ 5, 'Very Fast']	// 5 - ppms = .24180
					}; // interval (msecs) : [ pixels, label ] */
/* var currentspeed = 51; */

var swintop = 0;
var swinlimit = 0;

function scrollit(scrollreq)
{
	if (timerrunning) {
		swintop+=1;
		$('#song .content').css({'top': '-'+swintop+'px'});
		if ( swintop==swinlimit )
			stopscroll();
	}
}

function stopscroll()
{
	clearInterval(timerID);
	timerrunning = false;
}

function resetscroll(ani)
{
	stopscroll();
	swintop = 0;
	if (ani) {
		$('#song .content').animate( {'top': '0px'}, 200, 'swing' );
	}
	else {
		$('#song .content').css({'top': '0px'});
	}
	$('#song .content').unbind('click');
	$('#btnbar').fadeIn();
	$('#playbtn').removeClass('active');
}

function play_mode(scrollreq) // NEW
{
	swinlimit = $('#song .content').height()-window.innerHeight+10;
	
	timerID = setInterval('scrollit()', 65);
	timerrunning = true;
	
	$('#btnbar').fadeOut();

	$('#song .content').bind('click', function(){
		resetscroll(true);
	});

}

