var COOKIE_SEARCH_DATE = 'SEARCH_DATE';
var COOKIE_SEARCH_NIGHTS = 'SEARCH_NIGHTS';


var STATUS_VoucherNou=1;
var STATUS_VoucherConfirmat=2;
var STATUS_VoucherPlatit=3;
var STATUS_VoucherAnulat=99;


function TD_SHOW_OFFER(oTD)
{
	$(oTD).parent().find('th a')[0].click();
}

//var old_ROOM_ID=null;
function TD_Over(oTD,offer_id)
{
  col=$(oTD).index()-1;
  row=$(oTD).parent().index();
  $(oTD).parent().parent().children(':not(:eq('+(row)+'))').find('td:eq('+col+')').each(function() {$(this).css('backgroundColor',facilitati_camere_bgColor)});
  $(oTD).parent().parent().children(':eq('+(row)+')').find('td:eq('+col+')').each(function() {$(this).css('backgroundColor','#000000')});
  room_id=$(oTD).parent().parent().children(':eq('+(0)+')').find('th:eq('+(col+1)+')').attr('id').replace('TH_','ROOM_');
  //alert(room_id);
//  old_ROOM_ID=$('#'+room_id).css('backgroundColor','#eefffb');
  try 
   {
	$("#facilitati_camere_"+offer_id).goToPage(col+1,false);
	$("#facilitati_camere_"+offer_id).autoScrollActive=false;
  } catch(e){}
}
function TD_Out(oTD,offer_id)
{
  col=$(oTD).index()-1;
  $(oTD).parent().parent().children().find('td:eq('+col+')').each(function() {$(this).css('backgroundColor','transparent')});
// if (old_ROOM_ID!=null)
//    old_ROOM_ID.css('backgroundColor','transparent');
  try 
   {
  $("#facilitati_camere_"+offer_id).mbAutoscroll();
  } catch(e){}
}


function changeCheckBoxSelection(obj)
{
	if ($(obj).attr('checked'))
	{
		$(obj).parent().parent().parent().find('[name='+$(obj).attr('name')+']:enabled').each(function () { if (this!=obj) $(this).attr('checked',false); });
	}	
}


var toolTipInfo = null;
function infoToolTip(caller,info)
{
  if (toolTipInfo==null)
  {
     $(document).append('<');
  }
}
//'#fcf2e9'
var facilitati_camere_bgColor="#ffffff";
$(document).ready(function(){
$(".facilitati_camere").mbScrollable({
   width:"550",
   elementsInPage:1,
   elementMargin:2,
   shadow:"#999 2px 2px 2px",
   height:"auto",
   slideTimer:50,
   autoscroll:true,
   scrollTimer:10000
 }); 
	facilitati_camere_bgColor=$('#oferta_hotel tr th:first').css('backgroundColor');
 });
 
    var next_checkin = new Date(new Date().getTime()  + 0*24*60*60*1000);
 
	$(document).ready( 
		function()
		{	
			
			//alert("cookie="+document.cookie)
			$(".template_SelectListMultiple").selectList({ sort: true ,
							onAdd: function () {setTimeout(getTotalOffers,0);},   
							onRemove: function () {setTimeout(getTotalOffers,0);}
						});
			
			function formatText(index, panel) {
			  return index + "";
			}
			
			
			selectDateField_Cookie('search_checkin',COOKIE_SEARCH_DATE,next_checkin);
			selectField_Cookie('search_nights',COOKIE_SEARCH_NIGHTS,7);
					

			$("#search_checkin").change(function(){getTotalOffers();});
			$("#search_nights").change(function(){getTotalOffers();});
			
			
			
			$(".template_ImageSlideGallery").ImageSlideGallery();

			var acfb = $("ul.first").autoCompletefb({urlLookup:All_DB_Keywords,acOptions:{width:145,onchange:function() { $('#form_search_hotel').submit();} }}); 
			
			$('.anythingSlider').anythingSlider({
                easing: "easeInOutCirc",        // Anything other than "linear" or "swing" requires the easing plugin
                autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
                delay: 5000,                    // How long between slide transitions in AutoPlay mode
                startStopped: false,            // If autoPlay is on, this can force it to start stopped
                animationTime: 600,             // How long the slide transition takes
                hashTags: true,                 // Should links change the hashtag in the URL?
                buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
        		pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
        		startText: "Go",             // Start text
		        stopText: "Stop",               // Stop text
		        navigationFormatter: formatText,       // Details at the top of the file on this use (advanced use)
				nextButtonTitle:"Urmatoarea Oferta",
				prevButtonTitle:"Oferta Anterioara"
            });
			
			setTimeout(getTotalOffers,10);
			
			Reservation_Load($('#content_section_reservation'),{action:'checkin_date',HotelID:$('#content_section_reservation').attr('HotelID')})
			
			$('#passwordLogin').keyup(function(event) 
			{
			  if (event.keyCode == '13') {
				 event.preventDefault();
				 $('#login_form form').submit();
			   }
			});


       	}
	);



function checkNextCheckINDate()
{
   
	$obj=$('#search_checkin');
	$search_checkin=$obj.val();
	next_checkin = new Date(new Date().getTime()  + 0*24*60*60*1000);
	//alert(next_checkin);
	tmp = $search_checkin.split('.');
	if (tmp.length==3)
	{
		tmp=new Date( tmp[2] , tmp[1]-1 , tmp[0]);
		if (tmp<next_checkin)
		{
		  $obj.datepicker( "setDate" , next_checkin )	
		  $search_checkin = $obj.val();
		}   
	}
	else
	{
		  $obj.datepicker( "setDate" , next_checkin )	
		  $search_checkin = $obj.val();
	}
//	$.cookie(COOKIE_SEARCH_DATE, $search_checkin)	;

}


