$(function() {
  	$("#rstGallery div").mousewheel(function(event, delta){
        	var scrl = $("#rstGallery div").scrollLeft();
        	var x = scrl + (50*delta);
	        if(x<0) x=0;		
	        $("#rstGallery div").scrollLeft(x);
        });
});

function Application(containerId, menuId) 
{
    Application.col[containerId] = {};
    _this = Application.col[containerId];
    
    Application.pages = [];
    Application.titles = ["Главная", "Это интересно", "Наше меню", "Адреса", "Наши предложения", "Отзывы"];

    for(var i=0; i<6; i++)
    {
        var x = i*990;
        var m = (x > 5957-$(document.body).width())? 5955-$(document.body).width() : x;
        var pageTitle = "Менза - территория лапши / " + Application.titles[i];
        var item = {id: i, x: m, alias: "page"+(i+1), title: pageTitle};
        Application.pages.push(item);
    } 
   
    _this.containerId = containerId;
    _this.menuId = menuId;
    _this.currentPage = null;
    _this.currentIndex = 1;
    _this.container = null;
    _this.menu = null;
    _this.timer = 0;
    _this.movingStep = 0;
            
    _this.preloader == null;
    _this.preloadWatcher = setTimeout("Application.watchImages('"+containerId+"')", 100);
    
    $(window).resize(function(){
        Application.start(containerId);
    });   

    $(document.body).keypress(function(e){
        if(e.keyCode == 13)
            Application.setUrl(containerId, true);
    });
};

Application.col = {};

Application.watchImages = function(id)
{
    _this = Application.col[id];
    if(_this.preloader == null)
        Application.initPreloader(id);
     
     if(_this.preloader == null)
     {
         _this.preloadWatcher = window.setTimeout("Application.watchImages('"+id+"')", 200);
         return;
     }
     
     var totalImages = document.images.length;
     var loadedImages = 0;
     var percent = 0;
     
     for(var i=0; i<totalImages; i++)
     {
        if(document.images[i].complete)
            loadedImages++;
     } 
     
     percent = Math.floor((loadedImages/totalImages)*65);
     if(totalImages == 0)
        percent = 65;
    
     if(_this.preloader != null)
     {
        var percentsDiv = _this.preloader.loadMonitor;
        if(percentsDiv != null)
        { 
            _this.preloaderState = !_this.preloaderState;
            Application.createLine(id, percentsDiv, percent);
        } 
        if(loadedImages == totalImages)
        {   
            Application.startingPercent = 66;
            Application.finishLoading(id);
        } 
        else
            _this.preloadWatcher = window.setTimeout("Application.watchImages('"+id+"')", 50);
     }    
};

Application.finishLoading = function(id)
{
    _this = Application.col[id];        
            
     var percentsDiv = _this.preloader.loadMonitor;
     if(Application.startingPercent == 101)
     {
         window.clearTimeout(_this.preloadWatcher);
            
         $("html").css({"overflow":"auto"});
         _this.preloadWatcher = window.setTimeout("Application.start('"+id+"')", 10);

         if(jQuery.browser.opera)
             $(window).scrollTop(10);
         return;
     } 
     
     if(percentsDiv != null)
     { 
        var percent = Application.startingPercent;
        Application.createLine(id, percentsDiv, percent);
     } 
     
     Application.startingPercent++;
     _this.preloadWatcher = window.setTimeout("Application.finishLoading('"+id+"')", 300);
};

Application.initPreloader = function(id)
{
    _this = Application.col[id];
    
     _this.preloader = $("#divPreloader");
     if(_this.preloader == null)
        return;         
        
    _this.preloader.css({"left": "0px"});
    
     var center = $("<span></span>");
     var sh = $(document.body).height()/2-35;
     var sw = $(document.body).width()/2-160;
     center.css({"left":sw+"px", "top":sh+"px"});
     
     _this.preloaderState = true;
     
     _this.preloader.loadMonitor = center;
     center.appendTo(_this.preloader);
};

