var size = 0;

$(document).ready(function(){
	$('body').removeClass('nojs');
	spo.init();

	$('.food a', '.spo').live('click', function(){
		if ($(this).parents('li').hasClass('active'))
			return false;
	    var $spo = $(this).parents('.spo');

		$spo
			.append('<div class="loading" />')
			.find('.scroll')
			.animate({left: 0}, 200);
		/* NB: getting here new table.legend + div.data = all the contents of .overflow */

		// fake getting data
	    	$('li.active', $spo).removeClass('active');
			$(this).parents('li').addClass('active');
			html = $('.legend .wrap', $spo).html();
			setTimeout(function(){
		// /fake getting data

				// got data
				$('.overflow', $spo).html(html);
				spo.init($spo);
				$('.loading', $spo).remove();

		// fake getting data
			}, 500);
		// /fake getting data

		return false;
	});

	$('.shd').bgiframe();

	$('.index .promo-content .country:first').show();

	$("a[rel='blank']").click(function(){
		window.open($(this).attr('href'));
		return false
	});

	$('.search input[type="text"],.shd input[type="text"],.shd input[type="password"],.bron .bron-form .bl input.text')
		.blur(function() {if(this.value=='') {this.value=this.defaultValue; $(this).removeClass('active')}
	})
		.focus(function() {if(this.value==this.defaultValue) {this.value='';$(this).addClass('active')}
	});

	$('.c-right .comments .comment-mid').hover(function(){
		$(this).parent().addClass('active');
	},function(){
        $(this).parent().removeClass('active');
	});

	$('.articles .one .text h2 a,.articles .one .photo a img,.hotel-list .one .text h2 a,.hotel-list .one .photo a img,.sblock .photo img,.sblock .text a').hover(function(){
		$(this).parent().parent().parent().addClass('active');
	},function(){
        $(this).parent().parent().parent().removeClass('active');
	});

	$('.carousel ul').jcarousel();
	$('#footer-txt ul').jcarousel({scroll:1});

	/*Input+check all*/
	$('.hotel-filter ul li,.bron .bron-form li,.bron .bron-form .header span').click(function(){
		if ($(this).hasClass('active')){
			$(this).removeClass('active');
			$('input[type="checkbox"]',this).attr('checked','');
		} else {
            $(this).addClass('active');
			$('input[type="checkbox"]',this).attr('checked','checked');
		}
	});
	$('.hotel-filter ul li.all,.br-checks ul li.all,.bron ul.stars li.all').click(function(){
		if ($(this).hasClass('active')){
		    $(this).parent().addClass('alll');
			$(this).parent().find('li').addClass('active');
			$(this).parent().find('input[type="checkbox"]').attr('checked','checked');
		} else {
		    $(this).parent().removeClass('alll');
			$(this).parent().find('li').removeClass('active');
			$(this).parent().find('input[type="checkbox"]').attr('checked','');
		}
		$('.hotel-filter ul.alll li, .br-checks ul.alll li,.bron ul.stars li').not('.all').click(function(){
		    $(this).parent().removeClass('alll');
		    $(this).parent().find('.all').removeClass('active');
			$(this).parent().find('.all input[type="checkbox"]').attr('checked','');
		});
	});
	$('.hotel-filter ul li label,.bron .bron-form li label,.bron .bron-form .header span label').click(function(){
		$(this).parent().click();
		return false
	});



	/*Input+check kurort*/
	$('#br-city').parent().click(function(){
	    if ($(this).hasClass('active')){
		    $('#city-list').addClass('alll');
			$('#city-list').find('li').addClass('active');
			$('#city-list').find('input[type="checkbox"]').attr('checked','checked');
		} else {
		    $('#city-list').removeClass('alll');
			$('#city-list').find('li').removeClass('active');
			$('#city-list').find('input[type="checkbox"]').attr('checked','');
		}
		$('#city-list li').not('.all').click(function(){
		    $('#city-list').removeClass('alll');
		    $('#br-city').parent().removeClass('active');
			$('#br-city').parent().find('input[type="checkbox"]').attr('checked','');
		});
	});


	/*Input+check hotel*/
	$('#br-hotel').parent().click(function(){
	    if ($(this).hasClass('active')){
		    $('#hotel-list').addClass('alll');
			$('#hotel-list').find('li').addClass('active');
			$('#hotel-list').find('input[type="checkbox"]').attr('checked','checked');
		} else {
		    $('#hotel-list').removeClass('alll');
			$('#hotel-list').find('li').removeClass('active');
			$('#hotel-list').find('input[type="checkbox"]').attr('checked','');
		}
		$('#hotel-list li').not('.all').click(function(){
		    $('#hotel-list').removeClass('alll');
		    $('#br-hotel').parent().removeClass('active');
			$('#br-hotel').parent().find('input[type="checkbox"]').attr('checked','');
		});
	});



	$('.sblock .sblock-bot div').click(function(){
		if ($(this).hasClass('active')){
			$(this).removeClass('active');
  			if ($.browser.msie){
        		$('.sblock .hidden').hide();
			} else {
				$('.sblock .hidden').slideUp();
			}
		} else {
            $(this).addClass('active');
   			if ($.browser.msie){
        		$('.sblock .hidden').show();
			} else {
				$('.sblock .hidden').slideDown();
			}
		}
	});

	$('.tabs li a').click(function(){
        $(this).parent().parent().find('li').removeClass('active');
        $(this).parent().addClass('active');
	loadpagecnt($(this).attr('id'));        
	return false;
	});

	$('.tabs li a').click(function(){
        $(this).parent().parent().find('li').removeClass('active');
        $(this).parent().addClass('active');
		//*
		var id = $(this).attr('id')
		$('.prices td').each(function(index, element){
			if(index > 4) return false;
			$(element).load('/auto/auto-83-'+id+'-100510000863-'+index+'.html');
			//console.log(index);
		})
		// */
		return false;
	});

	$('#feedback-form').submit(function(){return false;});

	$('#feedback-submit').click(function(){
		var name = encodeURIComponent($('input#feedback-name').val());
		var email = encodeURIComponent($('input#feedback-email').val());
		var text = encodeURIComponent($('textarea#feedback-text').val());
		if (name == null || name.length == 0 || email == null || email.length == 0 || text == null || text.length == 0 || name == "Ваше имя" || email == "Адрес e-mail") {
			return false;
		} else if (name.indexOf('Ваше') > -1 && name.indexOf('имя') > -1) {
			return false;
		} else if (email.indexOf('Адрес') > -1 && email.indexOf('e-mail') > -1) {
			return false;
		} else {
        		$.ajax ({
        		url: '/site?tid=1&action=feedback&name='+name+'&email='+email+'&text='+text,
        		success: function(data){$('div.shd-mid').html('<form class="feedback-form"><div class="close"></div><p>Ваше мнение нам очень важно.<br>Спасибо!</p></form>')},
        		error: function(data){$('div.shd-mid').html('<form class="feedback-form"><div class="close"></div><p>Во время отправки сообщения произошла ошибка</p></form>')}
        		});
			setTimeout(function() {$('.shd').hide();}, 2000); 
		}
        });


	$('.promo-menu li a').click(function(){
		countrysize = $(this).parent().prevAll().size();
	    $('.promo-menu li').removeAttr('id');
	    $(this).parent().attr('id','active');
	    $('.promo-content .country').hide();
	    $('.promo-content .country:eq('+countrysize+')').show();
		return false
	});

    sint = setInterval("promogo()",4000);

	$('.promo').hover(function(){
		clearInterval(sint);
	},function(){
		sint = setInterval("promogo()",4000);
	});

	$('.simple-calendar').datepick({
		showOn: 'both',
        buttonImageOnly: true,
		buttonImage: '/i/calendar.gif',
        useThemeRoller: true,
        duration: 0,
        showOtherMonths: true,
        selectOtherMonths: true,
        alignment: 'bottomRight',
        yearRange: '-70:+1'
	});

 	$('.twice-calendar').datepick({
		showOn: 'both',
        buttonImageOnly: true,
		buttonImage: '/i/calendar.gif',
        useThemeRoller: true,
        duration: 0,
        showOtherMonths: true,
        selectOtherMonths: true,
        alignment: 'bottomRight',
        yearRange: '-70:+1',
       	rangeSelect: true,
		onSelect: function(value, date) {
            if (value.length==0){
				return false
			}
            das = value.split(" - ");
            $(this).parent().parent().find('input.from').attr('value',das[0]);
            $(this).parent().parent().find('input.to').attr('value',das[1]);
		 }
	});


	$('.date-calendar').datepick({
        dateFormat: 'MM, d, yy',
        useThemeRoller: true,
        duration: 0,
        showOtherMonths: true,
        selectOtherMonths: true,
        alignment: 'bottomLeft',
        yearRange: '-70:+1',
        onSelect: function(value, date) {
           $('.text-calendar span').html(value)
		 }
	});

	$('.text-calendar').click(function(){
		$('.date-calendar').focus();
		return false
	});

	$('.feedback a.ico').click(function(){
	    $('.feedback .shd').show();
		return false
	});
	$('.enter a.login').click(function(){
	    $('.enter .shd').show();
		return false
	});

	$('.shd .close').click(function(){
	    $('.shd').hide();
		return false
	});

	$('.shd-mid .close').click(function(){
            $('.shd').hide();
                return false
        });

	$('.from, .to').click(function(){
		$(this).parent().parent().find('.twice-calendar').focus();
	});


	$('.carousel li a').click(function(){
		$('.carousel div').removeClass('active');
	    $(this).parent().addClass('active');
	    alink = $(this).attr('href');
	    miniphotos = $('.carousel ul').html();
	    $('#wrapper').append('<div id="overlay"></div><div id="gallery"><div class="big-pic"><img src="'+alink+'" alt="" /></div><div class="small-pic"><ul>'+miniphotos+'</ul></div></div>')
        $('#gallery .small-pic li').removeAttr('class').removeAttr('jcarouselindex');
        getscroll();
		$('select').css('visibility','hidden');
		$('#gallery').css('top',yScroll+90).show();
		if ($.browser.msie && $.browser.version==6){
			$('#overlay').css('height',$('#wrapper').height());
		}
		$('#overlay').css('opacity','0.9').show();
		$('#footer').css('z-index','1');
		$('#gallery .small-pic li a').click(function(){
		    $('#gallery .small-pic div').removeClass('active');
	   		$(this).parent().addClass('active');
		    slink = $(this).attr('href');
		    $('.big-pic img').attr('src',slink);
            return false
		});
		$('#overlay').click(function(){
			$(this).remove();
			$('#gallery').remove();
	 		$('#footer').css('z-index','11');
	 		$('select').css('visibility','visible');
		});
		return false
	});

	$('.gmap-point').click(function(){
	    $.scrollTo('.gmap',500);
		return false
	});

    if (navigator.userAgent.indexOf ('Linux')!= -1) {
$('#flash').html('<object type="application/x-shockwave-flash" data="/testStage.swf" width="100%" height="500" wmode="transparent" scale="noscale"><param name="movie" value="/testStage.swf" /><param name="scale" value="noscale" /><param name="wmode" value="transparent" /></object>')
	} else {
		
	}

});

