// Variables for timeots
var complex_time_out, hintTimeOutId, techTimeOut, vassalTimeOut, msgTimeout, lastSearchTimer, bulidingBuild, searchAvatarTimeout;
var global_js_vars = new Object();
// Променливи за външни прехвърляния при eval
var external_bnt;
// Променлива за статуса на аватара
user_online=true;

// Basic Functions
function setCaretTo(obj, pos) { 
    if(obj.createTextRange) { 
        var range = obj.createTextRange(); 
        range.move("character", pos); 
        range.select(); 
    } else if(obj.selectionStart) { 
        obj.focus(); 
        obj.setSelectionRange(pos, pos); 
    } 
} 
function focusElement(el) {
	if (el && typeof(el) != 'undefined') {
		if (el.focus) el.focus();
		if (document.all)
			setCaretTo(el,el.value.length+1);
	}
}
function getTagsByName(name, type) {
	if (type && type.indexOf(',') >= 0) {
		type = type.split(',');
		var arr = new Array();
		
		for(var j=0; j<type.length; j++) {
			var tags = document.getElementsByTagName(type[j]);
			for(var i = 0, iarr = arr.length; i < tags.length; i++) {
				att = tags[i].getAttribute("name");
				if(att == name) {
					arr[iarr] = tags[i];
					iarr++;
				}
			}
		}
	} else {
		var tags = document.getElementsByTagName(type ? type : "div");
		var arr = new Array();
		for(var i = 0,iarr = 0; i < tags.length; i++) {
			 att = tags[i].getAttribute("name");
			 if(att == name) {
				  arr[iarr] = tags[i];
				  iarr++;
			 }
		}
	}
	if (arr.length > 0) return arr;
}
function autoRefreshTags(){
	// Временно за опресняване на ресурсите докато се преправи AjaxRequests.loadGetRequestAndExecute-a
	document.is_refresh_sent = true;
	
	if (user_online===true) {
		var tags = getTagsByName("for_refresh[]");
		
		for(step = 0; step < tags.length; step++) {
			if (tags[step].lang != '' && user_online === true) {
				changeCssClass(tags[step].id+'_loading', 'refresh show');
				eval(tags[step].lang);
			}
		}
		loadHints();
	}
    
    document.is_refresh_sent = false;
}

function refreshResources() {
	var resources = $('panel_resources');
	
	if (resources && typeof(resources.lang) != 'undefined') {
		changeCssClass('panel_resources_loading', 'refresh show');
		eval(resources.lang);
	}
}


function refreshShipInProgress(planet_id) {
	insert_code('_sender.php?show=build_ships_progress&planet_id='+planet_id,'progress_list','changeCssClass(\'progress_list_loading\',\'refresh hide\')');
}
function refreshNews(planet_id, system_id, action) {
	insert_code('_sender.php?show=star_news&planet_id='+planet_id+'&system_id='+system_id+'&action='+action, 'scroller','scrollRestart(\'scroller\');changeCssClass(\'scroller_loading\',\'refresh hide\')');
}

var timeOutDraftSave = null;
function draftRefresh(){
	
}
function showCloak() {
	var cloak = $('cloak'),
		body = $('body');
	
	if (cloak) {
		cloak.className = 'cloak';
		cloak.style.width = body.offsetWidth+'px';
		cloak.style.height = body.offsetHeight+'px';
	}
}

function switchClassName(id, class_a, class_b){
    if(id.className == class_a)
        id.className = class_b;
    else
        id.className = class_a;
}
function changeGraph(link, type, class_a, class_b){
    var graph = $("avatar_graph");
    var cont = $("avatar_graph_cont");
    var filters = cont.lang;
        
    if(filters != ''){
        if(filters.match(type)){
            index = filters.indexOf(type);
            if(index)
                filters = filters.replace("|"+type, "");
            else
                filters = filters.replace(type, "");
            if(filters == '')
                filters = type;
        } else {
            filters += "|"+type;
        }
    } else {
        filters = type;
    }
    if(filters != cont.lang){
        cont.lang = filters;
        switchClassName(link, class_a, class_b);
    }
    graph.src = "draw.stats.php?show=avatar&action=avatar_stats&filters="+filters;
}

function loadHints(hints){
	var hints_list = getTagsByName("hints", "div,a,strong,td,button,span"),
		hint_panel = document.getElementById('hint_panel');
	
	if (hints)
		document.hints = hints;
	else if (document.hints)
		hints = document.hints;
	else return false;
	
	if (!hints_list || !hint_panel) return false;
	
	for(step = 0; step < hints_list.length; step++){
        hints_list[step].className = hints_list[step].className.length > 0 ? hints_list[step].className+' for_hints' : 'for_hints';
		hints_list[step].onmouseover = function(){
			var options = this.lang.split(":"),
				arr = options[0].split("|"),
				pageOffset = getScrollXY();
			
			clearObj(hint_panel);
			hideObj(hint_panel);
			if(typeof(hintTimeOutId) != 'undefined') clearTimeout(hintTimeOutId);
			
			switch(arr[0]) {
				case 'planet': case 'system':
					// Тези се обработват оп php
					hintTimeOutId=setTimeout('insert_code(\'_sender.php?show=hints&hint='+options[0]+'\', \'hint_panel\', \'showObj(\\\'hint_panel\\\');\')', 1000);
				break;
				
				default:
					// Тук би трябвало всичко да е заредено вече в js
					if (hints[arr[0]]) {
						hint_panel.innerHTML = hints[arr[0]];
						hintTimeOutId=setTimeout('showObj(\'hint_panel\')', 500);
					}
				break;
			}
			
			if(document.addEventListener) {
				document.addEventListener("mousemove",moveHandler,true);
				document.addEventListener("mouseout",outHandler,true);
			} else if(document.attachEvent){
				document.attachEvent("onmousemove",moveHandler);
				document.attachEvent("onmouseout",outHandler);
			}
			
			// извършва самото преместване
			function moveHandler(event){
				var hint_panel = document.getElementById('hint_panel');
				
				if (!hint_panel) return false;
				
				if(!event) event = window.event;
				
				if (hint_panel) {
					hint_panel.style.top = (pageOffset[1] + event.clientY + 10)+"px";
					hint_panel.style.left = (pageOffset[0] + event.clientX + 10)+"px";
				}
			}
			
			function outHandler(event){
				var hint_panel = document.getElementById('hint_panel');
				
				if (!hint_panel) return false;
				
				if(!event) event = window.event;
				
				if(document.removeEventListener){
					document.removeEventListener("mouseout",outHandler,true);
					document.removeEventListener("mousemove",moveHandler,true);
					
					if(typeof(hintTimeOutId) != 'undefined') clearTimeout(hintTimeOutId);
					
					hint_panel.innerHTML = '';
					hideObj(hint_panel);
				}else if(document.detachEvent){
					document.detachEvent("onmousemove",moveHandler);
					document.detachEvent("onmouseout",outHandler);
					if(typeof(hintTimeOutId) != 'undefined') clearTimeout(hintTimeOutId);
					
					hint_panel.innerHTML = '';
					hideObj(hint_panel);
				}
			}
		}
	}
	
	/* OLD CODE
	var hints = getTagsByName("hints", "div,a,strong,td,button");
	var pageOffset = getScrollXY();
	
	if (!hints) return false;
	
	for(step = 0; step < hints.length; step++){
		var hint = hints[step];
		
		hint.onmouseover = function(){
            var timeout = 1000,
                options = this.lang.split(":"),
                mine = this.lang.split("@"),
                hint_panel = document.getElementById('hint_panel');
				
			if (!hint_panel) return false;
            
            if(typeof(options[1]) != 'undefined'){
                timeout = options[1]*1000;
                this.lang = options[0];
            }
			
			hint_panel.innerHTML = '';
			hideObj(hint_panel);
			
			if(typeof(hintTimeOutId) != 'undefined') clearTimeout(hintTimeOutId);
            
            if (typeof(insert_code) != 'undefined') {
				hintTimeOutId=setTimeout('insert_code(\'_sender.php?show=hints&hint='+options[0]+'\', \'hint_panel\', \'showObj(\\\'hint_panel\\\');\')',timeout);
			}
			
			if(document.addEventListener) {
				document.addEventListener("mousemove",moveHandler,true);
				document.addEventListener("mouseout",outHandler,true);
			} else if(document.attachEvent){
				document.attachEvent("onmousemove",moveHandler);
				document.attachEvent("onmouseout",outHandler);
			}
			
			// извършва самото преместване
			function moveHandler(event){
				var hint_panel = document.getElementById('hint_panel');
				
				if (!hint_panel) return false;
				
				if(!event) event = window.event;
				
				if (hint_panel) {
					hint_panel.style.top = (pageOffset[1] + event.clientY + 10)+"px";
					hint_panel.style.left = (pageOffset[0] + event.clientX + 10)+"px";
				}
			}
			
			function outHandler(event){
				var hint_panel = document.getElementById('hint_panel');
				
				if (!hint_panel) return false;
				
				if(!event) event = window.event;
				
				if(document.removeEventListener){
					document.removeEventListener("mouseout",outHandler,true);
					document.removeEventListener("mousemove",moveHandler,true);
					
					if(typeof(hintTimeOutId) != 'undefined') clearTimeout(hintTimeOutId);
					
					hint_panel.innerHTML = '';
					hideObj(hint_panel);
				}else if(document.detachEvent){
					document.detachEvent("onmousemove",moveHandler);
					document.detachEvent("onmouseout",outHandler);
					if(typeof(hintTimeOutId) != 'undefined') clearTimeout(hintTimeOutId);
					
					hint_panel.innerHTML = '';
					hideObj(hint_panel);
				}
			}
		}
	}*/
}

