/**
 * Zpracovani rezervace 2010-01-25
 * @author Petr Megac Svamberg <megac@email.cz> ICQ UIN:38535991
 * @version 2.1
 */
var kontrolniStr = "@#$%^&*";
var i = 0;
var pocetSelectu = 5;
var focusedSel = '';
var xmlSelIdMain = '#reservationSelect';
var fgC = []; 

	var lastSelectIndex = -1;
	var lastSelectName  = '';

$(document).ready(function(){
	// zacatek selectu
	$("input,select").live('focus',function(){
		if( $(this).attr('type') != 'button' && $(this).attr('type') != 'submit' && $(this).attr('type') != 'image' ){
			$(this).attr('style','');
		}
	});
	
	
	$(".showRooms")
		.live('focus',function(){
			if( lastSelectName == '' || lastSelectName != $(this).attr('name')){
				if( this.nodeName == 'SELECT'){
					lastSelectIndex = this.selectedIndex;
					lastSelectName = $(this).attr('name');
				}
			}
		})
		.live('change',function(){
			rezervaceChangeSettings(this);
		})
	;

	if( $('#obsah .napln').size() > 0 ){
		//$('#obsah .napln').css('position','inherit');
	}
	if( $('#hint').size() >0 ){
		$('#hint').appendTo('body');
	}
	if( $('#errorText.rezervaceError').size() > 0 ){
		var url = "#TB_inline?height="+($('#errorText.rezervaceError').height() +40)+"&width=450&inlineId=errorText&modal=true";
		tb_show("Chyba", url);
		if( $('#scrollTop').size()> 0){
			$.scrollTo( "#scrollTop", 600 );
		}else{
			$.scrollTo( "#obsah", 600 );
		}
	}
	$('.rezervace').live('mousemove',function(e){
		$('#hint').html( $('#id'+$(this).attr('title')).html() );
		//var pos = $(this).offset();
		var scroll = getScrollXY();
		var topPozice = e.pageY - $('#hint').height() - 10;
		var leftPozice = e.pageX + 20;
		if( $(window).width() < (e.pageX + $('#hint').width())){
			leftPozice = e.pageX - $('#hint').width() - 20;
		}
		if( topPozice < scroll[1]){
			topPozice = scroll[1] - 10;
		}
		$('#hint').css('top', topPozice );
		$('#hint').css('left',leftPozice );
		$('#hint').show();
	}).live('mouseout',function(){
		$('#hint').html('');
		$('#hint').hide();
	});
	// autorefresh
	var refreshInterval = 0;
	$('select[name=rezervaceRefreshInterval]').live('change',function(){
			refreshInterval = parseInt($(this).val());
			if(  refreshInterval > 0 ) {
				RezervaceAutoRefresh(refreshInterval, false);
			}
		});
		
	function RezervaceAutoRefresh( interval , automat ){
		if( interval > 0 ){
			if(  !automat || interval == refreshInterval ){
				LoadData();
				setTimeout(
					function() { 
						RezervaceAutoRefresh(interval, true); 
					}
					,interval*1000*60
				);
			}
		}
		
	}
	
	
	
	// nova rezervace
	$('.nova_rezervace').click(function(){
		var url = zacatekUrl + "reservations-admin-edit/?datum="+ $.base64Encode($('input[name=A__datum_od]').val())+"&keepThis=true&TB_iframe=true&height=auto&width=650";
		tb_show("Nový záznam", url);
	});
	
	$(".showNoteType")
		.change(function(){
			$('#NoteType').html($('#NoteTypeItem'+$('#reservationSelect2').attr("value")).html());
		})
	;
	// nastaveni poctu selectu

	
	// ukotveni velikosti selectboxu
	for( i = 1; i <= pocetSelectu; i++ ){
	   	$(xmlSelIdMain+i).css('width', $(xmlSelIdMain+i).css('width'));
	}
	// pamet pozadi
	for( i = 1; i <= pocetSelectu; i++ ){
		fgC[i] = $(xmlSelIdMain+i ).css('color');
	}
	$('#reload').live('click',function(){
		LoadData();
		$(this).blur(); 
		return false;
	});
	
	$('.date-pick-all-rez').livequery(function(){
		$(this).datepick(
			{
				monthsToShow: 1,
				dateFormat: 'dd.mm.yyyy',
				showStatus: true, 
			    showOn: 'slideDown',
			    //showWeeks: true, 
			    showOnFocus: true, 
			    onShow: $.datepick.showStatus,
			    onClose: LoadData,
			    //firstDay: 1, 
			    showOtherMonths: true, 			    
			    //renderer: $.datepick.weekOfYearRenderer,
			    rangeSelect: false,
			    showTrigger: '#calImg'
			}
		)
	});
	$('.date-pick-right-rez').livequery(function(){
		$(this).datepick(
			{ 
				minDate: 0,
				dateFormat: 'dd.mm.yyyy',
				showStatus: true, 
				showOn: 'slideDown',
				showWeeks: true,
			    renderer: $.datepick.weekOfYearRenderer,
				onClose: function(){ $(".showRooms").change(); },
				showTrigger: '#calImg'
			}
	    ); 
	});
	

	$('.reload').live('change',function(){
		LoadData();
	});
	$('#reloadBalicky').live('click',function(){
		LoadBalicky();
	});

	$('#reloadStorno').live('click',function(){
		LoadStorno();
	});

	$('.closeTB').click(function(){
		tb_remove();
	});
	
	if( $('#A__check_in_date').size() > 0 && $('#A__number_of_unit__index').size() > 0 ){
		LoadDataSelectBoxs($('#A__check_in_date').attr("value"),$('#A__number_of_unit__index').attr("value"));
	}
});
function PrevPage( v ){
	$('#dataSend').attr("value",v);
 	FormSendData($('#reservation'),true); 
}
// admin
function MDCloseProcessDiv(){
	$('#processDiv').css('display','none');
	$('#processDivStats').css('display','none');
	$('#processBalikDiv').css('display','none');
	$('#processStornoDiv').css('display','none');
}
var runLoadDataSelectBoxs = false;
function LoadDataSelectBoxs(datum,noc){
	if( datum == 0 ) return false;
	if( runLoadDataSelectBoxs ) return false;
	runLoadDataSelectBoxs = true;
	var getStr = 'ajax=1&r='+Math.round(Math.random()*1000)+'&datum='+ $.base64Encode(datum)+'&noc='+noc;
	if( typeof(regAdmin) !== 'undefined' ){
		getStr +='&allObj=1'
	}
	// oznaceni updatovanych selectu
	for( i = 1; i <= pocetSelectu; i++ ){
		if( $(xmlSelIdMain+i).size() > 0 ){
			$(xmlSelIdMain+i).addClass('loadInput');
		   	$(xmlSelIdMain+i).attr('disabled','disabled');
		   	getStr +='&sel'+i+'='+$(xmlSelIdMain+i).attr('value');
		}
	}
	if( focusedSel != '' ){
		getStr +='&f='+focusedSel;
	}
	getStr +='&hodina='+$('select[name=A__start_cas__index] option:selected').val()+'&id='+$('#idRez').attr('value');
	if( $('select[name=A__number_of_persons__index]').size() ){
		getStr +='&lidi='+$('select[name=A__number_of_persons__index] option:selected').val();
	}
   	if( typeof(LoadObjektuDoCB) == 'function'){
		if( $('.objectCB input').size() > 0 ){
			$('.objectCB input').each( function() {
				if($(this).attr('checked') ){ 
					getStr +='&'+$(this).attr('name')+'='+$(this).attr('value');
				}
			});
		}
	}
	// promenne selectu pro generator options
	$.ajax({
	    url: zacatekUrlHttps+'class/rezervace/xmlselectdata_rezervace.php',
	    type: 'POST',
	    data: getStr,
	    dataType: 'xml',
	    timeout: 30000,
	    error: function(){ mdAjaxLoadDataSelectBoxsError(); },
	    success:  function( xml ){  mdAjaxLoadDataSelectBoxsSuccess(xml); }
	});
}
var loadDataBezi = false;
LoadData = function(){
	if( !loadDataBezi ){
		loadDataBezi = true;
		$('#errorMsg').html('<h2 style="color:black">Probíhá přenos dat...</h2>');
		$('#processDiv').css('display','block');
		var getStr = 'A__datum_od='+$('#A__datum_od').attr('value') + '&A__pocet_dni__index='+$('#A__pocet_dni__index').attr('value');
		getStr +='&hodina='+$('select[name=A__start_cas__index] option:selected').val();
		if( $('select[name=A__number_of_persons__index]').size() ){
			getStr +='&lidi='+$('select[name=A__number_of_persons__index] option:selected').val();
		}
    	if( typeof(LoadObjektuDoCB) == 'function'){
    		if( $('.objectCB input').size() > 0 ){
    			$('.objectCB input').each( function() {
    				if($(this).attr('checked') ){ 
    					getStr +='&'+$(this).attr('name')+'='+$(this).attr('value');
    				}
    			});
    		}
    	}
		
	    $('#dataRezervace').html('');
		
		// promenne selectu pro generator options
		//alert(zacatekUrlHttps+'reservations-admin-cal/?'+getStr);
		$.ajax({
		    url: zacatekUrlHttps+'reservations-admin-cal/',
		    type: 'POST',
		    data: getStr,
		    dataType: 'html',
		    timeout: 30000,
		    error: function(){ mdAjaxLoadError(); },
		    success:  function(html){ mdAjaxLoadSuccess(html); }
		});
	}
}
function LoadBalicky(){
	$('#errorBalikMsg').html('<h2 style="color:black">Probíhá přenos dat...</h2>');
	$('#processBalikDiv').css('display','block');
	$('#processBalikDiv').css('height',$('#baliky').css('height'));
	$('#processBalikDiv').css('width',$('#baliky').css('width'));
	var getStr = '';

	// promenne selectu pro generator options
	$.ajax({
	    url: zacatekUrlHttps+'reservations-admin-balik-data/',
	    type: 'GET',
	    data: getStr,
	    dataType: 'html',
	    timeout: 30000,
	    error: function(){ mdBalikAjaxError(); },
	    success:  function(html){ mdBalikAjaxSuccess(html); }
	});
}
function LoadStorno(){
	$('#errorStornoMsg').html('<h2 style="color:black">Probíhá přenos dat...</h2>');
	$('#processStornoDiv').css('display','block');
	$('#processStornoDiv').css('height',$('#storno').css('height'));
	$('#processStornoDiv').css('width',$('#storno').css('width'));
	var getStr = '';
	// promenne selectu pro generator options
	$.ajax({
	    url: zacatekUrlHttps+'reservations-admin-storno-data/',
	    type: 'GET',
	    data: getStr,
	    dataType: 'html',
	    timeout: 30000,
	    error: function(){ mdStornoAjaxError(); },
	    success:  function(html){ mdStornoAjaxSuccess(html); }
	});
}
function RegBalicekEdit( o ){
	var id = 1;
	if( o ) {
		id = $(o).attr('title');
	}
	tb_show("Editace balíčku ID "+id, zacatekUrlHttps+"reservations-admin-balik/?idBalik="+id+"&keepThis=true&TB_iframe=true&height=auto&width=650","images/cart.jpg" );
}
function RegEditor( o ){
	var id = 1;
	if( o ) {
		id = $(o).attr('title');
	}
	tb_show("Editace záznamu ID "+id, zacatekUrlHttps+"reservations-admin-edit/?id="+id+"&keepThis=true&TB_iframe=true&height=auto&width=650","images/cart.jpg" );
}
function RegEditorNew( o ){
	var id = 1;
	if( o ) {
		id = $(o).attr('title');
	}
	tb_show("Nový záznam ", zacatekUrlHttps+"reservations-admin-edit/?&keepThis=true&TB_iframe=true&height=auto&width=650","images/cart.jpg" );
}

