/*
	BrainFuckScrolling Script
	Version: 0.2.1 (20090903)
	Copyright (C) 2009 seva <seva321@gmail.com>
	
	The JavaScript code in this page is free software: you can
    redistribute it and/or modify it under the terms of the GNU
    General Public License (GNU GPL) as published by the Free Software
    Foundation, either version 3 of the License, or (at your option)
    any later version.  The code is distributed WITHOUT ANY WARRANTY;
    without even the implied warranty of MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.

    As additional permission under GNU GPL version 3 section 7, you
    may distribute non-source (e.g., minimized or compacted) forms of
    that code without the copy of the GNU GPL normally required by
    section 4, provided you include this license notice and a URL
    through which recipients can access the Corresponding Source.
	
*/

var FBScrolling = function(){
	
	//статические значения
	var scrollEnable, minLim = 0;
	var scrollStep = 50; //шаг скролла
	
	//узлы
	var bottomButton, topButton, newsBlock, scrollLine, handPoint, scrollArea, parentScrollLine;
	
	//вычисляемые переменные
	var IDiNTERVAL1, clearHeight, scrollHeight, scrollLineHeight, handHeight, maxLim, mouseShift, lineTopPos, mouseY, nMarg;
	
	//Scroll page
	function ___getPageScroll() {
		var xScroll, yScroll;
		if (self.pageYOffset || self.pageXOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}
		arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	}
	
	function ___buttonChanger(val){
		switch(val){
			case 'HideShow':
				topButton.style.backgroundPosition = '-22px 0';
				bottomButton.style.backgroundPosition = '-33px 0';
				break;
			case 'ShowHide':
				topButton.style.backgroundPosition = '-11px 0';
				bottomButton.style.backgroundPosition = '-44px 0';
				break;
			case 'ShowShow':
				topButton.style.backgroundPosition = '-11px 0';
				bottomButton.style.backgroundPosition = '-33px 0';
				break;
		}
	}

	//собственно расчет и позиционирование
	function scrollPos(dir){
		var currentPosition = parseInt(newsBlock.style.marginTop);
		if(!currentPosition) currentPosition = 0;
		if(dir=='down' && currentPosition > -maxLim){
			var qVal = scrollHeight + currentPosition - scrollArea.offsetHeight;
			if(qVal <= scrollStep){
				newsBlock.style.marginTop = -maxLim + 'px';
				bottomButton.style.backgroundPosition = '-44px 0';
			}
			else{
				newsBlock.style.marginTop = (currentPosition - scrollStep) + 'px';
			}
			topButton.style.backgroundPosition = '-11px 0';
		}
		else if(dir=='up' && currentPosition < minLim){
			if(currentPosition > -100){
				newsBlock.style.marginTop = minLim;
				topButton.style.backgroundPosition = '-22px 0';
			}
			else{
				newsBlock.style.marginTop = currentPosition + scrollStep + 'px';
			}
			bottomButton.style.backgroundPosition = '-33px 0';
		}
		var shiftPercent = parseInt((parseInt(newsBlock.style.marginTop) * 100) / scrollHeight);
		var shiftAbs = parseInt((shiftPercent * scrollLineHeight) / 100);
		handPoint.style.marginTop = -shiftAbs + 'px';
	}
	
	/* блок новостей с прокруткой */
	if(document.getElementById('scroll_area')&&document.getElementById('scBottom')&&document.getElementById('scTop')&&document.getElementById('news_scroll')&&document.getElementById('scroll_line')&&document.getElementById('hand_point')&&document.getElementById('scroll_layer')){
		
		scrollArea = document.getElementById('scroll_area'); //режущий блок
		bottomButton = document.getElementById('scBottom'); //кнопка вниз
		topButton = document.getElementById('scTop'); //кнопка вверх
		newsBlock = document.getElementById('news_scroll'); //блок с новостями
		scrollLine = document.getElementById('scroll_line'); //полоса прокрутки
		handPoint = document.getElementById('hand_point'); //ползунок
		parentScrollLine = document.getElementById('scroll_layer'); //блок, содержащий элементы прокрутки
		
		//высота режущего блока
		clearHeight = parseInt(scrollArea.offsetHeight); 
		
		//высота блока с новостями
		scrollHeight = parseInt(newsBlock.offsetHeight);
		
		//высота полосы прокрутки
		scrollLineHeight = scrollLine.offsetHeight;
		
		//если блок с новостями больше режущего блока
		if(scrollHeight > clearHeight){
			
			//относительная величина видимой области
			var countt = parseInt(clearHeight * 100 / scrollHeight);
			
			//пересчитываем относительно полосы прокрутки
			//TODO: +4px -- костыль. Будет исправлен в следующих версиях.
			handHeight = (parseInt((countt * scrollLineHeight) / 100)) + 4;
			
			//присваиваем высоту ползунку
			handPoint.style.height = handHeight + 'px';
			
			//показываем полосу прокрутки
			parentScrollLine.style.visibility = 'visible';
			
			//макс.сдвиг по вертикали:
			//высота блока с новостями минус высота видимой области
			maxLim = (scrollHeight - clearHeight);
			
			//ловим прокрутку колеса мыши 
			$$(scrollArea, parentScrollLine).addEvent('mousewheel', function(event) {
				event = new Event(event);
				event.preventDefault();
				// Mousewheel UP 
				if ((event.wheel > 0)){
					scrollPos('up');
				}
				
				// Mousewheel DOWN 
				else if ((event.wheel < 0)) {
					scrollPos('down');
				}
			});
			
			//нажатия на кнопки
			
			//нижняя
			bottomButton.onmousedown = function (){
				function ffstb(){
					scrollPos('down');
				}
				IDiNTERVAL1=setInterval(ffstb, 50);
			}
			
			bottomButton.onmouseup = function (){
				clearInterval(IDiNTERVAL1);
			}
			
			//верхняя
			topButton.onmousedown = function (){
				function ffstb(){
					scrollPos('up');
				}
				IDiNTERVAL1=setInterval(ffstb, 50);
			}
			
			topButton.onmouseup = function (){
				clearInterval(IDiNTERVAL1);
			}
			
			//mouseover с полосы прокрутки	
			scrollLine.onmouseover = function() {
				clearInterval(IDiNTERVAL1);
			}
			
			//клик на полосе прокрутки
			scrollLine.onclick = function(event) {
				event = new Event(event);
				
				//на ползунок -- не считаем
				if(event.target.id == 'hand_point') return;
				
				___getPageScroll();
				
				//позиция мыши по Y относительно окна + скролл окна
				mouseY = event.client.y + arrayPageScroll[1];
				
				//offsetTop полосы прокрутки относительно документа
				lineTopPos = scrollLine.offsetTop + parseInt(document.getElementById('root').offsetTop);
				
				//расчет позиции ползунка 
				var hgPos = mouseY - lineTopPos-(handHeight/2);
				
				//подсветка кнопочек скрола и проверка позиции ползунка
				
				//верх
				if(hgPos < 0){
					hgPos = 0;
					___buttonChanger('HideShow');
				}
				
				//низ
				else if(hgPos > (scrollLineHeight-handHeight)){
					hgPos = scrollLineHeight-handHeight;
					___buttonChanger('ShowHide');
				}
				
				//все остальное
				else{
					___buttonChanger('ShowShow');
				}
				
				//margin ползунка пересчитываем для блока с новостями 
				var _mp_ = parseInt((hgPos * 100)/scrollLineHeight);
				var _nm_ = -parseInt((_mp_ * scrollHeight)/100);
				
				//позиционируем ползунок и блок с новостями
				$$(handPoint,newsBlock).set('tween', {duration: 'normal', transition: Fx.Transitions.Expo.easeOut});
				handPoint.tween('marginTop', hgPos);
				newsBlock.tween('marginTop', _nm_);
				
			}
			
			//ловим клики на ползунке для mousemove
			handPoint.onmousedown =  function(event){
				
				event = new Event(event);
				
				//определяем скрол окна
				___getPageScroll();
				
				//разрешаем mousemove
				scrollEnable = 1;
				
				//позиция мыши по Y относительно окна + скролл окна
				mouseY = event.client.y + arrayPageScroll[1];
				
				//позиция полосы прокрутки
				lineTopPos = scrollLine.offsetTop;
				
				//определяем margin у ползунка
				nMarg = parseInt(handPoint.style.marginTop);
				if(!nMarg) nMarg = 0;
				
				//сдвиг мыши относительно ползунка
				mouseShift = mouseY - (nMarg + lineTopPos);
			}
			
			//собственно mousemove
			//parentScrollLine.onmousemove =  function(event){
			document.body.onmousemove =  function(event){
				
				event = new Event(event);
				
				if(scrollEnable == 1){
					
					//это я почти нетрезвый писал
					___getPageScroll();
					
					//считаем позицию мыши
					mouseY = event.client.y + arrayPageScroll[1];
					
					//позиция полосы прокрутки + высота прокрутки -- вещь нужная!
					var scrollLineHeightMarg = lineTopPos + scrollLineHeight;
					
					//считаем позицию курсора на ползунке (кажется)...
					var bottomRest = mouseY + handHeight - mouseShift;
					
					//если курсор в каком-то странном диапазоне
					if( ((mouseY - mouseShift) > lineTopPos) && (bottomRest < scrollLineHeightMarg)){
						
						//считаем отступ и применяем его к ползунку
						nMarg = (mouseY - lineTopPos - mouseShift);
						handPoint.style.marginTop = nMarg + 'px';
						
						//пересчитываем для блока с новостями и применяем к новостям
						var relPersent = parseInt(((mouseY - lineTopPos - mouseShift) * 100) / scrollLineHeight);
						var absVal = parseInt((scrollHeight * relPersent)/100);
						
						//отлавливаем граничные значения для подсветки кнопок
						if(absVal == 0){
							___buttonChanger('HideShow');
						}
						
						//TODO: +8px -- поргешность в вычислениях. Будет исправлена в следующих версиях.
						else if((scrollLineHeight-nMarg) <= (handHeight + 8)){
							___buttonChanger('ShowHide');
							absVal = maxLim;
						}
						else{
							___buttonChanger('ShowShow');
						}
						newsBlock.style.marginTop = -absVal + 'px';
					}
				}
			}
			
			//отрубаем mousemove
			document.body.onmouseup = function(){
				scrollEnable = 0;
			}
		}
	}
	
	//запрещаем выделение текста на все странице -- сурово
    /*
	if(Browser.Engine.trident){
		document.body.onselectstart = function() {return false}
	}
	else{
		document.body.onmousedown = function(e) {return false}
	}
    */
}