function findPosX(obj){
	var curleft = 0;
	
	if(obj.offsetParent)
		while(obj.offsetParent) {
            //alert(obj.offsetParent.tagName);
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	
	return curleft;
}

//намира Y позицията на обекта
function findPosY(obj){
	var curtop = 0;
	if(obj.offsetParent)
		while(1) {
		  curtop += obj.offsetTop;
		  if(!obj.offsetParent) break;
		  obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
		
	return curtop;
}

function showMenuHint(menu, obj) {
	if (menu && obj) {
		var x = findPosX(obj)+obj.offsetWidth,
			y = findPosY(obj),
			timeout = 100;
		
		if (typeof($('menu_hints').style) == 'undefined') return false;
		
		$('menu_hints').style.top=y+'px';
		$('menu_hints').style.left=x+'px';
		
		if (hintTimeOutId > 0) clearTimeout(hintTimeOutId);
		hintTimeOutId = setTimeout('$(\'menu_hints\').innerHTML=\''+menu+'\';showObj(\'menu_hints\')', 100);
	}
	
	return false;
}

function hideMenuHint() {
	var menu_hints = $('menu_hints');
	
	if (menu_hints) {
		if (hintTimeOutId) 
			clearTimeout(hintTimeOutId);
		
		menu_hints.innerHTML='';
		hideObj(menu_hints);
	}
}

function loading(id){
	obj = $(id);
	if (obj)
		obj.innerHTML = '<p class="loading">Now loading, please wait...</p>';
}

function scrollInit(divName){
    var scrollId = document.getElementById(divName);
    var divBorderString = scrollId.style.border;
    
    divBorder = scrollId.style.border.substring(0, divBorderString.indexOf("px"));

    scrollId.style.top = divTop+"px";
    scrollId.style.left = divLeft+"px";
    if (divWidth) scrollId.style.width = divWidth+"px";
    scrollId.style.height = divHeight+"px";
    scrollId.style.position = "absolute";
    
    showScroll(divName);
}
		
function showScroll(divName){
	var scrollId = document.getElementById(divName);
	scrollId.style.clip = "rect("+(clipTop)+"px, "+(clipWidth)+"px, "+(clipHeight + clipTop)+"px, "+(clipLeft)+"px)";
}

function scrollRestart(divName){//, row=currentRow
	var scrollId = document.getElementById(divName);
    row = currentRow;
	
	divTop = divTop + (amount * (row - 1));
	clipTop = clipTop - (amount * (row - 1));
	
	scrollId.style.top = divTop+"px";
	showScroll(divName);
	currentRow = 1;
}
		
function scrollDown(divName){
	allRows = document.getElementById('frm_news_filter').news_count.value - (news_amount_on_panel - 1);
	if(currentRow < allRows){
		var scrollId = document.getElementById(divName);
		divTop = divTop - amount;
		scrollId.style.top = divTop+"px";
		clipTop = clipTop + amount;
		showScroll(divName);
		currentRow++;
	}
	//var scrollId = document.getElementById(divName);
	
	//scrollId.scrollTop += 5;
}
		
function scrollUp(divName){
	allRows = document.getElementById('frm_news_filter').news_count.value;
	if(currentRow > 1){
		var scrollId = document.getElementById(divName);
		divTop = divTop + amount;
		scrollId.style.top = divTop+"px";
		clipTop = clipTop - amount;
		showScroll(divName);
		currentRow--;
	}
}

function toInteger(str){
	var str_len = str.length - 1,
		num = 0;
	for(i = 0; i < str_len; i++) {
		num = num + (str_len - i)*10*parseInt(str.substring(i,i+1));
	}
	
	num = num + parseInt(str.substring(str_len,str_len+1));
    return num;
}

var changeClockTimeOutReference;
var isRequestSend = null;

function changeClock(interval, new_turn, frase){
	var clockTime = $("turn_clock_time");
	
	if (changeClockTimeOutReference) {
		clearTimeout(changeClockTimeOutReference);
	}
	
	if(clockTime){
        // скрива покриващият див - 'антиклик'
		var newMinutes = toInteger(clockTime.innerHTML.substr(0, 2)),
            newSeconds = toInteger(clockTime.innerHTML.substr(3, 2)),
            img = clockTime.parentNode.getElementsByTagName('img')[0];
        
		if (newSeconds > 0) {
			newSeconds--;
		} else {
			newMinutes--;
			newSeconds = 59;
		}
        
        seconds = newMinutes*60 + newSeconds;
        if (seconds > 0) {
            seconds = 3-Math.floor(seconds / 225);
            
            img.src = 'interface/inheader/hd_turn_'+(seconds > 0 ? seconds : 0)+'.gif';
            img.alt = (seconds+1)+'/4 turn';
        } else {
            img.src = 'interface/inheader/hd_turn_end.gif';
            img.alt = 'turn is left';
        }
		
		if (newMinutes >= 0) {
			if (newMinutes < 10) newMinutes = "0"+newMinutes;
			if (newSeconds < 10) newSeconds = "0"+newSeconds;
			
			clockTime.innerHTML = newMinutes+":"+newSeconds;
			changeClockTimeOutReference = setTimeout("changeClock("+interval+", '', '"+frase+"')", interval * 1000);
			clockTime.is_refresh_sent = false;
		} else {
			if (!document.is_refresh_sent) {
				clockTime.innerHTML = frase;
				changeClockTimeOutReference = setTimeout("changeClock("+interval+", '', '"+frase+"')", 11000);
				AjaxRequests.loadGetRequestAndExecute('_sender.php?show=turns','autoRefreshTags();');
			}
		}
	} else {
		// Не е зареден никакав час опитваме да го заредим
		changeClockTimeOutReference = setTimeout("changeClock("+interval+", '', '"+frase+"')", 16000);
		AjaxRequests.loadGetRequestAndExecute('_sender.php?show=turns','autoRefreshTags();');
	}
	
}

function showBuildPanel(build_panel, planet_id, choice, schools, system_id) {
	switch (build_panel) {
		case 'build_ground':
			loading('inner_window');
			showObj('in_window');
			changeLinks('pre_next', build_panel, 'add');
			AjaxRequests.loadGetRequestAndExecute('_sender.php?show=building_build&planet_id=' + planet_id + '&type=ground','loadHints();');
			changeAttribute('in_window', 'lang', 'AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=building_build&planet_id=' + planet_id + '&type=ground\',\'loadHints();\');');
		break;
		
		case 'build_orbital':
			loading('inner_window');
			showObj('in_window');
			changeLinks('pre_next', build_panel, 'add');
			AjaxRequests.loadGetRequestAndExecute('_sender.php?show=building_build&planet_id=' + planet_id + '&type=orbital',  'loadHints();');
            changeAttribute('inner_window', 'lang', 'AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=building_build&planet_id=' + planet_id + '&type=orbital\',  \'loadHints();\');');
		break;
		
		case 'build_ships':
			loading('inner_window');
			showObj('in_window');
			changeLinks('pre_next', build_panel, 'add');
			AjaxRequests.loadGetRequestAndExecute('_sender.php?show=build_ship&planet_id='+planet_id);
		break;
		
        case 'info_resources':
            loading('inner_window');
			showObj('in_window');
            changeLinks('pre_next', build_panel, 'add', choice);
            insert_code('_sender.php?show=resources&section=detailed&planet_id='+planet_id+'&choice='+choice,'inner_window');
        break;
		
		case 'info_complex':
			var type = choice.split('_');
			
			if (typeof(type[0]) != 'undefined' && typeof(type[1]) != 'undefined') {
				loading('inner_window');
				showObj('in_window');
				changeLinks('pre_next', build_panel, 'add', choice)
				AjaxRequests.loadGetRequestAndExecute('_sender.php?show=building_complex&type='+type[0]+'&group='+type[1]+'&planet_id='+planet_id);
			}
			
		break;
	
        case 'local_schools':
            loading('inner_window');
			showObj('in_window');
            changeLinks('pre_next', build_panel, 'add', choice);
            AjaxRequests.loadGetRequestAndExecute('_sender.php?show=local_schools&planet_id='+planet_id);
        break;
		
		case 'news_panel':
			AjaxRequests.loadGetRequestAndExecute('_sender.php?show=news'+(planet_id > 0 ? '&planet_id='+planet_id : (system_id > 0 ? '&system_id='+system_id : ''))+(choice != '' ? '&category='+choice : '')+(schools != '' ? '&unreaded='+schools : ''));
		break;
    
        case 'radar_panel':
            if(planet_id != '' || choice != '')
                AjaxRequests.loadGetRequestAndExecute('_sender.php?show=radar&search_what='+choice+'&search_text='+planet_id);
            else
                AjaxRequests.loadGetRequestAndExecute('_sender.php?show=radar');
        break;
		
        case 'local_scientists_limit':
            AjaxRequests.loadGetRequestAndExecute('_sender.php?show=local_scientists_limit&planet_id='+planet_id);
        break;
        
        case 'star_gate':
            loading('inner_window');
			showObj('in_window');
            AjaxRequests.loadGetRequestAndExecute('_sender.php?show=star_gate&planet_id='+planet_id);
        break;
        
	}
}
///
// Функция която подменя линковете prev next ако е отворен прозорец за строене
//
function changeLinks(list_id, build_panel, action, choice) {
	var list = getReference(list_id);
    
	if (list) {
		list = list.getElementsByTagName('a');
		for(var i=0; i<list.length; i++) {
            list[i].href = urlCleanup(list[i].href, Array('build_panel'));
			if (action == 'add'){
                list[i].href += '&build_panel='+build_panel;
                if(choice) {
					list[i].href = urlCleanup(list[i].href, Array('choice'));
					list[i].href += '&choice='+choice;
                }
            }
		}
	}
}

function changePlanetListTag(){
    currentUrl = urlCleanup(location.href, Array('tab'));
    
    tempUrl = currentUrl+"&tab=ally";
    //alert(tempUrl);
    location.href = tempUrl;
}

////////////////////////////////////////////////////////
// скролер на листа на планетите на началната страница
////////////////////////////////////////////////////////
function slowMotionHomePlanets(div_id, direction, step, what){//state_cont, direction, step, all_planets, by
	var scrollId = document.getElementById(div_id);
    
    //lockLinks(new Array("home_planet_link_left", "home_planet_link_right"));
    
	switch(direction){
		case "right":{
            window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] - window[div_id]['amountSelector'];
			scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
			window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] + window[div_id]['amountSelector'];
			
            showSelectorScroll(div_id);
            if(step < 4){
				step++;
				setTimeout('slowMotionHomePlanets(\''+div_id+'\', \'right\', '+step+', \''+what+'\')', 100);
			} else {
                var selector_1 = getReference('home_planet_1'),
					selector_2 = getReference('home_planet_2'),
                    selector_3 = getReference('home_planet_3'),
					selector_4 = getReference('home_planet_4'),
					selector_5 = getReference('home_planet_5'),
                    selector_6 = getReference('home_planet_6'),
					selector_7 = getReference('home_planet_7'),
					selector_8 = getReference('home_planet_8'),
                    selector_9 = getReference('home_planet_9'),
					selector_10 = getReference('home_planet_10'),
					selector_11 = getReference('home_planet_11'),
                    selector_12 = getReference('home_planet_12');
					
					selector_1.parentNode.removeChild(selector_1);
					
					if (document.all) {
						new_selector_12 = document.createElement('div');
						new_selector_12.style.float = 'left';
					} else
						new_selector_12 = document._importNode(selector_12, true);
					
					selector_2.id = 'home_planet_1';
					selector_3.id = 'home_planet_2';
					selector_4.id = 'home_planet_3';
					selector_5.id = 'home_planet_4';
					selector_6.id = 'home_planet_5';
					selector_7.id = 'home_planet_6';
					selector_8.id = 'home_planet_7';
					selector_9.id = 'home_planet_8';
					selector_10.id = 'home_planet_9';
					selector_11.id = 'home_planet_10';
					selector_12.id = 'home_planet_11';
					
					if (document.all) new_selector_12.id='home_planet_12';
					selector_2.parentNode.appendChild(new_selector_12);
					
					if (document.all) {
						$('home_planet_1').parentNode.outerHTML = $('home_planet_1').parentNode.outerHTML;
						// Взимаме новия референс
						var scrollId = document.getElementById(div_id);
						
						var imgs = $('home_planet_1').parentNode.getElementsByTagName('img');
						for(var i=0; i<imgs.length; i++) {
							var real = imgs.realSrc;
							imgs.realSrc = '';
							imgs.src = real;
						}
					}
                    
                    if(window[div_id]['planet_index_ext'] < window[div_id]['planets_all']){
                        window[div_id]['planet_index_ext']++;
                    } else
                        window[div_id]['planet_index_ext'] = 0;
                    nextPlanet = (window[div_id]['planet_index_ext'] + 11) > window[div_id]['planets_all']
                                    ? (window[div_id]['planet_index_ext'] + 10) - window[div_id]['planets_all']
                                    : (window[div_id]['planet_index_ext'] + 10);
                    insert_code('_sender.php?show='+what+'&planet='+nextPlanet, 'home_planet_12');
					
					window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] + 5 * window[div_id]['amountSelector'];
                    window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] - 5 * window[div_id]['amountSelector'];
					showSelectorScroll(div_id);
                    scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
					
            }
			break;
		}
		case "left":{
            window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] + window[div_id]['amountSelector'];
			scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
			window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] - window[div_id]['amountSelector'];
			
			showSelectorScroll(div_id);
            if(step < 4){
				step++;
				setTimeout('slowMotionHomePlanets(\''+div_id+'\', \'left\', '+step+', \''+what+'\')', 100);
			} else {
                var selector_1 = getReference('home_planet_1'),
					selector_2 = getReference('home_planet_2'),
                    selector_3 = getReference('home_planet_3'),
					selector_4 = getReference('home_planet_4'),
					selector_5 = getReference('home_planet_5'),
                    selector_6 = getReference('home_planet_6'),
					selector_7 = getReference('home_planet_7'),
					selector_8 = getReference('home_planet_8'),
                    selector_9 = getReference('home_planet_9'),
					selector_10 = getReference('home_planet_10'),
					selector_11 = getReference('home_planet_11'),
                    selector_12 = getReference('home_planet_12');
					
					selector_12.parentNode.removeChild(selector_12);
					
					if (document.all) {
						new_selector_1 = document.createElement('div');
						new_selector_1.style.float = 'left';
					} else
						new_selector_1 = document._importNode(selector_1, true);
					
					selector_11.id = 'home_planet_12';
					selector_10.id = 'home_planet_11';
					selector_9.id = 'home_planet_10';
					selector_8.id = 'home_planet_9';
					selector_7.id = 'home_planet_8';
					selector_6.id = 'home_planet_7';
					selector_5.id = 'home_planet_6';
					selector_4.id = 'home_planet_5';
					selector_3.id = 'home_planet_4';
					selector_2.id = 'home_planet_3';
					selector_1.id = 'home_planet_2';
					
					if (document.all) new_selector_1.id='home_planet_1';
					selector_2.parentNode.insertBefore(new_selector_1, selector_1);
					// Хак за Експлодера
					if (document.all) {
						$('home_planet_1').parentNode.outerHTML = $('home_planet_1').parentNode.outerHTML;
						// Взимаме новия референс
						var scrollId = document.getElementById(div_id);
						
						var imgs = $('home_planet_1').parentNode.getElementsByTagName('img');
						for(var i=0; i<imgs.length; i++) {
							var real = imgs.realSrc;
							imgs.realSrc = '';
							imgs.src = real;
						}
					}
                    
                    if(window[div_id]['planet_index_ext'] > 1){
                        window[div_id]['planet_index_ext']--;
                    } else
                        window[div_id]['planet_index_ext'] = window[div_id]['planets_all'];
                    nextPlanet = window[div_id]['planet_index_ext']-1;
                    
                    insert_code('_sender.php?show='+what+'&planet='+nextPlanet, 'home_planet_1');
					
					window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] - 5 * window[div_id]['amountSelector'];
                    window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] + 5 * window[div_id]['amountSelector'];
					showSelectorScroll(div_id);
                    scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
            }
			break;
		}
	}
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

function updateScrollerButtons() {
	var up = document.getElementById('up'),
		down = document.getElementById('down'),
		count = document.getElementById('news_count');
		
	up.href="javascript:scrollUp('scroller'," + count.value + ");";
	down.href="javascript:scrollDown('scroller'," + (count.value-3) + ");";
}

function scrollSelectorInit(divName){
	var scrollId = document.getElementById(divName);
	
	if (!scrollId) return;
	
	var divBorderString = scrollId.style.border;
	
	divBorder = scrollId.style.border.substring(0, divBorderString.indexOf("px"));

    scrollId.style.top = window[divName]['divSelectorTop']+"px";
	scrollId.style.left = window[divName]['divSelectorLeft']+"px";
	scrollId.style.height = window[divName]['divSelectorHeight']+"px";
	scrollId.style.position = "absolute";
	scrollId.style.width = window[divName]['divSelectorWidth']+"px";
    
	showSelectorScroll(divName);
}
		
function showSelectorScroll(divName){
	var scrollId = document.getElementById(divName);

    scrollId.style.clip = "rect("+(window[divName]['clipSelectorTop'])+"px, "+(window[divName]['clipSelectorWidth'] + window[divName]['clipSelectorLeft'])+"px, "+(window[divName]['clipSelectorHeight'])+"px, "+(window[divName]['clipSelectorLeft'])+"px)";
}

var locked_links_href, locked_links_ref, locked_links;
	locked_links_href = new Array();
	locked_links_ref = new Array();
	locked_links		= new Array();
	
function saveLink(link) {
    if (link) {
        if (link.href)
            this.href = link.href;
            
        if (link.onclick)
            this.onclick = link.onclick;
        
        if (link.id)
            this.id = link.id;
    }
}

function unlockLinks(){
	if (locked_links)
		for(var i=0; i<locked_links.length; i++) {
			var link = $(locked_links[i].id);
			if (link) {
				link.href = locked_links[i].href;
				link.onclick = locked_links[i].onclick;
			}
		}
}

function lockLinks(link_to_lock){
	if (link_to_lock)
		for(var i=0; i<link_to_lock.length; i++) {
			link = $(link_to_lock[i]);
            if(link){
                locked_links[i] = new saveLink(link);
                link.href='javascript: void[]';
				link.onclick=function (){return false;};
            } 
		}
}

function unlockSelectorLinks(all_planets, div_id, state_cont, by){
	var left = document.getElementById(div_id+'_left_link');
		right = document.getElementById(div_id+'_right_link');
    
	if (left) left.href = "javascript: slowMotion('"+div_id+"', '"+state_cont+"', 'left',  5, '"+all_planets+"', '"+by+"');lockSelectorLinks('"+div_id+"');";
	if (right) right.href = "javascript: slowMotion('"+div_id+"', '"+state_cont+"', 'right', 0, '"+all_planets+"', '"+by+"');lockSelectorLinks('"+div_id+"');";
}

function lockSelectorLinks(link){
	var left = document.getElementById(link+'_left_link'),
		right = document.getElementById(link+'_right_link');
    if (left) left.href = "javascript: void[];";
	if (right) right.href = "javascript: void[];";
}

function updateSelectorDivs(div_id, state_cont, all_planets, by) {
	if (!window[div_id]) return false;
	
	planet_index = window[div_id]['planet_index_ext'];
	
	
	if ($(div_id+'_1')) {
		AjaxRequests.loadGetRequestAndExecute('_sender.php?show=selector_planets&position_planet='+(planet_index)+'&by='+by+'&name='+div_id+'&count=1');
	}
}

function RefreshTraining(name) {
	if (typeof(name) == 'undefined') return false;
	
	changeValue(name+'_planet_id', getReference(name+'_1').lang);
    changeValue(name+'s__planet_id', getReference(name+'_1').lang);
	var input_planet_id = getReference(name + '_planet_id');
    
	insert_code('_sender.php?show=training_refresh_list&planet_id='+input_planet_id.value+'&what='+name+'s', name+'s_progress');
}

function RefreshResearch(name) {
	if (typeof(name) == 'undefined') return false;
    
	changeValue(name+'_planet_id', getReference(name+'_1').lang);
	var input_planet_id = getReference(name + '_planet_id');
	
	//insert_code('_sender.php?show=training_refresh_list&planet_id='+input_planet_id.value+'&what='+name+'s', name+'s_progress');
}

