function fetchdata(divname, url, method, postdata){

// Define the callback object for Connection Manager that will set the body of our content area when the content has loaded

var content = document.getElementById(divname);

var callback = {
	success : function(o) {
		if (divname =="ct"){
      eval(o.responseText);
      }
    else {
    content.innerHTML = o.responseText;
		content.style.visibility = "visible";
    }
	
	//alert("before");
	var countdown = document.getElementById("countdown");
	if (countdown != null){
		var code = document.getElementById("countdown").innerHTML;
		if (window.countdown != 'started'){ eval(code); 
		document.getElementById("ct").style.visiblity ="visible";
    } 
	}
    
	},
	failure : function(o) {
		content.innerHTML = o.responseText;
		content.style.visibility = "visible";
		content.innerHTML = "Unable to connect to server, please try again...";
	}
}




// Connect to our data source and load the data
if (postdata == "null"){
var conn = YAHOO.util.Connect.asyncRequest(method, url, callback, null);
}

else {var conn = YAHOO.util.Connect.asyncRequest(method, url + new Date().getTime(), callback, postdata);}


//YAHOO.util.Event.addListener("show", "click", YAHOO.example.container.simpledialog1.show, YAHOO.example.container.simpledialog1, true);

}


function evalRequest(url){

// Define the callback object for Connection Manager that will set the body of our content area when the content has loaded

var content = null;

var callback = {
	success : function(o) {
		//content.innerHTML = o.responseText;
		//content.style.visibility = "visible";
		eval(o.responseText);
		
	},
	failure : function(o) {
		content.innerHTML = o.responseText;
		content.style.visibility = "visible";
		content.innerHTML = "Unable to connect to server, please try again...";
	}
}
// Connect to our data source and load the data
var conn = YAHOO.util.Connect.asyncRequest("GET", url, callback, null);
//YAHOO.util.Event.addListener("show", "click", YAHOO.example.container.simpledialog1.show, YAHOO.example.container.simpledialog1, true);

}


function openURL(url, div){
  
  if (typeof mytime === "undefined"){}
  else{
  clearTimeout(mytime);
  }
  
  window.countdown = "stopped";
  
	fetchdata(div, url, "GET", "null");

}

function cancelmission(mission){
   var conf = confirm("Are you sure you want to cancel this mission? \n\nYour Fleet will return to the planet of departure.");
		if (conf == true) {
    var postdata = "type=mission" + "&mission="+mission;
	  fetchdata("ct", "cancel.php?time=", "POST", postdata);
  }
  

}

function cancelshipbuild(canceltype, ship){
  	
    var conf = confirm("Are you sure you want to cancel building the remaining ships? \n\nYou will only be able to recover half of the construction costs.");
		if (conf == true) {
		//document.getElementById("ct").innerHTML = "";
    var postdata = "type=" +canceltype + "&ship="+ship;
	  fetchdata("ct", "cancel.php?time=", "POST", postdata);
  }
  
}

function cancelresearch(research){
  	
    var conf = confirm("Are you sure you want to cancel the current research? \n\nYou will only be able to recover half of the research costs.");
		if (conf == true) {
		//document.getElementById("ct").innerHTML = "";
    var postdata = "type=research" + "&research="+research;
	  fetchdata("ct", "cancel.php?time=", "POST", postdata);
  }
  
}



function cancelupgrade(canceltype, id){
  	
    var conf = confirm("Are you sure you want to cancel this upgrade? \n\nYou will only be able to recover half of the upgrade costs.");
		if (conf == true) {

    var postdata = "type=" +canceltype + "&structure="+id;
	  fetchdata("ct", "cancel.php?time=", "POST", postdata);
  }
  
}


