﻿
function TipMessage(object,balloon_id,arrow,align){
	if(typeof(getElementByCache("jquery","#"+object).css("height")) == 'undefined') return false;
	var arrow_top = parseInt(getElementByCache("jquery","#"+object).css("height").replace("px",""))+4;
	var balloon_top = arrow_top+15;
	if(align == 'left'){
		var balloon_left = getElementByCache("jquery","#"+balloon_id).css("width").replace("px","")-$("#"+object).css("width").replace("px","");
		var arrow_left = getElementByCache("jquery","#"+object).css("width").replace("px","")/2;
	}else{
		var balloon_left = getElementByCache("jquery","#"+object).css("width").replace("px","")/10;
		var arrow_left = 20;
	}
	if(align == 'out'){
		getElementByCache("jquery","#"+arrow).hide()
		getElementByCache("jquery","#"+balloon_id).hide();
	}else{
		getElementByCache("jquery","#"+arrow).show().css({"top":getElementByCache("jquery","#"+object).position().top+arrow_top,"left":getElementByCache("jquery","#"+object).position().left+arrow_left});
		getElementByCache("jquery","#"+balloon_id).show().css({"top":getElementByCache("jquery","#"+object).position().top+balloon_top,"left":getElementByCache("jquery","#"+object).position().left-balloon_left});
	}
}

var object_cache = new Array();
var object_cache_firstload = new Array();
function getElementByCache(mode,object_name,mode2){
	if(mode2 == 'new') object_cache_firstload[object_name+"-"+mode] = 0;
	if(object_cache_firstload[object_name+"-"+mode] != 1){
		object_cache_firstload[object_name+"-"+mode] = 1;
		if(mode == 'id'){
			object_cache[object_name+"-"+mode] = document.getElementById(object_name);
		} else if ( mode == 'name') {
			object_cache[object_name+"-"+mode] = document.getElementByName(object_name);
		} else if ( mode == 'name-0') {
			object_cache[object_name+"-"+mode] = document.getElementsByName(object_name)[0];
		} else if ( mode == 'jquery') {
			object_cache[object_name+"-"+mode] = $(object_name);
		}
	}
	return object_cache[object_name+"-"+mode];
}