function selectorDelayRefresh(name, key, id, by, view_all_planets, close){
    eval(name+'.planet_index_ext='+key);
    if(id > 0) document.getElementById(name+'_planet_id').value = id;
    else document.getElementById(name+'_planet_id').value = 0;
    
    if(by != 'scientists'){
        RefreshTraining(name);
    }
}

function slowMotion(div_id, state_cont, direction, step, all_planets, by){
	var scrollId = document.getElementById(div_id);
    
	switch(direction){
		case "right":{
            window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] - window[div_id]['amountSelector'];
			scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
			window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] + window[div_id]['amountSelector'];
			
			showSelectorScroll(div_id);
			if(step < 5){
				step++;
				setTimeout('slowMotion(\''+div_id+'\', \''+state_cont+'\', \'right\', '+step+', '+all_planets+', \''+by+'\')', 100);
			} else {
				var selector_0 = document.getElementById(state_cont+'_0'),
					selector_1 = document.getElementById(state_cont+'_1'),
					selector_2 = document.getElementById(state_cont+'_2');

                var inputId = document.getElementById(div_id+'_planet_id');
                
                input_planet_id = selector_2.childNodes[0]; i=1;
                while(i<selector_2.childNodes.length && input_planet_id.tagName != 'DIV') {
                    input_planet_id = selector_2.childNodes[i];
                    i++;
                }
                planet_index = window[div_id]['planet_index_ext'];
				planet_index += 2;
				planet_index = planet_index > (all_planets-1) ? planet_index - all_planets : planet_index;
                
				selector_0.innerHTML = selector_1.innerHTML;
				selector_1.innerHTML = selector_2.innerHTML;
            
                window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] + 6 * window[div_id]['amountSelector'];
				scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
				window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] - 6 * window[div_id]['amountSelector'];
				showSelectorScroll(div_id);
				
                window[div_id]['planet_index_ext'] = planet_index-1;
				window[div_id]['planet_index_ext'] = window[div_id]['planet_index_ext'] > (all_planets-1) ? 0 : window[div_id]['planet_index_ext'];
                window[div_id]['planet_index_ext'] = window[div_id]['planet_index_ext'] < 0 ? (all_planets-1) : window[div_id]['planet_index_ext'];
                
                inputId.value = input_planet_id.lang;
				insert_code('_sender.php?show=selector_planets&position_planet='+(planet_index)+'&by='+by,'planet_'+div_id+'_2','unlockSelectorLinks('+all_planets+', \''+div_id+'\', \''+state_cont+'\', \''+by+'\')');
                if(by != 'scientists')
                    insert_code('_sender.php?show=training_refresh_list&planet_id='+input_planet_id.lang+'&what='+div_id+'s', div_id+'s_progress');
			}
			break;
		}
		case "left":{
            window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] + window[div_id]['amountSelector'];
			scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
			window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] - window[div_id]['amountSelector'];
			showSelectorScroll(div_id);
			if(step > 0){
				step--;
				setTimeout('slowMotion(\''+div_id+'\', \''+state_cont+'\', \'left\', '+step+', '+all_planets+', \''+by+'\')', 100);
			}else{
				var selector_0 = document.getElementById(state_cont+'_0'),
					selector_1 = document.getElementById(state_cont+'_1'),
					selector_2 = document.getElementById(state_cont+'_2');
                    
                var inputId = document.getElementById(div_id+'_planet_id');
				
                input_planet_id = selector_0.childNodes[0]; i=1;
                while(i<selector_0.childNodes.length && input_planet_id.tagName != 'DIV') {
                    input_planet_id = selector_0.childNodes[i];
                    i++;
                }
                
				selector_2.innerHTML = selector_1.innerHTML;
				selector_1.innerHTML = selector_0.innerHTML;
				
                planet_index = window[div_id]['planet_index_ext'];
				planet_index -= 2;
				planet_index = planet_index < 0 ? (all_planets+planet_index) : planet_index;
				
                window[div_id]['planet_index_ext'] = planet_index+1;
                window[div_id]['planet_index_ext'] = window[div_id]['planet_index_ext'] > (all_planets-1) ? 0 : window[div_id]['planet_index_ext'];
				window[div_id]['planet_index_ext'] = window[div_id]['planet_index_ext'] < 0 ? (all_planets-1) : window[div_id]['planet_index_ext'];
                
                window[div_id]['divSelectorLeft'] = window[div_id]['divSelectorLeft'] - 6 * window[div_id]['amountSelector'];
				scrollId.style.left = window[div_id]['divSelectorLeft']+"px";
				window[div_id]['clipSelectorLeft'] = window[div_id]['clipSelectorLeft'] + 6 * window[div_id]['amountSelector'];
				showSelectorScroll(div_id);
                
                inputId.value = input_planet_id.lang;
                
                insert_code('_sender.php?show=selector_planets&position_planet='+(planet_index)+'&by='+by,'planet_'+div_id+'_0','unlockSelectorLinks('+all_planets+', \''+div_id+'\', \''+state_cont+'\', \''+by+'\');');
                if(by != 'scientists')
                    insert_code('_sender.php?show=training_refresh_list&planet_id='+input_planet_id.lang+'&what='+div_id+'s', div_id+'s_progress');
			}
			break;
		}
	}
}

function changePlanetIndex(index){
//	alert(index);
	var input = document.getElementById("planet_index");
	input.value = index;
}

function clearSortSelection(sort_list) {
	var list = getReference(sort_list);
	
	if (list) {
		list = list.childNodes;
		for(i=0; i<list.length; i++) {
			if (list[i].nodeType == document.ELEMENT_NODE) {
				inner_a = list[i].childNodes[0];
				if (inner_a.nodeType != document.ELEMENT_NODE) inner_a = inner_a.nextSibling;
				
				inner_a.className = 'control_link link_hide';
			}
		}
	}
}
function selectSort(sort_list, sel_obj) {
	
	clearSortSelection(sort_list);
	
	sel_obj.className = 'control_link link_show';
}

function clearSelectedBuild() {
	var build_img = document.getElementById('img_0'),
		i=0;

	while(build_img) {
		build_img.className = 'border';
		i++;
		build_img = document.getElementById('img_'+i);
	}
	return true;
}
function closeShipSelectors(list_id) {
	clearSelectedBuild();
	//затваряме предните списъци ако има такива
	var old_lists_id = list_id.split("_")[0]+ '_' + list_id.split("_")[1] +'_0';
	var old_lists = getReference(old_lists_id);
	i=0;
	while (old_lists) {
		hideObj(old_lists_id);
		i++;
		old_lists_id = list_id.split("_")[0]+ '_' + list_id.split("_")[1] +'_'+i;
		old_lists = getReference(old_lists_id);
	}
}
function shipBuildSelector(list_id, ship_btn, item_id, select_obj) {
	var list = getReference(list_id),
		checkId = document.getElementById("check"),
		field = document.getElementById('build_id'),
		bcount = document.getElementById('build_count');
	
	closeShipSelectors(list_id)
	
	if (!select_obj) {
		//Избираме първия в списъка
		var select_obj = list.childNodes[0];
		
		if (select_obj.nodeType != document.ELEMENT_NODE) select_obj = select_obj.nextSibling;
		
		if (checkId) {
		   select_obj.parentNode.insertBefore(checkId, select_obj);
		}
		
	} else {
		//Избираме този върху който е кликнато
		if (checkId) {
			select_obj = select_obj.childNodes[0];
			
			if (select_obj.nodeType != document.ELEMENT_NODE) select_obj = select_obj.nextSibling;
			
			select_obj.parentNode.insertBefore(checkId, select_obj);
		}
	}
	showObj('check');
	ship_btn.className = 'hightlight';
	showObj(list_id);
	
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=ship_short_info&ship_id='+item_id, 'loadHints()');
	
	showObj('building_form');
	hideObj('message');
	field.value=item_id;
	bcount.value=1;
}
function selectBuild(item_id, img_id) {
	var field = document.getElementById('build_id'),
		bcount = document.getElementById('build_count'),
		img = document.getElementById(img_id),
		check = document.getElementById('check');

	clearSelectedBuild();
	showObj('building_form');
	hideObj('message');
	field.value=item_id;
	bcount.value=1;
	img.className = 'hightlight';
	check.style.position = 'absolute';
	check.style.top=(img.y+8)+'px';
	check.style.left=(img.x+12)+'px';
	check.className = 'show';
}
// индивидуална ф-я, изпълнява се при кликване на връзката "view all planets" за страницата Research,
function viewAllPlanets(view_all_planets, close, inv, class1, class2, div_id, by){
    if(inv){
        showObj('planetsList_'+div_id+'_all');
        insert_code('_sender.php?show=selector_planets&all=true&by='+by+'&name='+div_id, 'planetsList_'+div_id+'_all');
        changeOnclick('link_'+div_id+'_all',view_all_planets,close,'javascript: viewAllPlanets(\''+view_all_planets+'\',\''+close+'\',true,\''+class1+'\',\''+class2+'\',\''+div_id+'\',\''+by+'\');','javascript: viewAllPlanets(\''+view_all_planets+'\',\''+close+'\',0,\''+class1+'\',\''+class2+'\',\''+div_id+'\',\''+by+'\');',class1,class2);
    }
    else{
        hideObj('planetsList_'+div_id+'_all');
        changeOnclick('link_'+div_id+'_all',view_all_planets,close,'javascript: viewAllPlanets(\''+view_all_planets+'\',\''+close+'\',true,\''+class1+'\',\''+class2+'\',\''+div_id+'\',\''+by+'\');','javascript: viewAllPlanets(\''+view_all_planets+'\',\''+close+'\',0,\''+class1+'\',\''+class2+'\',\''+div_id+'\',\''+by+'\');',class1,class2);
    }
}
//за даден линк, сменя имато му и target-a при кликване
function changeHrefText(link, text1, text2, target1, target2, class1, class2){
	var link = getReference(link);
	
	if(link && link.innerHTML == text1) {
        link.innerHTML=text2;      
        link.href=target2;
        link.className=class2;
    } else { 
        link.innerHTML=text1;
        link.href=target1;
        link.className=class1;
    }    
}
function changeOnclick(linkId, text1, text2, target1, target2, class1, class2) {
	var link = document.getElementById(linkId);
	
	if(link && link.innerHTML == text1) {
        link.innerHTML=text2;      
        link.onclick= function () {eval(target2)};
        link.className=class2;
    } else {
        link.innerHTML=text1;
		link.onclick= function () {eval(target1)};
        link.className=class1;
    }
}
function showHideObj(option, div1, div2, div3){
    var linkId1 = getReference(div1+"_link");
    var linkId2 = getReference(div2+"_link");
    var linkId3 = getReference(div3+"_link");
    
    var divId1 = getReference(div1);
    var divId2 = getReference(div2);
    var divId3 = getReference(div3);
    
    if(option){
        linkId1.onclick = function () {showHideObj(false, div1, div2, div3);};
        linkId1.className = "link_show";
        showObj(div1);
        
        linkId2.onclick = function () {showHideObj(true, div2, div1, div3);};
        linkId2.className = "link_hide";
        hideObj(div2);
        
        linkId3.onclick = function () {showHideObj(true, div3, div1, div2);};
        linkId3.className = "link_hide";
        hideObj(div3);
        
        changeLinks('pre_next', 'info_resources', 'add', div1);
    } else {
        linkId1.onclick = function () {showHideObj(true, div1, div2, div3);};
        linkId1.className = "link_hide";
        hideObj(div1);
    }
}
function changeCheckPosition(btn){
    var checkId = getReference("check");

    if (checkId) {
        btn.parentNode.insertBefore(checkId, btn);
		showObj(checkId, 'inline');
    }
}

function changeValueResearch(id, value){
    var inp = document.getElementById(id);
    if(value == 0){
        hideObj(id);
    }else{
        inp.value=value;
        showObj(id, 'inline');
    }
}

// mailbox
function mailboxDeleteRow(msg_id) {
	var row = $('msg_'+msg_id);
	
	if (row) row.parentNode.removeChild(row);
}
function selectMail(mail, cicle, replyId){
    // Махаме всички селекции
    var list = mail.parentNode.getElementsByTagName('tr'),
		selectedMail = document.getElementById("selected_mail");
    
    for(i=0; i<list.length; i++) {
		list[i].className = list[i].className.indexOf('unreaded') >= 0 ? 'unreaded ' + cicle[(i%2)] : cicle[(i%2)];
    }
    
    selectedMail.value = replyId;
    
    mail.className = mail.className.indexOf('unreaded') >= 0 ?  'sel unreaded' : 'sel';
    hideObj("top_band");
    showObj("top_band_link");
}
function readMail(mail, link){
    document.getElementById("message_block").innerHTML = "";
    location.href = link;
}



function cloakDisplay(cloak){
    if(cloak){
        var bodyId = document.getElementById("body");
        var cloakId = document.getElementById("cloak");
        
        cloakId.style.width = cloakId.parentNode.clientWidth+"px";
        cloakId.style.height = cloakId.parentNode.clientHeight+"px";
        showObj("cloak");
    } else {
        hideObj("cloak");
    }
}
function cloakDisplayTrans(cloak){
	return false;
}
function RefreshProgress(who, planet_id, local) {
    var url = '_sender.php?show=training_progress&who='+who+'&planet_id='+planet_id;
    if (local=='yes') url=url+'&local=yes';
	insert_code(url,who+'_progress');
}

function checkCrewInput(e) {
	if (!e) e = window.event;
	
	if (e.target) elm = e.target;
		else if (e.srcElement) elm = e.srcElement;
	
	if (elm.nodeType == 3) // defeat Safari bug
		elm = elm.parentNode;
		
	if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		
	var character = String.fromCharCode(code);
	
	var new_value = parseInt(elm.value);
	
	if (new_value > elm.max_value)
		elm.value = elm.last_valid;
	else if (elm.value == '' || new_value < 0) elm.value = 0;
		else elm.last_valid = elm.value;
}
function checkShip(btn, ship_id, hull, shield, fuel, electronics, crew, max_crew) {
	var repair_btn = $('btn_repair_ship'),
		recharge_btn = $('btn_recharge_ship'),
		refuel_btn = $('btn_refuel_ship'),
		//electronic_btn = $('btn_electronic_ship'),
		crew_val = $('ship_crew_value'),
		inp = $('ship_id'),
		form = $('dock_ship_form');
	
	repair_btn.className = 'button_disabled';
	repair_btn.disabled = true;
	
	recharge_btn.className = 'button_disabled';
	recharge_btn.disabled = true;
	
	refuel_btn.className = 'button_disabled';
	refuel_btn.disabled = true;
	
	if (hull < 100) {
		repair_btn.className = 'button_repair';
		repair_btn.disabled = false;
	}
	
	if (shield < 100) {
		recharge_btn.className = 'button_recharge';
		recharge_btn.disabled = false;
	} 
	
	if (fuel < 100) {
		refuel_btn.className = 'button_refuel';
		refuel_btn.disabled = false;
	}
	
	var list = btn.parentNode.parentNode.getElementsByTagName('tr');
	for(var i=0; i<list.length; i++) {
		var pos=list[i].className.indexOf('sel');
		if (pos > -1)
			list[i].className = list[i].className.substring(0, pos);
	}
	
	btn.parentNode.className = btn.parentNode.className + ' sel';
	
	inp.value = ship_id;
	
	moveObj(form, btn.parentNode.parentNode.parentNode.parentNode);
	showObj(form);
	
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=dock_price&ship_id='+ship_id);
}
function refreshResourcesPage(planet_id, page) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=resources&id='+planet_id+'&show_page='+page,'changeCssClass(\'resources_loading\',\'refresh hide\')');
}