function promogo(){
	var all = $('.promo-menu li').size();
	size = $('.promo-menu li#active').prevAll().size()+1;
	if (size==all){
		$('.promo-menu li:eq(0) a').click();
	} else {
		$('.promo-menu li:eq('+size+') a').click();
	}
}

function getscroll(){
	if (self.pageYOffset){
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body){
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}
};


/**
 * Таблица SPO отеля
 */
var spo = {
	night_width: 25,
	cursor: 0,

	_cache: [],
	_cur: 0,

	_night_offset: -7,
	_right_offset: 12,

	/**
	 * Запуск
	 * @param jQuery Если передан div.spo, будет обработан только он, иначе все
	 */
	init: function($spo){
		if (typeof $spo == 'undefined' || !$spo.is('div.spo'))
			$spo = $('.spo');
		spo.prepare($spo);
		spo.scroller($spo);
		spo.nightJumps($spo);
		spo.hoverTrs($spo);
	},

    /**
     * Склонировать таблицу, закешировать размеры и DOM-элементы
     * @param jQuery
     */
	prepare: function($spo){
        $spo.each(function(){
			var $nojs = $('.nojs-wrap', this);
			if ($nojs.length) {
				$nojs.parents('.overflow').html($nojs.html()).end().remove();
			}

			var $table = $('.overflow > table', this);

            if ($table.length != 1)
            	return true;

			// clone
            $table
            	.wrap('<div class="legend"><div class="wrap" /></div>')
				.clone()
				.insertAfter($table.parents('.legend'))
				.wrap('<div class="data"><div class="wrap" /></div>');


			// cache
			var i = spo._cache.length + 1;
			$(this).data('spo', i);
			spo._cache[i] = {};
			spo._cache[i].$scroll = $('.scroll', this);
			spo._cache[i].$nights = $('.nights', this);
			spo._cache[i].$spo = $(this);
			spo._cache[i].$data = $('.data .wrap', this);
			spo._cache[i].left = 0;
			spo._cache[i].right = spo._cache[i].$nights.width() - spo._cache[i].$scroll.width() - spo._right_offset;
			spo._cache[i].td_width = $('.data th', spo._cache[i].$spo).not('.food').not('.placement').eq(1).outerWidth();
        });
    },

    /**
     * Подсветка строк при наведении
     * @param jQuery
     */
	hoverTrs: function($spo) {
		$spo.each(function(){
			var $spo = $(this);
			var $data_trs = $('.data tr', this);
            var $lege_trs = $('.legend tr', this);

            $data_trs.unbind().hover(function(){
				var i = $data_trs.index(this);
				$data_trs.eq(i).addClass('hover');
                $lege_trs.eq(i).addClass('hover');
			}, function(){
				$('tr.hover', $spo).removeClass('hover');
			});

			$lege_trs.unbind().hover(function(){
				var i = $lege_trs.index(this);
				$data_trs.eq(i).addClass('hover');
                $lege_trs.eq(i).addClass('hover');
			}, function(){
				$('tr.hover', $spo).removeClass('hover');
			});

			$('td.food', $spo).unbind().hover(function(){
				$('tr.hover', $spo).removeClass('hover');
				return false;
			},function(){
				$('td.placement', $spo).one('mouseover', function(){
					$(this).parents('tr').mouseover();
				});
				return false;
			});

		});
	},

    /**
     * Обработка ползунка "количество ночей" (start drag)
     * @param jQuery
     */
	scroller: function($spo){
		$('.scroll', $spo).unbind().mousedown(function(e){
			spo._cur = $(this).parents('.spo').data('spo');
			spo.cursor = e.clientX - spo._cache[spo._cur].$nights.offset().left + document.documentElement.scrollLeft - spo._cache[spo._cur].$scroll.position().left;

			if (!($.browser.msie && $.browser.version < 8))
				$('body').addClass('dragged'); // в IE тормозит
			else
				$(this).addClass('dragged');

			$(document)
        		.mouseup(spo._mouseup)
        		.mousemove(spo._mousemove);
    		return spo._stopEvent(e);
		});

	},

	/**
	 *  Клик по количеству ночей на ползунке
	 *  @param jQuery
	 */
	nightJumps: function($spo){
		$('.nights a.night', $spo).unbind().click(function(){
			spo._cur = $(this).parents('.spo').data('spo');

			var nights = parseInt(spo._cache[spo._cur].$spo.attr('class').replace(/spo| /g, ' ').replace('nights-', ' '));

			var $a  = $(this);
			var $as = $('a.night', spo._cache[spo._cur].$nights)
			if ($as.index(this) > $as.length - nights)
				$a = $as.eq($as.length - nights);

			var x = $a.position().left + spo._night_offset;
			var dif = Math.abs(x - spo._cache[spo._cur].$scroll.position().left);

			spo._cache[spo._cur].$scroll.animate({
				left: x
			}, dif * 10);
			spo._cache[spo._cur].$data.animate({
				left: 0 - Math.floor(x * (spo._cache[spo._cur].td_width / spo.night_width))
			}, dif * 10);

			return false;
		});
	},

	/**
	 *  Обработка drag ползунка
	 *  @access private
	 *  @param object
	 *  @return bool
	 */
	_mousemove: function(e){
	    var x = e.clientX - spo._cache[spo._cur].$nights.offset().left + document.documentElement.scrollLeft - spo.cursor ;

	    if (x > spo._cache[spo._cur].right)
	        x = spo._cache[spo._cur].right;
	    else if (x < spo._cache[spo._cur].left)
	        x = spo._cache[spo._cur].left;

	    spo._cache[spo._cur].$scroll.css({left: x });
	    spo._cache[spo._cur].$data.css({left: 0 - Math.floor(x * (spo._cache[spo._cur].td_width / spo.night_width)) });

		return spo._stopEvent(e);
	},

	/**
	 * Обработка drop ползунка
	 * @access private
	 * @param object
	 * @return bool
	 */
	_mouseup: function(e){
		$('.dragged').removeClass('dragged');

	    $(document)
	        .unbind('mousemove', spo._mousemove)
	        .unbind('mouseup', spo._mouseup);

	    var x = e.clientX - spo._cache[spo._cur].$nights.offset().left + document.documentElement.scrollLeft - spo.cursor ;

	    if (x > spo._cache[spo._cur].right)
	        x = spo._cache[spo._cur].right;
	    else if (x < spo._cache[spo._cur].left)
	        x = spo._cache[spo._cur].left;
	    else {
			var prev_x = Math.floor(x / spo.night_width) * spo.night_width;
			var next_x = Math.ceil(x / spo.night_width) * spo.night_width;
			if (x - prev_x < next_x - x) {
				var dif = Math.abs(x - prev_x);
				x = prev_x;
			} else {
				var dif = Math.abs(next_x - x);
				x = next_x;
			}

			spo._cache[spo._cur].$scroll.animate({
				left: x
			}, dif * 10);
			spo._cache[spo._cur].$data.animate({
				left: 0 - Math.floor(x * (spo._cache[spo._cur].td_width / spo.night_width))
			}, dif * 10);
		}

	    return spo._stopEvent(e);
	},

	/**
	 * Сброс события
	 * @param object
	 * @return bool
	 */
	_stopEvent: function(e){
	    if (e.preventDefault) {
	    	e.preventDefault();
	    	e.stopPropagation();
	    } else {
	    	e.returnValue = false;
	    	e.cancelBubble = true;
	    }
	    return false;
	}

};
/* / var spo */
$(document).ready(function(){


/*if (navigator.appName=="msie"){*/

	$('ul.block_col_name').hover(
		function() {
			var n = $('li', this); var s = $('ul.block_col_sub', n);
			$(s).css("display","block").css("margin-top","-15px");
		},
		
		function(){
			var n = $('li', this); var s = $('ul.block_col_sub', n);
			$(s).css("display","none");

		});

/* } */ 

});

function loadpagecnt(id){
	$('#pagecnt').html('loading...');
	$('#pagecnt').load('auto/autong-66-'+id+'-100510000863-700.html');
}

function loaddefpage(){
	var lID = '';
	var s = document.location+'';
	var x = s.indexOf('?',0);
	s = s.substr(x+1,s.length-x);
	var seq = s.split('&');
	for(i=0;i<seq.length;i++){
		var prm = seq[i].split('=');
		if((prm.length>1)&&(prm[0]=='flt')){
			lID = prm[1];
			break;
		}
	}
	if(lID.length==0){lID='100410000049'};
	$('#x'+lID).addClass('active');
	loadpagecnt(lID);
}