/*
	M$IE6 min-width/height fix
*/

//размер окна
function ___winSize(){
	var myWidth = 0, winHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		winWidth = window.innerWidth;
		winHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		winWidth = document.documentElement.clientWidth;
		winHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		winWidth = document.body.clientWidth;
		winHeight = document.body.clientHeight;
	}
	var arrayWinSize = new Array(winWidth,winHeight);
	return arrayWinSize;
}
	
var ieMinFix = function(){
	if(Browser.Engine.version <= 4 && Browser.Engine.trident){
		var arrayWinSize = ___winSize();
		if(arrayWinSize[0] < 1000){
			document.body.style.width = '1000px';
		}
		else{
			document.body.style.width = '100%';
		}
		
		if(arrayWinSize[1] < 640){
			document.body.style.height = '640px';
		}
		else{
			document.body.style.height = '100%';
		}
	}
}

window.addEvent('domready', function() {
	ieMinFix();
	FBScrolling();
});

window.addEvent('resize', function() {
	ieMinFix();
});
window.addEvent('load', function() {
    if (location.hash != "" && location.hash != "#") {
        tryShowPageFromHash();
    }
    if (navigator.userAgent.indexOf("MSIE 6") == -1) {
        setInterval("hookHashChange()", 50);
    }
})

// ------------------ //