function getplanet(planetid){

  document.getElementById("planetoverview").innerHTML = "Fetching Planet Data ... ";
	postdata = "pid=" +planetid;
	fetchdata("planetoverview", "planetoverview.php?time=", "POST", postdata);
	//page_viewplanet();
	}
	
	function getfleets(planetid){

  document.getElementById("fleetsoverview").innerHTML = "Fetching Fleet Data ...";
	postdata = "pid=" +planetid;
	fetchdata("fleetsoverview", "fleetsoverview.php?time=", "POST", postdata);
	//page_viewplanet();
	}
	
	function filterplanets(){

  //document.getElementById("fleetsoverview").innerHTML = "Fetching Fleet Data ...";
	
	var searchname = document.getElementById("searchname").value;
	var ctype = document.choosetype.ctype.options[document.choosetype.ctype.selectedIndex].value;
  var sector = document.choosesector.sector.options[document.choosesector.sector.selectedIndex].value;
  var hasshipyard = 0; //document.getElementById("hasshipyard").value;
  
  if(document.getElementById("hasshipyard").checked == true){
      hasshipyard = 1;
  }
  
  postdata = "searchname=" +searchname+"&type="+ctype+"&sector="+sector+"&hasshipyard="+hasshipyard;
	fetchdata("filterresults", "filterplanets.php?time=", "POST", postdata);

	}
	
	function getplanetoverview(slot, planetid){
  
  //document.getElementById("fleetsoverview").innerHTML = "Fetching Fleet Data ...";
	postdata = "pid=" +planetid;
	fetchdata(slot, "planetminidata.php?time=", "POST", postdata);
  
  }
  
  function systeminfo(star){
  postdata = "star=" +star;
	fetchdata("staroverview", "staroverview.php?time=", "POST", postdata);
  }