function getTotalOffers()
{
	$('#search_button_div').html("Asteptati ...");
	
	$.ajax({
		url: getOffersPage,
		data:"search_price_min="+encodeURIComponent($("#search_price_min").val())+
			 "&search_price_max="+encodeURIComponent($("#search_price_max").val())+
			 "&search_checkin="+encodeURIComponent($("#search_checkin").val())+
			 "&search_nights="+encodeURIComponent($("#search_nights").val())+
			 "&search_locatie="+encodeURIComponent($.ui.SelectList.getSelectedList($("#search_locatie")))+
			 "&search_categorie="+encodeURIComponent($.ui.SelectList.getSelectedList($("#search_categorie")))+
			 "&search_camera="+encodeURIComponent($.ui.SelectList.getSelectedList($("#search_camera")))+
			 "&search_facilitati_masa="+encodeURIComponent($.ui.SelectList.getSelectedList($("#search_facilitati_masa")))+
			 "&search_facilitati_hotel="+encodeURIComponent($.ui.SelectList.getSelectedList($("#search_facilitati_hotel")))+
			 "&search_facilitati_camera="+encodeURIComponent($.ui.SelectList.getSelectedList($("#search_facilitati_camera")))
		, 
               
		success: function(data) {/* alert(data);*/ $('#search_button_div').html(data);setTimeout(resizeSearchFields,0);},
		error:function(xhr, ajaxOptions, thrownError){	$('#search_button_div').html("Error:"+xhr.status+"("+thrownError+")");setTimeout(resizeSearchFields,0);}
	});
	
}

