var _waiter = "<html><body></body></html>";
var indexHeight;
var _rootKey = '';
var _contentWasLoadedByKey = false; //dlya update parent links pri ruchnom perehode po ssylkam
var _prevIndexWord = '';
var _prevIndexKey = '';//chtobi nachinat poisk ne s pervoy sovpavshey bukvi
var _errorMessage;
var _searchMessage;
var _multipleMessage;
var _currentHistoryKey;
var _prevHistoryKey;
var _keepInputValue;
var _prevOpenedTab;
var _cookieDomain;

//eto chtobi v parentLinks ne bilo lishliy raz vibiralki dlya odnogo nazvania "PHP Manual"
function setRootKey(key){ _rootKey = key; _prevHistoryKey = key; _currentHistoryKey = key; }
function setErrorMessage(t){ _errorMessage = t; }
function setSearchMessage(t){ _searchMessage = t; }
function setMultipleMessage(t){ _multipleMessage = t; }
function setKeepInputValue(t){ _keepInputValue = t; }
function setPrevOpenedTab(t){ _prevOpenedTab = t; }
function setCookieDomain(t){ _cookieDomain = t; }

function setCookie (name, value, expires, path, domain, secure) {
	//http://stackoverflow.com/questions/1019876/cookie-on-an-intranet-domain
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((_cookieDomain) ? "; domain=" + _cookieDomain : "") +
	((secure) ? "; secure" : "");
}

function arrangeElements()
{
	var aSize = getPageSize();
	var h = aSize[1];
	resizeIndex(h);
	resizeSearch(h);
	resizeContent(h);
	resizeComments(h);
	$('draggableSeparator').style.height = $('left_td').offsetHeight;
	
	if(aSize[0] < 1050)
	{
		$('threeColumns').removeChild($('adSense'));
	}
}

function resizeIndex(h)
{
	var newIndexHeight = h-111;
	
	$('indexItems').style.height = newIndexHeight+'px';
	$('indexItems').setOpacity(1);
}

function resizeSearch(h)
{
	var newSearchHeight = h-140;
	
	$('searchItems').style.height = newSearchHeight+'px';
}

function resizeContent(h)
{
	var newContentHeight = h-106;
			
	$('content').style.maxHeight = newContentHeight+'px';
	$('content').style.height = newContentHeight+'px';
	$('content').setOpacity(1);
}

function resizeComments(h)
{
	var newCommentsHeight = h-80;
	
	$('comments').style.maxHeight = newCommentsHeight+'px';	
	$('comments').style.height = newCommentsHeight+'px';
}

function changeTab(tableId, el)
{
	focused = el.getAttribute("rel");

	/*if(_keepInputValue=='1'){
		if(focused=='search' && _prevOpenedTab=='index'){
			$('searchWords').value = $('search').value;
		}else if(focused=='index' && _prevOpenedTab=='search'){
			$('search').value = $('searchWords').value;
		}
	}*/
	
	var selector = '#'+tableId+' div[type="tab"]';
	$$(selector).each(function(item)
	{
		var cl = item.className;
		var rel = item.getAttribute("rel");
		var spaces = rel.indexOf(" ");

		var pos = rel.indexOf(focused)
		if(pos!=-1)
		{
			cl = cl.replace("Blured", "Focused");

			if(spaces!=-1)
			{
				if(pos>0)
				{
					cl = "tab beforeFocused";
				}
				else
				{
					cl = "tab afterFocused";
				}
			}
		}
		else
		{
			cl = cl.replace("Focused", "Blured");

			if(spaces!=-1)
			{
			cl = "tab centerBlured";
			}
		}

		item.className = cl;
	});

	var selector = '#'+tableId+' div[type="tabContents"]';
	$$(selector).each(function(item)
	{
		if(item.getAttribute("rel")!=focused)
		{
			item.hide();
		}
		else
		{
			item.show();
		}
	});
    
	_prevOpenedTab = focused;
	/*if(focused=='search'){
		$('searchWords').select();
	}else if(focused=='index'){
		$('search').select();
	}*/
}

function showIssue()
{
    var selectName, keyAttr;
    if($('tabContents_index').style.display!='none') {selectName = 'indexItems'; keyAttr = 'id';}
    else if($('tabContents_search').style.display!='none'){selectName = 'searchItems'; keyAttr = 'key';}
    else return false;

    number=$(selectName).selectedIndex;
    if(number == -1) return false;
    var key = $(selectName).options[number].getAttribute(keyAttr);
    updateContent(key);
    //updateComments(key); ne nado, links.php vizivaet
}

