$(document).ready(
  function()
  {	
		current_marg_top = 0;
		li_count = $("ul#img_list > li").length;
		if (typeof(currentThumb)!='undefined') {	
		//фотоальбом (страна, курорт, отель)
			$("ul#img_list li img").bind("mouseover",function(){$(this).addClass('hover')});
			$("ul#img_list li img").bind("mouseout",function(){$(this).removeClass('hover')});
			$("ul#img_list li img").bind("click",function(){ChangePhoto($(this).attr('id'))});
				
			$("ul#img_list li img#"+currentThumb).unbind('mouseover');
			$("ul#img_list li img#"+currentThumb).unbind('mouseout');
			$("ul#img_list li img#"+currentThumb).unbind('click');
				
			$("ul#img_list li img#"+currentThumb).addClass('current');
				
			bind_arrows();
			bind_change_arrows();
		}				
  }
);
function OpenAskForm(a) {	
	
	var feedback_window = {
			width: 510,
			height: 436,			
			left: function() {return Math.ceil((screen.availWidth - this.width)/2)},
			top: function() {return Math.ceil((screen.availHeight - this.height)/2)},
			open: function(href) {
				window.open(href, 'feedback', 'scrollbars=0,width='+this.width+',height='+this.height+',left='+this.left()+',top='+this.top()+',resizable=0,toolbar=0,location=0,status=0,menubar=0,directories=0');
			}
	};
	
	feedback_window.open(a.href);
	
	return false;
}
function ScreenSize(){
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
    myTop = window.pageYOffset;
    myLeft = window.pageXOffset;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
    myTop = document.documentElement.scrollTop;
    myLeft = document.documentElement.scrollLeft;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
    myTop = document.body.scrollTop;
    myLeft = document.body.scrollLeft;
  }
}
function CheckForm(mf) {
  var error=0;  
  if (error==0 && mf.fio.value=='') {
    alert('Заполните, пожалуйста, поле \"ФИО\"');
		mf.fio.focus();
		error=1;
  }
	if (error==0 && (mf.phone.value=='' || mf.phone.value.match(/[^\d \-()\+]+/i))) {
    alert('Введите, пожалуйста, корректный номер телефона');
	  mf.phone.select();
		mf.phone.focus();
	  error=1;
  }
	if (error==0 && !mf.email.value.match(/^\s*[a-zA-Z0-9._-]+\@[^\s:,]+\.[^\s:,]+$/i)) {
    alert('Заполните, пожалуйста, поле \"e-mail\" корректным e-mail адресом');
		mf.email.select();
		mf.email.focus();
		error=1;
  }
	if (error==0 && mf.about.value=='') {
		alert('Введите, пожалуйста, ваше сообщение');
		mf.about.focus();
		error=1;
  }
	if (error==0 && !mf.code.value.match(/^\d{4}$/)) {
    alert('Введите, пожалуйста, четыре цифры кода');
	  mf.code.select();
		mf.code.focus();
	  error=1;
  }
  if (error==0) {
    //mf.submit();		
		script = document.createElement("script");
		script.src = "/sendmail.phtml?fio="+mf.fio.value+"&email="+mf.email.value+"&phone="+mf.phone.value+"&about="+mf.about.value+"&code="+mf.code.value+"&ref="+escape(location.href);		
		document.body.appendChild(script);
  }
	return false;
}
function CloseForm() {	
	document.getElementById('send_form_cont').style.display = 'none';
	document.getElementById('send_form_cont_iframe').style.display = 'none';
	document.zakaz.reset();
	document.getElementById('captcha').src='/captcha.php?id='+(Math.round(10000*Math.random()));
}

