//document.write('<!--[if IE 6]><scr'+'ipt type="text/javascript" src="reservation/jquery.pngFix.pack.js"></scr'+'ipt><![endif]-->');
document.write('<scr'+'ipt type="text/javascript" src="reservation/fancybox/jquery.fancybox-1.3.4.pack.js"></scr'+'ipt>');
//document.write('<scr'+'ipt type="text/javascript" src="reservation/fancybox/jquery.mousewheel-3.0.4.pack.js"></scr'+'ipt>');
//document.write('<link rel="stylesheet" href="reservation/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />');
document.write('<link rel="stylesheet" href="reservation/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />');
String.prototype.insert = function (index, string) {
  if (index > 0)
    return this.substring(0, index) + string + this.substring(index, this.length);
  else
    return string + this;
};

function img_exist(url) {

    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

function checkboxes(){
$("input[type='checkbox']").not(':checked').each(function() {
      //$(this)
	  $(this).val(0);
	  //alert(0);
    });
}

function removeSpaces(string) {
 return string.split(' ').join('');
}
// jQueru DOM loaded..
$(function()
{	
	
/////////GALLERY
	$('#horizontal_menu').nextAll('img').each(function() {
		var small_img_path = jQuery(this).attr('src');
		var big_img_path = small_img_path.insert((small_img_path.length-4), "-big");
		//something.insert(3, " are");
		if(img_exist(big_img_path)) { var real_img = big_img_path; } else { var real_img = small_img_path; }
		
		jQuery('<a etr="'+img_exist(big_img_path)+'" href="'+real_img+'" rel="hotel_pics" style="border:none" title="'+jQuery(this).attr('alt')+'"></a>').insertBefore(this);
		jQuery(this).clone().appendTo(jQuery(this).prev());
		//jQuery(this).closest('a').append(jQuery(this).clone()); 
		jQuery(this).detach();
	   })
	
	$("a[rel=hotel_pics]").fancybox({
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over">' + title + '</span>';
		}
	});
//////////////////////////////////////////
	var curindex = 0;
	$('table[id="price"] tr').each(function(index) {
		if( (index===0 && $(this).find('td:first').text()==='Тип номера') || (index===0 && $(this).find('td:first').text()==='район') ) {} 				
		else
			{
				if($(this).find('td:first').text()!=='район'){
					if(index===0){curindex=curindex+1;}
					$(this).find('td:first').append(' <a class="reservation" cur="'+(curindex)+'">Забронировать</a>');
				}
			}
		curindex=curindex+1;
	})
//////////////////////////////////////////
	$('#reservation input[type="submit"]').mouseover( function() { checkboxes(); })
	//$('a.reservation').hide();
	var path = '/reservation/';
	$('body').append('<div style="display:none"><div id="res_form"></div></div>');
	
	$('#res_form').load(path+'form2.html', function() {
		$('#res_form input.calendar').each(function() { parseCalendarFields($(this)); })
  		$('a.reservation').attr('href','#res_form').fancybox({
				//	'transitionIn'		: 'elastic',
				//	'transitionOut'		: 'elastic',
					'scrolling'		: 'no',
					'centerOnScroll': true,
					'titleShow'		: false,
					'overlayOpacity': 0.8,
					'autoDimensions': false,
					'width':		630,
					'height':		560,
					'autoScale': false//,
					//'content': txt,
					//'onComplete':	function(){	$(document).pngFix(); }
				})
		
		var hotels = [];
		
		$.get(path + 'hotels_vnd.txt', function(text)
				{
					hotelsData = text
								.replace(/\t/g, '')
								.split(/\n{2,}/);
				
					$.each(hotelsData, function()
						{
							var 
							hotel = this.split('\n'),
							ur = hotel.splice(1,1);
							title = hotel.shift();
							hotels[title] = [$.map(hotel, function(type){ return '<option value="'+ type +'">'+ type +'</option>' }).join('\n'),ur];
							
							//hotels[title][0] = ur;
							//hotels[title] = $.map(ur, function(type){ return '<option value="'+ type +'">'+ type +'</option>' }).join('\n');
						});
				
					var form = $('#reservation');
					//alert('hotels.txt loaded');
					$('a.reservation').click(function() { 
						var cur2 = $(this).attr('cur');
						prepareForm2(form, hotels, cur2);							  
					});
					$('a.reservation').fadeIn();
					
				});
	//$('.datepicker img').pngFix( { blankgif:'blank.gif' } );
	
	//alert('Load was performed.');
	});
	
	
	
///////////////////////		
			
			

							
							
///////////////////////

	
	// Календарь
	function parseCalendarFields(inp)
	{ 
		var 
			input 		= inp,
			delimiter 	= ' - ',
			dates 		= input.val().split(delimiter),
			from 		= dates[0] || new Date,
			to			= dates[1] || new Date,
			range 		= input.hasClass('range');
		
		inp.DatePicker(
		{
			prev		: '&larr;',
			next		: '&rarr;',
			date		: range ? [from, to] : from,
			mode		: range ? 'range' : 'single',
			calendars	: range ? 2 : 1,
			current		: from,
			format		: 'd.m.Y',
			starts		: 1,
			locale		: 
			{
				days: ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
				daysShort: ['Вск','Пнд','Втр','Срд','Чтв','Птн','Сбт'],
				daysMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
				months: ['Январь','Февраль','Март','Апрель','Май','Июнь', 'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
				monthsShort: ['Янв','Фев','Мар','Апр','Май','Июн', 'Июл','Авг','Сен','Окт','Ноя','Дек'],
				weekMin: 'Н'
			},
			onChange: function(formated, dates)
			{
				var date, from, to;
				
				if( $.isArray(formated) )
				{
					from 	= formated[0];
					to 		= formated[1];
					date 	= from == to ? from : formated.join(delimiter);
				}
				else date = formated;
				
				// update
				if( input.val() != date )
				{
					input
						.val(date)
						.focus();
					
					if( !range || (range && to) ) input.DatePickerHide();
				}
			}
		});
		//$('.datepicker img').pngFix( { blankgif:'blank.gif' } );
	}
	

////////////////
	// Форма бронирования
function prepareForm2( form, hotels, cur )
	{ 	cur = cur || 0;
		// options
		var 
			titles 			= [],
			hotelsList 		= form.find('select[id="hotel_id"]'),
			hotelsRooms 	= form.find('select[id="room_id"]');
		
		$('#hotel_id option[value="0"]').html('- выберите гостиницу -').removeAttr('disabled');
		$('#hotel_id').removeAttr('disabled');
		$('#room_id').removeAttr('disabled');
		
		var stv = $('#gurl').val()+'.html';
		var stv2 = stv.substr(0,stv.length-11)+'.html';
		//alert(stv2);
		//alert(stv);
		for(hotel in hotels)
		{	
			//alert(hotel[0]);
			if( hotels.hasOwnProperty(hotel) )
			{
				titles.push('<option value="'+ hotel +'">'+ hotel +'</option>');
				var ltd ='';
				//if( hotels.hasOwnProperty(ur) ) {alert(ur);}
				if(stv==hotels[hotel][1] || stv2==hotels[hotel][1]){ltd = ' selected';}
				$(hotelsList).append('<option value="'+ hotel +'"'+ltd+'>'+ hotel+'</option>');
			}
		}
		
		$(hotelsList).change(function() {
  		//alert('Handler for .change() called.');
		});
		
		hotelsList
			//.html( '<option value="'+ hotel +'">'+ hotel +'</option>' )
			.change(function()
			{	//alert(this.value);
				if(this.value!='0'){hotelsRooms.html( hotels[this.value][0] );$('#room_id').removeAttr('disabled');
				
				if(cur.length>0){ $('#room_id option:eq('+cur+')').attr('selected', 'selected'); }
				
				
				} 
				else {hotelsRooms.html('- выберите гостиницу -').attr("disabled","disabled");}
			});
		
		hotelsList.trigger('change');
		
		// other
		form
			.attr('action', path + 'php/form.php')
			//.css('height', $(document).height());
			
		//form.find('input.calendar').each( parseCalendarFields(); );
		//$('input.calendar').each(function() {parseCalendarFields})
		//form.find('#fancybox-content input.calendar').each( parseCalendarFields );
		//form.find('i.close').click(function(){ form.hide() });
		
		var required = form
				.find(':input')
				.filter('.required');
				
		required.change(function()
		{
			var 
				field = $(this),
				value = field.val();
			
			if( ! value ) field.addClass('error');
			else field.removeClass('error');
		});
		
		form.submit(function()
		{	

			checkboxes();
			var 
				fields	= form.find(':input[type!="hidden"]'),
				empty	= required.filter('[value=""]'),
				loader	= form.find('i.loader'),
				send	= [];
			
			fields.filter('[name]').each(function()
			{
				var 
					field = $(this),
					title = encodeURIComponent( $(this).prev().val()),
					value = encodeURIComponent( field.val() );
				
				value && send.push( field.attr('name') +"="+ title +"~@~"+ value );
			});
			
			required.removeClass('error');
			
			if( empty.length > 0 ) empty.addClass('error').first().focus();
			else 
			{
				loader.show();
				fields.attr('disabled', true);
				
				$.ajax
				({
				 	url		: form.attr('action'),
					type	: form.attr('method'),
					data	: send.join('&'),
					success : function( response )
					{
						loader.hide();
						fields.attr('disabled', false);
						
						if( response )
						{
							alert(response);
							$.fancybox.close();
						}
						else alert('Произошла ошибка! Форма не отправлена.');
						
						$('#reservation').unbind('submit');
					}
				 });
			}

			return false;
		});

	}


});