function writeItemName()                                                                                       
{
    var selectName,keyAttr;
    if($('tabContents_index').style.display!='none') {selectName = 'indexItems'; keyAttr = 'id';}
    else if($('tabContents_search').style.display!='none'){selectName = 'searchItems'; keyAttr = 'key';}
    else return false;

    number=$(selectName).selectedIndex;
    if(number == -1) return false;
    var name = $(selectName).options[number].innerHTML;
    name = name.replace("&gt;",">");
    
    $('search').value = name;
}

function setInnerLinksEvent()
{
	if(navigator.userAgent.toLowerCase().indexOf("msie")!=-1) { var src = $('content').src; }
	else { var src = window["content"].document.location; }
	//$('piska').innerHTML += src+'<br>';
//	alert(src);
	
	if(src != "about:blank") // inache pri quicksearch budet lishniy request
	{
		new Ajax.Request('/links.php',
		{
			method: 'post',
			parameters: '?src='+src,
			onSuccess: function(transport)
			{
//				alert('success');
				if (200 == transport.status && transport.responseText.substring(0,1)=='{')//json check
				{ 
//					alert('doshlo');
					var json = transport.responseText;
					var json = eval('(' + json + ')');
					
					$('shareLink').href = json.shareLink;
					$('shareLink').innerHTML = json.shareLink;
					$('hiddenForm').action = json.phpNetLink;
					
					if(json.transKey == 'false')
					{
						$('pageLanguage').setAttribute('disabled', 'disabled');
						$('pageLanguage').setAttribute('key', '');
					}
					else
					{
						$('pageLanguage').removeAttribute('disabled');
						$('pageLanguage').setAttribute('key', json.transKey);
					}

					var inner = '';
					var linksCount = json.parentLinks.size();

					for(var c=0; c<linksCount; c++)
					{
						var key = json.parentLinks[c].key;
						var title = json.parentLinks[c].title;
						inner += '<a href="" onclick="updateContent(\''+key+'\'';
						if(key==_rootKey) { inner += ', true'; }
						inner += ');return false;">'+title+'</a>';
						if(c < linksCount-1) { inner += '&nbsp;&raquo;&nbsp;'; }
					}
//					alert(inner);
					$('parentContentLinks').innerHTML = inner;

					selectTitle(json.key);
					updateComments(json.key);
					writeItemName();

					//$('piska').innerHTML += json.key+' '+_prevHistoryKey+' '+_currentHistoryKey+'<br>';
					if(_currentHistoryKey != json.key) { 
					    _prevHistoryKey = _currentHistoryKey; 
					    
					}
				        _currentHistoryKey = json.key;
					//alert('now it is '+_currentHistoryKey);
				}
			}
		});
        }
}

function updateContent(key, withoutList)
{
    withoutList = withoutList || false;
    
    new Ajax.Request('/page.php',
    {
		method: 'post',
		parameters: '?key='+key+'&withoutList='+withoutList,
		onSuccess: function(transport)
		{
			if (200 == transport.status && transport.responseText.substring(0,1)=='{')//json check
			{
				var json = transport.responseText;
				var json = eval('(' + json + ')');
			
				$('hiddenForm').action = json.phpNetLink;

				if(json.pagesCount==1)
				{
					$('content').src = json.pageLink;
				}
				else
				{
					// Esli na odno nazvanie neskolko stranits
					$('parentContentLinks').innerHTML = '';
					
					$('pageLanguage').setAttribute('disabled', 'disabled');
					$('pageLanguage').setAttribute('key', '');
					
					$('tabTitle_comments').style.color = '#6a6864'; 
					$('commentsCount').innerHTML = '';
					
					if(_currentHistoryKey != key) { 
					    _prevHistoryKey = _currentHistoryKey; 
					    //$('piska').innerHTML += _prevHistoryKey+' '+_currentHistoryKey+'<br>';
					}
				        _currentHistoryKey = key;
					//alert('now it is '+_currentHistoryKey);

					var innerList = '<h3>'+_multipleMessage+'</h3>';
					var n = 1;
					Object.keys(json.fileNames).each
					(
						function(key)
						{
							if(key.length==5)
							{
								innerList += n+'. <a href="" onclick="parent.updateContent(\''+key+'\', true);return false;" style="color:black;">'+json.fileNames[key]+'</a><br>';
								n++;
							}
						}
					);
					
					window["content"].document.body.innerHTML = innerList;
					
				}
				
				if(navigator.userAgent.toLowerCase().indexOf("msie")!=-1) { setInnerLinksEvent(); }
			}
			else
			{
				window["content"].document.body.innerHTML = _errorMessage;
			}
		}
    });
}