// fce pro update selectu
function mdAjaxLoadSuccess(htmlStr){
	loadDataBezi = false;
	$('#errorMsg').html('<h2 style="color:green">Přenos ukončen</h2>');
    $('#dataRezervace').html(htmlStr);
	MDCloseProcessDiv();
}
function mdBalikAjaxSuccess(htmlStr){
	$('#errorBalikMsg').html('<h2 style="color:green">Přenos ukončen</h2>');
    $('#dataBalik').html(htmlStr);
	MDCloseProcessDiv();
}
function mdStornoAjaxSuccess(htmlStr){
	$('#errorStornoMsg').html('<h2 style="color:green">Přenos ukončen</h2>');
    $('#dataStrono').html(htmlStr);
    setTimeout('MDCloseProcessDiv();',1000);
}
// error fce  
function mdAjaxLoadError(){
	loadDataBezi = false;
	$('#errorMsg').html('<h2 style="color:red">ERROR: selhal přenos dat.</h2>');
	setTimeout('MDCloseProcessDiv();',1000);
}
function mdBalikAjaxError(){
	$('#errorBalikMsg').html('<h2 style="color:red">ERROR: selhal přenos dat.</h2>');
	setTimeout('MDCloseProcessDiv();',1000);
}
function mdStornoAjaxError(){
	$('#errorStornoMsg').html('<h2 style="color:red">ERROR: selhal přenos dat.</h2>');
	setTimeout('MDCloseProcessDiv();',1000);
}
function ObjektEditor( o, id ){
	tb_show("Editace objektu ID "+id, "#TB_inline?height=170&amp;width=400&amp;inlineId=hiddenModalObjekt"+id+"&amp;modal=true","images/cart.jpg" );
}

