var dragelement;

var topx;
var topy;
var offsetx;
var offsety;

var desktopwidth;
var desktopheight;

var backgroundOffset = 0;

var currentdialogid = '';
var currentwizardid = '';
var totalwizardpages = 0;
var currentwizardpage = 0;

function appInit()
{
	var els = document.getElementsByTagName('DIV');
	for( i=0; i<els.length; i++ )
	{
		if( els[i].id == 'Handle' )
			els[i].onmousedown = startdrag;
		else if( els[i].id == 'Maximise' )
			els[i].onmousedown = maximise;
		else if( els[i].id == 'Minimise' )
			els[i].onmousedown = minimise;
	}
	
	el = document.getElementById('Desktop');
	if( el )
	{
		desktopwidth = el.offsetWidth;
		desktopheight = el.offsetHeight;
		
//		// document.getElementById('Debug').innerHTML = 'Desktop:'+desktopwidth+','+desktopheight;
	}
		
	setInterval("scrolleventbar()",25);
	setTimeout("hidenotifications()",3000);
	setTimeout("updatestatus()",5000);
}

function gettarget(e)
{
	var targ = null;
	if( e ) {
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
	}
	return targ;
}

function donothing()
{
}

function startdrag()
{
	var e = window.event;
	if( e ) {
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		// document.getElementById('Debug').innerHTML = targ.id;
		if( targ ) {
			while( targ.className != 'Widget' )
				targ = targ.parentNode;

			dragelement = targ;
		//	dragelement.style.zIndex = '10';
		//	dragelement.style.position = 'absolute';

			topx = parseInt(dragelement.style.left+0);
			topy = parseInt(dragelement.style.top+0);
			offsetx = e.clientX;
			offsety = e.clientY;

			document.onmousemove = dodrag;
			document.onmouseup = stopdrag;
		} else {
			// document.getElementById('Debug').innerHTML = 'No element error!';
		}
	}
			
	return false;
}

function dodrag()
{
	var e = window.event;
	if( e ) {
		// document.getElementById('Debug').innerHTML = ''+(event.clientX - offsetx)+'px,';
		// document.getElementById('Debug').innerHTML += (event.clientY - offsety)+'px';
		if( dragelement != null )
		{
			dragelement.style.left = ''+(topx + event.clientX - offsetx)+'px';
			dragelement.style.top = ''+(topy + event.clientY - offsety)+'px';
		}
	}
	
	return false;
}

function stopdrag()
{
	var e = window.event;
	if( dragelement != null && e ) 
	{
		// document.getElementById('Debug').innerHTML = 'Stopped dragging';
	//	dragelement.style.zIndex = '0';
	//	dragelement.style.position = 'relative';
		dragelement.style.left = '0px';
		dragelement.style.top = '0px';
		
		pagex = event.clientX - offsetx;
		pagey = event.clientY - offsety;
		
		if( pagex > desktopwidth || pagex < 0 || pagey > desktopheight || pagey < 0 )
			dragelement.style.display = 'none';

		document.onmousemove = null;
		document.onmouseup = null;
		dragelement = null;
	}
	
	return false;
}

function maximise( el )
{
	var e = window.event;
	if( e ) {
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		// document.getElementById('Debug').innerHTML = targ.id;
		if( targ ) {
			while( targ.className != 'Widget' )
				targ = targ.parentNode;
			
			widgetid = targ.id.substr(7,targ.id.length-7);
			document.location.href = "?p="+widgetid;
		}
	}
}

function minimise( el )
{
	document.location.href = "?p=flightdeck";
}

function scrolleventbar()
{
	el = document.getElementById('EventBar');
	if( el ) {
		backgroundOffset -= 1;
//		el.style.backgroundPosition = "" + backgroundOffset + "px 0px";
	}
}

function showdialog( id )
{
	el = document.getElementById('FullPageMask');
	if( el ) {
		el.style.left = '0px';
		el.style.top = '0px';
		el = document.getElementById( id );
		if( el ) {
			el.style.top = '50px';
		}
	}
}