function updateComments(key)
{
    //window["comments"].document.body.innerHTML = _waiter;
    
    new Ajax.Request('/comment.php',
    {
        method: 'post',
        asynchronous: false,
		parameters: '?key='+key,
		onSuccess: function(transport, json)
		{
			if (200 == transport.status && transport.responseText!='')
			{
				window["comments"].document.body.innerHTML = transport.responseText;

				$('commentLink').href = json.shareLink;
				$('commentLink').innerHTML = json.shareLink;
				
				if(json.commentsCount==0)
				{
					$('tabTitle_comments').style.color = '#6a6864'; 
					$('commentsCount').innerHTML = '';
				}
				else
				{ 
					$('tabTitle_comments').style.color = '#000'; 
					$('commentsCount').innerHTML = '('+json.commentsCount+')';
				}
			}
			else
			{
				window["comments"].document.body.innerHTML = _errorMessage;
			}
		}
    });
}
//alert(navigator.userAgent.toLowerCase());
function selectTitle(key)
{
    if(navigator.userAgent.toLowerCase().indexOf("firefox")!=-1) { var optionHeight = 14; } 
    else if(navigator.userAgent.toLowerCase().indexOf("chrome")!=-1) { var optionHeight = 17; } 
    else if(navigator.userAgent.toLowerCase().indexOf("safari")!=-1) { var optionHeight = 13; } 
    else if(navigator.userAgent.toLowerCase().indexOf("opera")!=-1) { var optionHeight = 15; } //v10.10
//    else if(navigator.userAgent.toLowerCase().indexOf("msie")!=-1) { var optionHeight = 14; } 
    else { var optionHeight = 13; }
//    alert(optionHeight);
    var scrollTo = $(key).index * optionHeight;
    if(navigator.userAgent.toLowerCase().indexOf("firefox")!=-1) { scrollTo += 1; }
//    if(navigator.userAgent.toLowerCase().indexOf("opera")!=-1) { var ih = $('indexItems').style.height; ih = ih.substring(0, ih.length-2); scrollTo += ih; }
    
//    alert($(key).index+'x'+optionHeight+'='+scrollTo);
    if(navigator.userAgent.toLowerCase().indexOf("msie")==-1) { $('indexItems').scrollTop = scrollTo; }
    
    $(key).selected = true;
    _prevIndexKey = key;
}

//ent 13, esc 27, bs 8, del 46, command 17 for opera, shift 16
//var letterKeycodes = [0 49 50 51 52 53 54 55 56 57 48 189 187 81 87 69 82 84 89 85 73 79 80 219 221 65 83 68 70 71 72 74 75 76 186 222 220 192 90 88 67 86 66 78 77 188 190 191];
// mac: shift 16, ctrl 17, alt 18, command 91 & 93, bs 8, arrows 37-40, delete 46, help 45, pages 33-36, enter 13
//dozvoleny tolko letters + aux [shift,arrows,ctrl,alt,cmd,bs,ent,del,ins]
//var letterKeycodes = [8,46,13,38,40,192,49,50,51,52,53,54,55,56,57,48,109,107,220,81,87,69,82,84,89,85,73,79,80,219,221,222,59,76,75,74,72,71,70,68,83,65,90,88,67,86,66,78,77,188,190,191];


