$(document).ready(function(){
    
    $.ajaxSetup({cache: false});

	$("#tabs").tabs({
			cookie: {},		

			ajaxOptions: {
				error: function(xhr, status, index, anchor) {
					$(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible.");
				}
			},
		
	   		select: function(event, ui) {
//				var div = ui.tab.id;
//				var id_sport = $(ui.tab).attr('rel');
            destroy('table.schema');
	   		},
	   		load: function(event, ui) {
			
				var id_sport = $(ui.tab).attr('rel');
				
	           //show basket
                if ($(ui.tab).hasClass('tabActivity'))      //tabActivity => no legend                
				    {
                    $("#basket_out").hide();
                    $("#activityBasketOut").show();
                    $("#legend_out").html('');
                    $(".weekNavigation").show();
                    }
                else
                    {
                    $("#legend_out").load("ajax/ajax.legend.php?id_sport="+id_sport);
                    $("#basket_out").load("ajax/ajax.basket.php").show();
                    $("#activityBasketOut").hide();
                    }

                if (id_sport == 'all')
                    {
                    $(".weekNavigation").hide();                        
                    }
                    
				//zablokování selectu s přehledem
				if (id_sport == 'all' || id_sport == 'summary' || $(ui.tab).hasClass('tabActivity'))
					{
					$("#prehled option:eq(0)").attr("selected", true);
					$("#prehled").attr('disabled', true);
					}
				else
					{
					$("#prehled").attr('disabled', false);				
					}

				//skrytí kalendáře
				if (id_sport == 'summary' || $(ui.tab).hasClass('tabActivity') || $("select#prehled").val()!='day')
					{
					$("#datepicker").hide();
					}
				else
					{
					var year=$("#year").val();
					var month=$("#month").val();
					var day=$("#day").val();
					$("#datepicker").show();
		   			}
			   }
		});

	$("select#prehled").change(function(){
		var index = $("#tabs").tabs("option", "selected");
		changeUrlTabs(true);
		$("#tabs").tabs("load", index);
	});

	//přednastavení prehled ze session
	var prehled = $("#schema_prehled").val();
	$("select#prehled option[value="+prehled+"]").attr('selected', true);


	function changeUrlTabs(resetActivityDate)
		{
		var year=$("#year").val();
		var month=$("#month").val();
		var day=$("#day").val();
		var pocet = $("#tabs").tabs("length");
		var prehled = $("#prehled").val();
		for (i=0; i<pocet; i++)
			{
			var $tabs = $('#tabs').tabs();
			var id_sport = $('#tabs a.tab:eq('+i+')').attr("rel");
			var activityTab = $('#tabs a.tab:eq('+i+')').hasClass('tabActivity');
            if (activityTab && resetActivityDate)
                reset_date = 1;
            else
                reset_date = 0;
            $("#tabs").tabs("url", i, "ajax/ajax.schema.php?day="+day+"&month="+month+"&year="+year+"&id_sport="+id_sport+"&prehled="+prehled+"&reset_date="+reset_date);				
			}
		}


	//calendar----
	var max_days = $("#max_day_future").attr("value");
	var days_forward = $("#days_forward").val();

	$("#datepicker").datepicker({
					minDate: 0, 
					maxDate: max_days,
					dateFormat: 'DD, d. m. yy',
					defaultDate: +days_forward,
					onSelect: function(dateText, inst)  {

														//alert(dateText);
														date_name=dateText.split(",");
														date_array=date_name[1].split(".");
														
														$("#day").val(parseInt(date_array[0]));
														$("#month").val(parseInt(date_array[1]));
														$("#year").val(parseInt(date_array[2]));
														var index = $("#tabs").tabs("option", "selected");
														changeUrlTabs(true);
														$("#tabs").tabs("load", index);
														}
				}, $.datepicker.regional['cs']);


   $("a.notAvailable").live('click', function(e){
        e.preventDefault();
        });
    
    //jquery dialog vložení do košíku pro aktivity
	$("a.slot:not(.notAvailable)").live('click', function(e){
	   e.preventDefault();
		
        $(".activityDialogMessage").html('');
        
		var cell = $(this).attr("rel");
		var parsed = cell.split("|");
  		var id_term = parsed[3];		//3 => id_activity_term
	  
        var backgroundColor = $(this).css('background-color');
        var textColor = $(this).css('color');
        $(".ui-dialog .ui-dialog-titlebar").attr('style', 'border: '+ backgroundColor+'; background: '+ backgroundColor + '; color: '+textColor +';');
        var activityName = $(this).children('span.name').text();
        var target = $(this);
		//stažení obsahu dialogu
  		$("#activityDialogContent .activityDesc").load("ajax/ajax.activity.php?id_term="+id_term, function(data){

	        var btns = {};
	        var vybratText = $("input[name=vybrat]").val();
            var zavritText = $("input[name=zavrit]").val();
	        //define buttons --------------
	        btns[vybratText + ' "' + activityName + '"'] = function(){ 
	    											
            
            $.get("ajax/ajax.basket.php", {action: 'add', cell: cell},
                 function(data){
       // alert(data);
                    var parsed = data.split("*");          //oddelovaci znak pro chybu a obsah
                    $(".activityDialogMessage").html(parsed[1]);
                    if (parsed[0] == 0)
                        {
						$("#activityDialog").dialog('option', 'buttons', { "Zavřít": function() { $(this).dialog("close");} });                           
                        }			         
                    
                    $(".activityBasket").html('<div id="activityBasketOut">' + parsed[2] + '</div><div class="cleaner"></div>');
	               });
                };
	        btns[zavritText] = function(){ 
	                        $(this).dialog('close'); 
                            };
	

	        $("#activityDialog").dialog('option', 'buttons', btns);
	        $("#activityDialog").dialog('option', 'title', activityName);
	        $("#activityDialog").dialog('option', 'hide', 300);
	        $("#activityDialog").dialog("open");                

		});
    });


    $("a.nextWeek, a.prevWeek").live('click', function(e){
        if (!$(this).hasClass('ui-state-disabled'))
            {
            e.preventDefault();
            
            var date = $(this).attr('rel');
            var parsed = date.split('|');
            
            $("#day").val(parseInt(parsed[0]));
            $("#month").val(parseInt(parsed[1]));
            $("#year").val(parseInt(parsed[2]));
            
            var index = $("#tabs").tabs("option", "selected");
            changeUrlTabs(false);
            $("#tabs").tabs("load", index);
            }
    });
	
    
    
	//schema click on empty or mark cell
	$("table.schema tr td a.empty").live('click', function(e){
        e.preventDefault();
        if (!$(this).hasClass('slot'))
            {
    		//var all = $("#selected_cell").val();
    		
    		if ($(this).hasClass('selected')) 
    			{
    			$(this).removeClass('selected');		//remove cell				
    			var cell = $(this).attr("rel");
    			var action = 'remove';
    			//all = all.replace(cell+",","");
    			}
    		else
    			{
    			$(this).addClass('selected');			//add cell
    			var cell = $(this).attr("rel");					
    			var action = 'add';
    			//all = all + cell + ",";					
    			}
            
            $("#basket_out").load("ajax/ajax.basket.php?action="+action+"&cell="+cell, function(){
                
            if ($(".noticeSubject").length>0)    //notice for dialog
                {
                 var content = $(".noticeContent").html();
                 $("#noticeDialogContent").html(content);
    			 $("#noticeDialog").dialog('option', 'title', $(".noticeSubject").text());
    			 $("#noticeDialog").dialog('option', 'hide', 300);
    			 $("#noticeDialog").dialog('option', 'buttons', {
    		 										
    										'Zavřít': function() {
    											$(this).dialog('close');
    										}
    			 });
                $("#noticeDialog").dialog("open");  
                } 
    
            //open login panel
            if ($("input[name=openLoginPanel]").length>0)
                {
            	// Expand Panel
            		$("div#panel").slideDown("slow");
            		$("ul.open").addClass('close');
            		$("ul.open").removeClass('open');
            		$("#toggle a").toggle();
                }
           });
        }       //end class slot
	});
	

    //terms dialog ---------
    
	$("a.showTermsDialog").click(function(e){

      var zavritText = $("input[name=zavrit]").val();
      var btnsTerms = {};
      btnsTerms[zavritText] = function(){ 
	                        $(this).dialog('close'); 
                            };

    $("#termsDialog").dialog('option', 'buttons', btnsTerms);
    $("#termsDialog").dialog('option', 'width', 600);
    $("#termsDialog").dialog("open");
   });    




	$("#noticeDialog, #activityDialog, #termsDialog").dialog({
	                modal: true,
				    autoOpen: false,
		 			width: 400,
		 			position: ['center', 80]
					});


	//--------------remove from basket
	$("td.tdBasketDelete a").live('click', function(e){
		
		e.preventDefault();
		var cell = $(this).attr('rel');
//		alert(cell);
        $("#basket_out").load("ajax/ajax.basket.php?action=delete&cell="+cell);	
		var index = $("#tabs").tabs("option", "selected");
		$("#tabs").tabs("load", index);
		
	});



/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
	//tooltip preview
	$(".tooltip, table.schema a").live('mouseover', function(e) { 

		var xOffset = 10;
		var yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		

//		$(this).live("hover", function(e) { 
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");


		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    });
	
	$(".tooltip, table.schema a").live('mouseout', function(e) {
			this.title = this.t;		
			$("#tooltip").remove();
	    });	
	
	$(".tooltip, table.schema a").live('mousemove', function(e){
		var xOffset = 10;
		var yOffset = 20;		

		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			


	//remove tooltip after click
	$("a.tooltip, table.schema a").live('click', function(){
		$("#tooltip").remove();
	});


	//submit reservation
	$(".buttonSubmit a").click(function(e){
		e.preventDefault();
		 $(this).closest("form").submit();
	})
	
	//multiuser selectboxy, vyblokování ---- 
	$("select.multiuser").change(function(){
		var i = 0;
	 	var active = $(this).attr('name');
	 	var id_user = $(this).val();
//	 	if (id_user != '' && id_user>0)
//			$("select.multiuser:not([name="+active+"]) option[value="+id_user+"]").removeAttr('selected');

		if (id_user != '' && id_user == 0)	//host
			{
			$(this).parent().parent().next().show();
			}
		else if (id_user == '' || id_user > 0)		//nic
			{
			$(this).parent().parent().next().hide();			
			}
	});

	
    $("input[name=defaultPricesYes]").live('click', function(){
       location.reload();
    });
    
	
	//destroy  element - clear DOM and jquery object
	function destroy(element)
		{
		if ($(element).length>0) {
			var des = $(element).remove();
			delete des;
			}
		}



	//ajax loader
	$( function  () { 
	 	// vhodně nastylovaný div vložím po načtení stránky 
	     $( '<div id="ajax-spinner"></div>' ).ajaxStart( function  () { 
	 		// po ajaxStartu ukážu 
	         $( this ).show(); 
	     }).ajaxStop( function  () { 
	 		// a při ajaxStopu schovám 
	         $( this ).hide(); 
	     }).appendTo( "body" ).hide(); 
 	}); 

	//$("#tabs").removeClass('ui-corner-all');

});