var now_date = new Date();
var planet_count = 0;
var resource_time = '';
function ResourceUpdate(){
	var thisObj = this;

	thisObj.time  = Math.round((new Date().getTime() - now_date.getTime()) / 1000.);

	now_date = new Date();
	if(planet_control.metal_s > 0){
		if(planet_control.metal_max < planet_control.metal){
 			getElementByCache("id","MetalValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.metal))+'</font>';
		}else{
			planet_control.metal += (planet_control.metal_s*thisObj.time);
 			getElementByCache("id","MetalValue").innerHTML = comma(Math.round(planet_control.metal));
		}
	}else{
 		getElementByCache("id","MetalValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.metal))+'</font>';
	}
	if(planet_control.crystal_s > 0){
		if(planet_control.crystal_max < planet_control.crystal){
 			getElementByCache("id","CrystalValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.crystal))+'</font>';
		}else{
			planet_control.crystal += planet_control.crystal_s*thisObj.time;
 			getElementByCache("id","CrystalValue").innerHTML = comma(Math.round(planet_control.crystal));
		}
	}else{
 		getElementByCache("id","CrystalValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.crystal))+'</font>';
	}
	if(planet_control.deuterium_s > 0){
		if(planet_control.deuterium_max < planet_control.deuterium){
 			getElementByCache("id","DeuteriumValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.deuterium))+'</font>';
		}else{
			planet_control.deuterium += planet_control.deuterium_s*thisObj.time;
 			getElementByCache("id","DeuteriumValue").innerHTML = comma(Math.round(planet_control.deuterium));
		}
	}else{
 		getElementByCache("id","DeuteriumValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.deuterium))+'</font>';
	}
	if(planet_control.jentronium_s > 0){
		if(planet_control.jentronium_max < planet_control.jentronium){
 			getElementByCache("id","JentroniumValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.jentronium))+'</font>';
		}else{
			planet_control.jentronium += planet_control.jentronium_s*thisObj.time;
 			getElementByCache("id","JentroniumValue").innerHTML = comma(Math.round(planet_control.jentronium));
		}
	}else{
 		getElementByCache("id","JentroniumValue").innerHTML = '<font color=red>'+comma(Math.round(planet_control.jentronium))+'</font>';
	}

	purge(thisObj);
	delete thisObj;
}

function comma(num) {
	var num = num.toString();
	var len = num.length;
	var str = "";
	for(i=1; i<=len; i++) {
		var str = num.charAt(len-i)+str;
		if((i%3 == 0)&&(len-i != 0)) var str = ","+str;
	}
	delete num,len;
	return str;
}

function MaxResourceMarchand(type,type2) {
	if(type == 'metal'){
		if(type2 == 'crystal'){
			var remain_metal = planet_control.metal - (document.forms['marchand'].elements['deuterium'].value * 4);
			if(remain_metal > 1) remain_metal -= 1;
			document.forms['marchand'].elements['crystal'].value = Math.floor(remain_metal / 2);
		}
		if(type2 == 'deuterium'){
			var remain_metal = planet_control.metal - (document.forms['marchand'].elements['crystal'].value * 2);
			if(remain_metal > 1) remain_metal -= 1;
			document.forms['marchand'].elements['deuterium'].value = Math.floor(remain_metal / 4);
		}
		calcul('metal','crystal','deuterium');
	}
	if(type == 'crystal'){
		if(type2 == 'metal'){
			var remain_crystal = planet_control.crystal - (document.forms['marchand'].elements['deuterium'].value * 2);
			if(remain_crystal > 1) remain_crystal -= 1;
			document.forms['marchand'].elements['metal'].value = Math.floor(remain_crystal*2);
		}
		if(type2 == 'deuterium'){
			var remain_crystal = planet_control.crystal - (document.forms['marchand'].elements['metal'].value / 2);
			if(remain_crystal > 1) remain_crystal -= 1;
			document.forms['marchand'].elements['deuterium'].value = Math.floor(remain_crystal / 2);
		}
		calcul('crystal','metal','deuterium');
	}
	if(type == 'deuterium'){
		if(type2 == 'metal'){
			var remain_deuterium = planet_control.deuterium - (document.forms['marchand'].elements['crystal'].value / 2);
			if(remain_deuterium > 1) remain_deuterium -= 1;
			document.forms['marchand'].elements['metal'].value = Math.floor(remain_deuterium * 4);
		}
		if(type2 == 'crystal'){
			var remain_deuterium = planet_control.deuterium - (document.forms['marchand'].elements['metal'].value / 4);
			if(remain_deuterium > 1) remain_deuterium -= 1;
			document.forms['marchand'].elements['crystal'].value = Math.floor(remain_deuterium * 2);
		}
		calcul('deuterium','metal','crystal');
	}
}

function CompleteFunction(xhr){
	getElementByCache("jquery","#ajax_loading").css("display","none");
	ajax_mode = 'off';
	purge(xhr);
	delete xhr;
	return true;
}

function ErrorFunction(xhr){
	if(error_count < 3){
		getElementByCache("id","helping_message").innerHTML = "<font color=red>서버 환경이 원활하지 않습니다. 자동으로 다시 시도합니다. 잠시만 기다려주세요.</font>";
	}else{
		getElementByCache("id","helping_message").innerHTML = "<font color=red>서버 환경이 원활하지 않습니다. 다시 시도해주세요.</font>";
	}
	ajax_mode = 'off';
	purge(xhr);
	delete xhr;
	return false;
}

var NowPage=new Array();
var before_value_id='page_control';
var before_form_value='';
var ajax_mode='off';
var page_type='no_page';
var error_count=0;
var page_count=0;
var page_data_save = new Array();
function ChangePlanet(planetid){
	if(document.URL.indexOf('?') != -1)
	{
		location = document.URL+"&re=0&cp="+planetid;
	} else {
		location = document.URL+"?re=0&cp="+planetid;
	}
}

function FormAjaxInsert(page,form,value_id,type){
	if(page != "") $("form#"+form).attr("action",page);
	$("form#"+form).attr("name",form);
	$("form#"+form).submit();
	return true;
}

function ChangeLeftTab(value_id){
	if(value_id != before_value_id){
	$("#"+before_value_id).css("display","none");
	$("#"+before_value_id).html('');
	$("#"+value_id).css("display","block");
	before_value_id = value_id;
	}
}


var multi_count=new Array();
var multi_time = new Array();
function TimeCount(type,id,time,element,next_link,cancel_link){
	var thisObj_multi = this;
	if(multi_count[type] == id && id != '' && multi_count[type] != '' && getElementByCache("id",id)){ 
		if(type == 'fleet_make'){ 
			if ( hs == 0 ) {
				xd();
				hs = 1;
			}
			if(p > b.length - 2){
				document.Atr.auftr.options[document.Atr.auftr.length] = new Option("완료");
				document.Atr.Submit_Form.disabled = true; 
			} else {
				document.Atr.Submit_Form.disabled = false;
			}
			thisObj_multi.s = c[p] - time - Math.round((new Date().getTime() - multi_time[type].getTime()) / 1000.);
			thisObj_multi.s = Math.round(thisObj_multi.s);
		}else{
			thisObj_multi.s  = time - Math.round((new Date().getTime() - multi_time[type].getTime()) / 1000.);
		}
		thisObj_multi.m  = 0;
		thisObj_multi.h  = 0;

		if ( thisObj_multi.s < 0 ) {
			if(type == 'fleet_make'){
				a[p]--;
				if(c[p] == 0) a[p] = 0;
				xd();
				if ( a[p] <= 0 ) {
					p++;
					xd();
				}
				multi_time[type] = new Date();
				thisObj_multi.s = 0;
				window.setTimeout("TimeCount('"+type+"','"+id+"',0,'"+element+"','"+next_link+"','"+cancel_link+"')", 500);
			}
			if(type == 'research'){
				getElementByCache("id",id).innerHTML = '<a href=\'planet_control.php?page=buildings&mode=research\'>완료</a>';
				window.setTimeout('location.href="planet_control.php?page=buildings&mode=research";', 500);
				purge(thisObj_multi);
				delete multi_count[type],multi_time[type],thisObj_multi;  
				return;
			}
			if(type == 'fleet_upgrade'){
				getElementByCache("id",id).innerHTML = '<a href=\'planet_control.php?page=buildings&mode='+cancel_link+'&cp='+next_link+'\'>완료</a>';
				window.setTimeout('location.href="planet_control.php?page=buildings&mode='+cancel_link+'&cp='+next_link+'";', 500);
				purge(thisObj_multi);
				delete multi_count[type],multi_time[type],thisObj_multi;  
				return;
			}
			if(type == 'building'){
				getElementByCache("id",id).innerHTML = '<a href=\''+next_link+'\'>완료</a>';
				page_type='building';
				window.setTimeout('location.href="'+next_link+'","page_control","no_page_change";', 100);
				purge(thisObj_multi);
				delete multi_count[type],multi_time[type],thisObj_multi;
				return;
			}
			getElementByCache("id",id).innerHTML = ' - ';
			delete thisObj_multi;
			return true;
		} else {
			thisObj_multi.d = 0;
			if ( thisObj_multi.s > 59 ) {
			thisObj_multi.m = Math.floor( thisObj_multi.s / 60 );
			thisObj_multi.s = thisObj_multi.s - thisObj_multi.m * 60;
			}
			if ( thisObj_multi.m > 59 ) {
				thisObj_multi.h = Math.floor( thisObj_multi.m / 60 );
				thisObj_multi.m = thisObj_multi.m - thisObj_multi.h * 60;
			}
			if ( thisObj_multi.h > 24 ) {
				thisObj_multi.d = Math.floor( thisObj_multi.h / 24 );
				thisObj_multi.h = thisObj_multi.h - thisObj_multi.d * 24;
			}
			if ( thisObj_multi.s < 10 ) {
				thisObj_multi.s = "0" + thisObj_multi.s;
			}
			if ( thisObj_multi.m < 10 ) {
				thisObj_multi.m = "0" + thisObj_multi.m;
			}
			if(thisObj_multi.d > 0){
				thisObj_multi.d = thisObj_multi.d + "일 ";
			} else {
				thisObj_multi.d = '';
			}
			thisObj_multi.no_update=0;
	
			if(type == 'fleet_make'){
				thisObj_multi.no_update=1;
				getElementByCache("id",id).innerHTML = b[p]+" " + thisObj_multi.d + thisObj_multi.h+":"+thisObj_multi.m+":"+thisObj_multi.s;
			}

			if(type == 'research'){
				thisObj_multi.no_update=1;
				getElementByCache("id",id).innerHTML = thisObj_multi.d + thisObj_multi.h + ':' + thisObj_multi.m + ':' + thisObj_multi.s + '<BR><a href=\'planet_control.php?page=buildings&mode=research&cmd=cancel&tech='+element+'\'>취소</a>';
			}
			if(type == 'fleet_upgrade'){
				thisObj_multi.no_update=1;
				getElementByCache("id",id).innerHTML = thisObj_multi.d + thisObj_multi.h + ':' + thisObj_multi.m + ':' + thisObj_multi.s + '<BR><a href=\'planet_control.php?page=buildings&mode='+cancel_link+'&cmd=cancel&fleet='+element+'\'>취소</a>';
			}
			if(type == 'building'){
				thisObj_multi.no_update=1;
				getElementByCache("id",id).innerHTML = thisObj_multi.d + thisObj_multi.h + ':' + thisObj_multi.m + ':' + thisObj_multi.s + '　<a href=\''+cancel_link+'\'>취소</a>';
			}
			if(thisObj_multi.no_update != 1){
				getElementByCache("id",id).innerHTML = thisObj_multi.d + thisObj_multi.h + ':' + thisObj_multi.m + ':' + thisObj_multi.s;
			}
			window.setTimeout("TimeCount('"+type+"','"+id+"','"+time+"','"+element+"','"+next_link+"','"+cancel_link+"')", 999);
		}
	}
	purge(thisObj_multi);
	delete thisObj_multi;
	return false;
}


var before_view='';
function viewelement(i){
	if(before_view != i){
		if(before_view != '') getElementByCache("jquery",'#'+before_view).hide();
		getElementByCache("jquery",'#'+i).show();
		before_view=i;
	}
}


function xd() {
	while (document.Atr.auftr.length > 0) {
		document.Atr.auftr.options[document.Atr.auftr.length-1] = null;
	}
	if ( p > b.length - 2 ) {
		document.Atr.Submit_Form.disabled = true;
		document.Atr.auftr.options[document.Atr.auftr.length] = new Option("완료");
		$("#fleet_now_list").html("");
		delete multi_count['fleet_make'],multi_time['fleet_make'];
	}
	for ( iv = p; iv <= b.length - 2; iv++ ) {
		if ( iv == p ) {
			var act = " (진행 중)";
		} else {
			var act = "";
		}
		document.Atr.auftr.options[document.Atr.auftr.length] = new Option( a[iv] + "  \"" + b[iv] + "\"" + act, iv + 1 );
		delete act;
	}
	
}


function purge(d) {
	var a = d.attributes, i, l, n;
 	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			n = a[i].name;
 			if (typeof d[n] === 'function') {
				d[n] = null;
				delete d[n];
			}
		}
	}
 	a = d.childNodes;
 	if (a) {
		l = a.length;
 		for (i = 0; i < l; i += 1) {
			purge(d.childNodes[i]);
		}
	}
}

function calculateRemainResource(){

    var fm = document.resources_main;

 	fm.resource1.value=comma(Math.round(fm.point1.value * 30000));
 	fm.resource2.value=comma(Math.round(fm.point2.value * 15000));
 	fm.resource3.value=comma(Math.round(fm.point3.value * 7500));
 	fm.resource4.value=comma(Math.round(fm.point4.value * 3000));

}
var SlidingArray=new Array();
function SlidingMade(id,bid){
	if(!SlidingArray[id]) SlidingArray[id] = 0;
	$("#"+id).click(function() {
		if(SlidingArray[id] == 1){
			SlidingArray[id]=0;
			getElementByCache("jquery",'#'+bid).slideDown('fast'); //슬라이드업 : 숨기기
		}else{
			SlidingArray[id]=1;
			getElementByCache("jquery",'#'+bid).slideUp('fast'); //슬라이드업 : 숨기기
		}
	});
}

function f(target_url, win_name) {
	var new_win = window.open(target_url,win_name,'resizable=yes,scrollbars=yes,menubar=no,toolbar=no,width=650,height=480,top=0,left=0');
}

var element = new Array();
var xvalue = new Array();
function fcntchar(m,this_form) {
	if(this_form.value.length > m) {
		this_form.value = xvalue[this_form.name];
	} else {
		xvalue[this_form.name] = this_form.value;
	}
	element[this_form.name] = document.getElementById('cntChars');
	element[this_form.name].childNodes[0].data = this_form.value.length;
	element[this_form.name] = null;
}

var strInfo = "";
function galaxy_submit(value) {
	AjaxGalaxyControl(value+"=1",'galaxy.php?mode=1','Galaxy_Containter','galaxy_form');
}

function whenResponse (html) {
	var retVals   = html.split("|");
	var Message   = retVals[0];
	var Infos     = retVals[1];
	retVals   = Infos.split(" ");
	var UsedSlots = retVals[0];
	var SpyProbes = retVals[1];
	var Recyclers = retVals[2];
	var Missiles  = retVals[3];
	retVals   = Message.split(";");
	var CmdCode   = retVals[0];
	strInfo   = retVals[1];
	addToTable("완료", "success");
	changeSlots( UsedSlots );
	setShips("probes", SpyProbes );
	setShips("recyclers", Recyclers );
	setShips("missiles", Missiles );
}

function AjaxGalaxyControl(add_data,url,div_id,form_id){
	
	var send_data = "ajax=1&"+$("form[name='"+form_id+"']").serialize();
	if(add_data != '') send_data = send_data + "&" +add_data;

	var ajax_load=$.ajax({
	type:"POST",     //전송방식
	url:url,     //호출될 파일
	data:send_data,       //넘길 값
	cache: false,
	xhr: window.XMLHttpRequest ? 
	function() { return new window.XMLHttpRequest(); } : 
	function() { 
		try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } 
		catch(e) {} 
	},
	success:function(html){
		getElementByCache("jquery",'#'+div_id).hide().fadeTo(500,1).html(html);
	}
	});
	purge(ajax_load);
	delete ajax_load;

}
function doit (order, galaxy, system, planet,planettype,thisgalaxy, thissystem, thisplanet, thisplanettype, shipcount) {

	if (order == 6)
		var add_data="&ship210="+shipcount;
	if (order == 7) {
		var add_data="&ship208=1&ship203=2";
	}
	if (order == 8){
		var add_data="&ship209="+shipcount;
	}

	var ajax_load=$.ajax({
	type:"POST",     //전송방식
	url:"flotenajax.php?action=send",     //호출될 파일
	data:"no_display=1&ajax_mode=1&planettype="+planettype+"&planet="+planet+"&system="+system+"&galaxy="+galaxy+"&mission="+order+""+add_data,       //넘길 값
	timeout: 3000,
	cache: false,
	error: ErrorFunction,
	xhr: window.XMLHttpRequest ? 
	function() { return new window.XMLHttpRequest(); } : 
	function() { 
		try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } 
		catch(e) {} 
	},
	success:function(html){
		whenResponse(html);
	}
	});
	purge(ajax_load);
	delete ajax_load;
}

function mdoit (order, galaxy, system, planet,planettype,thisgalaxy, thissystem, thisplanet, thisplanettype, shipcount) {

	if (order == 6)
		var add_data="&ship210="+shipcount;
	if (order == 7) {
		var add_data="&ship208=1&ship203=2";
	}
	if (order == 8){
		var add_data="&ship209="+shipcount;
	}

	var ajax_loads=$.ajax({
	type:"POST",     //전송방식
	url:"mflotenajax.php?action=send",     //호출될 파일
	data:"no_display=1&ajax_mode=1&planettype="+planettype+"&planet="+planet+"&system="+system+"&galaxy="+galaxy+"&mission="+order+""+add_data,       //넘길 값
	timeout: 3000,
	cache: false,
	error: ErrorFunction,
	xhr: window.XMLHttpRequest ? 
	function() { return new window.XMLHttpRequest(); } : 
	function() { 
		try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } 
		catch(e) {} 
	},
	success:function(html){
		if(html != '') whenResponse(html);
	}
	});
	purge(ajax_loads);
	delete ajax_loads;
}
 
function addToTable(strDataResult, strClass) {
	getElementByCache("id",'fleetstatusrow','new').style.display = '';
	if(getElementByCache("id",'fleetstatustable','new').rows.length > 2) {
		getElementByCache("id",'fleetstatustable','new').deleteRow(2);
	}
	var row = getElementByCache("id",'fleetstatustable','new').insertRow(0);
	var td1 = document.createElement("td");
	var td1text = document.createTextNode(strInfo);
	td1.appendChild(td1text);
	var td2 = document.createElement("td");
	var span = document.createElement("span");
	var spantext = document.createTextNode(strDataResult);
	var spanclass = document.createAttribute("class");
	spanclass.nodeValue = strClass;
	span.setAttributeNode(spanclass);
	span.appendChild(spantext);
	td2.appendChild(span);
	row.appendChild(td1);
	row.appendChild(td2);
}
 
function changeSlots(slotsInUse) {
	getElementByCache("id",'slots').innerHTML = slotsInUse;
}
 
function setShips(ship, count) {
	getElementByCache("id",ship).innerHTML = comma(count);
}


function FleetResourceCalculate(){
	var Need_metal = 0;
	var Need_crystal = 0;
	var Need_deuterium = 0;
	
	$("#Fleetline input[type='text']").each(function(){
		Need_metal += FleetResourceList[$(this).attr("alt")]['metal'] * $(this).attr("value");
		Need_crystal += FleetResourceList[$(this).attr("alt")]['crystal'] * $(this).attr("value");
		Need_deuterium += FleetResourceList[$(this).attr("alt")]['deuterium'] * $(this).attr("value");
	});
	if(planet_control.metal >= Need_metal){
		getElementByCache("jquery","#need_metal").html(comma(Need_metal));
	}else{
		getElementByCache("jquery","#need_metal").html("<font color=red>"+comma(Need_metal)+"</font>");
	}
	if(planet_control.crystal >= Need_crystal){
		getElementByCache("jquery","#need_crystal").html(comma(Need_crystal));
	}else{
		getElementByCache("jquery","#need_crystal").html("<font color=red>"+comma(Need_crystal)+"</font>");
	}
	if(planet_control.deuterium > Need_deuterium){
		getElementByCache("jquery","#need_deuterium").html(comma(Need_deuterium));
	}else{
		getElementByCache("jquery","#need_deuterium").html("<font color=red>"+comma(Need_deuterium)+"</font>");
	}
}
function FleetMaxCreate(element){
	var Need_metal = planet_control.metal;
	var Need_crystal = planet_control.crystal;
	var Need_deuterium = planet_control.deuterium;
	$("#Fleetline input[type='text']").each(function(){
		if(element != $(this).attr("alt")){
			Need_metal -= FleetResourceList[$(this).attr("alt")]['metal'] * $(this).attr("value");
			Need_crystal -= FleetResourceList[$(this).attr("alt")]['crystal'] * $(this).attr("value");
			Need_deuterium -= FleetResourceList[$(this).attr("alt")]['deuterium'] * $(this).attr("value");
		}
	});
	if(Need_metal < 0) Need_metal = 0;
	if(Need_crystal < 0) Need_crystal = 0;
	if(Need_deuterium < 0) Need_deuterium = 0;
	var amount = Math.floor(Math.min((Need_metal/FleetResourceList[element]['metal']),(Need_crystal/FleetResourceList[element]['crystal']),(Need_deuterium/FleetResourceList[element]['deuterium'])));
	if(amount > 0){
		$("#Fleetline input[alt='"+element+"']").attr("value",amount);
	}
}
