/* Fit homepage images to screen size */

var current_big_image = 0;
var resize_me = 1;
   
$(function () {

$("#pg_preview").css({
	height: $(window).height()+"px",
	width: $(window).width()+"px"
});

   $(window).resize(function () {
      $(".h").css({
         height: $(window).height()+"px"
      });
	  $("#pg_preview").css({
		height: $(window).height()+"px",
		width: $(window).width()+"px"
	  });
   });
   
if(resize_me > 0){

   $("#pg_preview img").each(function () {
	   var img = $(this);

	   var img_width = img.attr("width");
	   var img_height = img.attr("height");
/*	   img.attr("width", img_width);
	   img.attr("height", img_height);*/
	   img.attr("w", img_width);
	   img.attr("h", img_height);
      
      img.css({
         width: 'auto',
         'min-height': '0px',
         visibility: 'visible'
      });
      
      img.removeAttr("width").removeAttr("height");
      
      var img_w = parseInt( img.attr("w") );
      var img_h = parseInt( img.attr("h") );
      var current_img_prop = img_w/img_h;
      
      $(window).resize(function () {
         if ( img.index() != current_big_image )
            return;
         
         var window_h = $(window).height();
         var window_w = $(window).width();
         var h = window_h;
         var w = window_w;
         var w_margin = 0;
         var h_margin = 0;
         
         var current_prop = window_w/window_h;
         
         
         if (current_prop > current_img_prop)
         {
            w = window_w;
            h = w / current_img_prop;  
         }
         else
         {
            h = window_h;
            w = h * current_img_prop;  
         }
         w_margin = (window_w - w) / 2;
         h_margin = (window_h - h) / 2;
         
         img.css({
            height: h+"px",
            width:  w+"px",
            marginLeft: w_margin+"px",
            marginTop: h_margin+"px"
         });
         
      });
   });
   $(window).trigger('resize');
} else {
	var window_width= $(window).width();
	$("#pg_preview img").each(function () {
		var img = $(this);
		var img_width = img.width();
		img.css({
			left: (window_width-img_width)/2+"px",
			visibility: 'visible'
		});
	});
}

});




/* Slider thumbstrip, controls and autoplay */
var homeSlider = {
   animSpeed: 600,
   interval: 5000,
   //interval: 500,
   autostart: 1 // autoplay on
};

var sh_tout = false;
var sh_interval = homeSlider.interval + homeSlider.animSpeed;
var allow_slider_mouseover = true;

function stop_slideshow()
{
   if (sh_tout)
      clearTimeout(sh_tout);
}

function go_next_slide(p, new_slide, it_is_manual) {
   stop_slideshow();
   var nextSlide = current_big_image;
   
   if (it_is_manual)
   {
      nextSlide = new_slide;
   }
   else
   {
   
      nextSlide += (p > 0 ? -1 : 1);
      
      if (nextSlide > $("#thumbScroller .content").length-1)
         nextSlide = 0;
      if (nextSlide == -1)
         nextSlide = $("#thumbScroller .content").length-1; 
         
   }
   
   /*
   var e = new jQuery.Event("mousemove", {
      pageY: ( $(window).height()/2 )
   });
   $('#thumbScroller').trigger(e);
   */
   
	var h_one = 96;
	var ct = nextSlide*h_one + h_one/2 + 10;
	ct -= $(window).height() / 2;
	
	var e = new jQuery.Event("click");
	e.manual = true;
	
	e.no_anim_arrow = 0;
	
	if (ct < 0)
	{
	   ct = 0;
	   //e.no_anim_arrow = 1;
	}
	
	var max_h = $("#thumbScroller .container").height() - $(window).height() + 23;
	
	//console.log(ct +"; "+ max_h);
	
	if (ct > max_h)
	{
	   ct = max_h;
	   //e.no_anim_arrow = 1;
	}
	
	ct *= -1;
	
	var init_mt = parseFloat( $(".marker").css('top') );
	var new_mt = nextSlide*h_one + h_one/2 + 10;
	
	var old_ct = parseFloat( $("#thumbScroller .container").css('top') );
	
	var nochange = 0;
	
	if ( Math.abs( old_ct - ct ) < 1.5 )
	{
	   e.no_anim_arrow = 1;
	   nochange = 1;
	}
	
   allow_slider_mouseover = false;
   
   if (it_is_manual)
   {
      nochange = 1;
   }
	
	if ( ( $("#thumbScroller .container").height() < $(window).height() - 23 -44 ) || nochange )
	{
	   $(".marker").animate({
	      'top': new_mt+"px"
	   }, {
	      duration: homeSlider.animSpeed,
	      complete: function () {

   	      allow_slider_mouseover = true;
	      }
	   });
	}
	else
	{
      $("#thumbScroller .container").animate({
         top: ct+"px"
      }, {
         duration: homeSlider.animSpeed,
         queue: false,
         complete: function () {
            allow_slider_mouseover = true;
         },
         step: function (now, fx) {
            if (!e.no_anim_arrow || it_is_manual)
            {
               //console.log(now, fx);
               var mt = 0;
               mt += init_mt;
               var delta = (fx.start - now);
               var delta_all = (fx.start - fx.end);
               var delta_full = (new_mt - init_mt);
               
               var eps = Math.abs(Math.abs(delta_all) - 96.5);
               
               //console.log("eps="+eps+"; delta="+delta+"; delta_all="+delta_all+"; delta_full="+delta_full);
               
               if ( eps <= 1 )
               {
                  delta_full = delta;
               }
               else
               {
                  delta_full *= delta/delta_all;
               }
                  
               mt += delta_full;
               //mt += delta;
               //console.log(delta_full);
               $(".marker").css('top', mt+"px");
            }
         }
      });
   }
   
   if (!it_is_manual)
      $("#thumbScroller .content:eq("+nextSlide+")").trigger(e);
   
   if ( $(".navig a:eq(1)").hasClass('stop') && !it_is_manual )
   {
      start_slideshow();
   }
}

