var sudoku=new Array();
var level='veryeasy';

function setCookie(key, value, options) {
	if (window.widget) {
		return window.widget.setPreferenceForKey(value,key);
	} else {
		return $.cookie(key,value,options);
	}
}

function getCookie(key) {
	if (window.widget) {
		return window.widget.preferenceForKey(key);
	} else {
		return $.cookie(key);
	}
}

function createSudoku() {
	sudoku=new Array();
	for (var i = 0; i < size*size; i++) {
		sudoku[i]=new Array();
	}
	var empty;
	if (getCookie('sudoku')) {
		loadGame();
		empty=false;
	} else {
		shuffleSudoku();
		empty=true;
	}

	for (var i=0;i<9;i++) {
		for (var j=0; j<9; j++) {
			if ($(template).attr(level).grid[i][j]==1) {
				$('#cell-'+i+'-'+j)
					.setCellValue(sudoku[i][j])
					.addClass('fixed');
			} else {
				if (empty==true) {
					$('#cell-'+i+'-'+j)
						.setCellValue('')
						.removeClass('fixed');
				};
			}
		}
	}
	checkSudoku();
}

function shuffleSudoku() {
	var grid = 0;
	for(var i = 0; i < size; i++, grid++) {
		for(var j = 0; j < size; j++, grid+=size) {
			for(var k = 0; k < size*size; k++, grid++) {
				sudoku[size*i+j][k] = (grid % (size*size)) + 1;
			}
		}
	}
	
	for(var i=0;i<size*size;i=i+size){
		for(var j=0;j<size;j++){
			row1 = Math.floor(Math.random()*(size-1));	
			row2 = Math.floor(Math.random()*(size-1));	
			if(row2>=row1){
				row2 = row2+1;	
			}
			row1 = row1 + i;
			row2 = row2 + i;			
			var temp = new Array();
			temp = sudoku[row1];
			sudoku[row1] = sudoku[row2];
			sudoku[row2] = temp;
			
			col1 = Math.floor(Math.random()*(size-1));	
			col2 = Math.floor(Math.random()*(size-1));	
			if(col2>=col1){
				col2 = col2+1;	
			}
			col1 = col1 + i;
			col2 = col2 + i;
			var temp=0;
			for (var k=0; k<size*size; k++) {
				temp=sudoku[k][col1];
				sudoku[k][col1]=sudoku[k][col2];
				sudoku[k][col2]=temp;
			}

			
		}			
	}
}

function sudokuNotFinished() {
}
function saveGame(filled) {
	filled=$(filled).not('.fixed');
	if (!(filled.length>0)) {
		setCookie('sudoku',null,{path:'/'});
		return;
	}
	var date = new Date();
	date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
	
	var save={
		level: level,
		grid: new Array(),
		sudoku: sudoku
	};
	
	$(filled).not('.fixed').each(function() {
		var rowcol=$(this).getRowCol();
		if (typeof(save.grid[rowcol[0]])!=='object') {
			save.grid[rowcol[0]]=new Array();
		}
		save.grid[rowcol[0]][rowcol[1]]=$(this).getCellValue();
	});
	
	setCookie('sudoku', JSON.stringify(save), { path: '/', expires: date });
}

function loadGame() {
	if (getCookie('sudoku')) {
		var load=JSON.parse(getCookie('sudoku'));
	} else {
		var load={};
	}
	sudoku=load.sudoku;
	level=load.level;
	$(load.grid).each(function(row) {
		$(this).each(function(col){
			if (this>=0 && row>=0 && col>=0) {
				$('#cell-'+row+'-'+col).setCellValue(this);
			}
		});
	});
}

function checkSudoku() {
	//saving scheme
	filled=$('.cell:sudokuFilled');
	saveGame(filled);
	
	
	if(filled.length!=size*size*size*size) {
		sudokuNotFinished();
		return false;
	};
	if($('.cell.warning,.cell.warning-row,.cell.warning-col,.cell.warning-block').length>0) {
		sudokuNotFinished();
		return false;
	}
	
	animateReady();
	
	
	setCookie('sudoku',null,{path:'/'});
	if (getCookie('sudokulevels')) {
		var levels=JSON.parse(getCookie('sudokulevels'));
	} else {
		var levels=null;
	}
	if (levels===null) {
		levels={};
	}
	eval('levels.level_'+level+'=true;');
	var date = new Date();
	date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
	setCookie('sudokulevels', JSON.stringify(levels), { path: '/', expires: date });
	
	$('#end-game').show();
	$('#end-game #end-level').html($(template).attr(level).name);
	welcomeScreen(true);
}

function animateReady() {
}

function hideSelector() {
	$('#overlay').hide();
	$('#selector').animate({top:'480px'},'fast');
}
function showSelector() {
	$('#overlay').css({'opacity':0.3}).show();
	$('#selector').animate({top:'300px'});
	$('.select div.status').bind('click',function(e) {
		hideSelector();
	});
}

function initSudoku(){
	$('#welcome-screen').hide();
	$('#menu').show();
	$('.cell').show();
	createSudoku();
	
};

