var flashOffsetLeft = 0;
var sailingObjContainer;
var objTopMargin = 0;
var startTop = 0;
var posTo;

var headHeight;


$(document).ready(function(){
	floatBlockInit();
	moveSailingBlock();
});


$(window).scroll(function () { 
		moveSailingBlock();
});



    

function floatBlockInit() {  
  headHeight = document.getElementById('header').offsetHeight;
	sailingObjContainer = document.getElementById('sailingContainer');	
	$("#sailingContainer").css({'left' : flashOffsetLeft, 'display' : "block", "visibility" : "visible"});
}



function moveSailingBlock() {

	var dif = 0;
			
	menuHeight = document.getElementById('sailingContainer').offsetHeight;
	
	menuWidth = document.getElementById('menu').offsetWidth;
	
	if(document.getElementById('sidebar').offsetHeight < menuHeight /*+ botLimit*/)
		return;
	
	var documentObjTop = body_scrollTop();		
	
	documentObjTop = (documentObjTop < headHeight) ?  0 : documentObjTop - headHeight;
	
	startTop = document.getElementById('sailingContainer').offsetTop;
	
	if(screenSize().h < menuHeight) {
		
		// move down
		if(documentObjTop > startTop) {
			if(documentObjTop < (startTop + (dif = menuHeight - screenSize().h))) {
				return;
			} else {
				posTo = documentObjTop + objTopMargin - dif;	
			}
		}
		// move up
		else {
			if(documentObjTop > startTop) {
				return;
			} else {
				posTo = documentObjTop + objTopMargin;	
			}
		}	
	} else {
	
		posTo = documentObjTop + objTopMargin;	
		
	}	
	
	if(posTo > document.getElementById('sidebar').offsetHeight  - menuHeight){
		posTo = document.getElementById('sidebar').offsetHeight - menuHeight;
		
		}
	
		$('#sailingContainer').animate({top:posTo},{duration:1000,queue:false});

}

function screenSize() {
    var w, h; // Объявляем переменные, w - длина, h - высота
    w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
    
    return {w:w, h:h};
}
function body_scrollTop() {
   if (window.innerWidth) { // All browsers but IE
         return window.pageYOffset; 
}
else if (document.documentElement && document.documentElement.clientWidth) {
    // These functions are for IE 6 when there is a DOCTYPE
    return document.documentElement.scrollTop;
}
else if (document.body.clientWidth) {
    // These are for IE4, IE5, and IE6 without a DOCTYPE
    return document.body.scrollTop;
}

}
