var flashOffsetLeft = 0;
var sailingObjContainer;
var objTopMargin = 0;
var startTop = 0;
var posTo;

var headHeight = 230;
var underMenuBlock = 'bl_2';
var botBlock = 'bl_3';
//var botLimit = 0;

$(document).ready(function(){
	floatBlockInit();
	moveSailingBlock();
});


$(window).scroll(function () { 
		moveSailingBlock();
});


//$(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
    

function floatBlockInit() {  
  headHeight += document.getElementById('bl_1').offsetHeight;
	//botLimit = document.getElementById(botBlock).offsetHeight;
	sailingObjContainer = document.getElementById('sailingContainer');	
	$("#sailingContainer").css({'left' : flashOffsetLeft, 'display' : "block", "visibility" : "visible"});
}



function moveSailingBlock() {
	var dif = 0;
			
	menuHeight = document.getElementById('sailingContainer').offsetHeight;
	//menuHeight = document.getElementById('gPageMenu1').offsetHeight + document.getElementById(underMenuBlock).offsetHeight;
	menuWidth = document.getElementById('gPageMenu1').offsetWidth;
	
	if(document.getElementById('sailingBlockContainer').offsetHeight < menuHeight /*+ botLimit*/)
		return;
	
	documentObjTop = window.document.body.scrollTop;		
	
	documentObjTop = (documentObjTop < headHeight) ?  0 : window.document.body.scrollTop - headHeight;
	startTop = parseFloat(document.getElementById('sailingContainer').style.top);			
	
	// if menu is higher than screen
	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('sailingBlockContainer').offsetHeight /*- botLimit*/ - menuHeight)
		posTo = document.getElementById('sailingBlockContainer').offsetHeight /*- botLimit*/ - 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};
}