/* Ajax opr */
var ajax=false;
var ajaxPopup=false;
var popUpStatus=false
var crashFlip=false
var crashTimeout=false
var bErrorSvrd=false
/*
Create the new window
*/
function openInNewWindow() {	
	var newWindow = window.open(this.getAttribute('href'), '_blank');
	newWindow.resizeTo(screen.availWidth,screen.availHeight); 
	newWindow.focus();
   return false;
}

/*
 Add the openInNewWindow function to the onclick event of links with a class name of "non-html"
 */
function getNewWindowLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// Change this to the text you want to use to alert the user that a new window will be opened
		var strNewWindowAlert = " (opens in a new window)";
		// Find all links
		var objWarningText;
		var strWarningText;
		var link;
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			link = links[i];				
			
			// Find all links with a class name of "non-html"
			if (/\bnewwin\b/.exec(link.rel)) {					
				link.onclick = openInNewWindow;					
  			}
		}
  	objWarningText = null;
	}
}

/* Time looped ajax update*/
function ajaxPump(){
	
	requestProgress()

	/* Re-call ourselves every 10 seconds out*/
	setTimeout("ajaxPump()", 10000);

}

/* Time looped time update */
function updateTime(){
	
	/* get time */
	currentTime = new Date()
	
	timeSpan = document.getElementById('clock') 	
	
	hours = 	currentTime.getHours()
	minutes = currentTime.getMinutes()
	seconds = currentTime.getSeconds()
	
	if( hours<10   ){ hours = '0'+hours; }
	if( minutes<10 ){ minutes = '0'+minutes; }
	if( seconds<10 ){ seconds = '0'+seconds; }
		
	timeSpan.firstChild.nodeValue=hours+':'+minutes+':'+seconds	
	
	/* Re-call ourselves every 1/2 second*/
	setTimeout("updateTime()", 500);

}


function switchIcons(run){

	switchOk=false

	/*Switch tags*/
	divs = document.getElementsByTagName("div");

	if(run){
		
		for (var i=0;i<divs.length;i++){

			if(divs[i].className=='not-running-group')
			{
				divs[i].style.display='none'
			}
				
		}
		
	} else {
	
		for (var i=0;i<divs.length;i++){

			if(divs[i].className=='not-running-group')
			{
				divs[i].style.display='block'
				switchOk=true
			}
				
		}
		
	}

	return switchOk

}

function getAjax(){

	xmlHttp=false;

	try
	{
		// Mozilla
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		//IE xml2
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			//IE xml
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				/* We have a problem ! */
				return false;
			}
		}
	}

	return xmlHttp;

}

/*
 request a progress update from the server 
*/
function requestProgress(){
	
	ajax = getAjax();

	if(!ajax){		
		return "Unclean - need Ajax for cleaner browsing !";	
	}

	/* register our state change */
	ajax.onreadystatechange=renderProgress;	

	/* request progress */
	ajax.open("GET","/progress/",true);
	ajax.send(null);

}
	
function renderProgress(){

	/* Race hazard on page reload can result in ajax not being 
	defined for a breif moment */
	if(typeof ajax == 'undefined'){
		return;
	} else {
		if(ajax.readyState!=4) return;
	} 
	
	text = document.getElementById('progress-msg');
	canvas = document.getElementById('progress-bar');
	canvasBox =	document.getElementById('progress');
		
	if (!text.firstChild){
		text.appendChild(document.createTextNode(null))
	}

	xmlDom=ajax.responseXML;	
	
	if(xmlDom){	
		
		
		if (xmlDom.getElementsByTagName('class').length>0){
			classType = xmlDom.getElementsByTagName('class')[0].firstChild.nodeValue
		} else {
			classType = 1
		}
		
		if (xmlDom.getElementsByTagName('crashed').length>0){
			/* No currently running campaigns */
			text.firstChild.nodeValue='Process has encountered a problem !';
			canvasBox.style.display='none';
			switchIcons(true); /*Keep users locked out */
			aniCrash(1000);
			/* write out the error to bar-error */						
			error = xmlDom.getElementsByTagName('error')[0].firstChild.nodeValue
			bErrorObj = document.getElementById('bar-error')
			
			if(!bErrorSvrd) {
				bErrorObj.appendChild(document.createTextNode(error))
				bErrorSvrd=true
			}
			
			document.getElementById('error').style.display='block'
			return;
		} else {
			if(crashTimeout){
				window.location.reload();
			}
		}		

		if (xmlDom.getElementsByTagName('norun').length>0){
			/* No currently running campaigns*/
			text.firstChild.nodeValue='No running processes.';
			canvasBox.style.display='none'
			switchIcons(false)
			return
		}		
	
		if (xmlDom.getElementsByTagName('finished').length>0){
			/*Force reload of page and discard any POST*/											
			window.location.href = window.location.href
			return
		}
			
		if (xmlDom.getElementsByTagName('error').length>0){
			text.firstChild.nodeValue=xmlDom.getElementsByTagName('error')[0].firstChild.nodeValue		
			return
		} 	
	
		switchIcons(true)
		
		progress = xmlDom.getElementsByTagName('progress')[0].firstChild.nodeValue
		tim = (xmlDom.getElementsByTagName('etc')[0].firstChild.nodeValue)
		etm = Math.round(tim/60)
		
		ets = tim%59
		
		if( (ets+'').length<2){
			ets='0'+ets
		}
		
		if (xmlDom.getElementsByTagName('asleep').length>0){
			/* show the sleep icon ! */
			text.firstChild.nodeValue='>> Sleeping << '+progress+'% completed.'
		} else {
			/* hide the sleep icon */
			if (classType == 1){
				text.firstChild.nodeValue=progress+'% campaign process completed (est '+etm+':'+ets+' left).'
			} else {
				text.firstChild.nodeValue=progress+'% upload process completed (est '+etm+':'+ets+' left).'
			}
			
		}

		/*Show canvas area */		
		canvasBox.style.display='inline'
		
		/*Draw on our canvas */
		cWidth = canvas.width
		cHeight = canvas.height
	
		/* decorate */
		ctx = canvas.getContext('2d')
		
		ctx.fillStyle = "#5aaa5c";
		
		ctx.fillRect(0,0,cWidth,cHeight)
	
		/* progress */
			
		if( classType == 1 ){
			ctx.fillStyle = "#1f7525";	
		}

		if( classType == 2 ){
			ctx.fillStyle = "#1f1ff5";	
		}
		
		width = (cWidth/100)*progress
		ctx.fillRect(0,0,width,cHeight)
			 
	} else {
		text.firstChild.nodeValue='No progress - bad server responce !'
	}
	
	return true
}