var j=0;
function OpenCitiesPhAlbum() {
	
	if(typeof(intervalId)!='undefined')
		clearInterval(intervalId);
	
	var tmp = get("ph_cont0");
	ScreenSize();
	if(myHeight>485)
		tmp.style.top = (myHeight/2+myTop-250) + "px";
	else
		tmp.style.top = myTop + "px";	
		
	
	ChangePhoto("thumb"+prev);
	
	tmp.style.display = "block";
	
  $('iframe.ph_cont0_if').css({opacity: 0});
  
	//перелистываем на открытую фотку, если она вне зоны видимости
	if(prev>3) {
		initMarginTop = (prev-3)*(-106);
		unbind_arrows();
		$("ul#img_list li:first-child").animate({ marginTop: initMarginTop+"px" }, 300, after_move);
	}
	
	// привязываем событие - закрытие окна по Escape
	$("body").bind('keydown', CloseOnEsc);
	
	return false;
}
function CloseOnEsc(event) {
	
	if(event.keyCode==27) {
		CloseCitiesPhAlbum();
		return false;
	}
	else if(event.keyCode==38) {
		$("img#up_arrow").click();
		return false;
	}
	else if(event.keyCode==40) {
		$("img#down_arrow").click();
		return false;
	}
}
function CloseCitiesPhAlbum() {
	get('ph_cont0').style.display = 'none';
	// удаляем событие - закрытие окна по Escape
	
	$("ul#img_list li:first-child").css("margin-top","0");
	current_marg_top = 0;
	bind_change_arrows();
	
	$("body").unbind('keydown', CloseOnEsc);	
	if(typeof(COUNTRY_VITRINA_UPD)!='undefined' && li_count>1)
		intervalId = setInterval('changeCountryVitrina()', COUNTRY_VITRINA_UPD);
	return false;
}

function showMap() {
	
	var tmp = get("ph_cont0_map");
	ScreenSize();
	if(myHeight>485)
		tmp.style.top = (myHeight/2+myTop-250) + "px";
	else
		tmp.style.top = myTop + "px";	
	
  $('iframe.ph_cont0_map_if').css({width: $('table.cont').css('width'), height: $('table.cont').css('width'), opacity: 0});
  
	tmp.style.display = "block";
	
	// привязываем событие - закрытие окна по Escape
	$("body").bind('keydown', CloseOnEsc);
	
	return false;
}


function closeMap() {
	get('ph_cont0_map').style.display = 'none';
	// удаляем событие - закрытие окна по Escape
	
	$("body").unbind('keydown', CloseOnEsc);
  
	return false;
}

function NextPhoto() {	
	j++;
	if(j<photosList.length) {
		ChangePhoto(j);
	}
	else
		j=photosList.length-1;
		
	return false;
}
function PrevPhoto() {
	j--;	
	if(j>=0) {
		ChangePhoto(j);
	}
	else
		j=1;
	return false;	
}
function FirstPhoto() {
		ChangePhoto(0);
		j=0;
		return false;	
}
function LastPhoto() {
		ChangePhoto(photosList.length-1);
		j=photosList.length-1;
		return false;	
}

function get(id) {
    return document.getElementById(id);
}

function blockEvent(event) {
		if (!event) {
        event = window.event;
    }
    if (event.stopPropagation) {
        event.stopPropagation();
    }
    else {
        event.cancelBubble = true;
    }
    if (event.preventDefault) {
        event.preventDefault();
    }
    event.returnValue = false;
}

function wheel(event) {
	var wheelDelta = 0;
  
	if (!event) {
    event = window.event;
  }
	if (event.wheelDelta) {
		// В IE и Safari значения delta всегда строго 120, вне зависимости от настроек пользователя.
		wheelDelta = event.wheelDelta/120;
    // В Opera 9, значение delta домножается на 40 и совпадает по знаку со значениями в IE
        if (window.opera)
        {
            wheelDelta = event.wheelDelta/40;
        }
    } 
    else if (event.detail) 
    {
        // В Mozilla, значение wheelDelta отличается по знаку от значения в IE.
        // По модулю wheelDelta строго совпадает со значением в пользовательких настройках
        wheelDelta = -event.detail;
    }
    // При скроллинге вверх wheelDelta > 0
    // При скролинге вниз - wheelDelta < 0
    // Значение wheelDelta можно использовать, а можно игнорировать
    
    // Опытным путем установлено:
    // Если в Windows установлена прокрутка на "один экран" при одном сдвиге колеса
    // То в Mozilla мы получим, что wheelDelta принимает значение 32768
    // А в Opera событие при этом вообще не возникает
    
    // Определив все тонкости, обработаем значение wheelDelta:
    if (wheelDelta)
    {
        // Мы вне зависимости от значений wheelDelta будем сдвигать меню строго на 1 шаг
        if(wheelDelta < 0)
					alb_down();
				else
					alb_up();					
    }	
	
		blockEvent(event);
}	

