// Internet controls

//------------------------------------------------------------------------------
//  show - post a request to get DUB Messages Overall RSS topics when showing 
//    the widget.
//  Space requests by at least 15 minutes to avoid hitting the server too often. 
//  Also, note that you should cancel any outstanding request before posting 
//  the new one. 
//------------------------------------------------------------------------------

function getXMLdata(){

	addString = "version_code="+version+"&visit_count="+totalvisits+"&score_count="+tempgold+"&berry_count="+berry_count+"&roll_count="+roll_count;
	if(beta == true){
		feed = {title:"Fruitz updater", url:"http://fruitz.kevinandersson.dk/fruitz_system/updates/beta.php?"+addString};
		//alert('beta')
	}else{
		feed = {title:"Fruitz updater", url:"http://fruitz.kevinandersson.dk/fruitz_system/updates/stable.php?"+addString};	
	}
	
	//alert(feed.url)
   
	showInformation('<br> <br>Initializing Fruitz...',true, 1, false); // text, fade in, extraicon, closebutton		
	if (xml_request != null)
	{
		xml_request.abort();
		xml_request = null;
		
	}
	xml_request = new XMLHttpRequest();
    xml_request.onreadystatechange = alertContents;
	xml_request.onload = function(e) {xml_loaded(e, xml_request);}
	xml_request.overrideMimeType("text/xml");
	xml_request.open("GET", feed.url);
	xml_request.setRequestHeader("Cache-Control", "no-cache");
	xml_request.send(null);
    
   // DEBUG("/show");
}

  function alertContents() {
//	  alert('hmm')
    if (xml_request.readyState == 4) {
      if (xml_request.status == 200) {

        var string = xml_request.responseText;
      //alert(string);

      } else {
        alert('There was a problem with the request.');
      }
    }
  }

//-----------------------------------------------------------------------------
// findChild - scan the children of a given DOM element for a node matching
// nodeName; much more efficient than the standard DOM methods
// (getElementsByTagName, etc) if you know what you're looking for
//-----------------------------------------------------------------------------

function findChild (element, nodeName)
{
	var child;
	
	for (child = element.firstChild; child != null; child = child.nextSibling)
	{
		if (child.nodeName == nodeName)
			return child;
	}
	
	return null;
}

//----------------------------------------------------------------------------
// xml_loaded - extract the content of Apple RSS Hot News feed and place the
// items data into a results array: extract the title, link and publication 
// date for each item. 
//----------------------------------------------------------------------------

function xml_loaded (e, request) 
{
	//alert ('loaded');
	xml_request = null;
	
	//remoteversion = findChild(item, 'version');
	//dailyChecked = true;

	if (request.responseXML){		
		// Get the top level <rss> element 
		var rss = findChild(request.responseXML, 'rss');		
		if (!rss) {
			//alert("no <rss> element");
			showInformation('<br>Kevin must be sleeping, try and check again later...',true, 1, true); // text, fade in, extraicon, closebutton		
			extra_anitimer = setTimeout("extra_fadeout()", 3000);
			setMessage( "Let's start playing");
			 return;			
		}
		// Get single subordinate channel element
		var channel = findChild( rss, 'channel');
		if (!channel) {alert("no <channel> element"); return;}
	//	var results = new Array;
		var vrs	 		= findChild (channel, 'version');	
		var versionlnk	= findChild (channel, 'versionlink');			
		var wtext		= findChild (channel, 'welcometext');
		var today_link	= findChild (channel, 'today_link');
		var vnote		= findChild (channel, 'version_note');
		
		currentversion 	= vrs.firstChild.data;
		versionlink 	= versionlnk.firstChild.data;
		welcometext		= wtext.firstChild.data;
		todays_link		= today_link.firstChild.data;
		versionnote		= vnote.firstChild.data;		
			
		checkCurrentVersion();
		
		

		//alert(channel.firstChild.nodeValue)
		// Get all item elements subordinate to the channel element
		// For each element, get title, link and publication date. 
		// Note that all elements of an item are optional. 
		for( var item = channel.firstChild; item != null; item = item.nextSibling)
		{
			
			if( item.nodeName == 'item' )
			{
				//alert(item.firstChild.nodeValue)
				var title = findChild (item, 'title');
	
				
				// we have to have the title to include the item in the list 
				if( title != null ) 
				{
					var version = findChild (item, 'title');
					//alert('version: '+version.data)
//					var pubDate = findChild (item, 'pubDate');
					/*
					results[results.length] = {title:title.firstChild.data, 
						link:(link != null ? link.firstChild.data : null), 
						date:new Date(Date.parse(pubDate.firstChild.data))
				   };*/
				}
			}
		}
		
		
		// sort by date
		
		// copy title and date into rows for display. Store link so it can be used when user
		// clicks on title
		
	}
}


//
function getUpdate(){
	if(beta == true){
		widget.openURL('http://fruitz.kevinandersson.dk/fruitz_system/downloads/download.php?version_code='+version+'&beta=true');
	}else{
		widget.openURL('http://fruitz.kevinandersson.dk/fruitz_system/downloads/download.php?version_code='+version+'&beta=false');	
	}
}