function showtab( id )
{
	els = document.getElementsByTagName( "DIV" );
	for( i=0; i<els.length; i++ ) {
		if( els[i].className == 'Tab' )
			els[i].style.display = 'none';
	}
	els = document.getElementsByTagName( "DIV" );
	for( i=0; i<els.length; i++ ) {
		if( els[i].className == 'TabSelected' )
			els[i].className = 'TabSelector';
	}

	el = document.getElementById( 'tab_'+id );
	if( el ) {
		el.style.display = 'block';
	}

	el = document.getElementById( 'tabselector_'+id );
	if( el ) {
		el.className = 'TabSelected';
	}
	
	// document.getElementById('Debug').innerHTML = id;
}

function hidenotifications()
{
	el = document.getElementById('Notify');
	if( el ) {
		el.style.display = 'none';
	}
	el = document.getElementById('Notice');
	if( el ) {
		el.style.display = 'none';
	}
}

function initwizard( dialogid, id, totalpages ) 
{
	currentdialogid = dialogid;
	currentwizardid = id;
	totalwizardpages = totalpages;
	if( totalwizardpages > 0 ) 
		currentwizardpage = 1;
	
	showwizardpage();
}

function prevwizardpage()
{
	if( currentwizardpage > 1 )
		currentwizardpage--;
		
	showwizardpage();
}

function nextwizardpage()
{
	if( currentwizardpage < totalwizardpages-1 )
		currentwizardpage++;
		
	showwizardpage();
}

function showwizardpage()
{
	els = document.getElementsByTagName( "div" );
	for( i=0; i<els.length; i++ ) {
		if( els[i].id.substr( 0,currentwizardid.length+1 ) == currentwizardid+"_" ) 
			els[i].style.display = 'none';
	}
	
	el = document.getElementById( currentwizardid+"_"+currentwizardpage );
	if( el ) el.style.display = 'block';
	
	showwizardbuttons();
}

function showwizardbuttons()
{		
	el = document.getElementById('finish');
	if( el ) {
		if( currentwizardpage < totalwizardpages-1 ) {
			el.setAttribute( 'href','javascript:donothing();' ); 
			el.className = "buttondisabled";
		} else {
			el.setAttribute( 'href',"javascript:submitdialog('"+currentdialogid+"');" );
			el.className = "button";
		}
	}
	
	el = document.getElementById('back');
	if( el ) {
		if( currentwizardpage <= 1 ) {
			el.setAttribute( 'href','javascript:donothing();' ); 
			el.className = "buttondisabled";
		} else {
			el.setAttribute( 'href','javascript:prevwizardpage();' );
			el.className = "button";
		}
	}
		
	el = document.getElementById('next');
	if( el ) {
		if( currentwizardpage < totalwizardpages-1 ) {
			el.setAttribute( 'href','javascript:nextwizardpage();' );
			el.className = "button";
		} else {
			el.setAttribute( 'href','javascript:donothing();' ); 
			el.className = "buttondisabled";
		}
	}
}

function disableallbuttons()
{		
	el = document.getElementById('finish');
	if( el ) {
		el.setAttribute( 'href','javascript:donothing();' ); 
		el.className = "buttondisabled";
	}
	
	el = document.getElementById('back');
	if( el ) {
		el.setAttribute( 'href','javascript:donothing();' ); 
		el.className = "buttondisabled";
	}
		
	el = document.getElementById('next');
	if( el ) {
		el.setAttribute( 'href','javascript:donothing();' ); 
		el.className = "buttondisabled";
	}
		
	el = document.getElementById('cancel');
	if( el ) {
		el.setAttribute( 'href','javascript:donothing();' ); 
		el.className = "buttondisabled";
	}
}

function submitdialog( id ) 
{
	disableallbuttons();

	el = document.getElementById('Processing');
	if( el ) {
		el.style.left = '50%';
		el.style.top = '150px';
		img = el.getElementsByTagName('IMG')[0];
		img.src = img.src;
	}
	
	el = document.forms['dialog_'+id];
	if( el ) {
		updateRTEs();
		el.submit();
	}
}

var ajaxid = '';