function ChangePhoto(index) {
	
	$("ul#img_list li img#"+currentThumb).removeClass();
	
	$("ul#img_list li img#"+currentThumb).bind("mouseover",function(){$(this).addClass('hover')});
	$("ul#img_list li img#"+currentThumb).bind("mouseout",function(){$(this).removeClass('hover')});
	$("ul#img_list li img#"+currentThumb).bind("click",function(){ChangePhoto($(this).attr('id'))});
	
	$("ul#img_list li img#"+index).unbind('mouseover');
	$("ul#img_list li img#"+index).unbind('mouseout');
	$("ul#img_list li img#"+index).unbind('click');
	
	$("ul#img_list li img#"+index).removeClass();
	$("ul#img_list li img#"+index).addClass('current');
		
	$("span#big_img_span").html(big_img_list[index.substr(5)][0]);
	$("span#big_img_caption").html(big_img_list[index.substr(5)][1]);
	currentThumb = index;
}

function bind_change_arrows() {
	if(current_marg_top!=0) {
		$("img#up_arrow").attr("src","/img/photoalbum/top.gif");
		$("img#up_arrow").css("cursor","pointer");
		$("img#up_arrow").bind("mouseover", function(){$(this).attr("src","/img/photoalbum/top2.gif")});
		$("img#up_arrow").bind("mouseout", function(){$(this).attr("src","/img/photoalbum/top.gif")});
	}
	else {
		$("img#up_arrow").unbind("mouseover");
		$("img#up_arrow").unbind("mouseout");
		$("img#up_arrow").attr("src","/img/photoalbum/top0.gif");
		$("img#up_arrow").css("cursor","default");
	}
	
	if(li_count>4 && current_marg_top!=(li_count-4)*(-106)) {
		$("img#down_arrow").attr("src","/img/photoalbum/bottom.gif");
		$("img#down_arrow").css("cursor","pointer");
		$("img#down_arrow").bind("mouseover", function(){$(this).attr("src","/img/photoalbum/bottom2.gif")});
		$("img#down_arrow").bind("mouseout", function(){$(this).attr("src","/img/photoalbum/bottom.gif")});
	}
	else {
		$("img#down_arrow").unbind("mouseover");
		$("img#down_arrow").unbind("mouseout");
		$("img#down_arrow").attr("src","/img/photoalbum/bottom0.gif");
		$("img#down_arrow").css("cursor","default");
	}
	//$("img#down_arrow").bind("click", alb_down);
}

function bind_arrows() {
	$("img#up_arrow").bind("click", alb_up);
	$("img#down_arrow").bind("click", alb_down);
	
	// Инициализация обработчика колеса мыши, повесим его только на слой img_list 
  // Для Mozilla необходимо создать EventListener:	
	if (get('img_list').addEventListener) {
		get('img_list').removeEventListener('DOMMouseScroll', blockEvent, false);
		get('img_list').addEventListener('DOMMouseScroll', wheel, false);
	}
	
	// Для всех остальных браузеров подойдет вот такая инициализация:
	if(get('img_list'))
		get('img_list').onmousewheel = wheel;
	
}
function unbind_arrows() {
	$("img#up_arrow").unbind("click");
	$("img#down_arrow").unbind("click");
	
	if (get('img_list').addEventListener) {
		get('img_list').removeEventListener('DOMMouseScroll', wheel, false);
		get('img_list').addEventListener('DOMMouseScroll', blockEvent, false);
	}
	get('img_list').onmousewheel = blockEvent;
}
function after_move() {
	bind_arrows();
	current_marg_top = $("ul#img_list li:first-child").css("margin-top").replace("px","")*1;
	bind_change_arrows();
}

var current_marg_top=0;
var li_count;

function alb_down() {	
	if(li_count>4 && current_marg_top!=(li_count-4)*(-106)) {
		unbind_arrows();
		$("ul#img_list li:first-child").animate({ marginTop: "-=106px" }, 300, after_move );
	}
}
function alb_up() {		
	if(current_marg_top!=0) {
		unbind_arrows();
		$("ul#img_list li:first-child").animate({ marginTop: "+=106px" }, 300, after_move );
	}
}