function suggest(e)
{
	keyNum = e.keyCode;
	//alert(keyNum);
	if (keyNum == "13") //enter
	{
		showIssue();
	} 
	else if(keyNum == "38") //up
	{ 
		sel = $('indexItems').selectedIndex;

	        if (sel>0)
		{
			sel--;
		}
		$('indexItems').options[sel].selected=true; 
	
		writeItemName();
	}
	else if(keyNum == "40") //down
	{ 
		sel = $('indexItems').selectedIndex;
		if (sel<$('indexItems').length)
		{
			sel++;
		} 
		$('indexItems').options[sel].selected=true; 
	
		writeItemName();
	}
	else
	{ 
		var inSearch = $('search').value;
		inSearch = inSearch.toLowerCase();
		inSearch = inSearch.replace(/\'/g, "&#039;");

		if(inSearch!=_prevIndexWord)
		{
			len = inSearch.length;

			if(len == 0)
			{
				var firstLetter = aTitleStarts.keys();
				firstLetter = firstLetter[0];
				key = aTitleStarts.get(firstLetter);
				selectTitle(key);
			} 
			else if(len == 1)
			{
				key = aLettersToKeys.get(inSearch);
				if (key != null){ selectTitle(key); }
			} 
			else
			{ 
				var list = $('indexItems');
				firstTwoLetters = inSearch.substring(0,2);

				isStartExists = aTitleStarts.get(firstTwoLetters);
				if (isStartExists != undefined)
				{ 
					var prevLength = _prevIndexWord.length;
					var isAdding = len == prevLength+1 && _prevIndexWord == inSearch.substring(0, prevLength); //esli dobavili vsego 1 bukvu
					if(isAdding)
					{
						var startIndex = $(_prevIndexKey).index;
					}
					else
					{
						var startIndex = $(isStartExists).index;
					}
					
					var finishIndex = aStopKeys.get(firstTwoLetters);
					finishIndex = $(finishIndex).index;

					var maxMatchedLength = 0;
					var lastKey = null;
					var timeToStop = false;
					for(i=startIndex;i<finishIndex;i++)
					{ 
						if(timeToStop) { break; }
					
						var inTitle = list.options[i].innerHTML;
						inTitle = inTitle.toLowerCase();
						inTitle = inTitle.replace("&gt;", ">");
						inTitle = inTitle.replace(/\'/g, "&#039;");

						// Sravnivat budem maksimum dp razmera slova v poiske
						var minLength = len;
						if(minLength>30) { minLength=30; }
						
						var matchedLength = 0;
						var minCompareLength = 2;
						if(isAdding) { minCompareLength = prevLength; }
						if(minCompareLength<2) { minCompareLength = 2; }

						for(var lc = minCompareLength; lc <= minLength; lc++)// lc = letters count
						{
							if(timeToStop) { break; }
							if(inSearch.substring(0, lc) == inTitle.substring(0, lc))
							{
								//$('piska').innerHTML += inSearch.substring(0, lc)+' '+inTitle.substring(0, lc)+'<br>';
								if(lc >= matchedLength) { matchedLength = lc; } else { alert(_errorMessage[_manualLang]); }
								if(lc == minLength) { timeToStop = true; }
							}
						}
						
						if(matchedLength > maxMatchedLength) { maxMatchedLength = matchedLength; lastKey = list.options[i].id; } else if(matchedLength < maxMatchedLength) { break; }
					}
					
					if (lastKey != null) { selectTitle(lastKey); }
				}
				else
				{
					// выбираем по первой букве
					key = aLettersToKeys.get(inSearch.substring(0,1));
					if (key != null){ selectTitle(key); }
				}
			}
		
			_prevIndexWord = inSearch;
		} 
	} 
}

function checkEnter(e)
{
    key = e.keyCode;
    if(key == "13"){ showIssue(); }
    if(key >= '33'&&key <= '40'){setCaption();} 
}

function setCaption()
{ 
    sel = $('indexItems').selectedIndex; 
    $('search').value=$('indexItems').options[sel].innerHTML; 
} 

function checkEnterForSearch(e)
{ 
    key = e.keyCode; 
    if(key=="13"){searchTopics();} 
} 

function searchTopics()
{
        var searchItems = $('searchItems');
        while(searchItems.firstChild)
        {
		searchItems.removeChild(searchItems.firstChild);
        } 
	
	if($('searchWords').value=='') return false;
	
	new Ajax.Request('search.php',
	{
		method: 'post',
		parameters: '?words='+$('searchWords').value,
		onSuccess: function(transport, json)
		{
			if(200 == transport.status && transport.responseText=='success') 
			{
				$('searchResults').show();

				var found = json.total_found;
				$('total_found').innerHTML = found;

				if(found==0)
				{
					$('searchItems').style.backgroundColor = '#d4d0c8';
					alert(_searchMessage);
				}
				else
				{
					$('searchItems').style.backgroundColor = '#fff';
				}
				
				var i = 0;
				Object.values(json.matches).each
				(
					function(key)
					{
						if(key.length==5 && $(key)!=null)
						{
							var option = document.createElement('option');
							option.setAttribute('key', key);
							option.innerHTML = $(key).innerHTML;
							searchItems.appendChild(option);
							
							if(i==0)
							{
							    updateContent(key);
							    //updateComments(key); ne nado, links vizivaet
							}
							
							i++;
						}
					}
				);
				
				$('searchItems').options[0].selected = true;
				$('searchItems').focus();
			}
			else
			{
				$('searchItems').style.backgroundColor = '#d4d0c8';
				alert(_errorMessage);
			}
		}
	});
}
			
function getPageSize()
{
	var xScroll, yScroll;
 
 if (window.innerHeight && window.scrollMaxY) {
 xScroll = window.innerWidth + window.scrollMaxX;
 yScroll = window.innerHeight + window.scrollMaxY;
 } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
 xScroll = document.body.scrollWidth;
 yScroll = document.body.scrollHeight;
 } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
 xScroll = document.body.offsetWidth;
 yScroll = document.body.offsetHeight;
 }
 
 var windowWidth, windowHeight;
 
 if (self.innerHeight) { // all except Explorer
 if(document.documentElement.clientWidth){
 windowWidth = document.documentElement.clientWidth; 
 } else {
 windowWidth = self.innerWidth;
 }
 windowHeight = self.innerHeight;
 } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
 windowWidth = document.documentElement.clientWidth;
 windowHeight = document.documentElement.clientHeight;
 } else if (document.body) { // other Explorers
 windowWidth = document.body.clientWidth;
 windowHeight = document.body.clientHeight;
 } 
 
 // for small pages with total height less then height of the viewport
 if(yScroll < windowHeight){ 
 pageHeight = windowHeight; 
 } else {
 pageHeight = yScroll; 
 } 
  
 // for small pages with total width less then width of the viewport 
 if(xScroll < windowWidth){ 
 pageWidth = xScroll; 
 } else { 
 pageWidth = windowWidth; 
 } 
  
 return [pageWidth,pageHeight]; 
 }


