// Global variables
// timerFav is a global timer set to clear the flag's message window
var timerFav;
// timerAjaxFav is a global timer set to keep track of how long it is
// taking for the Geogad server to respond. If it is longer than some
// prefered value, the program redirects the user input to another operation.
var timerAjaxFav;  


function isAjaxSupportedFav() {
// Check if request can be created by is not used
   var request = null;
   if(typeof window.XMLHttpRequest != 'undefined')
   {
     request = new XMLHttpRequest();
   }
   else if(typeof window.ActiveXObject != 'undefined')
   {
     try { request = new ActiveXObject('Microsoft.XMLHTTP'); }
     catch(err) { request = null; }
   }
   if (request != null)
   	return(true); 
   else 
   	return(false); 

}

function favSuccess(id, link) {
	window.clearTimeout(timerFav);
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="favBox"><div style="text-align: center" ><span class="blueText">This has been added to your <a href="'+link+'">favorites</a>.</span></div></div>';
	timerFav = window.setTimeout('favClearMessage("'+id+'")', 7000); 
}

function favWaitMessage(id) {
	window.clearTimeout(timerFav);
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="favBox"><div style="text-align: center" >Sending....</span></div></div>';
}

function favProblemMessage(id) {
	window.clearTimeout(timerFav);
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="favBox"><div style="text-align: center" ><span class="yellowBackground redfont">Problem saving your favorite. Please try again later.</span></div></div>';
	timerFav = window.setTimeout('favClearMessage("'+id+'")', 7000); 
}

function favClearMessage(id) {
	var rt = document.getElementById(id);
	rt.innerHTML = '';
}


function favClearTimers() {
// free callback timer here
   window.clearTimeout(timerFav);
   window.clearTimeout(timerAjaxFav);
}


// Handler function for AJAX call
function print2DynamicMenuBox4Fav(data) {

// free callback timer here
   window.clearTimeout(timerAjaxFav);
// check for returned data
   if ((data == "") || (data == null)) {
   	favProblemMessage("dynamicMenuBox");
   }  else {
// build link
        var fullURL = window.location.href;
        var lastPos = fullURL.lastIndexOf("/");
        var baseURL = fullURL.substring(0, lastPos);
	var link = baseURL+"/myfaves?user="+data;
   	favSuccess("dynamicMenuBox", link)
   }
}

function sendFav(nickname, tID, ctID, tsID, box) { 

   if (isAjaxSupportedFav()) {
	favClearTimers();
   	JGetFavoritesInfo.createFavoritesJS(nickname, tID, ctID, tsID, print2DynamicMenuBox4Fav);
	timerAjaxFav = window.setTimeout('favProblemMessage("'+box+'")', 30000); 
	favWaitMessage(box);
	return false;
   } else { 
	return true ; 
   } 

}