function CheckUserQuestionForm(mf) {
  var error=0;  
  if (mf.fio.value=='' && error==0) {
    alert('Введите, пожалуйста, Ваше имя');
		mf.fio.focus();
		error=1;
  }
	if (error==0 && mf.email.value!='' && !mf.email.value.match(/^\s*[a-zA-Z0-9._-]+\@[^\s:,]+\.[^\s:,]+$/i)) {
    alert('Заполните, пожалуйста, поле \"e-mail\" корректным e-mail адресом');
		mf.email.select();
		mf.email.focus();
		error=1;
  }
	if (error==0 && mf.about.value=='') {
		alert('Введите, пожалуйста, ваше сообщение');
		mf.about.focus();
		error=1;
  }
	if (error==0 && !mf.code2.value.match(/^\d{4}$/)) {
    alert('Введите, пожалуйста, четыре цифры кода');
	  mf.code2.select();
		mf.code2.focus();
	  error=1;
  }
  if (error==0) {		
		//mf.submit();		
		script = document.createElement("script");
		script.src = "/user_question.phtml?fio="+mf.fio.value+"&email="+mf.email.value+"&city="+mf.city.value+"&about="+mf.about.value+"&code="+mf.code2.value;
		document.body.appendChild(script);
		
  }
	return false;
}

function AddRow() {  
  c++;
	tr = '<tr><td><input class="input_text" name="pass_fio[]" value="" /></td><td><input class="input_text" style="width: 80px;" name="pass_birthday[]" value="" /></td><td><a href="#" onClick="RemoveRow(this); return false;"><img align="absmiddle" src="/i/remove_row.gif" width="19px" height="18px" alt="удалить" /></a></td></tr>';
  $("table#passengers").append(tr);
  
}

function RemoveRow(obj) {
  
	if (c == 0) {
		$("table#passengers td input[type='text']").attr("value","");
    return false;
  }
	else c--;
  
  document.getElementById("passengers").getElementsByTagName('TBODY')[0].deleteRow(obj.parentNode.parentNode.sectionRowIndex);
  
  return false;
}

function CheckAviaForm(mf) {
  var error=0;  
  if (error==0 && mf.fio.value=='') {
    alert('Введите, пожалуйста, имя контактного лица');
		mf.fio.focus();
		error=1;
  }
	if (error==0 && (mf.phone.value=='' || mf.phone.value.match(/[^\d \-()\+]+/i))) {
    alert('Введите, пожалуйста, корректный номер телефона');
	  mf.phone.select();
		mf.phone.focus();
	  error=1;
  }	
	if (error==0 && !mf.email.value.match(/^\s*[a-zA-Z0-9._-]+\@[^\s:,]+\.[^\s:,]+$/i)) {
    alert('Заполните, пожалуйста, поле \"e-mail\" корректным e-mail адресом');
		mf.email.select();
		mf.email.focus();
		error=1;
  }
	if (error==0 && mf.route.value=='') {
		alert('Введите, пожалуйста, маршрут');
		mf.route.focus();
		error=1;
  }
	if (error==0 && mf.date_departure.value=='') {
		alert('Введите, пожалуйста, дату отправления');
		mf.date_departure.focus();
		error=1;
  }
	if (error==0 && !mf.code3.value.match(/^\d{4}$/)) {
    alert('Введите, пожалуйста, четыре цифры кода');
	  mf.code3.select();
		mf.code3.focus();
	  error=1;
  }
  if (error==0) {		
		return true;		
  }
	return false;
}

var prev = 0;
var next = 1;
function changeCountryVitrina() {
	var numBanners = $("ul#country_vitrina > li").length;
	
	$("li#ph"+prev).fadeOut(800);
	$("li#ph"+next).fadeIn(800);

	prev++;

	if(prev==(numBanners-1))
		next=0;
	else
		next = prev+1;
	
	if(prev==numBanners) {
		prev=0;
		next=1;
	}
	
}