function researchDetails(id){
	postdata ="id="+id;
	fetchdata("researchdetails", "researchdetails.php?time=","POST", postdata);
	}
  
   function build(id){
  postdata = "id=" +id;
  document.getElementById("structuredetails").innerHTML = "Loading Data ...";
	fetchdata("structuredetails", "build.php?time=", "POST", postdata);
  }
  
  function dobuild(id){
  postdata = "id=" +id;
  document.getElementById("structuredetails").innerHTML = "Loading Data ...";
	fetchdata("ct", "dobuild.php?time=", "POST", postdata);
  }
  
  function changesystem(system){
  document.getElementById("pw").innerHTML = "Changing system please wait...";
  postdata = "system=" +system;
	fetchdata("page", "changesystem.php?time=", "POST", postdata);
  
  }
  
    function changeplanetandsystem(system, pid){
  //document.getElementById("pw").innerHTML = "Changing system please wait...";
  postdata = "system=" +system+"&pid="+pid;
	fetchdata("page", "changesystem.php?time=", "POST", postdata);
  
  }
  
  function shipinfo(ship){
  document.getElementById("shipinfo").innerHTML = "Getting ship details please wait....";
  postdata = "ship=" +ship;
	fetchdata("shipinfo", "shipdetails.php?time=", "POST", postdata);
  
  }
  
   function structuredetails(structure){
  document.getElementById("structuredetails").innerHTML = "Fetching structure details ...";
  postdata = "structure=" +structure;
	fetchdata("structuredetails", "structuredetails.php?time=", "POST", postdata);
  
  }
  
    function bookmarksystem(system){
  postdata = "system=" +system;
	fetchdata("bookmarkoverview", "addbookmark.php?time=", "POST", postdata);
  
  }
  
     function deletebookmark(id){
  postdata = "id=" +id;
	fetchdata("bookmarkoverview", "deletebookmark.php?time=", "POST", postdata);
  
  }
  
     function upgrade(id){
  postdata = "id=" +id;
	fetchdata("ct", "upgradestructure.php?time=", "POST", postdata);
  
  }
  
       function research(id){
  postdata = "id=" +id;
	fetchdata("ct", "doresearch.php?time=", "POST", postdata);
  }
  
     function shipbuild(){
  var qty = document.getElementById("qty").value;
  var type = document.getElementById("type").value;
  
  postdata = "type="+type+"&qty="+qty;
	fetchdata("ct", "buildships.php?time=", "POST", postdata);
  
  }
  
    function newbuilddetails(id){
  postdata = "id=" +id;
  document.getElementById("structuredetails").innerHTML = "Fetching structure data...";
	fetchdata("structuredetails", "newbuilddetails.php?time=", "POST", postdata);
  
  }
  
     function getchat(){
	fetchdata("chatresults", "getchat.php?time=", "POST", "null");
	}
	
	function evalchat(){
	var code = document.getElementById("chatresults").innerHTML;
	alert(code);
	eval(code);
	document.getElementById("chatresults").innerHTML = "";
	}
	
	function filtermsg(msgType){
      var postdata = "filter="+msgType;
      fetchdata("inbox", "filterinbox.php?time=", "POST", postdata);
  }
  
  function showmessage(id){
      var postdata = "id="+id;
      fetchdata("preview", "getmessage.php?time=", "POST", postdata);  
  }
  
  function deletemessage(id){
      var postdata = "id="+id;
      fetchdata("ct", "deletemessage.php?time=", "POST", postdata);
  }
  
  function filterplayers(){
  
      var filter = document.getElementById('player').value;
      
      if(filter.length > 1){
          var postdata = "searchterm="+filter;
          fetchdata("filterwindow", "filterplayers.php?time=", "POST", postdata);
      }
  }
  
  function getplayerdetails(player){
  
      var postdata ="player="+player;
      fetchdata("playerdetails", "getplayerdetails.php?time=", "POST", postdata);
  
  }
  
    
  function acceptdelivery(id){
  
      var postdata ="id="+id;
      fetchdata("deliveryoverview", "acceptdelivery.php?time=", "POST", postdata);
  
  }
  
  function sendmessage(){
  
      var title = document.getElementById('title').value;
      var body = document.getElementById('message').value;
      var rec = document.getElementById('rec').value;
      var postdata = "title="+title+"&body="+body+"&rec="+rec;
      fetchdata("ct", "sendmessage.php?time=", "POST", postdata);
  
  }
  
  function showreply(){
      if(document.getElementById('replybox').style.visibility == "visible"){
        document.getElementById('replybox').style.visibility = "hidden";
        }
      else{
        document.getElementById('replybox').style.visibility = "visible";
        }
  }
  
  function updateastropedia(){
  
      var id = document.getElementById("articleid").value;
      //var text = document.getElementById("articletext").value;
      var editor_data = CKEDITOR.instances.articletext.getData();
      var title = document.getElementById("articletitle").value;
      var newarticle = 0;
      if (document.getElementById("isnew").checked == 1){ 
        newarticle = 1;
      }
      
      //alert(text);
      //alert(newarticle);
  
   
   var postdata = "id=" +id + "&text="+escape(editor_data)+"&title="+title+"&newarticle="+newarticle;
	 fetchdata("ocontent", "addarticle.php?time=", "POST", postdata);
  
  }
  
  function getarticle(id){
  
   //var postdata = "article="+id;
   //fetchdata("ocontent", "astropediacontent.php?time=", "POST", postdata);
   var loc = "astropedia.php?article="+id 
   window.location=loc;
  
  }
  
  function scrapships(){
    var conf = confirm("Are you sure you want to scrap the selected ships?  This can not be undone.");
		if (conf == true) {
		


    var availableShips = document.getElementById("availableShips").value;
    var fname = document.getElementById("fleetname").value;
    var shipList = availableShips.split(":");

    var postdata = "buildships=1&fleetname="+fname;

  for (var i = 0; i < shipList.length; i++){
	 if (shipList[i] == "") continue;
	
	 var id = "ship"+shipList[i];
	 var num = document.getElementById(id).value;
	 postdata = postdata + "&"+"ship_"+shipList[i]+"="+num;
	
	}
	
	fetchdata("ct", "scrapships.php?time=", "POST", postdata);


    
    
    
    
    }
  
  
  }
  
  
  
  
  function changesector(){
  //defunct but left in as a code example
  var x = changesectorform.sectorx.options[changesectorform.sectorx.selectedIndex].value;
  var y = changesectorform.sectory.options[changesectorform.sectory.selectedIndex].value;
  
   postdata = "x=" +x + "&y="+y;
	fetchdata("page", "changesector.php?time=", "POST", postdata);
  }
  
  function searchsystem(){
  
  var searchTerm = document.getElementById("systemname").value;
  
  if (searchTerm.length > 2){
  postdata = "search=" +searchTerm;
	fetchdata("searchresults", "search.php?time=", "POST", postdata);
    
  
    }
  
  }

	
function page_viewplanet(){
	YUI().use("async-queue", function(Y) {
	var q = new Y.AsyncQueue({fn:getslots, timeout:200}, {fn:planet_overview, timeout:200});
	q.run();
    });
	}
	

function startgame(){

setInterval ( "evalRequest('getchat.php')", 2000 );
}

