/*
wp-sudoku-plus.js
*/

jQuery(document).ready(function(){sudResize();sudVfyNav()});

var sudAjaxUrl;
var sudMatrix = [];
for (y=0;y<9;y++) {
	sudMatrix[y] = Array();
	for (x=0;x<9;x++) {
		sudMatrix[y][x] = 0;
	}
}
var sudDone = false;
var sudBusy = false;
var sudErrors = 0;

function sudScanSingle() {

	if ( sudDone ) return;

	sudSetBusy();

	var y,x,n,v,c;

	for ( y = 0; y < 9; y++ ) {
		for ( x = 0; x < 9; x++ ) {
			v = 0;
			c = 0;
			for ( n = 1; n <= 9; n++ ) {
				if ( jQuery('#sud-button-'+y+'-'+x+'-'+n).css( 'visibility') != 'hidden' ) { //visible' && jQuery('#sud-button-'+y+'-'+x+'-'+n).css( 'display') == 'block' ) {
					v = n;
					c++;
				}
			}
			if ( c == 0 && sudMatrix[y][x] == 0 ) {
				jQuery( '.sud-item-box-' + ( y * 9 + x ) ).html( '<span style="color:red;" >X</span>' );
				sudFail();
				return;
			}
			if ( c == 1 ) {
				setTimeout( function() { sudSetValue( y, x, v ); }, 200 );
				return;
			}
		}
	}

	// Test for ready
	for ( y = 0; y < 9; y++ ) {
		for ( x = 0; x < 9; x++ ) {
			if ( sudMatrix[y][x] == 0 ) {
				return;
			}
		}
	}

	sudWin();
	sudDone = true;
}

// Mouse down
function sudMD( event, y, x, v ) {

	event.stopPropagation();
	event.preventDefault();

	if ( sudDone ) return;
	if ( sudBusy ) return;
	sudSetBusy();
	sudStckPush();

	// Left button
	if ( event.button == 0 ) {
		var b = parseInt( y / 3 ) * 3 + parseInt( x / 3 );
		var i = y * 9 + x;
		jQuery( '.sud-bby'+y+'v'+v ).css( 'visibility', 'hidden' );
		jQuery( '.sud-bbx'+x+'v'+v ).css( 'visibility', 'hidden' );
		jQuery( '.sud-bbb-'+b+'v'+v ).css( 'visibility', 'hidden' );
		for ( j=1;j<10;j++ ) {
			jQuery( '.sud-bby'+y+'x'+x+'v'+j ).css( 'visibility', 'hidden' );
		}
		jQuery( '.sud-item-box-'+i ).html('<div id="sud-'+i+'" class="sud-number" style="color:#007">'+v+'</div>' );
		sudMatrix[y][x] = v;
	}

	// Right button
	sudKillButton(y,x,v);

	// Test for trivial choices
	sudScanSingle();

	// Test for nav buttons
	sudVfyNav( v );
}

function sudKillButton(y,x,v) {

	if ( sudDone ) return;

	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).html('');
	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).attr('class', 'sud-bb');
	var s = jQuery( '#sud-button-'+y+'-'+x+'-'+v ).css('width');
	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).removeAttr('style');
	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).css({visibility: 'hidden', width: s, height: s });
	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).removeAttr('onclick');
	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).removeAttr('onmousedown');
	jQuery( '#sud-button-'+y+'-'+x+'-'+v ).removeAttr('onmouseup');
}

var sudButtonTimer;
var sudLastBtn;

// Touch start
function sudTS( y, x, v ) {

	if ( sudDone ) return;
	if ( sudBusy ) return;
	sudLastBtn = 'btn'+y+x+v;
	sudSetBusy();
	sudStckPush();

	sudButtonTimer = setTimeout( function () { sudProcessTimeout(y,x,v) }, 500 );
}

// Touch end
function sudTE( y, x, v, auto ) {

	var btn = 'btn'+y+x+v;
	if ( btn != sudLastBtn ) {
		return;
	}
	sudSetValue( y, x, v );
}