function welcomeScreen(game_end) {

	if (getCookie('sudokulevels')) {
		var levels=JSON.parse(getCookie('sudokulevels'));
	} else {
		var levels=null;
	}
	if (levels===null) {
		levels={};
	}
	$("div.template").each(function() {
		if(eval('levels.level_'+$(this).attr('id').match(/template-([a-zA-Z0-9]+)/)[1])==true) {
			$(this).find('.name').toggleClass('green',true);
		};
	});
	
	$('.cell').hide();
	$('#menu').hide();
	$('#play-game').show();
	if (getCookie('sudoku')) {
		if (getCookie('sudoku')) {
			load=JSON.parse(getCookie('sudoku'));
		} else {
			load={};
		}
		$('#load-game').show();
		$('#load-game #load-level').html($(template).attr(load.level).name);
		$('#play-game').hide();
	} else {
		$('#load-game').hide();
	}
	if (game_end) {
		$('#end-game').show();
		$('#play-game').hide();
	} else {
		$('#end-game').hide();
	}
	$('#welcome-screen').show();
}

$(function() {
	if (!window.navigator.standalone) {
		$('body').css({'background-image':'none'});
		$('#install').show();
		$('#playground').hide();
		$('#welcome-screen').hide();
		return false;
	}
	
	$('#load-game').hide();
	$('#end-game').hide();
	$('#play-game').hide();

	if (false && !window.navigator.standalone) {
		$('body').css({'background-image':'none'});
		$('#playground').hide();
		$('#welcome-screen').hide();
		return false;
	}
	$.fn.getCellValue=function () {
		num=$(this).attr('class').match(/val-([0-9]+)/);
		if (num) {
			return num[1];
		} else {
			return false;
		}
	};
	$.fn.getRowCol=function () {
		num=$(this).attr('id').match(/cell-([0-9]+)-([0-9]+)/);
		if (num) {
			return [num[1],num[2]];
		} else {
			return false;
		}
	};
	
	$.fn.setCellValue=function (val) {
		$(this).attr('class',$(this).attr('class').replace(/val-[0-9]+/g,''));
		if (parseInt(val)>0) {
			return $(this).addClass('val-'+val);
		} else {
			return $(this);
		}
	};
	$.fn.delCellValue=function (val) {
		$(this).attr('class',$(this).attr('class').replace(/val-[0-9]+/g,''));
		return $(this);
	};
	
	$.fn.hasCellValue=function (val) {
		return $(this).getCellValue();
	};
	
	$.expr[ ":" ].sudokuFilled=function(obj,index,meta) {
		return $(obj).hasCellValue();
	};
	
	$.expr[ ":" ].sudokuValue=function(obj,index,meta) {
		return $(obj).getCellValue()==parseInt(meta[3]);
	};
	
	$('div.template').click(function() {
		level=$(this).attr('id').match(/template-([\w]+)/)[1];
		setCookie('sudoku', null, { path: '/' });
		initSudoku();
	});
	$('#load-game').click(function() {
		initSudoku();
	});
	
	$('#menu').click(function() {
		welcomeScreen();
	});
	
	$('div.template div.name').css({opacity:0.8});

	$('.cell:not(.fixed)').click(function() {
		if ($(this).hasClass('fixed')) {
			return false;
		}
		if ($(this).hasClass('select')) {
			hideSelector();
			$(this).removeClass('select');
			return;
		}
		$(this).addClass('select');
		$('#selector .option').removeClass('warning warning-row warning-cell warning-block');
		
		val=$('.cell.'+$(this).attr('class').match(/row-[\d]+/)+':sudokuFilled,.cell.'+$(this).attr('class').match(/col-[\d]+/)+':sudokuFilled,.cell.'+$(this).attr('class').match(/block-[\d]+/)+':sudokuFilled');
		val=val.not(this);
		if (typeof val === 'object') {
			$.each(val, function(i,v) {
				$('#selector .option.'+$(v).attr('class').match(/val-[\d]+/)).addClass('warning',true);
			});
		}
		
		
		showSelector();
		$('#parent').html($(this).attr('id'));
	});
	
	$('.option,#overlay').click(function() {
		$('.select').removeClass('select');
		var id='#'+$('#parent').html();
		var num=parseInt($(this).attr('id').match(/\d+/));
		var old_num=$(id).getCellValue();
		$(id).setCellValue(num);
		hideSelector();

		row=$('.'+$(id).attr('class').match(/row-[\d]+/)+':sudokuValue('+num+')');
		if (row.length>1) {
			row.toggleClass('warning-row',true);
		} else {
			$(id).toggleClass('warning-row',false);
		}
		row=$('.'+$(id).attr('class').match(/row-[\d]+/)+':sudokuValue('+old_num+')');
		if (row.length>1) {
		} else {
			row.toggleClass('warning-row',false);
		}
		
		col=$('.'+$(id).attr('class').match(/col-[\d]+/)+':sudokuValue('+num+')');
		if (col.length>1) {
			col.toggleClass('warning-col',true);
		} else {
			$(id).toggleClass('warning-col',false);
		}
		col=$('.'+$(id).attr('class').match(/col-[\d]+/)+':sudokuValue('+old_num+')');
		if (col.length>1) {
		} else {
			col.toggleClass('warning-col',false);
		}
		
		block=$('.'+$(id).attr('class').match(/block-[\d]+/)+':sudokuValue('+num+')');
		if (block.length>1) {
			block.toggleClass('warning-block',true);
		} else {
			$(id).toggleClass('warning-block',false);
		}
		block=$('.'+$(id).attr('class').match(/block-[\d]+/)+':sudokuValue('+old_num+')');
		if (block.length>1) {
		} else {
			block.toggleClass('warning-block',false);
		}
				
		checkSudoku();
	});
	
	welcomeScreen();
});