//
function checkCurrentVersion(){
	if(version < currentversion){
		// install notes
		if(versionnote != ''){

		showInformation(versionnote+'Click <a href="#" onclick="getUpdate()">here</a> to download.</a><br><p class="small"><br>Your version '+version+' <br>Online version '+currentversion+'</p>',true, 0, true); // text, fade in, extraicon, closebutton			
		extra_anitimer = setTimeout("extra_fadeout()", 3000);		
		}else{
		showInformation('Fruitz needs an update, click <a href="#" onclick="getUpdate()">here</a> to download it.<br><p class="small"><br>Your version '+version+' <br>Online version '+currentversion+'</p>',true, 0, true); // text, fade in, extraicon, closebutton
		extra_anitimer = setTimeout("extra_fadeout()", 5000);			
		}
		

	}else{

			
		if(version > currentversion){
			//showInformation('<br>You have a prerelease version. There could be bugs',true, 2, true); // text, fade in, extraicon, closebutton					
			//extra_anitimer = setTimeout("extra_fadeout()", 3000);			
		}else{
			//extra_anitimer = setTimeout("extra_fadeout()", 1000);
			//showInformation('<br><br>You have the latest version',true, 1, true); // text, fade in, extraicon, closebutton	
			extra_fadeout()
			hideInformation();
		}
		
		//hideInformation();
		
		
	}	

	setMessage(welcometext)	;
	//alert(currentversion)
}


function dailyUpdateCheck(){
	if(	dailyChecked == false){
		var now = new Date();
		alert(now-checkDate);
		checkDate = now;
		updateChecker = setTimeout("dailyUpdateCheck();",checktime); // check every minute
		getXMLdata();
		
	}
}



// submit and get highscore

function submitHighscore(){
	typer = false;
	scoresubber = document.getElementById('score_typer');
	if(scoresubber.value > tempgold || IsNumeric(scoresubber.value) == false){
		scoresubber.value = tempgold;
	}
	if(IsNumeric(scoresubber.value)){
		currentSubmit = scoresubber.value;
	}else{
		currentSubmit = 0;
		scoresubber.value == 0;
	}
	currentSubmit = roundFive(currentSubmit);

	addString = "version_code="+version+"&highscore="+currentSubmit+"&roll_count="+roll_count+"&user_id="+useridentify;
	feed = {title:"Fruitz highscores", url:"http://fruitz.kevinandersson.dk/fruitz_system/scores/submit_highscores.php?"+addString};
	
	//alert(feed.url)
	document.getElementById("submithigh").style.display = 'none';
	showInformation('<br />Submitting highscore...',true, 1, false); // text, fade in, extraicon, closebutton		
	if (xml_request != null)
	{
		xml_request.abort();
		xml_request = null;
		
	}
	xml_request = new XMLHttpRequest();
    xml_request.onreadystatechange = alertContents;
	xml_request.onload = function(e) {highscore_loaded(e, xml_request);}
	xml_request.overrideMimeType("text/xml");
	xml_request.open("GET", feed.url);
	xml_request.setRequestHeader("Cache-Control", "no-cache");
	xml_request.send(null);
    
}

 
 
 function highscore_loaded (e, request) 
{
	//alert ('loaded');
	xml_request = null;
	document.getElementById("submithigh").style.display = 'block';
	//remoteversion = findChild(item, 'version');
	//dailyChecked = true;

	if (request.responseXML){		
		// Get the top level <rss> element 
		var rss = findChild(request.responseXML, 'rss');		
		if (!rss) {
			//alert("no <rss> element");
			showInformation('<br>Maybe we pushed the server to far... No feed',true, 1, true); // text, fade in, extraicon, closebutton		
			extra_anitimer = setTimeout("extra_fadeout()", 3000);
			setMessage( "Let's start playing");
			 return;			
		}
		// Get single subordinate channel element
		var channel = findChild( rss, 'channel');
		if (!channel) {alert("no <channel> element"); return;}

		//var vrs	 		= findChild (channel, 'version');	
		//var versionlnk	= findChild (channel, 'versionlink');			
		//var wtext		= findChild (channel, 'welcometext'); // And you are number x
		var today_link	= findChild (channel, 'today_link');
		var vnote		= findChild (channel, 'version_note');
		var smission	= findChild (channel, 'submission');
		//currentversion 	= vrs.firstChild.data;
		//versionlink 	= versionlnk.firstChild.data;
		//welcometext		= wtext.firstChild.data;
		//todays_link		= today_link.firstChild.data;
		versionnote		= vnote.firstChild.data;		
		submission		= smission.firstChild.data;		
		if(submission == 1){	
			showInformation('<br/>'+versionnote+' <p class="small"><br/><br/>(Rounded to: '+currentSubmit+')</p>',true, 1, true); // text, fade in, extraicon, closebutton		
		}else{
			showInformation('<br />'+versionnote+'',true, 1, true); // text, fade in, extraicon, closebutton		
		}
		// reset score
		if(submission == 1){
			tempgold = tempgold-currentSubmit;
			totalgold = tempgold;

			setgold();
			savePrefs();
			//hideInformation();			
		}
		

		//alert(channel.firstChild.nodeValue)
		// Get all item elements subordinate to the channel element
		// For each element, get title, link and publication date. 
		// Note that all elements of an item are optional. 
		for( var item = channel.firstChild; item != null; item = item.nextSibling)
		{
			
			if( item.nodeName == 'item' )
			{
				//alert(item.firstChild.nodeValue)
				var title = findChild (item, 'title');
	
				
				// we have to have the title to include the item in the list 
				if( title != null ) 
				{
					var version = findChild (item, 'title');
				}
			}
		}
		
		
		// sort by date
		
		// copy title and date into rows for display. Store link so it can be used when user
		// clicks on title
		
	}
}




