var game = new GameOfLife (); /* Instancja gry */

function initOptionsDlg () {
    var intervalSlider      = $("#interval");
    var intervalLbl         = $("#interval_val");
    var vCellAmountSlider   = $("#verticalCellAmount");
    var vCellAmountLbl      = $("#verticalCellAmount_val");
    var hCellAmountSlider   = $("#horizontalCellAmount");
    var hCellAmountLbl      = $("#horizontalCellAmount_val");

    intervalSlider.slider ({
        value:  game.getOption ("interval") / 1000,
        min:    0.25,
        max:    2.0,
        step:   0.25,
        range:  "min",
        slide:  function (event, ui) {
            intervalLbl.text (ui.value + "s");
        }
    });
    intervalLbl.text (game.getOption ("interval") / 1000 + "s");
        
    vCellAmountSlider.slider ({
       value:   game.getOption ("cols"),
       min:     10,
       max:     64,
       range:   "min",
       slide:   function (event, ui) {
            vCellAmountLbl.text (ui.value);
			hCellAmountSlider.slider ("value", ui.value);
			hCellAmountLbl.text (ui.value);
       }
    });
    vCellAmountLbl.text (game.getOption ("cols"));

    hCellAmountSlider.slider ({
       value:   game.getOption ("rows"),
       min:     10,
       max:     64,
       range:   "min",
       slide:   function (event, ui) {
            hCellAmountLbl.text (ui.value);
			vCellAmountSlider.slider ("value", ui.value);
			vCellAmountLbl.text (ui.value);
       }
    });
    hCellAmountLbl.text (game.getOption ("rows"));
    
    $("#optionsDlg").dialog ({
        autoOpen:   false,
        modal:      true,
        title:      "Opcje gry",
        width:      400,
        resizable:  false,	
        buttons:    {
            "Anuluj":   function () {
                intervalSlider.slider    ("option", "value", game.getOption ("interval") / 1000);
                hCellAmountSlider.slider ("option", "value", game.getOption ("cols"));
                vCellAmountSlider.slider ("option", "value", game.getOption ("rows"));
                
                $(this).dialog ("close");
            },
            "Zastosuj": function () {
                $("#restart").click ();
                var options = new Array ();
                if (intervalSlider.slider ("value") * 1000 != game.getOption ("interval"))
                    options["interval"] = intervalSlider.slider ("value") * 1000;
                if (vCellAmountSlider.slider ("value") != game.getOption ("cols"))
                    options["cols"] = vCellAmountSlider.slider ("value");
                if (hCellAmountSlider.slider ("value") != game.getOption ("rows"))
                    options["rows"] = hCellAmountSlider.slider ("value");
                
				game.setOptions (options);
			                
                $(this).dialog ("close");
            }
        }
    });	
}

function initAboutDlg () {
        $(".tabs").tabs ();
        $("#aboutDlg").dialog ({
            autoOpen:   false,
            modal:      false,
            title:      "O grze",
            width:      530,
            height:     450,
            resizable:  false,
            buttons:    {
                "Zamknij":  function () {
                    $(this).dialog ("close");
                }
            }
        });
}

function initLoadDlg () {
	$(".tabs").tabs ();
	$("#loadDlg").dialog ({
		title: 		"Wczytaj grę",
		autoOpen:	false,
		resizable:	false,
		modal: 		true,
		width: 		600,
		buttons: 	{
			"Anuluj": 	function () {
				$(this).dialog ("close");
			},
			"Wczytaj":	function () {
				game.load ($("textarea", this).val (), $("#loadFormat").val ());
				game.centerPattern ();
				$(this).dialog ("close");
			}
		}
	});
}

function initSaveDlg () {
	var dataToCopy = $("#dataToCopy");
	var format = $("#saveFormat").change (setDataToCopy);
	var stepToSave= $("#stepToSave").change (setDataToCopy);
	
	function setDataToCopy () {
		dataToCopy.val (game.save (format.attr ("value"), stepToSave.attr ('selectedIndex')));
		dataToCopy.get(0).select ();		
	}
	
	$("#saveDlg").dialog ({
		title: 		"Zapisz grę",
		autoOpen: 	false,
		resizable: 	false,
		modal: 		true,
		width: 		500,
		open:		setDataToCopy,
		buttons: {
			"Zamknij": function () {
				$(this).dialog ("close");
			}
		}
	});	
}

