﻿//Инициализация
$(function(){
    initDropDown();
    if($('#mainPageContainer .banner').length > 0)
    {        
        $('#mainPageContainer .banner').rotateBanner({changeSpeed:0,menuElementSelector:'ul.links li'});
    }
    initGallery();  
});



var initGallery = function(){
    var interval = 50;
    var step = 7;
    if($("#galleryContainer").length == 0) return;
    var container = $("#galleryContainer .list");    
    var containerWidth = container.width();
    var driver = $(".driver", container);
    var driverPosition = 0;
    var driverWidth = driver.width(); 
    var fullView = $("#galleryContainer .fullView");
    var fullImageWidth = $('img', fullView).width(); 
    var clickDirection = 0;
     
    var timer = 0;    
    var mouseX = 0;
    
    container.unselectable();
    
    var smallImageLoaded = function(){
        driverWidth = driver.width();
        if(driverWidth < containerWidth)
        {
            driver.css('left',((containerWidth - driverWidth) / 2)+ 'px');
        }
        else
        {
            driver.css('left','0px');
        }    
    }
    
    $('img', container).load(smallImageLoaded);
    smallImageLoaded();
    
    var moveContainer = function()
    {
        //window.console && console.log(mouseX + " " + (containerWidth - 100) + " " + driverPosition + " " + (driverWidth));
        if(mouseX < 100 && driverPosition < 0)
        {
            //window.console && console.log("go left");
            driverPosition = Math.min(driverPosition + step, 0);
            driver.css("left",driverPosition);
            //window.console && console.log(driverPosition);
            return true;                    
        }     
        if(mouseX > containerWidth - 100 && driverPosition > containerWidth - driverWidth)
        {            
            driverPosition = Math.max(driverPosition - step, containerWidth - driverWidth);
            driver.css("left",driverPosition);
            //window.console && console.log(driverPosition);
            return true;                                
        }                                                                                  
        clearInterval(timer);
        timer = 0;
        return false;        
    }
    
    container.mousemove(function(e){  
        if(driverWidth > containerWidth)
        {  
            mouseX = e.pageX - this.offsetLeft; 
            if(timer == 0 && moveContainer())
            {
                //window.console && console.log("go to mouseX = " + mouseX);
                timer = setInterval(moveContainer, interval);
            }
        }    
    });    
    
    container.mouseleave(function(){
        if(timer != 0)
        {
            clearInterval(timer);
            timer = 0;
        }        
    });
    
    fullView.mousemove(function(e){     
        var mouseX = e.pageX - this.offsetLeft -10;
        var pos = 0;
        var fromCenter = mouseX - containerWidth / 2;
        var sign = (fromCenter > 0) ? 1 : -1;
        clickDirection = sign;
        if(Math.abs(fromCenter) > fullImageWidth / 2)
        {
            pos = containerWidth / 2 + sign * (fullImageWidth / 2);
        }
        else
        {
            pos = containerWidth / 2 + sign * (fullImageWidth / 2 - 64)  + 128 * fromCenter / fullImageWidth;
        }
        $(this).css('background-position',(pos-64)+'px 0px'); 
    });         

    fullView.mouseleave(function(){
        $(this).css('background-position','50% 0px');    
    });   
    
    fullView.click(function(){
        if(clickDirection == -1)
        {
            $('a.selected', driver).prev().click();    
        }
        else
        {
            $('a.selected', driver).next().click();
        }            
    });
     
    window.console && console.log($('a', driver).length);
    $('a', driver).click(function(){
    
        $('a', driver).removeClass("selected");
        $(this).addClass("selected");
        window.console && console.log(this.offsetLeft);
        var src= $(this).attr('href');
        fullView.addClass('loading');                    
        $('img', fullView).attr('src', src);
        
        var w = $(this).width();
        
        if(this.offsetLeft > containerWidth - driverPosition - w)
        {
            driverPosition = containerWidth - this.offsetLeft - w - 10; 
            driver.animate({"left":driverPosition},200);
        }
        
        if(this.offsetLeft < - driverPosition + 10)
        {
            driverPosition = 10 - this.offsetLeft; 
            driver.animate({"left":driverPosition},200);
        }        
                
        return false;        
    });
    
    $('img', fullView).load(function(){
        fullView.removeClass('loading');
        fullImageWidth = $(this).width();        
    });  
    
    $('a', driver).eq(0).click();  
}