function sendchat(){

var chattext = document.getElementById("chat").value;
if (chattext != ""){
   postdata = "chattext=" +chattext;
   document.getElementById("chat").value = "";
   fetchdata("chatblock", "sendchat.php?time=", "POST", postdata);
}

}

function countResources(){

    var cr = document.getElementById("currentresources");
    if (cr != null){
    
        var metal = parseInt(document.getElementById("storedMetalCount").innerHTML);
        var res = document.getElementById("currentresources").innerHTML;
        var r = res.split(":");
        var maxmetal = parseInt(r[1]);
        var mpm = parseInt(r[2]);
        
        
        //this is run every 1 second say.....
        
        var toAdd = mpm/12;
        a = parseInt((toAdd + metal));
       
        //alert(a);
        
        
        
        
        if (toAdd > maxmetal){toAdd = maxmetal;}
        document.getElementById("storedMetalCount").innerHTML = a;
        
        }
  }
  
  
function deleteselected(){

    var inputs = document.getElementsByTagName('input');
    var checkboxes = [];
    var postdata = "";
    
    for (var i = 0; i < inputs.length; i++) {
        
        if (inputs[i].type == 'checkbox') {
            if (inputs[i].checked == true){
            postdata = postdata + inputs[i].id +"=1&";
            }
        }
    }
    fetchdata("ct", "deleteselectedmessages.php?time=", "POST", postdata);
  }


function hideMenu(div){
//document.getElementById(div).style.visibility = 'hidden';

setTimeout(function(){hide(div); parameter = null},1000);

function hide(div){
  document.getElementById(div).style.visibility = 'hidden';
}
  
}

function showMenu(div, pid){
document.getElementById(div).style.visibility = 'visible';
document.getElementById(div).innerHTML ="Loading ...";
getplanetoverview(div, pid);
}

function buysub(sub){
   var conf = confirm("Are you sure you want to buy this upgrade?");
		if (conf == true) {
   var postdata = "sub="+sub;
   fetchdata("ocontent", "buysub.php?time=", "POST", postdata);
   }    
}

function buytf(){

    var conf = confirm("Are you sure you want to buy a Terraformer?");
		if (conf == true) {
		fetchdata("ocontent", "buytf.php?time=", "GET", "NULL");	
  }
}

function usetf(){
  
    var conf = confirm("Are you sure you want to use a Terraformer on this planet?\n\nA This will increase the amount of space on this planet by 50");
		if (conf == true) {
 	fetchdata("ocontent", "usetf.php?time=", "GET", "NULL");
   }	

}

function abandonplanet(){

  var conf = confirm("Are you sure you want to abandon this planet?\n\nThis cannot be undone!");
		if (conf == true) {
 	fetchdata("ocontent", "doabandonplanet.php?time=", "GET", "NULL");
   }

}

function allianceApply(id){
    var postdata = "id="+id;
    fetchdata("alliancetask", "appform.php?time=", "POST", postdata);
}

function submitApp(){
    
    var reason = document.getElementById("reason").value;
    var id = document.getElementById("allianceid").value;
    var postdata = "id="+id+"&reason="+reason;
    fetchdata("alliancetask", "submitapp.php?time=", "POST", postdata);
}

function cancelRequest(){

     var conf = confirm("Are you sure you want to cancel your application to this alliance?");
		if (conf == true) {
		
		  fetchdata("alliancetask", "cancelapp.php?time=", "GET", "NULL");
    
    } 
}

function joinaction(action, id){
  
  var postdata = "action="+action+"&id="+id;
  fetchdata("ct", "joinaction.php?time=", "POST", postdata);


}

function kickmember(member){
     var conf = confirm("Are you sure you want to expell this member from the alliance?");
		if (conf == true) {
		  var postdata = "member="+member;
		  fetchdata("ocontent", "kickmember.php?time=", "POST", postdata);
    
    } 

}

function leavealliance(member){
     var conf = confirm("Are you sure you want to leave this alliance?\nYou will loose all access to alliance resources and ships.");
		if (conf == true) {
		  var postdata = "member="+member;
		  fetchdata("ocontent", "leavealliance.php?time=", "POST", postdata);
    
    } 

}