// Set the selcted value in the diagram etc
function sudSetValue( y, x, v ) {

	if ( sudDone ) return;
	sudSetBusy();

	if ( jQuery( '.sud-bby'+y+'x'+x+'v'+v ).css( 'visibility' ) == 'hidden' ) {
		return;
	}
	if ( sudMatrix[y][x] ) {
		console.log('should never get here');
//		return;
	}

	// Yes
	var b = parseInt( y / 3 ) * 3 + parseInt( x / 3 );
	var i = y * 9 + x;

	// Remove buttons
	jQuery( '.sud-bby'+y+'v'+v ).css( 'visibility', 'hidden' );
	jQuery( '.sud-bbx'+x+'v'+v ).css( 'visibility', 'hidden' );
	jQuery( '.sud-bbb-'+b+'v'+v ).css( 'visibility', 'hidden' );
	for ( j=1;j<10;j++ ) {
		jQuery( '.sud-bby'+y+'x'+x+'v'+j ).css( 'visibility', 'hidden' );
	}

	// Fill value in
	jQuery( '.sud-item-box-'+i ).html(v);
	sudMatrix[y][x] = v;

	// Test for trivial choices
	sudScanSingle();
	sudVfyNav();
}

// Mouse down end timer
function sudProcessTimeout(y,x,v) {

	jQuery( '.sud-bby'+y+'x'+x+'v'+v ).css( 'visibility', 'hidden' );
	sudButtonTimer = 0;

	// Test for trivial choices
	sudScanSingle();
	sudVfyNav();
}


function sudButtonDestroy(y,x,v,hit) {

	var b = parseInt( y / 3 ) * 3 + parseInt( x / 3 );
	jQuery( '.sud-bby'+y+'v'+v ).css( 'visibility', 'hidden' );
	jQuery( '.sud-bbx'+x+'v'+v ).css( 'visibility', 'hidden' );
	jQuery( '.sud-bbb-'+b+'v'+v ).css( 'visibility', 'hidden' );

	if ( hit ) sudMatrix[y][x] = v;

	sudKillButton(y,x,v);
}


function sudKeyboardHandler( e ) {
	if ( e == null ) { // ie
		keycode = event.keyCode;
		escapeKey = 27;
	} else { // mozilla
		keycode = e.keyCode;
		escapeKey = 27; //e.DOM_VK_ESCAPE;
	}
	var key = parseInt( String.fromCharCode( keycode ).toLowerCase() );

	sudHiLite( key );
}

function sudHiLite( key ) {
	if ( key >= 0 && key < 10 ) {
		for ( i=1;i<10;i++ ) {
			jQuery( '.sud-bbv'+i ).css( 'background-color', 'transparent' );
		}
		jQuery( '.sud-bbv'+key ).css( 'background-color', '#99f' );

	}
	jQuery( '.sud-navi-box' ).css( 'background-color', 'transparent' );
	if ( key > 0 ) jQuery( '.sud-navi-box-' + key ).css( 'background-color', '#99f' );
}

function sudVfyNav() {

	var key;
	var btns;
	var cnt = 0;
	for ( key = 1; key < 10; key++ ) {
		btns = jQuery( '.sud-bbv'+key );
		cnt = 0;
		for ( j=0;j<btns.length;j++ ) {
			if ( jQuery( btns[j] ).css( 'visibility' ) == 'visible' && jQuery( btns[j] ).css( 'display' ) != 'none' ) {
				cnt++;
			}
		}
		if ( cnt == 0 ) {
			jQuery( '.sud-navi-box-' + key ).css( { color: 'transparent', backgroundColor: 'transparent' } );
		}
	}

	sudUpdateUndo();

}

// Install keyboard handler
jQuery( document ).on( 'keydown', sudKeyboardHandler );

// Ajax fail
function sudFail() {

	if ( sudDone ) return;
	sudDone = true;
	sudErrors ++;

	sudUpdateUndo();

	if ( sudErrors < 3 ) return;

	sudDone = true;

	jQuery.ajax( { 	url: 		sudAjaxUrl,
					data: 		'action=wpsud' +
								'&wpsud-action=sudfail' +
								'&nonce=' + jQuery( '#nonce' ).val() +
								'&puzno=' + jQuery( '#puzno' ).val() +
								'&prevpuzno=' + jQuery( '#puzno' ).val(),
					async: 		true,
					type: 		'GET',
					timeout: 	10000,
					beforeSend: function( xhr ) {
									var html = '<img class="sud-small-spin" src="' + sudSmallSpinnerUrl + '" />';
									jQuery( '#lost' ).html( html );
								},
					success: 	function( result, status, xhr ) {
									jQuery( '#lost' ).html(result);
									var c = jQuery( '#totlost' ).html();
									jQuery( '#totlost' ).html( parseInt(c)+1 );
								},
					error: 		function( xhr, status, error ) {

								},
					complete: 	function( xhr, status, newurl ) {
									var r = jQuery( '#rating' ).val();
									var c = jQuery( '#sud-'+r+'-lost' ).html();
									jQuery( '#sud-'+r+'-lost' ).html( parseInt(c)+1 );


								}
				} );
}