/*
 * Скрипт для формы
 */
function fieldFocus(e) {
    if (e.value == e.defaultValue) {
        e.className = 'styled';
        e.value = '';
    }
}
function fieldBlur(e) {
    if (e.value == '') {
        e.className = 'styled blurred';
        e.value = e.defaultValue;
    }
}
function formSubmit(f) {
    var request = new Request({url: f.action, method: "post", onSuccess: function(responseText, responseXML) {
        if (responseText == "ok") {
            f.className = "hidden_element";
            document.getElementById("label_form_ok").className = "";
            document.getElementById("label_form_error").className = "hidden_element";
        }
        else {
            document.getElementById("label_form_ok").className = "hidden_element";
            document.getElementById("label_form_error").className = "";
        }
        
        var captcha = document.getElementById("image_captcha");
        var indexOfQuestion = captcha.src.indexOf("?");
        if (indexOfQuestion == -1) {
            captcha.src += "?rand" + (Math.random() * 10) + "=" + (Math.random() * 100 * Math.random());
        }
        else {
            captcha.src = captcha.src.substr(0, indexOfQuestion) + "?rand" + (Math.random() * 10) + "=" + (Math.random() * 100 * Math.random());
        }
    }});
    var data = '';
    for (i in f.elements) {
        var temp = parseInt(i);
        if (!isNaN(temp)) {
            if (data == '') {
                data += f.elements[i].name + "=" + f.elements[i].value;
            }
            else {
                data += "&" + f.elements[i].name + "=" + f.elements[i].value;
            }
        }
    }
    request.send(data);
    return false;
}

// Проверка изменения якоря
function hookHashChange() {
    
    if (globalCurrentHash == location.hash) {
        // Если якорь не изменился, ничего не делаем
        return;
        
    } else {
        // Если изменился, то устанавливаем его, как текущий и запускаем функцию загрузки контента
        globalCurrentHash = location.hash;
        tryShowPageFromHash();
    }
}

function tryShowPageFromHash() {
    var request = new Request({
        url: "link.html?url=" + globalCurrentHash.substr(1) + "&lang=" + global_lang, method: "get", onSuccess: function(responseText, responseXML) {
                
            // Проверка ответа
            if (responseText.match(/[0-9]+,.+,.+/)) {
                var result = responseText.split(",");
                
                if (typeof(result[3]) == "undefined") {
                    // Запускаем обработку ссылки
                    linkHandler(responceUrl, result[0], result[1], true, true);
                        
                } else if (typeof(result[4]) == "undefined") {
                    // Запускаем обработку ссылки
                    linkHandler(responceUrl, result[0], result[1], true, true, result[3]);
                } else {
                    // Запускаем обработку ссылки
                    linkHandler(responceUrl, result[0], result[1], true, true, result[3], result[4]);
                }
            }
        }
    });
    request.send();
}