// fce pro update selectu
function mdAjaxLoadDataSelectBoxsSuccess(xml){
   	var xmlSelId = '';
   	var lastVal = new Array();

   	$('select',xml).each(function() {
    	
    	var selectBox = $(this);
		// atributy
		var id = selectBox.attr('id');
		lastVal[id] = $(xmlSelIdMain+id).val();

		var selVal = selectBox.attr('selVal');
		var selEnabled = selectBox.attr('enabled');
		xmlSelId = xmlSelIdMain+id;
		var options = ''; 
    	var selItem = '';
    	var pocet = 0;
    	$(xmlSelId).empty();
    	if( id == 3 && typeof(LoadObjektuDoCB) == 'function'){
    		LoadObjektuDoCB(selectBox);
    	}
		$('option',selectBox).each(function() {
			pocet++;
			var itemVal = $('val',this).text();
			var itemText = $('name',this).text();
			var itemDisabled = $('disabled',this).text();
			var itemClass = $('class',this).text();
			if( itemDisabled != '' ) {
				itemDisabled = ' disabled="disabled" ';
			}
			if( itemClass != '' ) itemClass = ' class="'+itemClass+'" ';
			options += '<option value="' + itemVal+'"'+itemClass+itemDisabled+'>' + itemText + '</option>\n';

//			var option = new Option(itemText,itemVal);
//			option.className = itemClass;
//			option.text = itemText;
//			option.value = itemVal;
//			option.selected = (selVal == itemVal?true:false);
//			option.disabled = (itemDisabled == '1'?true:false);
//	        if ($.browser.msie) {
//	        	$(xmlSelId).append(option);
//	        }else {
//	        	$(xmlSelId).append(option, null);
//	        }
		});
		if( pocet < 1 ){ 
			selEnabled = '0';
		}
		if( selEnabled == '1' ){
			$(xmlSelId).attr('disabled','');
			$(xmlSelId).css('color','black');
			$(xmlSelId).html(options);	
			$(xmlSelId).val(selVal);
		}else{
			$(xmlSelId).attr('disabled','disabled');
			$(xmlSelId).css('color','red');
			$(xmlSelId).html('<option value="0"> obsazeno </option>');
			if( window.location.pathname.match(/reservations-admin-edit/)){
				$('#NoteType').html('');
			}else{
				$('#NoteType').html('<div class="errorBox"><p>Ve vybraný terním je bohužel celý objekt dle zaznamů již obsazen.</p><p><b>Prosím, kontaktujte nás pomocí kontaktního formuláře v sekci kontaktů</b> a mi se pokusíme najít vhodné řešení.</p>Děkujeme.</div>');
			}
		}
		
		var changeOption = false;
		var selSelect =  $(xmlSelId).eq(0);

		
		var selIndex = selSelect.selectedIndex;
		var newSelIndex = -1;
		var poradi = 0;
		$('option',selSelect).each(function() {
			if( this.className != 'disableOption' ){
				if( newSelIndex == -1 ){
					newSelIndex = poradi;
				}

			}else{
				if( $(this).attr('value')  == selVal || selVal == ''  ){
					changeOption = true;
				}
			}
			poradi++;
		});

		if( changeOption && newSelIndex > -1 ){
			selSelect[0].selectedIndex = newSelIndex;
		}
    });

	for( i = 1; i <= pocetSelectu; i++ ){
	   	if( $( xmlSelIdMain+i).size()> 0 ){
			$( xmlSelIdMain+i).removeClass('loadInput');
		   	$( xmlSelIdMain+i).attr('disabled','');
		   	if( lastVal[i] !=  $( xmlSelIdMain+i).val() ){
		   		// indikace autochange
		   		$( xmlSelIdMain+i)
		   			.css('border','1px solid #AAA')
		   			.animate({ 
		   				borderTopColor: "#AAA" 
		   				,borderLeftColor: "#AAA" 
		   				,borderRightColor: "#AAA" 
		   				,borderBottomColor: "#AAA"
		   			},100)
		   			.animate({ 
		   				borderTopColor: "#F00" 
		   				,borderLeftColor: "#F00" 
		   				,borderRightColor: "#F00" 
		   				,borderBottomColor: "#F00"
		   			},100)
		   			.animate({ 
		   				borderTopColor: "#AAA" 
		   				,borderLeftColor: "#AAA" 
		   				,borderRightColor: "#AAA" 
		   				,borderBottomColor: "#AAA"
		   			},100)
		   			.animate({ 
		   				borderTopColor: "#F00" 
		   				,borderLeftColor: "#F00" 
		   				,borderRightColor: "#F00" 
		   				,borderBottomColor: "#F00"
		   			},1000)
		   			.animate({ 
		   				borderTopColor: "#AAA" 
		   				,borderLeftColor: "#AAA" 
		   				,borderRightColor: "#AAA" 
		   				,borderBottomColor: "#AAA"
		   			},2000)
				;
		   	}
		}
	}

   	$('data',xml).each(function() {
		var totalPrice = $('total_price',this).text();
		$('#totalPrice').html(totalPrice);
    });
    runLoadDataSelectBoxs = false;    
    
}
// error fce  
function mdAjaxLoadDataSelectBoxsError(){
   	for( i = 1; i <= pocetSelectu; i++ ){
	   	if( $( xmlSelIdMain+i).size()> 0 ){
			$( xmlSelIdMain+i ).removeClass('loadInput');
		   	$( xmlSelIdMain+i).attr('disabled','');
	   	}
	}
   	runLoadDataSelectBoxs = false;   	
}
var rezervaceChangeSettings = function( o ){
	var changeOptionOK = false;
	var valueS = $(o).val();
	if( lastSelectIndex != o.selectedIndex ){
		changeOptionOK = true;
		var selBox = o;
		$('option[class=disableOption]',this).each(function() {
			if( valueS == $(this).attr('value')){
				changeOptionOK = false;
				var barva = $(selBox).parent('TD').css('background-color');
				$(selBox).parent('TD').css('background-color','red');
				$('.msgObsazeno').html('<strong style="color:white">OBSAZENO</strong>');
				$('#NoteType').html('Ve vybraný terním je celý objekt dle zaznamů již obsazen.<br/> Prosím kontaktujte nás pomocí kontaktního formuláře v sekci kontaktů a mi se vám pokusíme vyhovět.');
				$(selBox).parent('TD').animate( { backgroundColor: "white" },1000,null,
					function(){
						$('.msgObsazeno').html('');
					}
				);
			}
		});
		
	}
	
	if( changeOptionOK || o.nodeName != 'SELECT' ){
		if( o.nodeName == 'SELECT') lastSelectIndex = o.selectedIndex;
		focusedSel = $(o).attr('name');
		var ok = false;
		if( $('#A__check_in_date').size() > 0 && $('#A__number_of_unit__index').size() > 0 ){
			LoadDataSelectBoxs($('#A__check_in_date').attr("value"),$('#A__number_of_unit__index').attr("value"));
			$('.objectCB').html('Žádná data');
			ok = true;
		}
		if( $('#A__check_in_date').size() > 0 && $('#A__number_of_unit__index').size() == 0 ){
			LoadDataSelectBoxs($('#A__check_in_date').attr("value"),0);
			$('.objectCB').html('Žádná data');
			ok = true;
		}
		$('#NoteType').html($('#NoteTypeItem'+$('#reservationSelect2').attr("value")).html());
	}else{
		if( o.nodeName == 'SELECT'){
			o.selectedIndex = lastSelectIndex;
		}
	}
}