function callAjaxFunction( request, post, callback, id, data )
{
	var xmlHttp;
	ajaxid = id;
	
	try { xmlHttp=new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari  
	catch (e) {  
    	try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } // Internet Explorer 
  		catch (e) {    
			try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
    		catch (e) { 
				alert("Your browser does not support AJAX!");
				return false;      
			}   
		}  
	} 
	
	var randomnumber=Math.floor(Math.random()*99999999)
	if( post == true || data == null ) request = request.replace( "?", "?rid="+randomnumber+"&" );
	else request = request.replace( "?", "?rid="+randomnumber+"&data="+urlencode(data)+"&" );
	
	xmlHttp.onreadystatechange = function()
	{
		if( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
		{
			if( xmlHttp.responseText.length > 0 ) 
				callback( xmlHttp.responseText, ajaxid );
			else 
				callback( xmlHttp.responseBody, ajaxid );
		}
		delete xmlHttp;
	}
	
	if( post == true ) {
		xmlHttp.open("POST",request,true);
		xmlHttp.send(data);
	} else {
		xmlHttp.open("GET",request,true);
		xmlHttp.send(null);
	}
}

function selectrow( widget, type, name, id )
{
	var request = "widgets/"+widget+".php?ajax="+type+"&name="+name+"&id="+id;
	// document.getElementById('Debug').innerHTML = request;
	callAjaxFunction( request, false, cb_selectrow, name+"_"+id );
}

function cb_selectrow( response, nameandid )
{
	params = nameandid.split('_',2);
	
	els = document.getElementsByTagName('TR');
	for( i=0; i<els.length; i++ ) 
	{
		if( els[i].id == params[0]+"_"+params[1] )
		{
			classBase = els[i].className.split("_",2);
			els[i].className = classBase[0]+"_"+response;
			// document.getElementById('Debug').innerHTML = els[i].className;
		}
	}
}

function showlistimage( divid, imagepath )
{
	el = document.getElementById(divid);
	if( el ) {
		el.style.background = "url("+imagepath+")";
	}
}

function clickedbanner( id )
{
	var request = "widgets/advert.php?ajax=banner&id="+id;
	// document.getElementById('Debug').innerHTML = request;
	callAjaxFunction( request, false, cb_clickedbanner, id );
}

function cb_clickedbanner( response, id )
{
}

function updatestatus()
{
	var randomnumber=Math.floor(Math.random()*99999999);
	var request = "app/status.php?r="+randomnumber;
	callAjaxFunction( request, false, cb_updatestatus, 'UserInfo_Status' );
	setTimeout("updatestatus()",5000);
}

function cb_updatestatus( response, id )
{
	el = document.getElementById(id);
	if( el ) el.innerHTML = response;
}

function urlencode( str ) 
{                            
	if( str.length < 1 ) return str;

	var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function initmarquee(name)
{
	MarqueeName = name;
	
	el = document.getElementById(MarqueeName);
	if( el )
	{
		MarqueePosition = 0;
		AnnounceWidth = 0;
		if( window.innerWidth ) AnnounceWidth += window.innerWidth;
		else if( document.body.clientWidth ) AnnounceWidth += document.body.clientWidth;
		
		marqueetext = el.innerHTML;
		MarqueeReturn = el.offsetWidth;
		
		MarqueeRepeat = Math.ceil(AnnounceWidth/el.offsetWidth);
		for( i=0; i<=MarqueeRepeat; i++ ) el.innerHTML += marqueetext;

		el.style.width = el.offsetWidth*(MarqueeRepeat+1);
	}
	
	scrollmarquee();
}

function scrollmarquee()
{
	el=document.getElementById(MarqueeName);
	if( el ) {
		clearTimeout(MarqueeTimer);
		MarqueePosition -= MarqueeStep;
		el.style.left = MarqueePosition+'px';
	
		if(MarqueePosition <= -MarqueeReturn ){
			MarqueePosition = 0;
			el.style.left = MarqueePosition;
		}
		MarqueeTimer=setTimeout("scrollmarquee()",10);
	}
}
