$(function(){
	
	var $window = $(window),
		$body = $('body'),
		$container = $('#container'),
		$header = $('#header'),
		$footer = $('#footer'),
		$main = $('#main'),
		$bg = $('#bg'),
		$nav = $('#nav'),
		$content = $('#content'),
		$loading = $('#loading');
	
	
	// вычисляемые переменные
	var win_width, win_height, bg_width, bg_height, bg_k, image_width, image_height, image_k, // размеры
		backgrounds = [], $bgs, // фон
		e = {}, mouse_x = 0, mouse_y = 0, // мышка
		i, cursor_before = 'default', loading_status = 0; // разное
	
	// устанавливаемые переменные
	var image_k = 1920 / 576;
	

	
	var initial = function() {
		
		loading_start();
		
		loading_images = $('img[data-src]');
		loading_status = 0;
		loading_length = loading_images.length;
		
		for (i = loading_length - 1; i >= 0; i--) {
			loading_images.eq(i).bind('load', function() {
				loading_status ++;
				//log($(this).data('src') + ' loaded');
				$main.stop().animate({'left': - 100 + 100 * loading_status / loading_length + '%'}, {
					duration: loading_length * 100 + 500 - loading_status * 100,
					step: function(now, obj) {
						$loading.text('ЗАГРУЗКА ' + Math.round(now + 100) + '%');
					},
					complete: function() {
						// загрузка последней картинки завершена
						if (loading_status == loading_length) {
							win_width = $window.width();
							win_height = $window.height();
							bg_k = win_width / (win_height - 300);
							if (image_k > bg_k) {
								$bg.children('img').css({'display': 'block', 'height': win_height - 300, 'width': 'auto', 'marginLeft': - (win_height - 300) * image_k / 2});
							} else {
								$bg.children('img').css({'display': 'block', 'width': win_width, 'height': 'auto', 'marginLeft': '-50%' });
							}
							$main.animate({'height': win_height - 300}, 1000, function() {
								$main.addClass('loaded');
								$('#content').fadeTo('fast', 1);
							});
							loading_stop();
							$(window).bind('mousemove click',	function(e) {playanimation(e)});
							$('#menu').animate({opacity: 1}, "slow");
						}
					}
				});
				
				$(this).unbind('load');
				
			}).attr('src', loading_images.eq(i).attr('data-src'));
		}
	},
	
	loading_start = function() {
		//log('loading_start');
		$loading.fadeIn();
		cursor_before = $('body').css('cursor');
		$('body').css('cursor', 'progress');
	},
	
	loading_stop = function() {
		//log('loading_stop');
		$loading.fadeOut();
		$('body').css('cursor', cursor_before);
	},
	
	window_resize = function() {
		if ($main.hasClass('loaded')) {
			win_width = $window.width();
			win_height = $window.height();
			bg_k = win_width / (win_height - 300);
			if (image_k > bg_k) {
				$bg.children('img').css({'height': win_height - 300, 'width': 'auto', 'marginLeft': - (win_height - 300) * image_k / 2});
			} else {
				$bg.children('img').css({'width': win_width, 'height': 'auto', 'marginLeft': '-50%' });
			}
			$main.css({'height': win_height - 300});
		}
	};
	
	
	
	
	$window.bind('resize', function() {
		//log('window_resize');
		window_resize();
	});
	

	
	/*
	for (i = 0; i < bg_count; i++) {
		$('<img id="bg_'+i+'" src="/img/3D/pic.php?n='+i+'&sleep=2">').bind('load', function(){
			loading_status++;
			log(loading_status + ' loaded');
			$(this).prependTo($bg);
			procent = 100*loading_status/bg_count;
			$main.stop().animate({width: procent + '%'}, {
				duration: bg_count*100 + 500 - loading_status*100,
				step: function(now, obj) {
					$loading.text('ЗАГРУЗКА ' + Math.round(now) + '%');
				},
				complete: function() {
					log(2600 - loading_status*100);
					if (loading_status == bg_count)
					{
						//win_height = $window.height();
						//new_height = (win_height - 576)/2;
						//log(new_height);
						$loading.fadeOut();
						$main.animate({'top': 150, 'height': win_height-300});
						//$header.add($footer).animate({'height': 150}, 2000, 'easeOutBack');
					}
				}
			});
		});
	}
		*/
		
	initial();
	
	frame = 0;
	old_frame = 0;


	// остановка и пуск анимации
	var animationplay = true; 
	
	var playanimation = function(e){
			mouse_x = e ? e.clientX : mouse_x;
			frame = Math.round(mouse_x * (loading_length - 1) / win_width);
			if (old_frame != frame) {
				// log('frame: '+frame, e, mouse_x);
				$bg.children('img').css('display', 'none').eq(frame).css('display', 'block');
			}
			old_frame = frame;
	};
	
	$('#animation_player').hover(
		function() {
			$(this).stop(true,true).animate({opacity: 0.5},"fast");
			},
		function() {
			$(this).stop(true,true).animate({opacity: 0.2},"slow");
		}
		);
	
	$('#animation_player').click(
		function() {
			if (animationplay == true) {
				$(window).unbind('mousemove click');
				$(this).text('Включить анимацию здания');
				animationplay = false;
			} else {
				$(window).bind('mousemove click',	function(e) {playanimation(e)});
				$(this).text('Выключить анимацию здания');
				animationplay = true;
			}
		}
	);
		
	
		
   /*******************************                  ЧЕРТА                   ********************************/
    var State = {}, section = '', page = ''
 	History = window.History; // Note: We are using a capital H instead of a lower h
    if ( !History.enabled ) {
         // History.js is disabled for this browser.
         // This is because we can optionally choose to support HTML4 browsers or not.
        return false;
    } else {
    	State = History.getState();
    	section = State.url.split('/')[3] || 'main';
    	page = State.url.split('/')[4] || 'index';
    }
    
    
    // Bind to StateChange Event
    History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
		State = History.getState(); // => State.data, State.title, State.url
		$('#content').fadeTo(500, 0, function () {
			// удаляем старое
			$body.removeClass('section-' + section + ' page-' + page);
			// загружаем новое
			$('#ctext').removeData('jsp').load(State.url, function () {
		    	section = State.url.split('/')[3] || 'main';
		    	page = State.url.split('/')[4] || 'index';
				$body.addClass('section-' + section + ' page-' + page);
				$('#ctext').jScrollPane();
				$('#content').fadeTo(500, 1);			
			});
		});
    });
    
    /*******************************************/
    
   
	$('#content').css('opacity','0');
		   
     var divresize = function (block, headerHeight, footerHeight) {
        var windowHeight = $(window).height();
        $(block).css('height', windowHeight - headerHeight - footerHeight);
    }
    divresize('#content', 210, 195);
	divresize('#ctext', 225, 220);
    $(window).bind("resize", function(){
        divresize('#content', 210, 195);
		divresize('#ctext', 225, 225);
		if ($('#ctext').data('jsp')) $('#ctext').data('jsp').reinitialise();
    });
	
			
	
	$('#cclose').click(function() {
		$('#content').fadeOut("slow", function () {
			$(this).css('display', 'none');
		});
	});
	
	// loading content & show #content if hidden #content
  	/*$('#menu A').click(function() {
		$('#content').css('display', 'block');
		$('#content').animate({
			opacity: 1
			}, "fast");*/
	
	//Навигация меню (rubber)
	$('.pagelink').bind('click',function(){
		href = $(this).attr('href');
		History.pushState({}, State.title, href);
		return false;
		/*
		var href = $(this).attr('href');
		$('#content').fadeOut(function(){
			$('#ctext').removeData('jsp').load(href, function(){
				$('#ctext').jScrollPane();
			})
			$('#content').fadeIn();
			
		});
		return false;
		*/
	});
	
	// end loading content & show #content
	
	$('.jspDrag').hover(
		function() {
			$(this).stop().animate({backgroundColor: '#226c1a'},"fast");
			},
		function(){
			$(this).stop().animate({backgroundColor: '#5e9258'},"slow");
		}
		);
		
		
	/**********************************     animated menu     *****************************/
	
	
		//When mouse rolls over	
	$('.sub_link').hover(
		function() {
			$(this).stop().animate({backgroundColor: '#089608'},"fast");
			},
		function(){
			$(this).stop().animate({backgroundColor: '#006600'},"slow");
		}
		);
	
	$('.node').hover( 
		function() {
			$(this).stop(true,true).animate({backgroundColor: '#dddddd'},"fast");
			$(this).find('.subtext').stop(true,true).animate({opacity: 1, height: "show"});
			},
		function(){
			$(this).animate({backgroundColor: '#cccccc'},"slow");
			$(this).find('.subtext').animate({opacity: 0, height: "hide"});
		}
		);
})