// Ajax win
function sudWin() {

	if ( sudDone ) return;
	sudDone = true;
	jQuery( '#sud-navi-box-10' ).html( '' );
	jQuery( '#sud-navi-box-10' ).removeAttr( 'onclick' );

	jQuery.ajax( { 	url: 		sudAjaxUrl,
					data: 		'action=wpsud' +
								'&wpsud-action=sudwin' +
								'&nonce=' + jQuery( '#nonce' ).val() +
								'&puzno=' + jQuery( '#puzno' ).val() +
								'&prevpuzno=' + jQuery( '#puzno' ).val(),
					async: 		true,
					type: 		'GET',
					timeout: 	10000,
					beforeSend: function( xhr ) {
									var html = '<img class="sud-small-spin" src="' + sudSmallSpinnerUrl + '" />';
									jQuery( '#won' ).html( html );

								},
					success: 	function( result, status, xhr ) {
									jQuery( '#won' ).html( result );
									var c = jQuery( '#totwon' ).html();
									jQuery( '#totwon' ).html( parseInt(c)+1 );
								},
					error: 		function( xhr, status, error ) {

								},
					complete: 	function( xhr, status, newurl ) {
									var r = jQuery( '#rating' ).val();
									var c = jQuery( '#sud-'+r+'-won' ).html();
									jQuery( '#sud-'+r+'-won' ).html( parseInt(c)+1 );
									sudClearStack();
								}
				} );
}

// Set visibility and color of undo button according to error and stack status
function sudUpdateUndo() {

	var color;
	var title;
	var display;
	switch( sudErrors ) {
		case 1:
			color = 'yellow';
//			title = '1/3 mistakes';
			display = 'inline';
			break;
		case 2:
			color = 'orange';
//			title = '2/3 mistakes';
			display = 'inline';
			break;
		case 3:
			color = 'red';
//			title = '3/3 mistakes';
			display = 'none';

			jQuery( '#sud-navi-box-10' ).html( '' );
			jQuery( '#sud-navi-box-10' ).removeAttr( 'onclick' );

			break;
		default:
			color = 'transparent';
//			title = 'Undo';
			display = 'inline';
	}

	if ( sudStack.length == 0 ) {
		display = 'none';
	}

	jQuery( '#sud-navi-box-10' ).css( 'background-color', color );
	jQuery( '#sud-navi-box-10' ).attr( 'title', sudErrorText[sudErrors] );
	jQuery( '#sud-undo' ).css( 'display', display );
}

// Ajax get puzzle
function sudGetPuzzle( puzno, rating, data, size ) {

	if ( sudResized ) size = sudResized;

	jQuery.ajax( { 	url: 		sudAjaxUrl,
					data: 		'action=wpsud' +
								'&wpsud-action=sudget' +
								'&nonce=' + jQuery( '#nonce' ).val() +
								( puzno !== false ? '&puzno=' + puzno : '' ) +
								( rating ? '&rating=' + rating : '' ) +
								( data ? '&data=' + data : '' ) +
								'&prevpuzno=' + jQuery( '#puzno' ).val() +
								'&size=' + size,
					async: 		true,
					type: 		'GET',
					timeout: 	10000,
					beforeSend: function( xhr ) {
									jQuery( '#sud-ajaxspin' ).css( 'visibility', 'visible' );
								},
					success: 	function( xresult, status, xhr ) {
									var theResult;
									if ( typeof( xresult ) == 'string' ) {
										theResult = JSON.parse(xresult);
									}
									else {
										theResult = xresult;
									}
									var html = theResult.html;
									var js   = theResult.js;
									for (y=0;y<9;y++) {
										sudMatrix[y] = Array();
										for (x=0;x<9;x++) {
											sudMatrix[y][x] = 0;
										}
									}
									jQuery( '#sud-container' ).html(html+'<script>'+js+'</script>');
									jQuery( '#sud-ajaxspin' ).css( 'visibility', 'hidden' );
									sudResize();
								},
					error: 		function( xhr, status, error ) {
									document.location = url;
								},
					complete: 	function( xhr, status, newurl ) {
									sudDone = false;
									sudVfyNav();
									sudErrors = 0;
									sudClearStack();
									sudUpdateUndo();
								}
				} );
}

function sudReload( url, rating ) {

	if ( url.indexOf( '?' ) == -1 ) {
		url += '?rating=' + rating.replace( '+', 'P' );
	}
	else {
		url += '&rating=' + rating.replace( '+', 'P' );
	}

	document.location = url;
}