function goBackInIframe()
{
	//window["content"].history.back();
	
	updateContent(_prevHistoryKey);
	$('goBack').blur();
}

function printManualPage()
{
	$('buttonsForm').action = window["content"].document.location;
	$('printPage').blur();
	$('buttonsForm').submit();
}

function openPhpNetPage()
{
	$('openPhpNet').blur();
	$('hiddenForm').submit();
}

function setSeparator()
{                                      
        new Draggable('draggableSeparator', { constraint : 'horizontal',
            onEnd : function(el){          
                    leftOffset = getSeparatorOffset();
		    //$('hui').innerHTML = leftOffset;
                    $('left_td').style.width = leftOffset;
                    $('draggableSeparator').style.left = '0px';
		    
		    setCookie('leftColumnWidth', leftOffset, 'Mon, 01-Jan-2015 00:00:00 GMT', '/');
        }});
}                                      
																																				
function getSeparatorOffset()          
{                                      
	var tdWidth = $('left_td').style.width;
	tdWidth = tdWidth.substring(0, tdWidth.length-2);

	leftOffset = $('draggableSeparator').style.left;
        leftOffset = leftOffset.substring(0, leftOffset.length-2);
	leftOffset = parseInt(tdWidth, 10)+parseInt(leftOffset, 10);
	
	if(leftOffset < 250) { leftOffset = 250; }

	return leftOffset+'px';
}


function changeInterfaceLanguage()
{
	var interfaceLang = $('interfaceLanguage').value;
	setCookie('interfaceLanguage', interfaceLang, 'Mon, 01-Jan-2015 00:00:00 GMT', '/');
	
	var manualLanguage = $('manualLanguage').value;
	setCookie('manualLanguage', manualLanguage, 'Mon, 01-Jan-2015 00:00:00 GMT', '/');
	
	var transLanguage = $('transLanguage').value;
	setCookie('transLanguage', transLanguage, 'Mon, 01-Jan-2015 00:00:00 GMT', '/');
	
	window.location.href = window.location.href;
}

function quickTranslate()
{
	var transKey = $('pageLanguage').getAttribute('key');
	updateContent(transKey, true);
	$('pageLanguage').blur();
}

function keepInputValue(el)
{
	if(el.checked){
		_keepInputValue = '1';
	}else{
		_keepInputValue = '0';
	}
	
	setCookie('keepInputValue', _keepInputValue, 'Mon, 01-Jan-2015 00:00:00 GMT', '/');
}