(function($) { 
        /** 
         * @author David Simpson david.simpson [at] nottingham.ac.uk 
         * @version 0.1 2008-06-08 
         * 
         * Clean the DOM when using Internet Explorer 
         * 
         * IE does bad things to the DOM e.g. 
         * - changes all elements to upper case 
         * - removes double quotes 
         * 
         * Additionally, in IE, the expando attributes such as webLib123456789="1" 
         * are not cleaned when .html() is called 
         * 
         * This function corrects the IE DOM and removes the webLib generated 
         * attributes to produce clean html. 
         * 
         * In other browsers, this function just returns .html() 
         * 
         * @param {Object} options[attributesRegExp] array of regular expressions to remove expando attributes 
         * 
         * usage: 
         *   var bodyHtml = $('body').cleanHtml(); // defaults to removing webLib expando 
         *   var bodyHtml = $('body').cleanHtml( {attributesRegExp: [/regexp1/, /regexp2/, /regexp3/]} ); 
         * 
         * instead of: 
         *   var bodyHtml = $('body').html(); 
         */ 
        $.fn.cleanHtml = function (options) 
        { 

                var me = this; // to reference the top level object 
                
                settings = $.extend({ 
                        attributesRegExp: [ /\sjquery\w+=\s*"[^"]*"/g ] // search for e.g. ' webLib123456789="1"' 
                }); 
                if (options) 
                { 
                        $.extend(settings, options); 
                } 

                var htmlString = $(this).html(); 
                
                if ($.browser.msie == false) 
                { 
                        // .html() seems to work quite nicely 
                        return htmlString; 
                } 
                else 
                { 
                        return  htmlString.replace( 
                                
                                /<(\/?[A-Z][^>]*)>/g, // match any html tag 
                
                                function (match) 
                                { 
                                        if (settings.attributesRegExp) 
                                        { 
                                                for (var i=0; i<settings.attributesRegExp.length; i++) 
                                                { 
                                                        // remove expando attributes 
                                                        match = match.replace( settings.attributesRegExp[i], '' ); 
                                                } 
                                        } 

                                        // add double quotes to unquoted attributes 
                                        match = match.replace( 
                                                /(\w+)(=+)([^"<>\' ]+)(\s+|\/|>)+/, 
                                                "$1$2\"$3\"$4" 
                                        ); 

                                        // drop the case of elements 
                                        match = match.replace( 
                                                /[\/]*[A-Z]+/, 
                                                function(match) 
                                                { 
                                                        return match.toLowerCase(); 
                                                } 
                                        ); 
                                        return match; 
                                } 
                        ); 
                } 
        } 
})(jQuery); 



function resizeSearchFields()
{
	//$('#content_search_fields').resize(function(){
					H = $('#content_search_fields').height();
					if (H>225)  $('#content_menu').css('left',245);
				                        else  $('#content_menu').css('left',0);
										
					leftH=H-250;
					spaceH=H-212;
					if (leftH<0) leftH=0;
					if (spaceH<0) spaceH=0;
					$('#content_left_search_space').css('height',17+spaceH)
					$('#content_left').css('top',leftH);	
					
					/*alert(Math.max($('#content_left').height(),$('#content_main').height()));
					alert($('#page_footer').css('top'));
					*/
					//page_footer
					
		//		});		
}				



function selectDateField_Cookie(obj,sCookie,defaultVal)
{
	
	$val=$.cookie(sCookie);
	$obj=$('#'+obj);
	
	$obj.datepicker({ minDate: defaultVal,changeMonth: true,changeYear: true  }); 
	if ($val!=null && $val!="") 
	{
		tmp = $val.split('.');
		if (tmp.length==3)
		{
			tmp=new Date( tmp[2] , tmp[1]-1 , tmp[0]);
			if (tmp<defaultVal)
			{
				$obj.datepicker( "setDate" , defaultVal )	
				$val = $obj.val();
			}   
		}
		else
			$val = null;
		   
	}
	if ($val==null || $val=="") 
	{
		  $obj.datepicker( "setDate" , defaultVal )	
		  $val = $obj.val();
	}
	
	$obj.val($val);
}					

function selectField_Cookie(obj,sCookie,defaultVal)
{
	$val=$.cookie(sCookie);
	$obj=$('#'+obj);
	if ($val==null || $val=="") $val=defaultVal;
	$obj.val($val);
}
			


/*********************** RESERVATION **************************/
var waitMSG_HTML="Asteptati ...";
function Reservation_Load($div,$params,$successFn,async)
{
 //$div.load(getReservationPage,$params)
  
    $div.html(waitMSG_HTML);
	
	if (async!=false) async=true;
	 
	 setTimeout(function () {
		$.ajax({
			type:'POST',
			async: async, 
			url: getReservationPage,
			data:$.param($params), 
			success: function(data) {/* alert(data);*/ $div.html(data);eval($successFn)},
			error:function(xhr, ajaxOptions, thrownError){	$div.html("Error:"+xhr.status+"("+thrownError+")");}
		});
	},0);
}

function Reservation_ShowRooms()
{
	if ($('#search_checkin').val()!=$('#checkin_date').val())  	$('#search_checkin').val($('#checkin_date').val());
	if ($('#search_nights').val()!=$('#checkin_nights').val())	$('#search_nights').val($('#checkin_nights').val());
	setTimeout(getTotalOffers,10);
	Reservation_Load($('#reservation_rooms'),{action:'reservation_rooms',HotelID:Reservation_HotelID,checkin_date:$('#checkin_date').val(),checkin_nights:$('#checkin_nights').val()});
	

}

function changeOccupation($obj,RoomID)
{

	var ocupationid = $obj.val();
	var occupations = eval('occupation_room_'+RoomID+'['+ocupationid+']');
	var adulti=parseInt(occupations['adulti']);
	var infant=parseInt(occupations['infant']);
	var copii=parseInt(occupations['copii']);

	var checkin_date=$('#checkin_date').val();
	start_copil=getOtherDate(checkin_date,-parseInt(occupations['start_copil']));
	start_adult=getOtherDate(checkin_date,-parseInt(occupations['start_adult']));
	start_date=getOtherDate(new Date(),0);

	//alert(checkin_date + ' - '+start_copil+'-'+start_adult);
	
	sHTML="<p>Completati numele persoanelor conform C.I / Pasaport: </p>"

	sHTML+='<input type="hidden" class="name text" name="room_'+RoomID+'_pers" value="'+(adulti+infant+copii)+'">';
	
	for(i=1;i<=adulti;i++)
	{
		sHTML+='<p><div class="name_description" name="name_description">Persoana ';
		sHTML+=i; 
		sHTML+=" : </div>";
		sHTML+='<select class="select_box" name="room_'+RoomID+'_form_addr"><option value="Mr.">Domnul</option><option value="Ms.">Doamna</option></select>';
		sHTML+='<input type="text" class="name text" name="room_'+RoomID+'_name"><span class="red_color"> <b>*</b></span><input type="text"  name="room_'+RoomID+'_birth_date" style="display:none" readonly="yes">';
		sHTML+="</p>";
	}

	for(i=1;i<=infant;i++)
	{
		sHTML+='<p><div class="name_description" name="name_description">Infant '; 
		sHTML+="(0-"+occupations['start_copil']+" ani) : </div>";
		sHTML+='<input type="hidden" name="room_'+RoomID+'_form_addr" value="Infant"><input type="text" class="name text" name="room_'+RoomID+'_name"><span class="red_color"> <b>*</b></span>';
		sHTML+='&nbsp;&nbsp;&nbsp;Data nastere : <input type="text" minDate="'+start_copil+'" maxDate="'+start_date+'"  name="room_'+RoomID+'_birth_date" class="date text" readonly="yes"><span class="red_color"> <b>*</b></span>';
		sHTML+="</p>";
	}

	for(i=1;i<=copii;i++)
	{
		sHTML+='<p><div class="name_description" name="name_description">Copil '; 
		sHTML+="("+occupations['start_copil']+"-"+occupations['start_adult']+" ani) : </div>";
		sHTML+='<input type="hidden" name="room_'+RoomID+'_form_addr" value="Child"><input type="text" class="name text" name="room_'+RoomID+'_name"><span class="red_color"> <b>*</b></span>';
		sHTML+='&nbsp;&nbsp;&nbsp;Data nastere : <input type="text"  minDate="'+start_adult+'" maxDate="'+start_copil+'" name="room_'+RoomID+'_birth_date" class="date text" readonly="yes"><span class="red_color"> <b>*</b></span>';	
		sHTML+="</p>";
	}

	$html=$obj.parent().parent().find('[name=reservation_step2]').html(sHTML);
	$html.find('[name=room_'+RoomID+'_birth_date]').each(function() {
		$(this).datepicker({
					minDate: $(this).attr('minDate'),
					maxDate: $(this).attr('maxDate'),
					changeMonth: true,
					changeYear: true }
				);
		$(this).change(function () {checkStep2();});		
	});

	$html.find('input').each(function() {
		$(this).keyup(function () {checkStep2();});
    });
	
	
	
}

function checkStep2()
{
bEnabled=true;
$("[name=reservation_step2]").find('input:visible').each(function() {
	if ($(this).val()=="")
	{
		bEnabled=false; 
		$(this).next().css('display','')
	}
	else
	{
		$(this).next().css('display','none')
	
	}
 });
 
$('[id=btn_next2]').attr('disabled',!bEnabled);

if (bEnabled)
	$('#step2_msg').css('display','none')
else
	$('#step2_msg').css('display','')

}


function setFocusStep2()
{
	bFound=false;
	$("[name=reservation_step2]").find('input:visible').each(
		function () 
		{
			if (!bFound)
			{
				if ($(this).val()=="")
				{
					$(this).focus();	
					bFound=true;
				}	
			}	
		}
		
	);

}


function getOtherDate(sDate,nYear)
{
	if (typeof(sDate)=='string')
	{
		tmp = sDate.split('.');		return tmp[0]+"."+tmp[1]+"."+(parseInt(tmp[2])+nYear);
		//tmp=new Date( (parseInt(tmp[2])+nYear)+"", tmp[1]-1 , tmp[0]);
		
	}
	else
	{
		tmp=sDate;
	}
	//tmp.setYear(tmp.getYear()+nYear);
	d=tmp.getDate();
	if (d<10) d="0"+d;
		m=tmp.getMonth()+1;
	if (m<10) m="0"+m;	//var dYear=tmp.getYear();	//if (tmp.getYear()<1900)	//	dYear=parseInt(tmp.getYear()+1900);	return d+"."+m+"."+tmp.getYear();
	
}

var ReservedRooms={};
function changeRoomsNo(noRoom,roomID,roomName)
{
	if (ReservedRooms[roomID]==null)
		ReservedRooms[roomID]={};
	ReservedRooms[roomID]['No']=noRoom;	
	ReservedRooms[roomID]['Name']=roomName;
	
	
	noRoom=parseInt(noRoom);
	for(i=(noRoom+1);i<=20;i++)  // serge tot ce e mai mare
	{
	   total_prices['room_'+roomID+'_'+i]=0;
	   obj=$('#room_'+roomID+'_'+i);
	   obj.remove();
	}
	firstObj=$('#room_'+roomID+'_0');
	for(var i=1;i<=noRoom;i++)  // adauga
	{
		obj=$('#room_'+roomID+'_'+i);
		if (obj.length==0)
		{
			firstObj.parent().append('<div class="reservation_rooms" id="room_'+roomID+'_'+i+'"><div class="room_name">'+roomName+' '+i+':</div>'+firstObj.html().replace('###ROOM_NAME###',roomName+' '+i)+'</div>');
			
			changeOccupation($('#room_'+roomID+'_'+i).find('[name=occupation_room]'),roomID);
			 
			changeRoomTotals($('#room_'+roomID+'_'+i),roomID);
			  
		}
		
	}

	
    showTotalReservation();	
	
}

var total_prices={};
function changeRoomTotals($obj,RoomID)
{
	//alert($obj.html());
	var price = eval('price_room_'+RoomID);
	var ocupationid = $obj.find('#occupation_room_'+RoomID).val();
	var occupations = eval('occupation_room_'+RoomID+'['+ocupationid+']');
	var adulti=parseInt(occupations['adulti']);
	var infant=parseInt(occupations['infant']);
	var copii=parseInt(occupations['copii']);
	var nPersoane =adulti+infant+copii;
	if (nPersoane>1) sPersoane = nPersoane + ' persoane';
	  else sPersoane=' o persoana';
	
	roomNo=$obj.attr('id');
 	total_cazare=0;
	sHTML_Discount="";	
	
	for (i=1;i<=adulti;i++)
	{
		discount=0;
		try {discount=eval('discount_room_'+RoomID+'['+ocupationid+']['+(i)+']') } catch(e){};
		if (discount!=undefined && discount!=0)
		{
			sHTML_Discount+='<div class="room_total red_color">Discount cazare '+discount+'% un adult x -'+(price*discount)/100+' EUR = -'+(price*discount)/100+' EUR</div>';
			total_cazare-=FormatPrice((price*discount)/100);
		}
	}
			
	
	if (infant>0)
	{ 
		for (i=1;i<=infant;i++)
		{
			discount=0;
			try {discount=eval('discount_room_'+RoomID+'['+ocupationid+']['+(adulti+i)+']') } catch(e){};
			if (discount!=undefined && discount!=0)
			{
				sHTML_Discount+='<div class="room_total red_color">Discount cazare '+discount+'% un copil (0-'+occupations['start_copil']+' ani) x -'+(price*discount)/100+' EUR = -'+(price*discount)/100+' EUR</div>';
                total_cazare-=FormatPrice((price*discount)/100);
			}
		}
		if (infant==1)	sInfant= 'un copil (0-'+occupations['start_copil']+' ani)';	
			else sInfant= infant+' copii (0-'+occupations['start_copil']+' ani)';	
	}
	if (copii>0)
	{ 
		for (i=1;i<=copii;i++)
		{
			discount=0;
			try {discount=eval('discount_room_'+RoomID+'['+ocupationid+']['+(adulti+infant+i)+']') } catch(e){};
			if (discount!=undefined && discount!=0)
			{
				sHTML_Discount+='<div class="room_total red_color">Discount cazare '+discount+'% un copil ('+occupations['start_copil']+'-'+occupations['start_adult']+' ani) x -'+(price*discount)/100+' EUR = -'+(price*discount)/100+' EUR</div>';
                total_cazare-=FormatPrice((price*discount)/100);
			}
			if (copii==1)	sCopii= 'un copil ('+occupations['start_copil']+'-'+occupations['start_adult']+' ani)';	
				else sCopii= copii+' copii ('+occupations['start_copil']+'-'+occupations['start_adult']+' ani)';	
		}	
	}


	$obj.find('#occupation_prices').html('<div class="room_total">Cazare '+sPersoane+' x '+price+' EUR = '+(nPersoane*price)+' EUR</div>'+sHTML_Discount+'<div class="clear"></div>');
    total_cazare+=FormatPrice(nPersoane*price);

	total_prices[roomNo]=total_cazare;
	
	if ($('#checkin_nights').length>0)
		nights=$('#checkin_nights').val();
	else
		nights=$('[name=room_checkin_nights]').val()
	if (nights==1)	sNights = 'o noapte'
		else sNights = nights+' nopti'
	
	total_services=0;
	services=eval('services_room_'+RoomID);
	
	
	for (serviceid in services)
	{

	 $obj.find('#price_service_discounts1_'+serviceid).html('');	
	 $obj.find('#price_service_discounts2_'+serviceid).html('');	
	if ($obj.find('#check_service_'+serviceid).attr('checked'))
	  {
	    price=services[serviceid]['pret'];
		if (price!=0)
		{
			calcul=services[serviceid]['calcul'];
			// calcul 
			//  1 pers/noapte
			//  2 pers/rezervare
			//  3 camera/noapte
			//  4 camera/rezervare
			//  5 pachet ----------- nu exista!!!!!!!!!!!!!
			
			switch (calcul)
			{
				case 1://  1 pers/noapte
					srvPrice=FormatPrice(nPersoane*price*nights);
					sPrice=srvPrice+' EUR';
					srvPrice_Description = sPersoane+" x " +sNights + " x "+ price+ " EUR = ";
					if (infant>0)
					{
						discount=FormatPrice(-infant*nights*price*services[serviceid]['discount1']/100);
						copiiDiscounts='<div class="price red_color">Discount '+services[serviceid]['discount1']+'% pentru '+sInfant+" x "+sNights + " x "+ price*services[serviceid]['discount1']/100 + " EUR = " +discount+" EUR</div>";
						total_services+=discount;
						$obj.find('#price_service_discounts1_'+serviceid).html(copiiDiscounts);	
					}
					if (copii>0)
					{
						discount=FormatPrice(-copii*nights*price*services[serviceid]['discount2']/100);
						copiiDiscounts='<div class="price red_color">Discount '+services[serviceid]['discount2']+'% pentru '+sCopii+" x "+sNights + " x "+ price*services[serviceid]['discount2']/100 + " EUR = " +discount+" EUR</div>";
						total_services+=discount;
						$obj.find('#price_service_discounts2_'+serviceid).html(copiiDiscounts);	
					}
					break;
				case 2://  2 pers/rezervare
					srvPrice=FormatPrice(nPersoane*price);
					sPrice=srvPrice+' EUR';
					srvPrice_Description = sPersoane+" x " + price+ " EUR = ";
					if (infant>0 && services[serviceid]['discount1']!=0)
					{
						discount=FormatPrice(-infant*price*services[serviceid]['discount1']/100);
						copiiDiscounts='<div class="price red_color">Discount '+services[serviceid]['discount1']+'% pentru '+sInfant+" x "+ price*services[serviceid]['discount1']/100 + " EUR = " +discount+" EUR</div>";
						total_services+=discount;
						$obj.find('#price_service_discounts1_'+serviceid).html(copiiDiscounts);	
					}
					if (copii>0 && services[serviceid]['discount2']!=0)
					{
						discount=FormatPrice(-copii*price*services[serviceid]['discount2']/100);
						copiiDiscounts='<div class="price red_color">Discount '+services[serviceid]['discount2']+'% pentru '+sCopii+" x "+ price*services[serviceid]['discount2']/100 + " EUR = " +discount+" EUR</div>";
						total_services+=discount;
						$obj.find('#price_service_discounts2_'+serviceid).html(copiiDiscounts);	
					}
					break;
				case 3://  3 camera/noapte
					srvPrice=FormatPrice(price*nights);
					sPrice=srvPrice+' EUR';
					srvPrice_Description = sNights + " x "+ price+ " EUR = ";
					break;
				case 4:// 4 camera/rezervare
					srvPrice=price;
					sPrice=srvPrice+' EUR';
					srvPrice_Description =  price+ " EUR = ";
					break;
				
			}
			$obj.find('#price_service_'+serviceid).html(srvPrice_Description+sPrice);	
			
			total_services+=srvPrice;
		}	
	  }	
	  else 
	  {
	    $obj.find('#price_service_'+serviceid).html('');	
		$obj.find('#price_service_discounts1_'+serviceid).html('');	
		$obj.find('#price_service_discounts2_'+serviceid).html('');	
	  }	
	}

	total_prices[roomNo]+=total_services;

	var discount_early_booking_cazare=0;
	var early_booking=eval('early_booking_room_'+RoomID);
	for (early_booking_id in early_booking)
	{

		$obj.find('#early_booking_cazare_'+early_booking_id).html('');	
		$obj.find('#early_booking_servicii_'+early_booking_id).html('');	
		
		if ($obj.find('#check_early_booking_'+early_booking_id).attr('checked'))
		{
			discount= early_booking[early_booking_id]['discount_cazare'];
			if (discount!=0)
			{
				price=FormatPrice(-total_cazare*discount/100);
				$obj.find('#early_booking_cazare_'+early_booking_id).html(price+" EUR");
				total_prices[roomNo]+=price;
				discount_early_booking_cazare = total_cazare*discount/100;
			}
			
			discount= early_booking[early_booking_id]['discount_servicii'];
			if (discount!=0)
			{
				price=FormatPrice(-total_services*discount/100);
				$obj.find('#early_booking_servicii_'+early_booking_id).html(price+" EUR");
				total_prices[roomNo]+=price;
			}
		}
		
	}	
	
	if (typeof(site_discount)!='undefined' && site_discount>0)
	{
		// discount site
		price=FormatPrice((-total_cazare+discount_early_booking_cazare)*site_discount/100);
		$obj.find('#discount_site_cazare').html(price+" EUR");
		total_prices[roomNo]+=price;
	}	
	
    $obj.find('#room_price').html(FormatPrice(total_prices[roomNo])+' EUR');
	
    showTotalReservation();	
}

function showTotalReservation()
{
    $('[name=comments]').css('width','100%');
	$('[name=comments]').height(70);
	Total_reservation_price=0;
	for(room in total_prices)
	{
	   Total_reservation_price+=total_prices[room];
	}
	//alert(Total_reservation_price+'EUR')
	$('#reservation_price').html(FormatPrice(Total_reservation_price)+' EUR');
	
	if (Total_reservation_price==0)
	{
		$('#total_rezervare').hide();
		$('#termeni_rezervare').hide();
	}
	else
	{
		$('#total_rezervare').show();
		$('#termeni_rezervare').show();
	}

}



function AcceptTerms(obj)
{
	if ($(obj).attr('checked'))
	{
		$('#btn_next1').attr('disabled',null)
	}
	else
		$('#btn_next1').attr('disabled','yes')
}


function Step1()
{
	$('#checkin_nights').attr("disabled", false);
	$('#checkin_date').attr('disabled',false);
	$('[name=no_room_select]').attr('disabled',false);
	$('[name=occupation_room]').attr('disabled',false);
	$('[name=reservation_step1]').show();
	$('[name=termeni_rezervare]').show();
	$('[name=step2_buttons]').hide();
	$('[name=reservation_step2]').hide();
}


function Step2()
{
	$('#checkin_nights').attr("disabled", true);
	$('#checkin_date').attr('disabled',true);
	$('[name=no_room_select]').attr('disabled',true);
	$('[name=occupation_room]').attr('disabled',true);
	$('[name=reservation_step1]').hide();
	$('[name=termeni_rezervare]').hide();
	$('[name=step2_buttons]').show();
	$('[name=reservation_step2]').show();
}


function Step3()
{
	
	$('[name=reservation_step2]').hide();
	$('[name=step2_buttons]').hide();
	$('[name=reservation_step3]').show();
	Reservation_Load($('#reservation_step3'),{action:'reservation_step3'})	

}	



function Rezervare()
{
	
	$('[name=reservation_step1]').show();
	
	oVoucher={};
	NoVoucher=0;
	for(var RoomID in ReservedRooms)
	{
		for(var camNo=1;camNo<=ReservedRooms[RoomID]['No'];camNo++)
		{
			oVoucher[++NoVoucher]={RoomID:RoomID,HotelID:Reservation_HotelID,checkin_date:$('#checkin_date').val(),checkin_nights:$('#checkin_nights').val()};
			$roomHTML=$('#room_'+RoomID+'_'+camNo);
			
			
			oVoucher[NoVoucher]['price']=$roomHTML.find('#room_price').html();
	
			oVoucher[NoVoucher]['PersNo']=$roomHTML.find('[name=room_'+RoomID+'_pers]').val();
			var persNo=0;
			oVoucher[NoVoucher]['Pers']={}
			$addrs=$roomHTML.find('[name=room_'+RoomID+'_form_addr]');
			$birth_date=$roomHTML.find('[name=room_'+RoomID+'_birth_date]')
			pers="";
			$roomHTML.find('[name=room_'+RoomID+'_name]').each(function (idx){
				pers+=$($addrs[idx]).val() + " " + $(this).val()
				birth_date=$($birth_date[idx]).val();
				if (birth_date!="")
				{
					pers+="##"+birth_date+"## &nbsp;&nbsp; birth date: "+birth_date
				}
				pers+="\n";
				//persNo++;
				//oVoucher[NoVoucher]['Pers'][persNo]= {name:$($addrs[idx]).val() + " " + $(this).val() };
				//birth_date=$($birth_date[idx]).val();
				//if (birth_date!="")
					//oVoucher[NoVoucher]['Pers'][persNo]['birth_date']=birth_date;
			});
			discount=0;
			$roomHTML.find('[name=early_booking]:checked').each(function (){discount=$(this).val()});
			
			//$roomHTML.find('[name^=check_service_]:checked').each(function (){alert($(this).val());});
			
			sService="";
			services=eval('services_room_'+RoomID);
			for (serviceid in services)
			{
			    if (serviceid>0)
				{
					if ($roomHTML.find('#check_service_'+serviceid).attr('checked'))
					{
						if (sService!="") sService+="," 
						sService+=serviceid;
					}
				}				
			}

			oVoucher[NoVoucher]['Services']=sService;

			$('[name=user_id]').each(function (){oVoucher[NoVoucher]['UserID']=$(this).val()});

			
			oVoucher[NoVoucher]['Comments']=$('[name=comments]').val();


			if (discount!=0) oVoucher[NoVoucher]['Early_Booking']=discount;
			oVoucher[NoVoucher]['Pers']=pers;

			sCheckList="";
			$roomHTML.find(':checkbox').each(function () 
			{
				if (sCheckList!="") sCheckList+=",";
				sCheckList+=$(this).attr('checked');
			});
			
			$roomHTML.find('#room_script').html($roomHTML.find('#room_script').html()+"setReservationCheckList(["+sCheckList+"]);");
			
			oVoucher[NoVoucher]['Details']=$roomHTML.html();
		}
		
	}
	//last STEP
	$('[name=reservation_step1]').hide();
	$('[name=reservation_step2]').hide();
	$('[name=step2_buttons]').hide();
	$('#reservation_comments').hide();
	
	$('[name=reservation_end]').show();
	
	Reservation_Load($('#reservation_end'),{action:'reservation_end',voucher:$.toJSON(oVoucher)})	
}


function OtherReservation()
{
	$('#checkin_nights').attr("disabled", false);
	$('#checkin_date').attr('disabled',false);
	Reservation_ShowRooms();
}

function getTermeni_Conditii()
{
	Reservation_Load($('#termeni_conditii'),{action:'termeni_conditii'})	
}

function FormatPrice(price)
{
	if (parseInt(price)==price) return price;
	return parseInt(price*100)/100;
}


function showLoginForm()
{
	$('#autentificare').css({width:270,right:0,height:38});
	$('#login_account').hide();
	$('#login_form').show();
	$('#user_name').focus();

}


function cancelLoginForm()
{
	$('#autentificare').css({width:100,right:170,height:20});
	$('#login_form').hide();
	$('#login_account').show();
	

}





function validateConfirmationPassword()
{
			if($('#register_form').find("#reg_password").val() != $('#register_form').find("#reg_confirmpassword").val())
			{
				return true;
			}
			else
			{
				return false;
			}
}


function ShowAcualizareStatus(selectObj,vid)
{
  $selectObj=$(selectObj);
  select_status=$selectObj.val();
  defaultval=$selectObj.attr('defaultval');
  $btnObj=$selectObj.parent().find('[name=btnSaveStatus]');
  if (defaultval!=select_status)
  {
     $btnObj.css('display','block');
	 if (defaultval<select_status)
	   {
		
		  if (select_status==STATUS_VoucherConfirmat)	
			$('#voucher_files_'+vid).html("Factura proforma : <input type='file' class='attachfile text' id='attachfile_"+vid+"' name='attachfile_"+vid+"' value='Alege proforma' msg='Alegeti o factura proforma'>");	 
		  else	
			if (select_status==STATUS_VoucherPlatit)	
				$('#voucher_files_'+vid).html("Factura fiscala : <input type='file'  class='attachfile text' id='attachfile_"+vid+"' name='attachfile_"+vid+"' value='Alege fiscala' msg='Alegeti o factura fiscala'>");	 
			else
				$('#voucher_files_'+vid).html('');
		}
		else
			$('#voucher_files_'+vid).html('');
	
  }
  else 
  {  
     $btnObj.css('display','none');
	 $('#voucher_files_'+vid).html('');
  }
}

function ExecutActualizareStatus(btnObj,vid)
{
  $btnObj=$(btnObj);
  $attachfile=$('#attachfile_'+vid);
  
  if ($attachfile.length>0 && $attachfile.val()=="") 
  {
		alert($attachfile.attr('msg'));
		return;
  }
  $selectObj=$btnObj.parent().find('select');
  $form=$('#status_form');
  
  //$form.find('[name=attachfile]').val($attachfile.val());
  //alert($form.find('[name=attachfile]').val());
  //$attachfile.val("");
  
  $form.find('[name=voucherid]').val(vid);
  $form.find('[name=voucherstatus]').val($selectObj.val());
  $form.submit();  
}



var lastVoucherID=0;
function ShowDetailsVoucher(objBtn,vid)
{
    lastVoucherID=vid;
    $div=$('#voucher_details_'+vid);
	if ($(objBtn).hasClass('button_details'))
	{
		$(objBtn).removeClass('button_details');
		$(objBtn).addClass('button_details1');
		Reservation_Load($('#voucher_details_'+vid),{action:'getvoucher',voucherid:vid},'updateVoucherDatepicker()');

	}
	else
	{
		$(objBtn).removeClass('button_details1');
		$(objBtn).addClass('button_details');
		$div.html("")
	}	
}

function updateVoucherDatepicker()
{
	$('#voucher_details_'+lastVoucherID).find('[name$=_birth_date]').each(function() {
				
				$(this).datepicker({
							minDate: $(this).attr('minDate'),
							maxDate: $(this).attr('maxDate'),
							changeMonth: true,
							changeYear: true }
						);
					});
}

function setReservationCheckList(checkList)
{
	$('#voucher_details_'+lastVoucherID).find(':checkbox').each(function (idx) 
	{
		$(this).attr('checked',checkList[idx]);
	});
}

function ShowVoucherPDF(vid)
{
  window.open(getReservationPage+"?action=getpdfvoucher&voucherid="+vid)
}


function CheckUpdateVoucher(vid,RoomID)
{
	
	update_voucher_msg=$('#update_voucher_msg_'+vid).html();
	if (update_voucher_msg!="")
	{
		$input=$('#update_voucher_msg_'+vid).find('input:first');
		if ($input.val()!="") 
		{
			 UpdateVoucher(vid,RoomID);
			return;
		}	
	}	
	
	oVoucher={};
	$roomHTML=$('#reservation_details_'+vid);
	
	discount=0;
	$roomHTML.find('[name=early_booking]:checked').each(function (){discount=$(this).val()});
			
	sService="";
	services=eval('services_room_'+RoomID);
	for (serviceid in services)
	{
		if (serviceid>0)
		{
			if ($roomHTML.find('#check_service_'+serviceid).attr('checked'))
			{
				if (sService!="") sService+="," 
				sService+=serviceid;
			}
		}				
	}
	oVoucher['Services']=sService;

	if (discount!=0) oVoucher['Early_Booking']=discount;

	sCheckList="";
	$roomHTML.find(':checkbox').each(function () 
	{
		if (sCheckList!="") sCheckList+=",";
		sCheckList+=$(this).attr('checked');
	});
	
	$roomHTML.find('#room_script').html($roomHTML.find('#room_script').html()+"setReservationCheckList(["+sCheckList+"]);");
	
	
	oVoucher['Pers']={}
	$addrs=$roomHTML.find('[name=room_'+RoomID+'_form_addr]');
	$birth_date=$roomHTML.find('[name=room_'+RoomID+'_birth_date]')
	pers="";
	$roomHTML.find('[name=room_'+RoomID+'_name]').each(function (idx){
		pers+=$($addrs[idx]).val() + " " + $(this).val()
		birth_date=$($birth_date[idx]).val();
		if (birth_date!="")
		{
			pers+="##"+birth_date+"## &nbsp;&nbsp; birth date: "+birth_date
		}
		pers+="\n";
	});
	oVoucher['Pers']=pers;

	
	oVoucher['Details']=$roomHTML.html();
	
	oVoucher['Price']=$roomHTML.find('#room_price').html();
	
	oVoucher['Comments_client']=$('[name=comments_client]').val();
	oVoucher['Comments_angajat']=$('[name=comments_angajat]').val();
	oVoucher['Comments_voucher']=$('[name=comments_voucher]').val();
	last_vid=vid;
	last_RoomID=RoomID;
	Reservation_Load($('#update_voucher_msg_'+vid),{action:'checkupdatevoucher',voucherid:vid,voucher:$.toJSON(oVoucher)},'UpdateVoucher()');
	
}

function ExecUpdateVoucher()
{
	$('#btn_save_'+last_vid).click()
}	

var last_vid=null;
var last_RoomID=null;

function UpdateVoucher(vid,RoomID)
{
	if (vid==null || typeof(vid)=='undefined') vid=last_vid;
	if (RoomID==null || typeof(RoomID)=='undefined') RoomID=last_RoomID;
	var bUploadFile=false;
	update_voucher_msg=$('#update_voucher_msg_'+vid).html();
	if (update_voucher_msg!="")
	{
	
	//	alert($('#update_voucher_msg_'+vid).text());
	
	/*	$input=$('#update_voucher_msg_'+vid).find('input:first');
		if ($input.val()=="") 
		{
			alert($input.attr('msg'));
			$input.focus();
			return;
		}	
		else
		{
		*/
		bUploadFile=true;
		//}
	
	}
	
	oVoucher={};
	$roomHTML=$('#reservation_details_'+vid);
	
	discount=0;
	$roomHTML.find('[name=early_booking]:checked').each(function (){discount=$(this).val()});
			
	sService="";
	services=eval('services_room_'+RoomID);
	for (serviceid in services)
	{
		if (serviceid>0)
		{
			if ($roomHTML.find('#check_service_'+serviceid).attr('checked'))
			{
				if (sService!="") sService+="," 
				sService+=serviceid;
			}
		}				
	}
	oVoucher['Services']=sService;

	if (discount!=0) oVoucher['Early_Booking']=discount;

	sCheckList="";
	$roomHTML.find(':checkbox').each(function () 
	{
		if (sCheckList!="") sCheckList+=",";
		sCheckList+=$(this).attr('checked');
	});
	
	$roomHTML.find('#room_script').html($roomHTML.find('#room_script').html()+"setReservationCheckList(["+sCheckList+"]);");
	
	
	oVoucher['Pers']={}
	$addrs=$roomHTML.find('[name=room_'+RoomID+'_form_addr]');
	$birth_date=$roomHTML.find('[name=room_'+RoomID+'_birth_date]')
	pers="";
	$roomHTML.find('[name=room_'+RoomID+'_name]').each(function (idx){
		pers+=$($addrs[idx]).val() + " " + $(this).val()
		birth_date=$($birth_date[idx]).val();
		if (birth_date!="")
		{
			pers+="##"+birth_date+"## &nbsp;&nbsp; birth date: "+birth_date
		}
		pers+="\n";
	});
	oVoucher['Pers']=pers;

	
	oVoucher['Details']=$roomHTML.html();
	
	oVoucher['Price']=$roomHTML.find('#room_price').html();
	
	oVoucher['Comments_client']=$('[name=comments_client]').val();
	oVoucher['Comments_angajat']=$('[name=comments_angajat]').val();
	oVoucher['Comments_voucher']=$('[name=comments_voucher]').val();
	if (bUploadFile)
	{
	
		var button=$('#btn_save_'+vid);
	 	new AjaxUpload(button,{
			action: getReservationPage,
			name:'attachfile_'+vid,
			data:{action:'updatevoucher',voucherid:vid,voucher:$.toJSON(oVoucher)},
			
			onSubmit : function(file, ext){
			
				//this.hide();
				$('#voucher_details_'+vid).html(waitMSG_HTML);
				
			},

			
			onComplete: function(file,ext) 
			{
				$('#voucher_details_'+vid).html(ext);
			}
		});
	
	}
	else
	{
		Reservation_Load($('#voucher_details_'+vid),{action:'updatevoucher',voucherid:vid,voucher:$.toJSON(oVoucher)});
	}
	$objBtn=$('#button_details_'+vid);
	$objBtn.removeClass('button_details1');
	$objBtn.addClass('button_details');
		
}

function SendAuthentificationInfo()
{
	Reservation_Load($('#msg_autentification'),{action:'auth',usr:$('#authentification_form').find('#reg_utilizator').val(),passwd:$('#authentification_form').find('#reg_password').val()},'RecvAuthentificationInfo()',false);
}



function RecvAuthentificationInfo()
{
	if ($('#msg_autentification').html()=="auth_ok")
	{
		$('#reservation_step3').hide();
		Rezervare();
	}	
}

function SendNewAccountInfo()
{
	type=$('#register_form').find('[name=type]').val();
	addr=$('#register_form').find('[name=addr]').val();
	reg_nume=$('#register_form').find('[name=reg_nume]').val();
	reg_email=$('#register_form').find('[name=reg_email]').val();
	reg_username=$('#register_form').find('[name=reg_username]').val();
	reg_password=$('#register_form').find('[name=reg_password]').val();
	
	Reservation_Load($('#msg_autentification_new'),{action:'new_account',type:type,addr:addr,reg_nume:reg_nume,reg_email:reg_email,reg_username:reg_username,reg_password:reg_password},'RecvNewAuthentificationInfo()',false);
}

function RecvNewAuthentificationInfo()
{
	if ($('#msg_autentification_new').html()=="auth_ok")
	{
		$('#reservation_step3').hide();
		Rezervare();
	}	
}


function TableSQLPaginationGO(obj,$page)
{
	$('[name=TableSQLPagination_pageno]').val($page);
	var pageForm = $(obj).parents('form:first'); 
	$(pageForm).submit();
}