var sudResized = 0;
var sudMaxSize = 36;
function sudResize() {

	var availWidth 		= jQuery('#sud-container').parent().width();
	var sudButtonBox 	= 8;
	var result 			= 0;
	var sizes 			= sudResizeCompute( sudButtonBox );

	while ( sizes['sudMainBox'] < availWidth ) {
		sudButtonBox += 1;
		sizes = sudResizeCompute( sudButtonBox );
	}
	sudButtonBox -= 1;
	sudButtonBox = Math.min( sudButtonBox, sudMaxSize );

	sizes = sudResizeCompute( sudButtonBox );

	jQuery( '#sud-outer' ).css( { width: sizes['sudMainBox']+2 } );
	jQuery( '#sud-container' ).css( { width: sizes['sudMainBox'] } );
	jQuery( '#sud-nav-container' ).css( { width: sizes['sudMainBox'] } );

	jQuery( '.sud-bb' ).css( { width: sizes['sudButtonBox'], height: sizes['sudButtonBox'] } );
	jQuery( '.sud-bb' ).each(function() {
		jQuery(this).css( { lineHeight: sizes['sudButtonBox']+'px', fontSize: sizes['sudButtonBox']+'px' } );
	});

	jQuery( '.sud-item-box' ).css( { width: sizes['sudItemBox'], height: sizes['sudItemBox'] } );
	jQuery( '.sud-item-box' ).each(function() {
		jQuery(this).css( { lineHeight: sizes['sudItemBox']+'px', fontSize: sizes['sudItemBox']+'px' } );
	});

	jQuery( '.sud-block-box' ).css( { width: sizes['sudBlockBox'], height: sizes['sudBlockBox'] } );
	jQuery( '.sud-main-box' ).css( { width: sizes['sudMainBox'], height: sizes['sudMainBox'] } );

	jQuery( '#sud-container' ).css( { visibility: 'visible' } );
	jQuery( '.sud-navi-box' ).css( { height: sizes['sudMainBox'] / 11, lineHeight: ( sizes['sudMainBox'] / 11 )+'px', fontSize: sizes['sudMainBox'] / 15 } );
	jQuery( '#sud-navi-box-10' ).css( { height: sizes['sudMainBox'] / 11, lineHeight: ( sizes['sudMainBox'] / 11 )+'px', fontSize: sizes['sudMainBox'] / 15 } );

	jQuery( '#wp-sudoku-legenda' ).css( { width:  sizes['sudMainBox'] } );

	jQuery( '#sud-ajaxspin' ).css( {
		width: (sizes['sudItemBox']*2)+'px',
		height: (sizes['sudItemBox']*2)+'px',
		left: (sizes['sudMainBox']/2-sizes['sudItemBox'])+'px',
		top: (sizes['sudMainBox']/2-sizes['sudItemBox'])+'px' } );

	sudResized = sizes['sudButtonBox'];
	return;
}

function sudResizeCompute( sudButtonBox ) {

	var result = [];
	result['sudButtonBox'] = sudButtonBox;
	result['sudItemBox'] = 3 * sudButtonBox + 2;
	result['sudBlockBox'] = 3 * result['sudItemBox'] + 2;
	result['sudMainBox'] = 3 * result['sudBlockBox'] + 4;
	return result;
}

function sudToggle(id) {

	if ( jQuery('#'+id).css('display') == 'none' ) {
		jQuery('#'+id).css('display', 'block');
	}
	else {
		jQuery('#'+id).css('display', 'none');
	}
}

var sudStack = [];
var sudLastStackItem = '';
function sudStckPush() {

	var text = jQuery( '#sud-container' ).html();
	var pos = text.indexOf( '<!-- end -->' );
	if (pos > 0) text = text.substr(0, pos);
	console.log('stackframe lenth = '+text.length);
	sudStack.push( text );

	jQuery( '#sud-undo' ).css( 'display', 'inline' );
}

function sudStackPop(puzno, size) {

	jQuery( '#sud-container' ).html( sudStack.pop() );
	sudDone = false;
	sudUpdateUndo();
	jQuery( '#sud-busy-spin' ).css( 'display', 'none' );
}

function sudClearStack() {

	sudStack = [];
	sudLastStackItem = '';
	sudDone = false;
	sudBusy = false;
	jQuery( '#sud-busy-spin' ).css( 'display', 'none' );
}

var sudBusyTimer;
function sudSetBusy() {

	if ( sudBusyTimer ) {
		clearTimeout( sudBusyTimer );
	}
	sudBusy = true;
	jQuery( '#sud-busy-spin' ).css( 'display', 'inline' );
	sudBusyTimer = setTimeout( function() {
		sudBusy = false;
		jQuery( '#sud-busy-spin' ).css( 'display', 'none' );
	}, 500 );
}

var sudErrorText = [];