$(document).ready (function () {					        
        /* Okna: */
        initOptionsDlg ();
        initAboutDlg ();
        initLoadDlg ();
		initSaveDlg ();

		/* Toolbar itp: */        
		var counter = 0;
		
        $("#start").click (function () {
			if (counter == 0) /* Play */ 
			{ 
            	counter = setInterval (game.doStep, game.getOption("interval"));
				
				/* Zapisujemy w ciasteczkach wzór poczatkowy... */
				$.cookie ("lastPattern", game.save ("rle"));
				
				$("span", this).removeClass ("ui-icon-play").addClass ("ui-icon-pause");
			}
			else /* Pause */
			{
	            clearInterval (counter);
	            counter = 0;
				
				$("span", this).removeClass ("ui-icon-pause").addClass ("ui-icon-play");				
			}
            return false;
        });
        
        $("#nextStep").click (function () {
            if (counter == 0) 
			{
				if (game.getStats().step == 0) 
					$.cookie("lastPattern", game.save("rle"));
				game.doStep();
			}
            return false;
        });
        
        $("#restart").click (function () {
            clearInterval (counter);
            counter = 0;
			if (game.getStats().aliveCells != 0 && game.getStats().step == 0) 
			{
				if (confirm("Czy napewno chcesz zabić wszytskie żywe komórki ?")) 
				{
					game.clear();
					$.cookie("lastPattern", null);
				}
			}
			else 
				game.backToInit();
				
			$("#start span").removeClass ("ui-icon-pause").addClass ("ui-icon-play");	
            return false;
        })

		$("#zoomIn").click (function () {
			var cells = $("#playground td");
			if ($.browser.safari)						
				cells.height (cells.height () + 1).width (cells.width () + 1);
			else 
				cells.height (cells.height () + 3).width (cells.width () + 1);			
			return false;
		});
		
		$("#zoomOut").click (function () {
			var cells = $("#playground td");
			if ($.browser.safari)						
				cells.height (cells.height () - 1).width (cells.width () - 1);
			else
				cells.height (cells.height () + 1).width (cells.width () - 1);
			return false;					
		})

		$("#tools").menu ({
			content: 	$("#toolsMenu").html (),
			width: 		195,
			onChooseItem: function (item) {
				if (counter != 0)
					$("#start").click ();
				switch (item) {
					case "Wyśrodkuj wzór": {
						game.centerPattern ();					
					} break;
				}
			}			
		});

		$("#stats").hover (
			function () {
				$(".ui-icon", this).css ("visibility", "visible")
			},
			function () {
				$(".ui-icon", this).css ("visibility", "hidden")
			}
		).toggle (
			function () {
				$("#aliveCellsCounter", this).show ();
				
				$(".ui-icon", this).removeClass ("ui-icon-triangle-1-e").addClass ("ui-icon-triangle-1-w");

				$(this).width ($(this).width () + 70);				
				$("#interface").width ($("#interface").width () + 70);				
			},
			function () {
				$("#aliveCellsCounter", this).hide ();
				
				$(".ui-icon", this).removeClass ("ui-icon-triangle-1-w").addClass ("ui-icon-triangle-1-e");
				
				$(this).width ($(this).width () - 70);
				$("#interface").width ($("#interface").width () - 70);
			}
		);					        
		
		$("#menu").menu ({
			content: 	$("#mainMenu").html (),
			width: 		195,
			onChooseItem: function (item) {
				if (counter != 0)
					$("#start").click (); //Pauza gry
				switch (item) {
					case "Wczytaj gre": {
						$("#loadDlg").dialog ("open");
					} break;
					case "Zapisz gre": {
						$("#saveDlg").dialog ("open")
					} break;
					case "Preferencje": {
						$("#optionsDlg").dialog ("open");
					} break;
					case "O grze": {
						$("#aboutDlg").dialog ("open");
					}
				}				
			}			
		});		
									    
        /* Inicjalizujemy gre w życie */
        game.init ($("#playground"), {
			onStatsUpdate: function () {
				var stats = game.getStats();				
				
				/* Uaktualniamy liczniki */
				$("#stepCounter").text ("Krok: " + stats.step);
				$("#aliveCellsCounter").text ("Żywych: " + stats.aliveCells)
			},
			onStep : function () {
				if (game.getStats().aliveCells == 0)
				{
					if (counter != 0) 
						$("#start").click ();
				}			
			}
		});
		
		/* Przywracamy ostatni wzór zapisany w ciasteczkach... */
		if ($.cookie ("lastPattern") != null) 
		{
			game.load ($.cookie ("lastPattern"), "rle");
			game.centerPattern ();
		}		
	}
);