function deletepost(post){
     var conf = confirm("Are you sure you want to delete this post?");
		if (conf == true) {
		  var postdata = "post="+post;
		  fetchdata("ct", "deletepost.php?time=", "POST", postdata);
    
    } 

}

function sendpost(){

    var postbody = document.getElementById("postbody").value;
    var posttitle = document.getElementById("posttitle").value;
    document.getElementById("postbutton").disabled = true;
    document.getElementById("postbutton").value = "Posting...";
    
    var postdata = "postbody="+postbody+"&posttitle="+posttitle;
    
    fetchdata("ocontent", "postmessage.php?time=", "POST", postdata);

}

function lostpassword(){

    fetchdata("contentsbox", "template/lostpass.php?time=", "GET", "NULL");

}

function resetpass(){

    var email = document.getElementById("email").value;
    var postdata = "email="+email;
    
    fetchdata("contentsbox", "template/resetpass.php?time=", "POST", postdata);


}

function changepasswordnew(){

    var password = document.getElementById("newpassword").value;
    var confpassword = document.getElementById("confpassword").value;
    
    var postdata = "p="+password+"&cp="+confpassword;
    fetchdata("passwordresetbox", "changepassword.php?time=", "POST", postdata);
    


}

function scanreports(planet){
  var loc = "http://www.astarum.com/main/scanreports.php?planet="+planet;
  window.open(loc,'','scrollbars=no,menubar=no,height=300,width=400,resizable=yes,toolbar=no,location=no,status=no,top=200,left=400');
}

function resourcelimit(user){
    
    var limit = document.getElementById("reslimit").value;
    var postdata = "limit="+limit+"&user="+user;
    fetchdata("ct", "changereslimit.php?time=", "POST", postdata);
    


}

function renameplanet(planet){

    var newname = document.getElementById("newname").value;
    var postdata = "newname="+newname;
    fetchdata("renamestatus", "renameplanet.php?time=", "POST", postdata);

}

function queue(action, structure){

    var postdata = "action="+action+"&structure="+structure;
    fetchdata("ct", "managebuildq.php?time=", "POST", postdata);
}

function researchq(action, research){

   var postdata = "action="+action+"&research="+research;
   fetchdata("ct", "manageresearchq.php?time=", "POST", postdata); 

}

function changecolor(c){
  
    var postdata = "color="+c;
     fetchdata("colfeedback", "changetextcolour.php?time=", "POST", postdata);


}

function deleteallmessages(type){

var conf = confirm("Are you sure you want to delete all currently displayed messages?");
		if (conf == true) {
		
		var postdata = "type="+type;
		     fetchdata("ct", "deleteallmessages.php?time=", "POST", postdata);
		}
}

function downgrade(structure){


   var conf = confirm("Are you sure you want to downgrade this structure - you will not get any resources back");
		if (conf == true) {
		    var postdata = "structure="+structure;
		    fetchdata("ct", "downgrade.php?time=", "POST", postdata);
    }

}



function display_c(start){
window.start = parseFloat(start);
window.countdown = "started";
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout('display_ct()',refresh)
}
else {document.getElementById("ct").innerHTML = "Complete";
	window.countdown = "stopped";
	var URL = document.getElementById("currentpage").innerHTML;
	
	function pausecomp(ms) {
  ms += new Date().getTime();
  while (new Date() < ms){}
  }
  
  pausecomp(5000); 
	
  openURL(URL, 'ocontent');
  //setTimeout("window.location='research.php'", 10000)
  }
}
function display_ct() {
// Calculate the number of days left
var days=Math.floor(window.start / 86400); 
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left 
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes. 
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))

if (secs < 0) secs = 0;

var x = days + ":" + hours + ":" + minutes + ":" + secs + "";

var x = "";
if (days > 0) {x = x + days + "d ";}
if (hours < 10 && hours > 0){x = x +"0";} //added
if (hours > 0) {x = x + hours + ":";}
if (minutes < 10 && minutes > 0){x = x +"0";} //added here
if (minutes > 0){x = x + minutes + ":";}
if (secs < 10){x = x +"0";}
if (secs > 0){x = x + secs + "s";}
if (secs == 0){x = x + "0";}

var check = document.getElementById('ct');
if (check != null){document.getElementById('ct').innerHTML = x;}

window.start= window.start- 1;

tt=display_c(window.start);
}