function openShipDockList(btn, fleet_id) {
	var list = btn.parentNode.parentNode.getElementsByTagName('div'),
		open_fleet = $('open_fleet');
	
	// Затваряме отворения таб
	for (var i in list)
		if (list[i].className == 'fleet_info show') {
			list[i].className = 'fleet_info hide';
			i = list.length;
		}
	
	btn.parentNode.getElementsByTagName('div')[1].className = 'fleet_info show';
	
	open_fleet.value = fleet_id;
	
	return true;
}

function changeFleetStatus(obj, current_status, new_status) {
	if (obj) {
		if (obj.old_content && obj.old_content != current_status) {
			obj.old_content = current_status;
			obj.innerHTML = current_status;
		} else {
			obj.old_content = new_status;
			obj.innerHTML = new_status;
		}
		
		switch (obj.className) {
			case 'ic_aggressive': obj.className = 'ic_passive'; break;
			case 'ic_passive': obj.className = 'ic_aggressive'; break;
			case 'ic_conquer': obj.className = 'ic_vassal'; break;
			case 'ic_vassal': obj.className = 'ic_conquer'; break;
		}
	}
}

function checkCheckbox(checkbox){
    var checkboxId = getReference(checkbox+'_priority');
    
    if(checkboxId.checked)
       checkboxId.checked = false;
    else
        checkboxId.checked = true;
}
////////////////
// FLEETS //////
////////////////
function selectFleet(btn) {
	if (btn) {
		var list = btn.parentNode.getElementsByTagName('tr');
		
		for (var i=0; i<list.length; i++) {
			var index = list[i].className.toString().indexOf('sel');
			if (index >= 0) {
				list[i].className = list[i].className.substring(0, index);
			}
		}
		btn.className = btn.className + " sel";
		//fleet_id_inp.value = fleet_id;
	}
}
function changeFormField(btn, form, field_id, value) {
	if (form) {
		var field = $(field_id);
		
		field.value = value;
		
		var list = btn.parentNode.getElementsByTagName('a');
		
		for (var i in list) {
			list[i].className = (list[i].className) ? list[i].className.split('_on')[0] : '';
		}
		
		if (btn) btn.className = btn.className + '_on';
	}
	return false;
}

function showFilterList(filter, win) {
	if (filter && filter != '') {
		AjaxRequests.loadGetRequestAndExecute('_sender.php?show=fleet_filter_list&filter='+filter+'&window='+win);
	}
	return false;
}

function getFleetList(form) {
	if (form) form.submit();
	
	return false;
}
/////////////////
// DRAG & DROP //
/////////////////
function moveShip(event, from_where, ship_id, element) {
	var left = element, //$('left_ships_list'),
		right = $('right_fleet_list'), //$('right_ships_list'), 
		pageOffset = getScrollXY();
	
	//alert(from_where);
	switch(from_where) {
		case 'left':
			if ((pageOffset[0] + event.clientX) > (findPosX(right)) &&
				(pageOffset[0] + event.clientX) < (findPosX(right) + right.offsetWidth) &&
				(pageOffset[1] + event.clientY) > findPosY(right) &&
				(pageOffset[1] + event.clientY) < (findPosY(right) + right.offsetHeight)) {
				
				// Търсим елемента върху които е пуснато
				var list = getTagsByName('right_fleet_info[]', 'div');
				var listOffset = getElementScrollXY(right);
				
				for(var i in list) {
					if ((pageOffset[0] + listOffset[0] + event.clientX) > (findPosX(list[i])) &&
						(pageOffset[0] + listOffset[0] + event.clientX) < (findPosX(list[i]) + list[i].offsetWidth) &&
						(pageOffset[1] + listOffset[1] + event.clientY) > findPosY(list[i]) &&
						(pageOffset[1] + listOffset[1] + event.clientY) < (findPosY(list[i]) + list[i].offsetHeight)) {
						
						//alert('Droped over: '+list[i].innerHTML);return false;
						var to_fleet_id = list[i].lang;break;
					}
				}
				
				if (to_fleet_id != '')
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=ship_move_form&ship_id='+ship_id+'&to_fleet='+to_fleet_id);
			}
		break;
		
		/*case 'right':
			if ((pageOffset[0] + event.clientX) > (findPosX(left)) &&
				(pageOffset[0] + event.clientX) < (findPosX(left) + left.offsetWidth) &&
				(pageOffset[1] + event.clientY) > findPosY(left) &&
				(pageOffset[1] + event.clientY) < (findPosY(left) + left.offsetHeight)) {
				//Преместваме от десния прозорец в левия
				
				var to_fleet_id=$('fleet_id_left').value;
				
				if (to_fleet_id != '')
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=ship_move_form&ship_id='+ship_id+'&to_fleet='+to_fleet_id);
			}
		break;*/
	}
	return false;
}
function dragShip(event, ship_name, from_where, ship_id, element) {
	var pageOffset = getScrollXY();

	var select_cursor = $("move_ship");
	var ship_list = getTagsByName('right_fleet_info[]', 'div');
	
	select_cursor.style.top = (pageOffset[1] + event.clientY - 7)+"px";
	select_cursor.style.left = (pageOffset[0] + event.clientX - 7)+"px";
	select_cursor.style.cursor = 'pointer';
	
	select_cursor.innerHTML = ship_name;
	select_cursor.className = 'show';
	
	for(var i in ship_list) {
		ship_list[i].onmouseover = function () {
			if (this.style.backgroundColor != '#777777') {
				this.oldColor=this.style.backgroundColor;
			}
			this.style.backgroundColor='#777777';
		}
		
		ship_list[i].onmouseout = function () {this.style.backgroundColor=this.oldColor;}
	}
	
	if(document.addEventListener) {
		document.addEventListener("mousemove",moveHandler,true);
		document.addEventListener("mouseup",upHandler,true);
	} else if(document.attachEvent){
		document.attachEvent("onmousemove",moveHandler);
		document.attachEvent("onmouseup",upHandler);
	}

	// извършва самото преместване ма цвета от палитрата
	function moveHandler(event){
		if(!event) event = window.event;
			select_cursor.style.top = (pageOffset[1] + event.clientY + 2)+"px";
			select_cursor.style.left = (pageOffset[0] + event.clientX + 2)+"px";
	}
	
	// унищожава цвета от палитрата
	function upHandler(event){
		if(!event) event = window.event;
		
		for(var i in ship_list) {
			ship_list[i].onmouseover = function () {}
			ship_list[i].style.backgroundColor=ship_list[i].oldColor;
		}
		
		if(document.removeEventListener){
			document.removeEventListener("mouseup",upHandler,true);
			document.removeEventListener("mousemove",moveHandler,true);
			select_cursor.className = "hide";
			moveShip(event, from_where, ship_id, element);
		}else if(document.detachEvent){
			document.detachEvent("onmousemove",moveHandler);
			document.detachEvent("onmouseup",upHandler);
			select_cursor.className = "hide";
			moveShip(event, from_where, ship_id, element);
		}
	}
}


function moveResources(event, from_where, name, resource_id) {
	var left = $('left'),
		right = $('right'),
		pageOffset = getScrollXY();
	
	
	switch(from_where) {
		case 'left':
			if ((pageOffset[0] + event.clientX) > (findPosX(right)) &&
				(pageOffset[0] + event.clientX) < (findPosX(right) + right.offsetWidth) &&
				(pageOffset[1] + event.clientY) > findPosY(right) &&
				(pageOffset[1] + event.clientY) < (findPosY(right) + right.offsetHeight)) {
				//Преместваме от левия прозорец в десния
				var fleet_id = $('fleet_id_right'),
					main_fleet = $('main_fleet_right'),
					planet_id = $('planet_id_right');
				
				if (planet_id && planet_id.value > 0) {
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=move_resources_form&planet_id='+planet_id.value+'&fleet_id='+main_fleet.value+'&resource='+name+'&resource_id='+resource_id+'&move_to=planet');
				} else if (fleet_id && fleet_id.value > 0) {
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=move_resources_form&resource_id='+resource_id+'&fleet_id='+fleet_id.value);
				} 
				
			}
		break;
		
		case 'right':
			if ((pageOffset[0] + event.clientX) > (findPosX(left)) &&
				(pageOffset[0] + event.clientX) < (findPosX(left) + left.offsetWidth) &&
				(pageOffset[1] + event.clientY) > findPosY(left) &&
				(pageOffset[1] + event.clientY) < (findPosY(left) + left.offsetHeight)) {
				//Преместваме от десния прозорец в левия
				var fleet_id = $('fleet_id_left'),
					planet_id = $('planet_id_right');
					
				if (planet_id && planet_id.value > 0) {
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=move_resources_form&planet_id='+planet_id.value+'&fleet_id='+fleet_id.value+'&resource='+name+'&move_to=fleet');
				} else if (fleet_id && fleet_id.value > 0) { 
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=move_resources_form&resource_id='+resource_id+'&fleet_id='+fleet_id.value);
				} else ;//Тук ще е проверката за планта
			}
		break;
		
	}
	return false;
}
function divDragDropResources(event, name, name_tr, from_where, resource_id, element){
	var pageOffset = getScrollXY();

	var select_cursor = document.getElementById("move_resources");
	
	select_cursor.style.top = (pageOffset[1] + event.clientY - 7)+"px";
	select_cursor.style.left = (pageOffset[0] + event.clientX - 7)+"px";
	
	select_cursor.innerHTML = name_tr;
	select_cursor.className = 'show';
	
	if(document.addEventListener) {
		document.addEventListener("mousemove",moveHandler,true);
		document.addEventListener("mouseup",upHandler,true);
	} else if(document.attachEvent){
		document.attachEvent("onmousemove",moveHandler);
		document.attachEvent("onmouseup",upHandler);
	}

	// извършва самото преместване ма цвета от палитрата
	function moveHandler(event){
		if(!event) event = window.event;
			select_cursor.style.top = (pageOffset[1] + event.clientY - 7)+"px";
			select_cursor.style.left = (pageOffset[0] + event.clientX - 7)+"px";
	}
	
	// унищожава цвета от палитрата
	function upHandler(event){
		if(!event) event = window.event;
  
		if(document.removeEventListener){
			document.removeEventListener("mouseup",upHandler,true);
			document.removeEventListener("mousemove",moveHandler,true);
			select_cursor.className = "hide";
			moveResources(event, from_where, name, resource_id);
		}else if(document.detachEvent){
			document.detachEvent("onmousemove",moveHandler);
			document.detachEvent("onmouseup",upHandler);
			select_cursor.className = "hide";
			moveResources(event, from_where, name, resource_id);
		}
	}
}

function DragDrop(event, text, obj) {
	var pageOffset = getScrollXY();
	var oThis = this;
	
	if (!obj) {
		// Ако няма див който да местим го създаваме
		obj = document.createElement('div');
		document.body.appendChild(obj);
	}
	
	// Преместваме го на мястото на координатите
	obj.style.top = (pageOffset[1] + event.clientY + 1)+"px";
	obj.style.left = (pageOffset[0] + event.clientX + 1)+"px";
	
	obj.innerHTML = text;
	obj.className = 'resource_move';
	
	if(document.addEventListener) {
		document.addEventListener("mousemove",moveHandler,true);
		document.addEventListener("mouseup",upHandler,true);
	} else if(document.attachEvent){
		document.attachEvent("onmousemove",moveHandler);
		document.attachEvent("onmouseup",upHandler);
	}
	
	// извършва самото преместване ма цвета от палитрата
	function moveHandler(event){
		if(!event) event = window.event;
		
		obj.style.top = (pageOffset[1] + event.clientY + 1)+"px";
		obj.style.left = (pageOffset[0] + event.clientX + 1)+"px";
	}
	
	// унищожава цвета от палитрата
	function upHandler(event){
		if(!event) event = window.event;
		
		if(document.removeEventListener){
			document.removeEventListener("mouseup",upHandler,true);
			document.removeEventListener("mousemove",moveHandler,true);
		}else if(document.detachEvent){
			document.detachEvent("onmousemove",moveHandler);
			document.detachEvent("onmouseup",upHandler);
		}
		
		document.body.removeChild(obj);
		
		if (oThis.onUp) {
			oThis.onUp(event); 
		}
	}
}