//Выпадающее меню, список магазинов
var initDropDown = function(){

    var opened = false;
    
    var documentClick = function()
    {
        if(opened)
        {        
            $("#siteSelector").animate({height:$("#siteSelector ul li").height()}, 100,function(){
                opened = false;   
            });                   
        }        
        $(document).unbind( "click", documentClick);
    }
    
    $("#siteSelector a.button").click(function(){
        if(!opened)
        {
            $("#siteSelector").animate({height:$("#siteSelector ul").height()}, 100, function(){
                opened = true;
                $(document).bind( "click", null, documentClick);            
            });
        }            
    });
}


//Плагин для баннера
jQuery.fn.rotateBanner = function(options)
{

	var options = jQuery.extend({
		changeDelay: 7000, // время смены, мс
		changeDelayAfterClick: 30000, // время смены после того, как пользователь выбрал какой-то элемент, мс
		changeSpeed: 1000, //Время на смену картинки
		menuElementSelector: 'li', //Селектор для элемента меню в баннере
		menuElementContentSelector: 'div' //Селектор для контента элемента меню, должен находится внутри самого элемента меню и скрыт
	},options);

	return this.each(function(){

		var banner = $(this);
		var height = banner.height();
		var items = [];
		var currentItem = null;
		var selectedItem = null;
		var timer = 0;
		var busy = false;

		function NavClicked(index)
		{
			selectedItem = index;
			UpdateMenu();
			Change();
			SetTimer(options.changeDelayAfterClick);
		}

		function UpdateMenu()
		{
			banner.find(options.menuElementSelector).removeClass('selected').eq(selectedItem).addClass('selected');
		}

		function Change()
		{
			if(busy)return;
			if(currentItem == selectedItem)return;

			if(currentItem != null)
			{
                if(options.changeSpeed > 0)
                {			     
    				busy = true;
    				items[currentItem].obj.animate({top:-height}, options.changeSpeed);
    				items[selectedItem].obj.css({top:height}).animate({top:0}, options.changeSpeed, function(){
    
    					busy = false;
    					if(currentItem != selectedItem)
    					{
    						Change();
    					}
    
    				});
				}
				else
				{
				    items[currentItem].obj.css({top:-height});
                    items[selectedItem].obj.css({top:0});
                }
			}
			else
			{
				items[selectedItem].obj.css({top:0});
			}
			currentItem = selectedItem;
		}

		function Next()
		{
			if(busy)return;
			selectedItem++;
			if(items[selectedItem] == null)selectedItem = 0;
			UpdateMenu();
			Change();
			SetTimer(options.changeDelay);
		}

		function SetTimer(delay)
		{
			if(timer!=0)clearTimeout(timer);
			timer = setTimeout(Next,delay);
		}

		banner.find(options.menuElementSelector).each(function(index){

			$this = $(this);
			var current = [];
			current.html = $this.find(options.menuElementContentSelector).html();
			$this.find('a').eq(0).click(function(){
				$(this).blur();
				NavClicked(index);
				return false;
			});
			current.url = $this.find('a').attr('href');
			current.obj = $('<div class="menuElementContainer"></div>');
			banner.append(current.obj);
			current.obj.css({
				position : 'absolute',
				width : '100%',
				'height' : height,
				'z-index' : index,
				top : -height,
				overflow:'hidden',
				cursor:'pointer'
			}).click(function(){location.href=current.url});
			current.obj.html(current.html)		
			items[index] = current;

		});

		NavClicked(0);
		timer = SetTimer(options.changeDelay);

	});
}


/**
 * @author Samele Artuso <samuele.a@gmail.com>
 */
jQuery.fn.unselectable = function() {
	return this.each(function() {
		
		$(this)
			.css('-moz-user-select', 'none')		// FF
			.css('-khtml-user-select', 'none')		// Safari, Google Chrome
			.css('user-select', 'none');			// CSS 3
		
		if ($.browser.msie) {						// IE
			$(this).each(function() {
				this.ondrag = function() {
					return false;
				};
			});
			$(this).each(function() {
				this.onselectstart = function() {
					return (false);
				};
			});
		} else if($.browser.opera) {
			$(this).attr('unselectable', 'on');
		}
	});
};

$(function(){	   
	$(".reserve_good_link").fancybox({
		'type'				: 'iframe',
		'padding' : 0
	});	
});