// user login

function userLogin(){
	typer = false;
	usernamepost = document.getElementById('user_name');
	passwordpost = document.getElementById('password_inp');
	username = usernamepost.value;
	// password inp


	if(usernamepost.value != '' && passwordpost.value != ''){
	addString = "user="+usernamepost.value+"&password="+passwordpost.value;
	feed = {title:"Fruitz highscores", url:"http://fruitz.kevinandersson.dk/fruitz_system/login_control/login.php?"+addString};
	
	showInformation(usernamepost.value+' please wait. <br>Checking login...',true, 1, false); // text, fade in, extraicon, closebutton		
	if (xml_request != null)
	{
		xml_request.abort();
		xml_request = null;
		
	}
	xml_request = new XMLHttpRequest();
    xml_request.onreadystatechange = alertContents;
	xml_request.onload = function(e) {user_loaded(e, xml_request);}
	xml_request.overrideMimeType("text/xml");
	xml_request.open("GET", feed.url);
	xml_request.setRequestHeader("Cache-Control", "no-cache");
	xml_request.send(null);
	}else{
		//fejl
		document.getElementById("fejl").innerHTML  = 'You need to enter both username and password';	
		typer = true;
		
		
	}
    
}

 
 
 function user_loaded (e, request) 
{
	//alert ('loaded');
	xml_request = null;
	//document.getElementById("submithigh").style.display = 'block';
	//remoteversion = findChild(item, 'version');
	//dailyChecked = true;

	if (request.responseXML){		
		// Get the top level <rss> element 
		var rss = findChild(request.responseXML, 'rss');		
		if (!rss) {
			//alert("no <rss> element");
			showInformation('<br>Maybe we pushed the server to far... No feed',true, 1, true); // text, fade in, extraicon, closebutton		
			extra_anitimer = setTimeout("extra_fadeout()", 3000);
			setMessage( "Let's start playing");
			 return;			
		}
		// Get single subordinate channel element
		var channel = findChild( rss, 'channel');
		if (!channel) {alert("no <channel> element"); return;}

		//var vrs	 		= findChild (channel, 'version');	
		//var versionlnk	= findChild (channel, 'versionlink');			
		var wtext		= findChild (channel, 'welcometext'); // And you are number x
		//var today_link	= findChild (channel, 'today_link');
		var vnote		= findChild (channel, 'version_note');
		var smission	= findChild (channel, 'submission');
		//currentversion 	= vrs.firstChild.data;
		//versionlink 	= versionlnk.firstChild.data;
		welcometext		= wtext.firstChild.data;
		//todays_link		= today_link.firstChild.data;
		versionnote		= vnote.firstChild.data;		
		submission		= smission.firstChild.data;		
		if(submission == 1){	
			showInformation('<span><p>Welcome '+username+'.</p><p> You can now submit your scores to the Fruitz server. </p><p>'+welcometext+'</p></span>',true, 1, true); // text, fade in, extraicon, closebutton
			useridentify = 	versionnote;	
			document.getElementById('submithigh').style.backgroundImage = 'none';
		}else{
			showInformation('<div class="small">'+versionnote+' <br/><br/><a href="" onclick="fruitzCreateUser();" >Create new user</a>.<div>',true, 1, true); // text, fade in, extraicon, closebutton		
		}
		// reset score
		if(submission == 1){
			//savePrefs();
			//hideInformation();			
		}
		

		//alert(channel.firstChild.nodeValue)
		// Get all item elements subordinate to the channel element
		// For each element, get title, link and publication date. 
		// Note that all elements of an item are optional. 
		for( var item = channel.firstChild; item != null; item = item.nextSibling)
		{
			
			if( item.nodeName == 'item' )
			{
				//alert(item.firstChild.nodeValue)
				var title = findChild (item, 'title');
	
				
				// we have to have the title to include the item in the list 
				if( title != null ) 
				{
					var version = findChild (item, 'title');
				}
			}
		}
		
		
		// sort by date
		
		// copy title and date into rows for display. Store link so it can be used when user
		// clicks on title
		
	}
}