//намира Y позицията на обекта
function findPosY(obj){
	var curtop = 0;
	if(obj.offsetParent)
		while(1) {
		  curtop += obj.offsetTop;
		  if(!obj.offsetParent) break;
		  obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
		
	return curtop;
}

// взима отместването на скролера 
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  
  if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape
	scrOfY = window.pageYOffset;
	scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM
	scrOfY = document.body.scrollTop;
	scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6
	scrOfY = document.documentElement.scrollTop;
	scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function getElementScrollXY(obj) {
	var scrOfX = 0, scrOfY = 0;
	
	if (obj && typeof(obj.pageYOffset) == 'number') {
		//Netscape
		scrOfY = obj.pageYOffset;
		scrOfX = obj.pageXOffset;
	} else if (obj && (obj.scrollLeft || obj.scrollTop ) ) {
		//DOM
		scrOfY = obj.scrollTop;
		scrOfX = obj.scrollLeft;
	}
	
	return [ scrOfX, scrOfY ];
}


var shortDescShown = true;
function showShortDescription(divId, buildingId){
    if(shortDescShown) {
        var shortDescId = $('short_desc');
        if (shortDescId) {
            shortDescId.innerHTML = "";
            
            shortDescId.style.top = findPosY(divId)+11+"px";
            shortDescId.style.left = findPosX(divId)+20+"px";
            
            insert_code("_sender.php?show=short_desc&building_id="+buildingId, 'short_desc');
            showObj('short_desc');
        }
    }
}

function hideShortDescription(){
    if(!shortDescShown) hideObj('short_desc');
}

var resourceTimeout = null;
function showResourceWeight(resource, count) {
	if (resourceTimeout != '') clearTimeout(resourceTimeout);
	resourceTimeout = setTimeout('AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=resource_weight&count='+count+'&resource='+resource+'\');', 1000);
}

function loadingMessage(msg, msg_id, css_class) {
	var msg_div = document.getElementById(msg_id);
	if (!css_class) css_class = 'loading';
	
	if (msg_div) {
		msg_div.innerHTML = '<p class="'+css_class+'">' + msg + '</p>';
	}
}

function BuildingRefreshProgress(type, planet_id) {
	clearObj('progress_list');
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=building_progress&type='+type+'&planet_id='+planet_id);
}

function clearSelected() {
	var building_img = document.getElementById('img_0'),
		i=0;
	
	while(building_img) {
		building_img.className = 'border';
		i++;
		building_img = document.getElementById('img_'+i);
	}
	
	//Скриваме картинката
	hideObj('check');
	
	return true;
}
function selectBuilding(item_id, img_id, is_unique) {
	var field = document.getElementById('building_id'),
		bcount = document.getElementById('building_count'),
		img = document.getElementById(img_id),
		check = document.getElementById('check');
		
	
	if (img.className != 'hightlight') {
		var	pageOffset = getScrollXY();
		
		if (bulidingBuild) clearTimeout(bulidingBuild);
		
		// изчистваме предишно избраната сграда, показваме формата и скриваме съобщението и иконката за уникалност
		clearSelected();
		showObj('building_form');
		$('form_desc_building').innerHTML = "";
		bulidingBuild = setTimeout('insert_code(\'_sender.php?show=short_desc&building_id='+item_id+'\', \'form_desc_building\');', 1000);
		
		bcount.type="text";
		hideObj('message');
		hideObj('unique');
		
		// предаваме id-то на сградата
		field.value=item_id;
		
		// предаваме броя сгради по подразбиране 1
		bcount.value=1;
		
		// ако сградата е уникална скриваме полето за брой сгради и показваме картинката unique
		showObj(bcount, 'inline');
		if (is_unique=='yes') {
			hideObj(bcount);
			showObj('unique','inline');
		}
		
		showObj(check, 'block');
		check.position='absolute';
		img.className = 'hightlight';
		
		moveBefore(check, img);
		check.style.marginLeft =(15)+'px';
		check.style.marginTop  =(15)+'px';
	}
}

function selectScience_li(item_id,li_id,item_price) {
	var field = document.getElementById('tech_id'),
		bcount = document.getElementById('min'),
		li = document.getElementById(li_id);
		
	var engineer_tech_list 		= getReference('engineer_tech_list') ? getReference('engineer_tech_list').getElementsByTagName('li') : null;
	var electronics_tech_list 	= getReference('electronics_tech_list') ? getReference('electronics_tech_list').getElementsByTagName('li') : null;
	var physics_tech_list 		= getReference('physics_tech_list') ? getReference('physics_tech_list').getElementsByTagName('li') : null;
	var complex_tech_list 		= getReference('complex_tech_list') ? getReference('complex_tech_list').getElementsByTagName('li') : null;
	var base_tech_list 			= getReference('base_tech_list') ? getReference('base_tech_list').getElementsByTagName('li') : null;
	
	if (list = engineer_tech_list)
		for(i in list) list[i].className = '';
	if (list = electronics_tech_list)
		for(i in list) list[i].className = '';
	if (list = physics_tech_list)
		for(i in list) list[i].className = '';
	if (list = complex_tech_list)
		for(i in list) list[i].className = '';
	if (list = base_tech_list)
		for(i in list) list[i].className = '';
	
	showObj('start_research_form');
	hideObj('message');
	field.value=item_id;
	bcount.value=item_price;
	li.className = 'hightlight';
}


// Cargo
function showCargoForm(fleet_id, show_close) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=cargo_form_map&fleet_id='+fleet_id+(show_close ? '&show_close=1' : ''), 'hideObj($(\'fleets_links_panel\'));');
}

function dragResource(event, text, from_where, what, planet_id, fleet_id, ship_panel, planet_panel, show_close) {
	var drag = new DragDrop(event, text);
	
	if (!event) event = window.event;
	
	function transferResource(event) {
		var pageOffset = getScrollXY();
		
		if (!event) event = window.event;
		
		switch(from_where) {
			case 'ship':
				if ((pageOffset[0] + event.clientX) > (findPosX(planet_panel)) &&
					(pageOffset[0] + event.clientX) < (findPosX(planet_panel) + planet_panel.offsetWidth) &&
					(pageOffset[1] + event.clientY) > findPosY(planet_panel) &&
					(pageOffset[1] + event.clientY) < (findPosY(planet_panel) + planet_panel.offsetHeight)) {
					
					//alert('droped in planet');
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=resource_transfer_form&transfer_to=planet&resource='+what+'&planet_id='+planet_id+'&fleet_id='+fleet_id+(show_close ? '&show_close=1' : ''));
				}
			break;
			
			case 'planet':
				if ((pageOffset[0] + event.clientX) > (findPosX(ship_panel)) &&
					(pageOffset[0] + event.clientX) < (findPosX(ship_panel) + ship_panel.offsetWidth) &&
					(pageOffset[1] + event.clientY) > findPosY(ship_panel) &&
					(pageOffset[1] + event.clientY) < (findPosY(ship_panel) + ship_panel.offsetHeight)) {
					
					//alert('droped in ship');
					AjaxRequests.loadGetRequestAndExecute('_sender.php?show=resource_transfer_form&transfer_to=ship&resource='+what+'&planet_id='+planet_id+'&fleet_id='+fleet_id+(show_close ? '&show_close=1' : ''));
				}
			break;
			
		}
		
		return false;
	}
	
	drag.onUp = function (event) {
		transferResource(event);
	}
}

function closeRenameWindow(rename){
    if($('new_name').value != '' && $('new_name').value.length >= 3 && $('rename_msg').className == 'message')
        location.href = urlCleanup(location.href, Array(rename))+rename+'='+$('new_name').value;
}

function showDismissForm(element, what, planet_id) {
    var dismiss_frm = $('short_dismiss_frm');
    AjaxRequests.loadGetRequestAndExecute('_sender.php?show=dismiss_frm&what='+what+'&pos='+(findPosX(element)-175)+'&planet_id='+planet_id, 'showObj(\'short_dismiss_frm\');');
}
var collectedSkills = 0;
function newAvatarSkillsLimit(checkbox){
    var checkboxId = $(checkbox);
    if(checkboxId.checked) {
        collectedSkills = collectedSkills - 1;
        checkboxId.checked = false;
    } else {
        if(collectedSkills < 5) {
            collectedSkills = collectedSkills + 1;
            checkboxId.checked = true;
        }
    }
}

function fixValue(obj_id, min_value, max_value) {
	var obj = $(obj_id);
	
	if (obj && obj.value) {
		if (min_value && obj.value < min_value) obj.value=min_value;
		if (max_value && obj.value > max_value) obj.value=max_value;
	}
}

function submitVassal(obj, min_value, max_value) {
	if (obj && obj.form) {
		if (vassalTimeOut) clearTimeout(vassalTimeOut);
		if (min_value && max_value)
			vassalTimeOut = setTimeout('fixValue(\''+obj.id+'\', '+min_value+', '+max_value+');$(\''+obj.form.id+'\').submit();', 1500);
		else
			vassalTimeOut = setTimeout('$(\''+obj.form.id+'\').submit();', 1500);
	}
	
	return false;
}

function changeTerminalStatus(planetId){
    if($('check_'+planetId).checked) {
        AjaxRequests.loadGetRequestAndExecute('_sender.php?show=changeTerminalStatus&activate=on&planet_id='+planetId);
    } else {
        AjaxRequests.loadGetRequestAndExecute('_sender.php?show=changeTerminalStatus&activate=off&planet_id='+planetId);
    }
}

function openCloseFleet(main_container_id, div_id, obj, fleet_id, position_type, position_name, type, position_icon, star_name, quadrant, offset_x, offset_y, posX, posY, star_position, planet_position) {
	var fleet_info = $(div_id);
	
	if (fleet_info && obj) {
		// Взимаме всички флитове и ги затваряме
		var list = getTagsByName(main_container_id, 'div');
		
		for(var i=0; i<list.length; i++) {
			var image = list[i].getElementsByTagName('h2')[0].getElementsByTagName('a')[0];
			var info = list[i].getElementsByTagName('div')[0];
			
			if (image != obj) {
				image.className = 'ic_fleet_closed hand';
				info.className = 'hide';
				var ships_numbers = list[i].getElementsByTagName('p')[0].getElementsByTagName('span');
				ships_numbers[0].className='hide';
				ships_numbers[1].className='show';
			}
		}
		
		if (fleet_info.className=='hide') {
			fleet_info.className='show';
			obj.className='ic_fleet_open hand';
			var ships_numbers = obj.parentNode.getElementsByTagName('p')[0].getElementsByTagName('span');
			ships_numbers[0].className='show';
			ships_numbers[1].className='hide';
			loading('right_fleet_list');
			AjaxRequests.loadGetRequestAndExecute('_sender.php?show=fleets_near&fleet_id='+fleet_id+'&window=right');
		} else {
			fleet_info.className='hide';
			obj.className='ic_fleet_closed hand';
			var ships_numbers = obj.parentNode.getElementsByTagName('p')[0].getElementsByTagName('span');
			ships_numbers[0].className='hide';
			ships_numbers[1].className='show';
		}
		
		var fleet_info = $('fleet_info'),
			fleet_position = $('fleet_position'),
			position_image = fleet_position.getElementsByTagName('img')[0],
			name_link_ = fleet_position.getElementsByTagName('a')[0],
			desc = fleet_position.getElementsByTagName('div')[0],
			name_link = desc.getElementsByTagName('a')[0],
			quadrant_link = desc.getElementsByTagName('a')[1],
			quadrant_name = desc.getElementsByTagName('strong')[0],
			small_map = fleet_position.getElementsByTagName('img')[2],
            auto_path_fleet_id = $('auto_path_fleet_id'),
            message_path = $('message_path');
		
        auto_path_fleet_id.value = fleet_id;
        message_path.innerHTML = '';
        
		fleet_info.className = 'right show';
		
		position_image.src = 'draw.php?path=interface/'+position_type+'s/'+position_icon+'&do=resize&w=x&h=95';
		name_link.innerHTML = position_name;
		name_link.className = 'tx_' + type;
		name_link_.className = 'tx_' + type;
		name_link.href = '?'+position_type+'='+position_name;
		name_link_.href = '?'+position_type+'='+position_name;
        
        if (planet_position > 0 || star_position > 0) {
            $('newfleet_planet_id').value = planet_position;
            $('newfleet_system_id').value = star_position;
            $('split_to_new_fleet').className='create_new_fleet';
        } else {
            $('split_to_new_fleet').className='hide';
        }
		
		quadrant_link.href='?galaxy=x3&quadrant='+quadrant+'&offset_x='+offset_x+'&offset_y='+offset_y+'&star='+star_name;
		quadrant_name.innerHTML=quadrant;
		
		//small_map.src='map.php?zoom=2&map_x='+posX+'&map_y='+posY+'&map_width=7.4&map_height=7&image_width=185&image_height=170&star='+star_name+'&offset_x='+offset_x+'&offset_y='+offset_y+'&da_mu_go_na4ukam_na_explorera=.png';
		
		return true;
	}
	
	return false;
}

function openCloseFleetShips(table_id, obj) {
	var ships_info = $(table_id);
	
	if (ships_info && obj) {
		// Взимаме всички флитове и ги затваряме
		if (ships_info.className=='fleet_ships_list hide') {
			ships_info.className='fleet_ships_list show';
			obj.className='bt_fleet_ships_open';
		} else {
			ships_info.className='fleet_ships_list hide';
			obj.className='bt_fleet_ships';
		}
		
		return true;
	}
	
	return false;
}

function addFleet(fleet_id, list_id, title, planet_id, system_id, interface_ships) {
	var list = $(list_id);
	
	interface_ships = decodeURIComponent(interface_ships);
	if (document.all) {
		var newNode = document.createElement('<div name="right_fleet_info[]" />');
		var strong = document.createElement('<strong>');
		var p = document.createElement('<p>');
		var a = document.createElement('<a>');
		var h2 = document.createElement('<h2>');
		var clear = document.createElement('<div />');
	} else {
		var newNode = document.createElement('div');
		newNode.setAttribute('name', 'right_fleet_info[]');
		var strong = document.createElement('strong');
		var p = document.createElement('p');
		var a = document.createElement('a');
		var h2 = document.createElement('h2');
		var clear = document.createElement('div');
	}
	
	newNode.className = 'fleet_info highlight';
	newNode.setAttribute('lang', fleet_id);
	newNode.setAttribute('id', 'right_fleet_'+fleet_id);
	
	clear.setAttribute('class', 'clear');

	strong.innerHTML = interface_ships+': 0';
	
	a.onclick = function (){$('search_text_left').value=title;$('fleet_list_form_left').submit();};
	a.innerHTML = ''+title;
	p.appendChild(a);
	p.appendChild(strong);
	h2.appendChild(p);
	newNode.appendChild(h2);
	newNode.appendChild(clear);
	
	list.insertBefore(newNode, list.childNodes[0]);
}

function refreshFleet(fleet_id, win, info) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=fleet_list_info&fleet_id='+fleet_id+'&window='+win+'&info='+info);
}

function SetFilterClass(obj,new_class) {
    if (obj) {
        var list = obj.parentNode.getElementsByTagName('a');
        
        for(var i in list) 
            list[i].className='';
        
        obj.className= new_class;
    }
}

function changeStatus(obj_id){
    if($(obj_id).className.indexOf('option_tab_checked') > -1) {
		pos = $(obj_id).className.indexOf(' ');
        $(obj_id).className = "option_tab_unchecked" + (pos > -1 ? $(obj_id).className.substring(pos, $(obj_id).className.length) : '');
	} else {
        $(obj_id).className = "option_tab_checked";
	}
}

function captureMouse(div, event) {
    if(!event) event = window.event;
    
    if(document.addEventListener) {
		document.addEventListener("mousedown",clearMouse,false);
	} else if(document.attachEvent){
		document.attachEvent("onmousedown",clearMouse);
	}
    
    function clearMouse(event){
		var pageOffset = getScrollXY(),
			obj = $(div);
		
		if ((pageOffset[0] + event.clientX) > (findPosX(obj)) &&
				(pageOffset[0] + event.clientX) < (findPosX(obj) + obj.offsetWidth) &&
				(pageOffset[1] + event.clientY) > findPosY(obj) &&
				(pageOffset[1] + event.clientY) < (findPosY(obj) + obj.offsetHeight)) {
		} else {
			hideObj(obj);
			if(document.removeEventListener){
				document.removeEventListener("mousedown",clearMouse,false);
			}else if(document.detachEvent){
				document.detachEvent("onmousedown", clearMouse);
			}
		}
    }
}