/* unhides the email update box and hide the email text */
function updateEmailBox(id){
	
	text = document.getElementById('bounce-email-text-'+id);
	text.style.display='none';
	
	form = document.getElementById('bounce-email-formblock-'+id);
	form.style.display='block';
}

/* Confirmation box for dangerouse operations !*/
function areYouSure(message){
	
	message+="\n"+'If you are not sure, click Cancel to abort.'	
	
	return confirm(message);
}

/* Clear DB error */
function clearError(obj){
	ajax = getAjax();

	if(!ajax){		
		return "Unclean - need Ajax for cleaner browsing !";	
	}
	
	/* request clear errors */
	ajax.open("GET","/clearerror/",true);
	ajax.send(null);
	
	obj.parentNode.removeChild(obj)	
	
}

function updateGroup(){

	if(!popUpStatus){
		popUpStatus=true;		
	}
	else {
		
		/* Update the group list from ajac call*/
	
		ajaxPopup = getAjax();

		if(!ajaxPopup){		
			return "Unclean - need Ajax for cleaner browsing !";	
		}

		/* register our state change */
		ajaxPopup.onreadystatechange=procUpdateGroup;	
	
		/* request list of groups - must be done syncronasly */
		ajaxPopup.open("GET","/group/?groupList",false);
		ajaxPopup.send(null);
		
	}


}

function procUpdateGroup(){

/* Race hazard on page reload can result in ajax not being 
	defined for a breif moment */
	if(typeof ajaxPopup == 'undefined'){
		return;
	} else {
		if(ajaxPopup.readyState!=4) return true;
	} 
	
	/* get a reference to the select object */
	select = window.document.getElementsByName('userGroup')[0];

	/* empty out the exiting list */
	for (sel in select.options){
		select.remove(sel);
	}

	xmlDoc = ajaxPopup.responseXML.firstChild;

	if(xmlDoc){

		/* process and add in new options */
		groups=xmlDoc.getElementsByTagName('group');
			
		for (i=0;i<groups.length;i++){
			id = groups[i].getElementsByTagName('id')[0].firstChild.nodeValue
			title = groups[i].getElementsByTagName('title')[0].firstChild.nodeValue		

			/* Create the option */
			opt = document.createElement('option')
			opt.text=title
			opt.value=id
		
			/* add in our option */
			try
			{
				select.add(opt,null)
			}
			catch(ex)
			{
				select.add(opt) /* I.E */			
			}
		
		}
				
		
	} else {
		
		/* something is wrong ! */			
		return false;		
	}

	return true;
}


function popUpGroup(){

	/* Open up the add group window */
	popUpWindow = window.open('/group/','_blank','fullscreen=0,height=450,width=680');
		
	popUpWindow.onunload = updateGroup;
	
}

function aniCrash(intvl)
{
	/* animates the progress bar to indicate a crash ! */
	canvas = document.getElementById('progress-bar');
	canvasBox =	document.getElementById('progress');
	
	/*Show canvas area */		
	canvasBox.style.display='inline';
		
	/*Draw on our canvas */
	cWidth = canvas.width;
	cHeight = canvas.height;
	
	/* decorate */
	ctx = canvas.getContext('2d');
	
	if(crashFlip){
		ctx.fillStyle = "#5aaa5c";	
		ctx.fillRect(0,0,cWidth,cHeight);
		crashFlip=false;	
	} else {
		ctx.fillStyle = "#ff0000";			
		ctx.fillRect(0,0,cWidth,cHeight);
		crashFlip=true;		
	}
	
	crashTimeout = setTimeout('aniCrash(\''+intvl+'\')', intvl);
}