function start_slideshow()
{
   if (sh_tout)
      clearTimeout(sh_tout);
   sh_tout = setTimeout(go_next_slide, sh_interval);
   
}

$(function () {

   if ( !$(".container").length ) 
      return;
   
   if ( $(".content").length < 2 )
   {
      $(".navig, #thumbContainter").hide();
      $("#pg_desc2 div, #pg_desc1 div").css({
         right: '20px'
      });
      return;
   }

   $(".navig a:eq(1)").click(function () {
      if ( $(this).hasClass("play") )
      {
         $(this).removeClass("play").addClass("stop");
         start_slideshow();
      }
      else
      {
         $(this).removeClass("stop").addClass("play");
         stop_slideshow();
      }
      return false;
   });

   $(".content:first").click();

   if (homeSlider.autostart)
      $(".navig a:eq(1)").trigger("click");
   
   var can_click = 1;
   $(".navig a:eq(0), .navig a:eq(2)").click(function () {
      if (!can_click)
         return false;
      can_click = 0;
      go_next_slide( $(this).index() == 0 ? 1 : 0 );
      setTimeout(function () {
         can_click = 1;
      }, homeSlider.animSpeed+100);
      return false;
   });
   
   $("#thumbScroller").hover(function () {
      if ( $(".stop").length )
         stop_slideshow();
   }, function () {
      if ( $(".stop").length )
         start_slideshow();
   });
   
   if ( $("#thumbScroller .container").length )
      $("body").bind('mousewheel', function () {
         return false;
      });
   
});

Cufon.CSS.ready(function() {
   var d = $("body:not(.home-static) #pg_desc1 > div:eq(0)");
   var right_t =  650 - d.outerWidth();
   d.css('right', right_t+"px");
   
   var hd = $("body.home-static #pg_desc1 > div:eq(0)");
   var hd_right_t =  262 - d.outerWidth();
   hd.css('right', hd_right_t+"px");
});


/* Autoadvance */
$(window).load(function(){

	// Событие window.load гарантирует, что все изображения
	// будут загружены прежде, чем автопроигрывание начнет действовать.
	
	var timeOut = null;

	$('#pg_preview .thumbContainter').click(function(e,simulated){
		
		// Параметр simulated устанавливается методом trigger/
				
		if(!simulated){
			
			// Произошло реальное событие click. Сбрасываем таймер.
						
			clearTimeout(timeOut);
		}
	});

	// Самовыполняющаяся функция:
	
	(function autoAdvance(){
		
		// Имитация события click на кнопке "следующий".
		$('#pg_preview .thumb').trigger('click',[true]);
		
		// Устанавливаем таймер на 2 секунды.
		timeOut = setTimeout(autoAdvance,2000);		
	})();

});