// RADAR
function selectRadarFilter(filter, obj, value) {
	if (filter)
		switch (filter) {
			case 'name':
                hideObj('radar_suggestions');
                
                var list = obj.parentNode.getElementsByTagName('img');
                
                for(var i=0;i<list.length;i++)
                    list[i].src = list[i].src.replace('_on','');
                
                obj.getElementsByTagName('img')[0].src = obj.getElementsByTagName('img')[0].src.replace('.gif', '_on.gif').replace('.png', '_on.png');
				
                $('radar_search_what').value = 'name';
                $('radar_search_text').value = '';
				$('radar_search_text').focus();
			break;
			
			case 'planet':
                var list = obj.parentNode.getElementsByTagName('img');
                
                for(var i=0;i<list.length;i++)
                    list[i].src = list[i].src.replace('_on','');
                
                obj.getElementsByTagName('img')[0].src = obj.getElementsByTagName('img')[0].src.replace('.gif', '_on.gif').replace('.png', '_on.png');
                
				$('radar_search_what').value = 'planet';
				$('radar_search_text').value = '';
				AjaxRequests.loadGetRequestAndExecute('_sender.php?show=radar_filter&what=planet&field=radar_search_text');
			break;
			
			case 'system':
                var list = obj.parentNode.getElementsByTagName('img');
                
                for(var i=0;i<list.length;i++)
                    list[i].src = list[i].src.replace('_on','');
                
                obj.getElementsByTagName('img')[0].src = obj.getElementsByTagName('img')[0].src.replace('.gif', '_on.gif').replace('.png', '_on.png');
                
				$('radar_search_what').value = 'system';
				$('radar_search_text').value = '';
				AjaxRequests.loadGetRequestAndExecute('_sender.php?show=radar_filter&what=system&field=radar_search_text');
			break;
            
            case 'avatar_name':
                var list = obj.parentNode.getElementsByTagName('img');
                
                for(var i=0;i<list.length;i++)
                    list[i].src = list[i].src.replace('_on','');
                
                obj.getElementsByTagName('img')[0].src = obj.getElementsByTagName('img')[0].src.replace('.gif', '_on.gif').replace('.png', '_on.png');
                
                $('radar_search_what').value = 'avatar';
				$('radar_search_text').value = '';
				$('radar_search_text').focus();
            break;
            
            case 'target_name':
                var list = obj.parentNode.getElementsByTagName('img');
                
                for(var i=0;i<list.length;i++)
                    list[i].src = list[i].src.replace('_on','');
                
                obj.getElementsByTagName('img')[0].src = obj.getElementsByTagName('img')[0].src.replace('.gif', '_on.gif').replace('.png', '_on.png');
                
                $('radar_search_what').value = 'target_name';
				$('radar_search_text').value = '';
				$('radar_search_text').focus();
            break;
            
            case 'mine':
                $('radar_mine').value = $('radar_mine').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
                break;
            
            case 'ally':
                $('radar_ally').value = $('radar_ally').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
            break;
            
            case 'enemy':
                $('radar_enemy').value = $('radar_enemy').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
            break;
            
            case 'moving':
                $('radar_moving').value = $('radar_moving').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
            break;
            
            case 'stoped':
                $('radar_stop').value = $('radar_stop').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
            break;
            
            case 'target_mine':
                $('radar_target_mine').value = $('radar_target_mine').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
            break;
            
            case 'target_alliy':
                $('radar_target_alliance').value = $('radar_target_alliance').value == 'on' ? 'off' : 'on';
                $('radar_filter_form').submit();
            break;
            
            case 'filter_alliance':
                $('radar_filter_alliance').value = value;
                $('radar_filter_form').submit();
            break;
		}
}
function submitRadarSearch() {
	hideObj('radar_suggestions');
	
	AjaxRequests.loadPostRequestAndExecute($('radar_filter_form'));
}
var lastOpenedRadar = 0;
function openRadarMessage(fleet_id) {
    if($('wraper_msg_'+fleet_id).className == 'wraper') {
        $('wraper_msg_'+fleet_id).className = 'opened';
        $('target_'+fleet_id).className = 'ic_close';
    } else {
        $('wraper_msg_'+fleet_id).className = 'wraper';
        $('target_'+fleet_id).className = 'ic_open';
    }
    
    if(lastOpenedRadar && lastOpenedRadar != fleet_id && $('wraper_msg_'+lastOpenedRadar)) $('wraper_msg_'+lastOpenedRadar).className = 'wraper';
    
    lastOpenedRadar = fleet_id;
}

// NEWS
function selectNewsFilter(filter, obj, dont_change_list) {
	if (filter)
		if (dont_change_list === true) ;
		else {
			list = obj.parentNode.getElementsByTagName('a');
			for(i in list) {
				if (list[i].className && list[i].className.indexOf('_on') > -1)
					list[i].className=list[i].className.substring(0, list[i].className.indexOf('_on'));
			}
			obj.className=obj.className + '_on';
		}
		
		switch (filter) {
			case 'news':
				$('news_search_what').value = 'news';
				$('news_search_text').value = '';
				$('news_search_text').focus();
			break;
			
			case 'planet':
				$('news_search_what').value = 'planet';
				$('news_search_text').value = '';
				AjaxRequests.loadGetRequestAndExecute('_sender.php?show=planet_filter&field=news_search_text');
			break;
			
			case 'system':
				$('news_search_what').value = 'system';
				$('news_search_text').value = '';
				AjaxRequests.loadGetRequestAndExecute('_sender.php?show=system_filter&field=news_search_text');
			break;
			
			case 'unreaded':
				if ($('news_unreaded').value == 'yes') $('news_unreaded').value = 'no';
				else $('news_unreaded').value = 'yes';
				submitNewsSearch();
			break;
			
		}
}
function submitNewsSearch() {
	hideObj('news_suggestions');
	
	AjaxRequests.loadPostRequestAndExecute($('news_filter_form'));
}
function showNewsCategories(sel_group) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=news_groups&group='+$('news_group').value+'&search_what='+$('news_search_what').value+'&search_text='+$('news_search_text').value+'&unreaded='+$('news_unreaded').value);
}
function changeNewsClass(news_id, cssClass) {
	var parent = $(news_id).parentNode.parentNode;
	
	pos=parent.className.indexOf(' ');
	if (pos > -1) {
		parent.className = cssClass + parent.className.substring(pos, parent.className.length);
	} else parent.className = cssClass;
	
	var list = parent.parentNode.getElementsByTagName('li');
	for(var i=0;i<list.length;i++) {
		var wraper = list[i].getElementsByTagName('span')[1];
		var image = list[i].getElementsByTagName('span')[3].getElementsByTagName('a')[0];
		
		if (wraper != $(news_id).parentNode) {
			image.className='ic_open';
			wraper.style.height="13px";
		}
	}
	
	var image = $(news_id).parentNode.parentNode.getElementsByTagName('span')[3].getElementsByTagName('a')[0];
	if ($(news_id).parentNode.style.height=='auto') {
		$(news_id).parentNode.style.height="13px";
		image.className='ic_open';
	} else {
		$(news_id).parentNode.style.height="auto";
		image.className='ic_close';
	}
}
function openNewsMessage(msg_id, btn) {
	if (btn.parentNode.parentNode.className.indexOf('unreaded') > -1)
		AjaxRequests.loadGetRequestAndExecute('_sender.php?show=news_set_readed&news_id='+msg_id, 'changeNewsClass(\''+btn.name+'\',\'readed\')');
	else
		changeNewsClass(btn.name,'readed');
}
function checkUncheckNews(obj) {
	if (obj) {
		var input = obj.parentNode.getElementsByTagName('input')[0];
		if (input.name == 'unchecked[]') {
			input.name = 'checked[]';
			obj.className='checkbox_checked';
		} else {
			input.name = 'unchecked[]';
			obj.className='checkbox_unchecked';
		}
		
		return true;
	}
	return false;
}
function checkNews(obj) {
	if (obj) {
		var input = obj.parentNode.getElementsByTagName('input')[0];
		input.name = 'checked[]';
		obj.className='checkbox_checked';
		
		return true;
	}
	return false;
}
function uncheckNews(obj) {
	if (obj) {
		var input = obj.parentNode.getElementsByTagName('input')[0];
		input.name = 'unchecked[]';
		obj.className='checkbox_unchecked';
		
		return true;
	}
	return false;
}
function selectNews(form_id, what) {
	var form = $(form_id),
		list = document.getElementsByName('check_image[]');
	
	switch(what) {
		case 'all':
			for(var i=0;i<list.length;i++)
				checkNews(list[i]);
		break;
		
		case 'none':
			for(var i=0;i<list.length;i++)
				uncheckNews(list[i]);
		break;
		
		case 'readed':
			for(var i=0;i<list.length;i++) {
				if (list[i].parentNode.parentNode.className.indexOf('unreaded')>-1) uncheckNews(list[i]);
				else checkNews(list[i]);
			}
		break;
		
		case 'unreaded':
			for(var i=0;i<list.length;i++) {
				if (list[i].parentNode.parentNode.className.indexOf('unreaded')>-1) checkNews(list[i]);
				else uncheckNews(list[i]);
			}
		break;
	}
}
function refreshNews(planet_id, system_id) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=news_refresh&planet_id='+planet_id+'&system_id='+system_id);
}
function refreshHomeNews(planet_id, system_id) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=news_home_refresh');
}

function getStyle( element, cssRule ) {
  if( document.defaultView && document.defaultView.getComputedStyle ) {
    var value = document.defaultView.getComputedStyle( element, '' ).getPropertyValue( cssRule.replace( /[A-Z]/g,
		function( match, char ){ 
			return "-" + char.toLowerCase(); 
		}
	  ) 
    );
  }
  else if ( element.currentStyle ) var value = element.currentStyle[ cssRule ];
  else                             var value = false;
	return value;
}