Application.createLine = function(id, percentsDiv, percent)
 {
    _this = Application.col[id];
     percentsDiv.empty();

     var size = Math.floor(328*percent/100);
     var txt = (percent < 75)? "Мы рады приветствовать вас на нашем сайте!" : "Пожалуйста, подождите немного, мы накрываем на стол..."; 
     var span = $("<small>"+txt+"</small>");
     span.appendTo(percentsDiv);
          
     var line = $("<div></div>");
     var progress = $("<b></b>");
     progress.css({"width":size+"px"});
     progress.appendTo(line);
     line.appendTo(percentsDiv);
     var pt = $("<em></em>");
     pt.css({"width":size+"px"});
     pt.appendTo(percentsDiv);
     pt.html(percent + "%");   
};

Application.checkPosition = function(id)
{
    var x = $(window).scrollLeft();
    var len = Application.pages.length;
    window.clearTimeout(_this.timer);
    window.clearTimeout(timer);

    _this = Application.col[id];

    if(x>=Application.pages[_this.currentIndex-1].x-5 && x<=Application.pages[_this.currentIndex-1].x+5)
        return;

    for(var i=0; i<len; i++)
    {                
        var start = Application.pages[i].x;
        var end = (i<len-1)? Application.pages[i+1].x : 5957;

        if(x > start+5 && x < (start+990/2)-5)
        {
            Application.initMenu(id, i+1);
            Application.setLocation(id);
            break;
        }
        if(x > (start+990/2)+5 && x < end-5)
        {   
            if(i<len-1)
	    {
                Application.initMenu(id, i+2);
                Application.setLocation(id);
	    }	
            break;
        }
        if(x < end+5 && x > end-5)
        {
            Application.initMenu(id, i+2);
            Application.setLocation(id);
            break;
        }    
        if(x < start+5 && x > start-5)
        {
            Application.initMenu(id, i+1);
            Application.setLocation(id);
            break;
        }    
    }
};
 
Application.start = function(id)
{
    _this = Application.col[id];
    window.clearTimeout(_this.preloadWatcher);

    Application.container = $("#"+_this.containerId);
    Application.menu = $("#"+_this.menuId);
   
    var dbh = $(document.body).height();
    var h = (dbh <=573)? 573 : (dbh > 1107)? 1107 : dbh;
    var k = (dbh < 1107)? -(parseInt(1107-h)/2): 0;

    Application.container.css({"height":h+"px"});
    $("#main").css({"top":k+"px"});

    var offsetTop = (dbh>Application.container.height())? parseInt((dbh-Application.container.height())/2) : 0;
    var top = (jQuery.browser.safari)? document.body.scrollTop : document.documentElement.scrollTop;

    Application.container.css({"top":offsetTop+"px"});
    Application.menu.css({"top":(offsetTop-top+k+275)+"px"});  
    Application.menu.css({"visibility":"visible"});         
    _this.preloader.remove();
    Application.setUrl(id, false);
};

Application.initMenu = function(id, index)
{
    _this = Application.col[id];

    if(_this.currentPage != null)
        $(_this.currentPage).attr("class","");

    _this.pages = $("#"+_this.menuId+" li");
    if(_this.pages == null)
        return;

    _this.currentPage = _this.pages[index];
    _this.currentIndex = index;
    $(_this.pages[index]).attr("class","active");
};

Application.navigateTo = function(id, index, stepMode)
{    
    _this = Application.col[id];

    var page = (index == "prev" && _this.currentIndex > 0)? _this.currentIndex-1 : (index == "next" && _this.currentIndex < 6)? _this.currentIndex+1 : (index == "prev" && _this.currentIndex <= 1)? 1 : (index == "next" && _this.currentIndex >= 6)? 6 : (index != "prev" && index != "next")? index : 1;    
   
    if((index == "prev" && _this.currentIndex <= 1) || (index == "next" && _this.currentIndex > 6))
        return;    
    
    $(_this.currentPage).attr("class","");        
    $(_this.pages[page]).attr("class","active");    

    _this.currentPoint = $(window).scrollLeft();
    _this.currentPage = _this.pages[page];
    _this.currentIndex = page;    
    
    var pageX = Application.pages[_this.currentIndex-1].x;    
    $("#menuMask").css({"visibility":"visible"});
    $(".addressLayer").css({"visibility":"hidden"});
    $("#menuAdditional li").attr("class","");
    $("#menuItems li").attr("class","");

    if(pageX == undefined || pageX == null)
        return;
     
    if(stepMode)
    {
        _this._movingStep = 0;                       
        Application.nextMove(id, pageX);
    }    
    else
    { 
	var px = (jQuery.browser.msie && jQuery.browser.version.indexOf("6")>-1)? pageX : (pageX+"px");	
        $.scrollTo(px, {axis:'x', duration: 1000, onAfter: function(){Application.setLocation(id)}});
    }
};