function changeShowcaseBanner(row, id_banner_to_show) {
	if(id_banner_to_show!=current_banner) {
		$("ul#main_ban_cont > li#ban"+current_banner).fadeOut(800);
		$("ul#main_ban_cont > li#ban"+id_banner_to_show).fadeIn(800);	
		$("ul.thumb_ban_cont > div > li#thumb_"+row+"_"+id_banner_to_show).fadeOut(800);
		$("ul.thumb_ban_cont > div > li#thumb_"+row+"_"+current_banner).fadeIn(800);
		
		
		script = document.createElement("script");
		script.src = "/js/ad_view.js.php?ban="+id_banner_to_show;
		document.body.appendChild(script);
		
		current_banner = id_banner_to_show;
	}
	return false;
}

function showMapMenu() {
                
  $('#flash_popup_menu').css({display: 'block', visibility: 'visible'});
  
  setTimeout('divBind()', 500); 
  
  return false;
}

function closeMapMenu(parm) {
  
  $('#flash_popup_menu').css({display: 'none', visibility: 'hidden'});
  
  $('body').unbind('click');
  
  //return false;
  
}

function divBind() {

  $('body').bind('click', function() {
    closeMapMenu();
  })
  
}

function openSearch(frm) {
  
  if (frm.elements["q"].value) {
  return true;
  // window.open("http://www.google.com/search?hl=ru&q=site%3Aexotictime.ru+" + frm.elements["q"].value,"_exotic_search").focus();
  } else {
    
    alert("Введите поисковую фразу");
    frm.elements["q"].focus();
    
  }
  
  return false;
}

//{{{ changeCat()
function changeCat() {
  
  var idCity = document.getElementById('scity_id').value;
  
  var req = new JsHttpRequest();
  req.onreadystatechange = function() {
      if (req.readyState == 4) {
        if (req.responseJS) {
          
          var aCategory = req.responseJS.listCategory;
          
          listCategory = document.getElementById('cat_hotel_id');
          var selCategory = listCategory.value; 
          listCategory.options.length = 0;
          
          // Выводим начальное значение
          listCategory.options[0] = new Option('- Выберите -', 0);
          
          // В цикле гоним все значения
          var i = 1;
          
          for (var key in aCategory) {
            listCategory.options[i] = new Option(aCategory[key], key);
            if (listCategory.options[i].value == selCategory) listCategory.options[i].selected = true;
            i ++;
          }
          
          // разблокируем для вывода
          if (i > 1) listCategory.disabled = false;// else resetList('serie_id');
          
        }
      }
  }
  
  document.getElementById('cat_hotel_id').disabled = true;
  req.caching = true;
  req.open('POST', '/rs/get_category/', true);
  req.send({city_id: idCity});
  
}
//}}}

//{{{ для работы с картинками exat.ru
function wi(img/*,width,height*/, comment, img_dir) {
	width=290;height=150;
	size='';
	var url='http://exat.ru/htdocs/getimage.php?img='+escape(img)+'&path='+escape('http://exat.ru/' + img_dir);
	if(comment)
		url+='&comment='+escape(comment);
	if(width && height)
		size=',width='+width+',height='+height;
	var strInitParam='directories=no,status=no,scrollbars=no,resizable=yes,menubar=no,toolbar=no';
	var wndname = genRandomStr(10);
//	alert(wndname);
	var description=window.open('', wndname, strInitParam+size);
//	description.document.title = 'Пожалуйста, подождите. Идет загрузка...';
	description.document.write('Downloading image...');
	if(! description.browser){
		description.document.location=url;
	}
	description.focus();
	return description;
}

function genRandomStr(strlen) {
	str = '';
	for (i = 0; i < strlen; i++) {
		str += String.fromCharCode(Math.random()*25 + 97);
	}
	return str;
}

/*Функция выбора показа превющих или нормальных изображений*/

function switch_layers(name){
	var piclist=document.getElementsByName(name);
	var i=0;
	for(;i<piclist.length;i++){
//			alert(piclist[i].name);
			if(piclist[i].style.display == "none"){
				piclist[i].style.display = "";
				piclist[i].style.visibility = "visible";
			}else{
				piclist[i].style.visibility = "hidden";
				piclist[i].style.display = "none"; 
			}
//			alert(piclist[i].name);
	}
}

function prepareDesc(){
}