function findPosXDR(obj){
	var curleft = 0;
	
	if(obj.offsetParent)
		while(obj) {
            if (getStyle(obj, 'position') == 'relative') {
				//alert(obj.className+' ; '+obj.tagName);
                return curleft;
            }
			
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	
	return curleft;
}

//намира Y позицията на обекта
function findPosYDR(obj){
	var curtop = 0;
	
	if(obj.offsetParent)
		while(obj) {
			//alert(obj.className+' ; '+obj.tagName+' ; '+curtop);
			if (getStyle(obj, 'position') == 'relative') {
                return curtop;
            }
			
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
		
	return curtop;
}

function showDropDown(obj_id, btn_id) {
	var pageOffset = getScrollXY(),
		obj= $(obj_id),
		btn= $(btn_id);
	
	obj.style.left = findPosXDR(btn)+'px';
	obj.style.top = findPosYDR(btn)+btn.offsetHeight+'px';
	
	showObj(obj_id);
	captureMouse(obj_id);
}
function selectFromDropDown(btn, link_id, inp_id, value) {
	var link = $(link_id),
		inp = $(inp_id);
	
	if (btn && link) {
		link.innerHTML = btn.innerHTML;
		if (inp && value) inp.value=value;
		
		var list = btn.parentNode.parentNode.getElementsByTagName('li');
		for(var i=0; i<list.length; i++)
			list[i].className = '';
		btn.parentNode.className='sel';
	}
}
function checkFleetPathOptions(btn, type, fleet_id) {
	if (btn) {
		var cssClass = (btn.className=='checkbox_unchecked_v2' ? 'checkbox_checked_v2' : 'checkbox_unchecked_v2');
		
		AjaxRequests.loadGetRequestAndExecute('_sender.php?show=change_fleet_status&status='+type+'&fleet_id='+fleet_id, '$(\''+btn.id+'\').className=\''+cssClass+'\'');
	}
}

/* FORUM FUNCTIONS */
function clearWhiteSpace( txt ) {
  var data = txt;
  // Use ECMA-262 Edition 3 String and RegExp features
  data = data.replace(/[\t ]+/g, " ");
  if (data.charAt(0) == " ")
    data = data.substring(1, data.length);
  if (data.charAt(data.length - 1) == " ")
    data = data.substring(0, data.length - 1);
  return data;
}
function quotePost(post_id, avatar_name, title) {
	var cont = $(post_id);
	
	if (cont) {
		var str = "<blockquote>\n";
		if (avatar_name != '') 
			str += '<strong>'+avatar_name+' wrote:</strong>';
		
		str += cont.innerHTML+"</blockquote>\n";
		$('content').value = str;
		$('title').value = title;
		showObj('new_post_form');
	}
}
function newPost(title){
	$('content').value = '';
	$('title').value = title;
	
	showObj('new_post_form');
}
function deleteTheme(theme_id, page) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=delete_theme&theme_id='+theme_id+'&page='+page);
}
function deletePost(post_id, page) {
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=delete_post&post_id='+post_id+'&page='+page);
}
function editPost(post_id) {
	var title = $('post_'+post_id+'_title'),
		content = $('post_'+post_id+'_content'),
		cancel = $('post_'+post_id+'_cancel'),
		save = $('post_'+post_id+'_save');
	
	if (title && content) {
		var list = document.getElementsByName('content');
		
		if (list.length > 0)
			for(var i=0; i<=list.length; i++) {
				if (list[i] && list[i].getAttribute('id') != '') {
					if (list[i].getAttribute('id').toString().split('_')[2] > 0)
						cancelEdit(list[i].getAttribute('id').toString().split('_')[2]);
				}
			}
		
		if ($('inp_post_'+post_id+'_title')) {
			
		} else {
			if (document.all) {
				var inp_title = document.createElement('<input name="title" />'),
					inp_content = document.createElement('<textarea name="content" />');
			} else {
				var inp_title = document.createElement('input'),
					inp_content = document.createElement('textarea');
				
				inp_title.setAttribute('name', 'title');
				inp_content.setAttribute('name', 'content');
			}
			
			inp_title.setAttribute('value', title.innerHTML);
			inp_content.appendChild(document.createTextNode(clearWhiteSpace(br2nl(content.innerHTML))));
			
			inp_title.setAttribute('id', 'inp_post_'+post_id+'_title');
			inp_content.setAttribute('id', 'inp_post_'+post_id+'_content');
			
			title.old = title.innerHTML;
			content.old = content.innerHTML;
			
			inp_title.className = 'in_long_forum';
			inp_content.className = 'ta_long_forum';
			
			title.innerHTML='';
			content.innerHTML='';
			
			title.appendChild(inp_title);
			content.appendChild(inp_content);
		}
		
		showObj(cancel, 'inline');
		showObj(save, 'inline');
		
		$('post_id').value = post_id;
	}
}
function cancelEdit(post_id) {
	var title = $('post_'+post_id+'_title'),
		content = $('post_'+post_id+'_content'),
		cancel = $('post_'+post_id+'_cancel'),
		save = $('post_'+post_id+'_save');
	
	if (title && content) {
		title.innerHTML = title.old;
		content.innerHTML = content.old;
		hideObj(cancel);
		hideObj(save);
		
		$('post_id').value = 0;
	}
}
function changePost(post_id) {
	var title = $('post_'+post_id+'_title'),
		content = $('post_'+post_id+'_content'),
		cancel = $('post_'+post_id+'_cancel'),
		save = $('post_'+post_id+'_save');
	
	if (title && content) {
		title.innerHTML = $('inp_post_'+post_id+'_title').value;
		content.innerHTML = nl2br($('inp_post_'+post_id+'_content').value);
		hideObj(cancel);
		hideObj(save);
		
		$('post_id').value = 0;
	}
}

// MAP FUNCTIONS
function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

function controlListsRefresh(planetId) {
    AjaxRequests.loadGetRequestAndExecute('_sender.php?show=planet_fleets_list&planet_id='+planetId, 'changeCssClass(\'control_lists_loading\',\'refresh hide\');');
}
function setBlink(obj_id, interval, by, rgb, change_value) {
    if (obj_id && $(obj_id)) {
        if (interval > 0 || (rgb.r+rgb.g+rgb.b) == 0) {
            interval -= by;
            $(obj_id).style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';
            setTimeout('setBlink(\''+obj_id+'\','+interval+','+by+', {r:'+(rgb.r-change_value)+',g:'+(rgb.g-change_value)+',b:'+(rgb.b-change_value)+'},'+change_value+');', by);
        } else {
            $(obj_id).style.backgroundColor = '';
            if ($(obj_id).className) $(obj_id).className = $(obj_id).className;
        }
    } 
}

function selectElement(element, cssClass, cont) {
	if (element) {
		var list = element.parentNode.getElementsByTagName(element.tagName);
        
		for(var i=0; i<list.length; i++) {
			list[i].className = list[i].className.replace(cssClass, '').replace(' ', '');
		}
		
		element.className = cssClass;
        
        if (cont) cont.innerHTML = element.innerHTML;
	}
}
function GateEmptyList() {
    var list = getTagsByName("delete_from_gate[]", 'a');
    
    if (list)
        for(var i=1; i<list.length; i++) {
            if (list[i].onclick) list[i].onclick();
        }
}
function resetService(obj,name) {
    var list = document.getElementsByName('services[]');
    
    for(var i=0; i<list.length; i++) {
        if (list[i].id.indexOf(name) >= 0) {
            arr = list[i].id.split('-');
            
            $(arr[0]+'-'+arr[1]+'-inp').value=0;
            $(arr[0]+'-'+arr[1]+'-price').value=0;
            
            var index = $(arr[0]+'-'+arr[1]+'-inp').parentNode.getElementsByTagName('a')[0].id;
            var sel_obj = list[i].parentNode.getElementsByTagName('li')[0];
            
            selectElement(sel_obj, 'sel', $(index));
        }
    }
}
function recalculateTotal(total, inp_name) {
    var list = document.getElementsByName(inp_name),
        total_price=0;
    
    for (var i=0; i<list.length; i++) {
        total_price += parseInt(list[i].value);
    }
    
    total.innerHTML=total_price;
}
function RecalcGatePrice() {
    var count_list = document.getElementsByName('transfer[count][]'),
        prices = document.getElementsByName('transfer[price][]'),
        total=0,
        modifier = $('planet_have_gate').value,
        max_cargo = $('total_cargo_space').innerHTML;
    
    for(var i=0; i<count_list.length; i++) {
        total += (parseInt(count_list[i].value) * prices[i].value);
    }
    
    if (modifier > 1) {
        if (document.all)
            $('price_modifier').style.display = 'block';
        else
            $('price_modifier').style.display = 'table-row';
        total_ = $('total_price_modifed').innerHTML = Math.round(total) * modifier;
        $('total_price_discount').innerHTML = (parseInt(total_) > parseInt(max_cargo) ? '<strong class="cargo_over">'+total_+'</strong>' : total_) +'/'+ max_cargo;
    } else {
        $('price_modifier').style.display='none';
        $('total_price_discount').innerHTML = (parseInt(total) > parseInt(max_cargo) ? '<strong class="cargo_over">'+Math.round(total)+'</strong>' : total) +'/'+ Math.round(max_cargo);
    }
}
function RefreshItemList() {
    $('transfer_form').action='_sender.php?show=gate_list&planet_id='+$('planet_id').value+'&group='+$('selected_list').value;
    $('transfer_form').submit();
}
function GateDeleteRow(obj, planet_id) {
    var row = obj.parentNode.parentNode,
        name = row.getElementsByTagName('td')[1].getElementsByTagName('strong')[0].innerHTML,
        type = row.getElementsByTagName('input')[0].value,
        id = row.getElementsByTagName('input')[1].value,
        price = row.getElementsByTagName('input')[2].value,
        count = parseInt(row.getElementsByTagName('td')[2].getElementsByTagName('strong')[0].innerHTML),
        count_ = $('transfer_'+type+'_'+id) ? $('transfer_'+type+'_'+id).getElementsByTagName('td')[1] : null;
    
    if (count_) {
        // Оправяме бройките
        count_.innerHTML = parseInt(count_.innerHTML)+parseInt(count);
        count_.parentNode.onmousedown= function (event) {
            dragFromGate(event, name, 'transfer_list', planet_id, id, count_.innerHTML, price, type, this);
            return false;
        }
        setBlink('transfer_'+type+'_'+id, 2000, 100, {r:0, g:71, b:87}, 5);
    }
    
    row.parentNode.removeChild(row);
    RecalcGatePrice();
}
function GetPlanetList(obj, planet_id) {
    if (obj.timeOut) clearTimeout(obj.timeOut);
    
    if (obj.value.toString().length >= 3) {
        loading('planets_list');
        obj.timeOut = setTimeout('AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=gate_planet_list&planet_id='+planet_id+'&search_text='+obj.value+'\')', 1500);
    }
}
function GateSelectTab(obj, parent, cssShow, cssHide) {
    var list = parent.getElementsByTagName(obj.tagName);
    
    for(var i=0; i<list.length; i++)
        list[i].className = list[i].className.replace(cssShow, cssHide);
    
    obj.className = obj.className.replace(cssHide, cssShow);
    
    return false;
}
function CloneGateRow(id, name, type, count, price, planet_id) {
    var tr = $('gate_transfer_list').getElementsByTagName('tr')[0],
        new_tr = document._importNode(tr, true),
        count_ = $('transfer_'+type+'_'+id).getElementsByTagName('td')[1];
    
    if (count > 0) {
        if (parseInt(count) > parseInt(count_.innerHTML)) {
            // Ако опита да завлече повече от колкото има оправяме бройката
            count = parseInt(count_.innerHTML);
        }
        
        // Оправяме текущата бройка
        count_.innerHTML = parseInt(count_.innerHTML) - parseInt(count);
        
        count_.parentNode.onmousedown= function (event) {
            dragFromGate(event, decodeURIComponent(name), 'transfer_list', planet_id, id, count_.innerHTML, price, type, this);
            return false;
        }
        setBlink('transfer_'+type+'_'+id, 2000, 100, {r:0, g:71, b:87}, 5);
        
        if ($('gate_transfer_'+type+'_'+id)) {
            $('gate_transfer_'+type+'_'+id).getElementsByTagName('input')[3].value = parseInt($('gate_transfer_'+type+'_'+id).getElementsByTagName('input')[3].value)+parseInt(count);
            setBlink('gate_transfer_'+type+'_'+id, 2000, 100, {r:0, g:71, b:87}, 5);
            return false;
        }
        
        new_tr.getElementsByTagName('td')[1].getElementsByTagName('strong')[0].innerHTML = decodeURIComponent(name);
        new_tr.getElementsByTagName('input')[0].value = type;
        new_tr.getElementsByTagName('input')[1].value = id;
        new_tr.getElementsByTagName('input')[2].value = price;
        new_tr.getElementsByTagName('input')[3].value = count;
        new_tr.getElementsByTagName('td')[2].getElementsByTagName('strong')[0].innerHTML = count;
        new_tr.getElementsByTagName('td')[3].getElementsByTagName('span')[0].innerHTML = Math.round(parseFloat(price) * parseInt(count));
        new_tr.style.visibility = 'visible';
        new_tr.id='gate_transfer_'+type+'_'+id;
        
        tr.parentNode.insertBefore(new_tr, $('gate_transfer_last'));
        RecalcGatePrice();
    }
}

function dragFromGate(event, text, from_where, planet_id, item_id, max_count, price, item_type, element) {
    
    if (!event) event = window.event;
    
	var pageOffset = getScrollXY();

	var select_cursor = $("move_ship");
	
	select_cursor.style.top = (pageOffset[1] + event.clientY - 7)+"px";
	select_cursor.style.left = (pageOffset[0] + event.clientX - 7)+"px";
	select_cursor.style.cursor = 'pointer';
    select_cursor.style.zIndex = 253;
	
	select_cursor.innerHTML = text;
	select_cursor.className = 'show';
    
    // IE простотии за драгването
    element.onselectstart= function (){return false;};
    element.ondrag = function () {return false;}
    element.onmouseover = function () {return false;};
    element.onactivate= function () {return false;};
    
	if(document.addEventListener) {
		document.addEventListener("mousemove",moveHandler,true);
		document.addEventListener("mouseup",upHandler,true);
	} else if(document.attachEvent){
		document.attachEvent("onmousemove",moveHandler);
		document.attachEvent("onmouseup",upHandler);
	}
    
    function moveItem(event) {
        var left = element,
            right = $(from_where),
            pageOffset = getScrollXY();
        
        if ((pageOffset[0] + event.clientX) < (findPosX(right)) ||
            (pageOffset[0] + event.clientX) > (findPosX(right) + right.offsetWidth) ||
            (pageOffset[1] + event.clientY) < findPosY(right) ||
            (pageOffset[1] + event.clientY) > (findPosY(right) + right.offsetHeight)) {
            
            AjaxRequests.loadGetRequestAndExecute('_sender.php?show=gate_move_form&planet_id='+planet_id+'&item_id='+item_id+'&group='+item_type+'&max_count='+max_count);
        }
        
        return false;
    }

	// извършва самото преместване ма цвета от палитрата
	function moveHandler(event){
		if(!event) event = window.event;
			select_cursor.style.top = (pageOffset[1] + event.clientY + 2)+"px";
			select_cursor.style.left = (pageOffset[0] + event.clientX + 2)+"px";
	}
	
	// унищожава цвета от палитрата
	function upHandler(event){
		if(!event) event = window.event;
		
		if(document.removeEventListener){
			document.removeEventListener("mouseup",upHandler,true);
			document.removeEventListener("mousemove",moveHandler,true);
			select_cursor.className = "hide";
			moveItem(event);
		}else if(document.detachEvent){
			document.detachEvent("onmousemove",moveHandler);
			document.detachEvent("onmouseup",upHandler);
			select_cursor.className = "hide";
			moveItem(event);
		}
	}
    
}


function dragFromSimulator(event, item_id, item_type, element) {
    
    if (!event) event = window.event;
    
	var pageOffset = getScrollXY();

	var select_cursor = $("move_ship");
	
	select_cursor.style.top = (pageOffset[1] + event.clientY - 7)+"px";
	select_cursor.style.left = (pageOffset[0] + event.clientX - 7)+"px";
	select_cursor.style.cursor = 'pointer';
    select_cursor.style.zIndex = 253;
	
	select_cursor.innerHTML = element.getElementsByTagName('td')[1].getElementsByTagName('strong')[0].innerHTML;
	select_cursor.className = 'show';
    
    // IE простотии за драгването
    element.onselectstart= function (){return false;};
    element.ondrag = function () {return false;}
    element.onmouseover = function () {return false;};
    element.onactivate= function () {return false;};
    
	if(document.addEventListener) {
		document.addEventListener("mousemove",moveHandler,true);
		document.addEventListener("mouseup",upHandler,true);
	} else if(document.attachEvent){
		document.attachEvent("onmousemove",moveHandler);
		document.attachEvent("onmouseup",upHandler);
	}
    
    function moveItem(event) {
        var left = $('left_list'),
            right = $('right_list'),
            pageOffset = getScrollXY();
        
        if ((pageOffset[0] + event.clientX) > (findPosX(right)) &&
            (pageOffset[0] + event.clientX) < (findPosX(right) + right.offsetWidth)) {
            
            AjaxRequests.loadGetRequestAndExecute('_sender.php?show=simulator_move_form&item_id='+item_id+'&item_type='+item_type+'&add_in=enemy');
        }
        
        if ((pageOffset[0] + event.clientX) > (findPosX(left)) &&
            (pageOffset[0] + event.clientX) < (findPosX(left) + left.offsetWidth)) {
            
            AjaxRequests.loadGetRequestAndExecute('_sender.php?show=simulator_move_form&item_id='+item_id+'&item_type='+item_type+'&add_in=mine');
        }
        
        return false;
    }

	// извършва самото преместване ма цвета от палитрата
	function moveHandler(event){
		if(!event) event = window.event;
			select_cursor.style.top = (pageOffset[1] + event.clientY + 2)+"px";
			select_cursor.style.left = (pageOffset[0] + event.clientX + 2)+"px";
	}
	
	// унищожава цвета от палитрата
	function upHandler(event){
		if(!event) event = window.event;
		
		if(document.removeEventListener){
			document.removeEventListener("mouseup",upHandler,true);
			document.removeEventListener("mousemove",moveHandler,true);
			select_cursor.className = "hide";
			moveItem(event);
		}else if(document.detachEvent){
			document.detachEvent("onmousemove",moveHandler);
			document.detachEvent("onmouseup",upHandler);
			select_cursor.className = "hide";
			moveItem(event);
		}
	}
    
}
function refreshSimulatorList(what) {
    AjaxRequests.loadGetRequestAndExecute('_sender.php?show=simulator_list&what='+what);
}
var avatar_bonus_timeout;
function saveAvatarBonuses(what, obj, start_value, level_step, max_level) {
    if (avatar_bonus_timeout) clearTimeout(avatar_bonus_timeout);
    // Преизчисляваме скила
    var level = obj.value > max_level+1 ? max_level+1 : obj.value;
    if (level < obj.value) obj.value=level;
    obj.parentNode.parentNode.getElementsByTagName('td')[2].innerHTML = level > 0 ? (start_value + level_step * (level-1))+'%' : '0%';
    avatar_bonus_timeout = setTimeout('$(\'avatar_bonus_'+what+'\').submit()', 1000);
}
function resetAvatarBonuses(what, obj) {
    var list = obj.form.elements;
    
    for(var i=0; i<list.length; i++) {
        if (list[i].type=='text') {
            list[i].value=0;
            list[i].parentNode.parentNode.getElementsByTagName('td')[2].innerHTML = '0%';
        }
    }
    
    avatar_bonus_timeout = setTimeout('$(\'avatar_bonus_'+what+'\').submit()', 1000);
}
function FixIEShit(obj, el_type) {
    if (obj) {
        el_type = el_type.split(",");
        for (var i=0; i<el_type.length; i++) {
            var list = obj.getElementsByTagName(el_type[i]);
            
            for(var j=0; j<list.length; j++) {
                list[j].onselectstart= function (){return false;};
                list[j].ondrag = function () {return false;}
                list[j].onmouseover = function () {return false;};
                list[j].onactivate= function () {return false;};
            }
        }
    }
}
function ShowScreenshot(obj, screenshot) {
    if ($('popup_screenshot')) removeObj('popup_screenshot');
    
    var div = document.createElement('div'),
        img = document.createElement('img');
    
    img.src = 'screenshots/'+screenshot;
    img.alt = "";
    
    div.id = 'popup_screenshot';
    div.style.position = 'absolute';
    
    div.style.left = findPosXDR(obj);
    div.style.top = findPosYDR(obj);
    
    div.appendChild(img);
    
    obj.parentNode.appendChild(div);
    obj.onmouseout = function () {
        if ($('popup_screenshot')) removeObj('popup_screenshot');
    }
}
function SearchAvatar(text, obj_id, fill_in) {
    if (searchAvatarTimeout) clearTimeout(searchAvatarTimeout);
    
    if (text.length < 3) return false;
    
    searchAvatarTimeout = setTimeout('AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=search_avatar&text='+text+'&obj_id='+obj_id+'&fill_in='+fill_in+'\');', 1000);
    
    $(fill_in).style.left = findPosXDR($(obj_id));
    $(fill_in).style.top = findPosYDR($(obj_id));
}
function RefreshWarList(page_w, page_l) {
    AjaxRequests.loadGetRequestAndExecute('_sender.php?show=wars_list&page_w='+page_w+'&page_l='+page_l);
}
/* TOP MENU */
var top_menu_timeout=null,
    top_menu_selected=null;

function initTopMenu(event, obj, what) {
    var posx = findPosXDR(obj),
        posy = findPosYDR(obj)+24;
    
    //if (top_menu_selected == obj.id) return false;
    hideObj('top_menu_info');
    clearObj('top_menu_info');
    
    if (window.event) window.event.cancelBubble=true;
    else if (event.stopPropagation) event.stopPropagation();
    
    if (top_menu_timeout) clearTimeout(top_menu_timeout);
    
    top_menu_selected = obj.id;
    obj.onmouseout = function (event) {
        hideTopMenu(event);
    }
    
    switch (what) {
        default:
            var menu = $('top_menu_info');
            menu.style.top = posy+'px';
            menu.style.left = posx+'px';
            showObj(menu);
            clearObj(menu);
            top_menu_timeout = setTimeout('AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=top_menu&what='+what+'\', \'showTopMenu('+posx+','+posy+');\');', 600);
        break;
    }
}
function contains_ns6(a, b) {
    if (b)
        while (b.parentNode)
            if ((b = b.parentNode) == a) return true;
    
    return false;
}
function showTopMenu(posx, posy, small_menu) {
    var menu = $('top_menu_info');
    
    menu.style.top = posy+'px';
    menu.style.left = posx+'px';
    showObj(menu);
    
    menu.onmouseout = function (event) {
        hideTopMenu(event);
    }
}
function hideTopMenu(event){
    if (!event) event = window.event;
    
    if (top_menu_timeout) clearTimeout(top_menu_timeout);
    
    var menu = $('top_menu_info');
    
    if (document.all && !menu.contains(event.toElement) && !$(top_menu_selected).contains(event.toElement)) {
        top_menu_selected = null;
        hideObj(menu);
    } else if (!document.all &&
            event.currentTarget != event.relatedTarget &&
            !contains_ns6(menu, event.relatedTarget) &&
            !contains_ns6($(top_menu_selected), event.relatedTarget)) {
        top_menu_selected = null;
        hideObj(menu);
    }
}

function showMenuHint(hint) {
    if (!$('menu_info').old) $('menu_info').old=$('menu_info').innerHTML;
    
    $('menu_info').innerHTML = hint;
}
function showMenuHover(hint) {
    var menu = $('menu_hover_holder');
    showObj(menu);
    
    showMenuHint(hint);
    
    menu.onmouseout = function (event) {
        hideMenuHover(event);
    }
}
function hideMenuHover(event){
    if (!event) event = window.event;
    
    if (top_menu_timeout) clearTimeout(top_menu_timeout);
    
    var menu = $('menu_hover_holder');
    if (document.all && !menu.contains(event.toElement)) {
        top_menu_selected = null;
        hideObj(menu);
    } else if (!document.all &&
            event.currentTarget != event.relatedTarget &&
            !contains_ns6(menu, event.relatedTarget)) {
        top_menu_selected = null;
        hideObj(menu);
    }
    if ($('menu_info').old) $('menu_info').innerHTML = $('menu_info').old;
}

function clearClass(obj, cssClass, node_type) {
    if (!node_type) var node_type='div';
    
	var list=obj.getElementsByTagName(node_type);
	
	for(var i=0; i<list.length; i++)
		list[i].className = list[i].className.replace(cssClass, '').replace(' ','');
}
var search_avatar;
function searchAvatar(title, avatar_id) {
	if (search_avatar) clearTimeout(search_avatar);
	
	search_avatar = setTimeout('AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=search_avatar&text='+title+'&avatar_id='+avatar_id+'&obj_id=near_avatar&get_free_system=1\');', 600);
}
function GetFreeSystem(avatar_id) {
    if (search_avatar) clearTimeout(search_avatar);
	
	search_avatar = setTimeout('AjaxRequests.loadGetRequestAndExecute(\'_sender.php?show=get_free_system&avatar_id='+avatar_id+'\');', 600);
}
function ArtificialRecalcPrice() {
    var abun = abundance_json,
        size = sizes_json[$('size').value],
        types = types_json,
        min,max;
    
    $('price_metal').innerHTML = parseInt(size ? size.price_metal : 0);
    $('price_mineral').innerHTML = parseInt(size ? size.price_mineral : 0);
    $('price_radioactive').innerHTML = parseInt(size ? size.price_radioactive : 0);
    $('price_specialists').innerHTML = parseInt(size ? size.price_specialists : 0);
    $('price_scientists').innerHTML = parseInt(size ? size.price_scientists : 0);
    $('price_turns').innerHTML = parseInt(size ? size.price_turns : 0) + parseInt(eval('types.'+$('planet_type').value+'.price_turns'));
    min = parseInt(size ? size.abundance_modifier : 0);
    max = parseInt(size ? size.abundance_modifier : 0);
    
    $('planet_type_text').innerHTML = $('planet_type').value;
    $('size_text').innerHTML = size.name;
    $('atmosphere_type').innerHTML = eval('types.'+$('planet_type').value+'.atmosphere_type');
    
    if (abun) {
        var abun_type = Array('abundance_metal', 'abundance_mineral', 'abundance_radioactive', 'abundance_energy', 'abundance_food');
        for(var i in abun_type) {
            var max_switch = parseInt(eval('types.'+$('planet_type').value+'.'+abun_type[i].substring(10)+'_'))-1,
                max_switch_text = eval('types.'+$('planet_type').value+'.'+abun_type[i]),
                list = $(abun_type[i]+'_switch').getElementsByTagName('a'),
                material_type = abun_type[i].substring(10);
            
            for (var k=0; k<list.length; k++) {
                for(j in abun) {
                    if (parseInt(abun[j].numeric)-1 == k) var abundance_text=abun[j].name;
                }
                
                if (k <= max_switch) {
                    list[k].className='';
                    list[k].abun_type = abun_type[i];
                    list[k].abundance_text = abundance_text;
                    list[k].onclick = function () {clearClass(this.parentNode.parentNode, 'sel', 'td');this.parentNode.className='sel';$(this.abun_type).value=this.abundance_text;ArtificialRecalcPrice();};
                    //alert(list[k].onclick.toSource());
                } else {
                    if (list[k].parentNode.className == 'sel') {
                        list[max_switch].parentNode.className = 'sel';
                        $(abun_type[i]).value=max_switch_text;
                        list[k].parentNode.className = list[k].parentNode.className.replace('sel', '').replace(' ','');
                    }
                    list[k].className = 'dissabled';
                    list[k].onclick = null;
                }
            }
            switch (material_type) {
                case 'metal': $('price_metal').innerHTML = parseInt($('price_metal').innerHTML) + parseInt(eval('abun.'+$(abun_type[i]).value+'.price_material'));break;
                case 'mineral': $('price_mineral').innerHTML = parseInt($('price_mineral').innerHTML) + parseInt(eval('abun.'+$(abun_type[i]).value+'.price_material'));break;
                case 'radioactive': $('price_radioactive').innerHTML = parseInt($('price_radioactive').innerHTML) + parseInt(eval('abun.'+$(abun_type[i]).value+'.price_material'));break;
            }
            $('price_specialists').innerHTML = parseInt($('price_specialists').innerHTML) + parseInt(eval('abun.'+$(abun_type[i]).value+'.price_specialists'));
            $('price_scientists').innerHTML = parseInt($('price_scientists').innerHTML) + parseInt(eval('abun.'+$(abun_type[i]).value+'.price_scientists'));
            $('price_turns').innerHTML = parseInt($('price_turns').innerHTML) + parseInt(eval('abun.'+$(abun_type[i]).value+'.price_turns'));
            $(abun_type[i]+'_percent').innerHTML = parseInt(min) + parseInt(eval('abun.'+$(abun_type[i]).value+'.abundance_min'));
            $(abun_type[i]+'_percent').innerHTML = $(abun_type[i]+'_percent').innerHTML + '%-' + (parseInt(max) + parseInt(eval('abun.'+$(abun_type[i]).value+'.abundance_max')))+'%';
        }
        $('price_metal').innerHTML = number_format($('price_metal').innerHTML);
        $('price_mineral').innerHTML = number_format($('price_mineral').innerHTML);
        $('price_radioactive').innerHTML = number_format($('price_radioactive').innerHTML);
        $('price_specialists').innerHTML = number_format($('price_specialists').innerHTML);
        $('price_scientists').innerHTML = number_format($('price_scientists').innerHTML);
        $('price_turns').innerHTML = number_format($('price_turns').innerHTML);
    }
}
function switchCheckBox(check_id, onCss, offCss) {
    var btn = $(check_id);
    if (btn) {
        if (btn.className.indexOf(onCss)>-1) 
            btn.className = btn.className.replace(onCss, '').replace(' ','')+' '+offCss;
        else
            btn.className = btn.className.replace(offCss, '').replace(' ','')+' '+onCss;
    }
    
}
function showWindow(url, width, height, error_msg, error_div_id) {
    var w = window.open(url,'new_window','scrollbars=1,resizable=1,width='+width+',height='+height);
    
    if (!w) {
        // Popup blocker
        if ($(error_div_id)) {
            $(error_div_id).innerHTML = error_msg+' <a href="'+url+'">'+url+'</a>';
            showObj(error_div_id);
        }
    }
    return w;
}

var trainingTimeOut=null;
function GetPrice(who) {
    
    if (trainingTimeOut) clearTimeout(trainingTimeOut);
    
    if (who)
        switch (who) {
            case 'engineers':
                trainingTimeOut = setTimeout('insert_code(\'_receiver.php?show=training_price&who=engineers&amount=\'+getValue(\'engineers_amount\')+\'&planet_id=\'+getValue(\'engineer_planet_id\'),\'local_engineers_price\');',1000);
            break;
            
            case 'scientists':
                trainingTimeOut = setTimeout('insert_code(\'_receiver.php?show=training_price&who=scientists&amount=\'+getValue(\'scientists_amount\')+\'&planet_id=\'+getValue(\'scientist_planet_id\'),\'local_scientists_price\');', 1000);
            break;
            
            case 'astronauts':
                trainingTimeOut = setTimeout('insert_code(\'_receiver.php?show=training_price&who=astronauts&amount=\'+getValue(\'astronauts_amount\')+\'&planet_id=\'+getValue(\'astronaut_planet_id\'),\'local_astronauts_price\');',1000);
            break;
        }
}


function ubbc(tArea, open, end) {
    var isIE = (document.all)? true : false,
        open = (open)? open : "",
        end = (end)? end : "";
        
    if(isIE){
        tArea.focus();
        var curSelect = document.selection.createRange();
        if(arguments[2]){
            curSelect.text = open + arguments[2] + "]" + curSelect.text + end;
        } else {
            curSelect.text = open + curSelect.text + end;
        }
    } else if(!isIE && typeof tArea.selectionStart != "undefined"){
        var selStart = tArea.value.substr(0, tArea.selectionStart);
        var selEnd = tArea.value.substr(tArea.selectionEnd, tArea.value.length);
        var curSelection = tArea.value.replace(selStart, '').replace(selEnd, '');
        if(arguments[2]){
            tArea.value = selStart + open + arguments[2] + "]" + curSelection + end + selEnd;
        } else {
            tArea.value = selStart + open + curSelection + end + selEnd;
        }
    } else {
        tArea.value += (arguments[2])? open + arguments[2] + "]" + end : open + end;
    }
}
var checkMail=null;
function CheckMail(param) {
    if (checkMail) clearTimeout(checkMail);
    AjaxRequests.loadGetRequestAndExecute('/_sender.php?show=check_mail&'+param);
    checkMail = setTimeout("CheckMail('"+param+"');", 30000);
}

function MailAddMessages(new_row) {
    for (var j=0;j<new_row.length;j++) {
        var tr = document.createElement('tr');
        for (var i=0;i<3;i++) {
            var td = document.createElement('td');
            if (new_row[j][i]) td.innerHTML = new_row[j][i];
            tr.appendChild(td);
        }                             
        $('active_chat_end').parentNode.insertBefore(tr, $('active_chat_end'));
    }                                    
}
var keyMap = Array(),
    ctrlPressed = null;
keyMap[13] = submitMessage;
function addListener(a,b,c,d){if(a.addEventListener){a.addEventListener(b,c,d);return true;}else if(a.attachEvent){var e=a.attachEvent("on"+b,c);return e;}else{alert("Handler could not be attached");}}

function bind(a,b,c,d){return window.addListener(a,b,function(){d.apply(c,arguments)});}
function handleKeystroke(evt) {
    // Grab the cross browser event
    if( !evt ) evt = window.event;
    // Character code of key pressed
    var asc = !evt.keyCode ? (!evt.which ? evt.charCode : evt.which) : evt.keyCode;
    if (ctrlPressed) {
        for (var i in this) {
            if (asc == i) {
                this[i](evt);
                break;
            }
        }
    }
    if (asc==17) ctrlPressed=true;
}

function handleCtrl(evt) {
    // Grab the cross browser event
    if( !evt ) evt = window.event;
    // Character code of key pressed
    var asc = !evt.keyCode ? (!evt.which ? evt.charCode : evt.which) : evt.keyCode;
    if (asc==17) ctrlPressed=false;
}

function submitMessage(evt) {
    if (!$('send_message_form').submited) {
        $('send_message_form').submited = true;
        $('send_message_form').submit();
    }
}
refresh_mail_timeout = null;
to_user_id = 0;
function refreshMail() {
	if (refresh_mail_timeout) clearTimeout(refresh_mail_timeout);
	AjaxRequests.loadGetRequestAndExecute('_sender.php?show=unread_mail'+(to_user_id && to_user_id>0 ? '&refresh_friends='+to_user_id:''));
	refresh_mail_timeout = setTimeout('refreshMail()', 10000);
}