Application.nextMove = function(id, x)
{
    _this = Application.col[id];
    
    var steps = [ 1, 2, 3, 5, 15, 25, 40, 70, 115, 70, 40, 25, 15, 5, 3, 2, 1 ];
    var offset = function(array, max){ 
            var s = 0;
            for(var i = 0; i < array.length; i++) 
                if(array[i] == max)
                    break;
                else
                    s += array[i];
            return s;
          }.call(_this, steps, 115);
                  	     
    var doNextStep = true;

    var step = steps[_this._movingStep];
    var directionX = (x > _this.currentPoint);
    
    if(directionX)
    {        
        if(_this.currentPoint < x - step)
            _this.currentPoint += (step == 115) ? Math.abs(x - _this.currentPoint) - offset : step;
        else 
           doNextStep = false;
    }
    if(!directionX)
    {    
        if(_this.currentPoint > x + step)        
            _this.currentPoint -= (step == 115) ? Math.abs(x - _this.currentPoint) - offset : step;
        else      
           doNextStep = false;                
    }

    if(doNextStep)
    {        
        $(window).scrollLeft(_this.currentPoint);
           
        _this._movingStep++;            
        _this.moving = window.setTimeout("Application.nextMove('"+id+"',"+x+")", 5);
    }    
    else
    {        
        _this._movingStep = 0;
        window.clearTimeout(_this.timer);
        window.clearTimeout(_this.moving);
        Application.setLocation(id);
    }            
};

Application.setUrl = function(id, mode)
{
    var len = Application.pages.length;

    for(var i=0; i<len; i++)
    {    
        if(Application.pages[i].alias != null)
        {
            if(location.href.indexOf(Application.pages[i].alias) > -1)        
            {
                if(mode)
                    Application.navigateTo(id, i+1, mode);
                else
                {                          
                    $(window).scrollLeft(Application.pages[i].x);
                    Application.initMenu(id, i+1);                
                }
                Application.setLocation(id);                
            }    
        }
        else
        {
            if(mode)
                Application.navigateTo(id, 1, mode);
            else
            {                
                $(window).scrollLeft(0);
                Application.initMenu(id, 1);
            }  
            Application.setLocation(id);
        }    
    }
};

Application.setLocation = function(id)
{
    $("#menuMask").css({"visibility":"hidden"});
    if(Application.pages[_this.currentIndex-1] == null)
        return;
    location.href = "#"+Application.pages[_this.currentIndex-1].alias;
    document.title = Application.pages[_this.currentIndex-1].title;
};

function loadCounters()
{                             
	var ht = "<a href='http://www.liveinternet.ru/click' target=_blank><img src='http://counter.yadro.ru/hit?t44.1;r"+
		escape(document.referrer)+((typeof(screen)=="undefined")?"":
		";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth?
		screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+
		";"+Math.random()+
		"' alt='' title='LiveInternet' "+
		"border=0 style='margin: 12px 7px 0 0;' width=31 height=31></a><p>Создание сайта &mdash; <a class='jeltofiol' href='http://jeltofiol.com' target='_blank'>Jeltofiol-design</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &copy; Все права защищены</p> <a href='http://vci.ru/' target='_blank'><img src='/img/partner.gif' style='margin: 0 0 0 35px' alt=''/></a>";
	$(".counters").html(ht);
}