/************* global variables **************/
var _NOSCROLL_POPUP_FEATURES = 'location=0,statusbar=0,menubar=0,resizable=no,scrollbars=no,top=100,left=100,screenX=100,screenY=100';
var _SCROLL_POPUP_FEATURES = 'location=0,statusbar=1,menubar=0,resizable=yes,scrollbars=yes,top=100,left=100,screenX=100,screenY=100';
var _SESSION_PING_INTERVAL = 10000; //10 seconds pinging interval
var _ONETOONE_PING_INTERVAL = 7500;
var _TITLE_BLINK_INTERVAL = 500;
var _DEFAULT_BG_COLOR = "#FFFFFF";
var _HOST = window.location.hostname;
var host_bits = _HOST.split(".");
host_bits.shift();
var _DOMAIN = "." + host_bits.join(".");
//var _BASE_URL = (_HOST.indexOf("qubers.com")==-1 && ) ? "/qube/" : "/";  //redundant statement
var _BASE_URL = "/";
var _DEFAULT_FLASH_VERSION = "6,0,0,0";
var idle = 0;
var objBody;
var chat121Width = 585;
var chat121Height = 350;
var noticesAllowed = true; // will be set to false if there are notices or processes running
var sessionTimer, check121Timer, titleTimer;
/* browser detect */
var ua = navigator.userAgent.toLowerCase();
var ua_version = navigator.appVersion.toLowerCase();
var is_minor = parseFloat(ua_version);
var is_major = parseInt(is_minor, 10);
var iePos = ua_version.indexOf('msie');
if (iePos !=-1) {
	is_minor = parseFloat(ua_version.substring(iePos+5,ua_version.indexOf(';',iePos)))
	is_major = parseInt(is_minor, 10);
}
var isIE = ((iePos!=-1));
var gtIE6 = (isIE && is_minor > 6) ? true : false;
var theWindow;


/************ generic functions ****************/
Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; };
function isUndefined(a) { return typeof a == 'undefined'; };

/* raw_popup and link_popup: accessible popup window functions. */
function raw_popup(url, target, can_scroll, w_width, w_height) {
  // define base set depending on whether the window can scroll or not
  var features = _SCROLL_POPUP_FEATURES;
  if (can_scroll==false) features = _NOSCROLL_POPUP_FEATURES;
  // define target attr
  if (isUndefined(target)) target = '_blank';
  // add width and height to features
  if (isUndefined(w_width)) w_width = 400;
  if (isUndefined(w_height)) w_height = 300;
  features += ',width='+w_width+',height='+w_height;
  // call the window
  theWindow = window.open(url, target, features);
  theWindow.focus();
  return theWindow;
}
function link_popup(src, can_scroll, w_width, w_height) {
  return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', can_scroll, w_width, w_height);
}

/* cookie functions, props to PPK @ QuirksMode */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/* clog: parent logging function which can take account of firefox's dump debug option. */
function clog(msg) { if (typeof(dump) != 'undefined'){dump(msg +"\n");} /* else alert(msg); */ }
/* launch: legacy popup function which does nothing. */
function launch(windowWidth, windowHeight, theURL)	{ clog("launch called! url: "+theURL); } 
function shuffleArray ( myArray ) { // fisher-yates algorithm
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}
function confirmAction( checkMessage, theURL ) { if (confirm(checkMessage)) window.location = theURL; }
function followLink( theURL ) { window.location = theURL; }
function parent_link(src) { window.opener.document.location.href = src.getAttribute('href'); self.close(); }
function imposeMaxLength(obj, maxLength) { if (obj.value.length>maxLength) obj.value = obj.value.substring(0,maxLength); }
function getMS() { var usec = new Date(); return usec.getTime(); }
function getPageScroll(){
	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	arrayPageScroll = new Array('',yScroll) 
	return yScroll; // arrayPageScroll;
}
function getWindowHeight()
{
	var windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowHeight = document.body.clientHeight;
	}	

	return windowHeight; 
}
function insertFlash(swf,width,height,bgcolor,params) {
	// set default bgcolor if not provided
	if(!bgcolor || bgcolor=="") bgcolor = _DEFAULT_BG_COLOR;
	if(!params) params = new Object();
	if(!params.version) params.version = _DEFAULT_FLASH_VERSION;
	// parse parameters
	var objectParams = "";
	var embedParams = "";
	for(var i in params) {
		objectParams += "<param name="+i+" value=\""+params[i]+"\">\n";
		embedParams += i+"=\""+params[i] + "\" ";
	}
	// write the object
	var objHTML = 	"<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" " +
						"codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version="+params.version+"\"" +
						"width=\""+width+"\" height=\""+height+"\" id=\"flash\">" +
						"<param name=\"movie\" value=\""+swf+"\">" +
						"<param name=\"quality\" value=\"high\">" +
						"<param name=\"bgcolor\" value="+bgcolor+">" +
						objectParams +
						"<embed src=\""+swf+"\" quality=\"high\" bgcolor=\""+bgcolor+"\"  width=\""+width+"\" height=\""+height+"\" " +
							embedParams +
							"type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></embed>" +
					"</object>";
	document.write(objHTML);
}
/********************* END generic functions *******************************/




/********************* rotating images functions ***************************/
function fadeOut() { 
	//clog("fading image out...");
	new Effect.Fade('rotating_images', { duration: 1.6,queue:'end',afterFinish:loadNew });
}

function loadNew()
{
	// increment current rotation counter
	document.c_rotate++;
	
	// if the rotation counter equals the ad frequency, then display an ad...
	if (document.c_rotate>document.rotate_ad_freq) {
		
		// cycle ad array if we've hit the end of it, or if the next one isn't defined.
		if (document.c_ad>document.num_rotate_ads || typeof document.rotate_ad_array[document.c_ad]=='undefined') document.c_ad = 0;
		
		clog("showing ad "+document.rotate_ad_array[document.c_ad]);
		
		// split up the ad details array
		var deets = document.rotate_ad_array[document.c_ad].split("|");
		
		// hide the user html, and show the other stuff
		$('rotate_user_content').setStyle( { display:'none' } );
		$('rotate_ad_content').setStyle( { display:'block' } );
		
		if (deets[2].indexOf('javascript')==0) {
			deets[2] = deets[2].substr(9);
			$('rotate_ad_content').innerHTML = "<a href=\"#\" onclick=\""+deets[2]+"return false;\" target=\"_blank\"><img src=\""+deets[0]+"\" border=\"0\" alt=\"Advertisement\" /></a>";
		}
		else {
			$('rotate_ad_content').innerHTML = "<a href=\""+deets[2]+"\" target=\"_blank\"><img src=\""+deets[0]+"\" border=\"0\" alt=\"Advertisement\" /></a>";
		}
		
		// set effects
		new Effect.Appear('rotating_images', { duration: 1.6, from: 0.0, to: 1.0 });
		setTimeout("fadeOut()",_ROTATE_FADE_TIME);
		
		// re-zero rotation counter
		document.c_rotate = 0;
		// isz ad counter
		document.c_ad++;
	}
	else {
		
		// increment position in user image array
		document.p++;
		
		// loop to zero again
		if (document.p>=document.rotateLength) document.p = 0;
		
		// get the p value
		document.pv = document.keys[document.p];
		
		// if this one doesn't exist, move on to the next after an interval
		if (typeof document.pv == 'undefined') {
			document.p++; 
			setTimeout( "loadNew()", 1000 );
		}
		else {
		
			clog(document.c_rotate+": showing user "+document.rnA[document.pv]+" ("+document.riA[document.pv]+")");
			
			// switch contents in case
			$('rotate_user_content').setStyle( { display:'block' } );
			$('rotate_ad_content').setStyle( { display:'none' } );
			
			document.preloadImage = null;
			
			document.preloadImage = new Image();
			// once image is preloaded, resize image container
			document.preloadImage.onload=function() {
				//clog("image loaded...");
				var sw = this.width*(100/this.height);
				if (sw>130) {
					// log
					clog(this.src+": too big");
					// since the image is not being displayed, reduce rotate counter
					document.c_rotate--;
					// go for a new one
					setTimeout("loadNew()",100);
					return;
				}
				document.getElementById('r_image').src = this.src;
				document.getElementById('r_img_link').href = this.profile_href;
				document.getElementById('r_poplink').href = this.profile_href;
				document.getElementById('r_name').innerHTML = this.member_name;
				document.getElementById('r_location').innerHTML = this.place;
				//clog("appearing...");
				new Effect.Appear('rotating_images', { duration: 0.6, from: 0.0, to: 1.0 });
				//clog("setting fade timeout");
				setTimeout("fadeOut()",_ROTATE_FADE_TIME);
			}
			document.preloadImage.onerror = function () {
				// log
				clog(this.src+": too big");
				// since the image is not being displayed, reduce rotate counter
				document.c_rotate--;
				// go for a new one
				setTimeout("loadNew()",100);
				return;
			}
			document.preloadImage.profile_href = document.rhA[document.pv];
			document.preloadImage.member_name = document.rnA[document.pv];
			document.preloadImage.place = document.rpA[document.pv];
			document.preloadImage.src = "images/users/"+document.riA[document.pv];
			
			clog("loading image "+document.riA[document.pv]);
		}
	}

	return;
}
/********************* END rotating images functions ***************************/


/********************* START David's rotating images functions ***************************/

var curr_rotating_banner = 0;
var ajax_frequency = 0;				// number of ajax calls made
var _ROTATE_FADE_TIME = 4000;		// 4000 millisec = 4 sec
var _ROTATE_BANNER_FREQUENCY = 4; 	// ratio of users to ads eg 3 => 2:1, 4 => 3:1
var _MAX_BANNER_CALLS = 50;			// if user is idling, stop ajax calls for goodness sake

function image_preloaded(){
	//not really necessary, could use with alternative binary display pattern
	if(document.images){
		curr_img = document.images['curr_rotating_image'];
	    if(curr_img.complete) return true;
	    else return false;
	} 
}
function wait_for_preload(){
	setTimeout('rotate_fadein()',100); // hehe, lazy alternative to image preload check
}

function rotate_members(){
	if(curr_rotating_banner > _MAX_BANNER_CALLS) {
		new Effect.Appear('rotating_members', { duration: 2.0, from: 0.0, to: 1.0 }); 
		return; //maximum time to call ajax, user is probably idle
	}
	//alert(ajax_frequency % _ROTATE_BANNER_FREQUENCY);
	//post curr_rotating banner according to frequency
	if(ajax_frequency++ % _ROTATE_BANNER_FREQUENCY == 0) new Ajax.Updater('rotating_members', '/ajax/fragment_rotate.php',{asynchronous:true,postBody:'bid='+curr_rotating_banner++,onComplete:wait_for_preload}); 
	else new Ajax.Updater('rotating_members', '/ajax/fragment_rotate.php',{evalScripts:true,asynchronous:true,onComplete:wait_for_preload}); 
}

function rotate_fadein(){
	new Effect.Appear('rotating_members', { duration: 2.0, from: 0.0, to: 1.0 });
	setTimeout('rotate_fadeout()',_ROTATE_FADE_TIME);
}

function rotate_fadeout() { 
	new Effect.Fade('rotating_members', {duration: 1.6,queue:'end',afterFinish:rotate_members });
}
/********************* END David's rotating images functions ***************************/



/********************* qube form functions ***************************/
function checkAll() // checks all checkboxes in forms[0] except the 'allbox'.
{
	var frm = document.forms[0];
	if (!frm) return;
	for (var i=0;i<frm.elements.length;i++) {
		var e=frm.elements[i];
		if ((e.name != 'allbox') && (e.type=='checkbox')) e.checked=frm.allbox.checked;
	}
}
function switchStars( v ) // called on mouseover of star ratings.
{	
	if (document.star_reset != 0) {
    	window.clearTimeout(document.star_reset);
    	document.star_reset = 0;
  	} 
	sImg = document.getElementById( 'starsImg' );
	sImg.style.width = v+'px';
}
function resetStars( v ) // called on mouseout of star ratings.
{
  	document.star_reset = window.setTimeout("switchStars("+document.starWidth+")", 500);
 	// msgTwinkler[asin] = window.setTimeout("amz_js_swapStarMsgs('"+asin+"')", delayTime);
}
function switchForum() // called when the forum select box is changed.
{
	var sb = document.getElementById('switchForumSelector');
	if (sb!=undefined) {
		var fid = sb.options[sb.selectedIndex].value;
		if (fid!="") window.location = _BASE_URL + "forum.php?fid="+fid;
	}
}
/* forum gui twiddles.... */
function forumOver( forum ) {
	// get the container DIV
	var cd = forum.parentNode.parentNode.parentNode.parentNode;
	// if this isn't "forummessagerows" then drop out
	if (cd.className!='forummessagerows') return;
	// change class of the container div
	cd.className = 'forummessagerows_over';
}
function forumOut( forum ) { 
	// get the container DIV
	var cd = forum.parentNode.parentNode.parentNode.parentNode;
	// if this isn't "forummessagerows" then drop out
	if (cd.className!='forummessagerows_over') return;
	// change class of the container div
	cd.className = 'forummessagerows';
}
function forumClick( fid ) { window.location = _BASE_URL + 'forum.php?fid='+fid; }
/* messenger gui twiddles... */
function messageItemOver( el )
{
	// get the container TR
	var tr = el.parentNode;
	// if this isn't "forummessagerows" then drop out
	if (tr.className!='message_row') return;
	// change class of the container div
	tr.className = 'message_row_over';
}
function messageItemOut( el )
{
	// get the container TR
	var tr = el.parentNode;
	// if this isn't "forummessagerows" then drop out
	if (tr.className!='message_row_over') return;
	// change class of the container div
	tr.className = 'message_row';
}
function switchInsiderCity() // called when the insider city select box is changed.
{
	var sb = document.getElementById('cid');
	if (sb!=undefined) {
		var fid = sb.options[sb.selectedIndex].value;
		if (fid!="") window.location = _BASE_URL + "insider.php?cid="+fid;
	}
}
/********************* END qube form functions ***************************/




/********************* QUBE session handling functions ***************************/
function sessionRequest() {
	var ms = getMS();
	var sReq = new Ajax.Request(_BASE_URL + "resource/session_tracker.php?zone="+document.zone+"&idle="+idle, {method:'post',parameters:'us='+ms,onComplete:handleSessionReturn} );
	return;
}
function handleSessionReturn( req )
{
	// only take action if there's no existing notice. this is to avoid duplicating them.
	if (req.responseText != '' && !qubeNoticeExists()) {
		
		var reqBits = req.responseText.split("|");
		
		if (reqBits[2]=="M") heShe = 'he';
		else if (reqBits[2]=="F") heShe = 'she';
		else heShe = 'they';
			
		offer121( reqBits[1], heShe, reqBits[3], reqBits[0] );
		NewWindow = window.open('/alert.php','TheWindow','toolbar=no,width=300,height=150,directories=no,status=no,scrollbars=no,resizable=no,location=no,menubar=no,titlebar=no');NewWindow.focus();



		return;
	}
	
	// reset the timer only if there's no window
	if (!qubeNoticeExists()) resetSessionTimer();
	
	// dispose a notice if there's actually nothing to say
	if (req.responseText == '' && qubeNoticeExists()) closeQUBENotice();
	
}
function resetSessionTimer() { sessionTimer = window.setTimeout( "sessionRequest()", _SESSION_PING_INTERVAL ); }
function updateIdle() { idle = 0; }
function increaseIdle() { idle++; /* window.status="idle for "+idle+" seconds."; */ }
/********************* QUBE session handling functions ***************************/




/********************* 121 Chat functions ***************************/
function launch121( theQID )
{
	return raw_popup(_BASE_URL + "chat121.php?tqid="+theQID, "_blank", true, chat121Width, chat121Height);
}
function send121Invite( theQID )
{
	// get the preface and send a request through - this will generate a database entry.
	var preface = $('preface').value;
	var req = new Ajax.Request(_BASE_URL + "resource/121/begin_121.php?tqid="+theQID+"&us="+getMS(), {method:'post',parameters:'preface='+preface,onComplete:show121InviteResponse} );
	
	new Effect.Fade('send_fields', { duration: 0.3, queue:'end' }); 
	new Effect.Appear('sending', { duration: 0.3, from: 0.0, to: 1.0, queue:'end' });
}
function show121InviteResponse( req )
{
	var reqBits = req.responseText.split('=');
	switch (reqBits[0]) {
		case "exists":
			var new_message = "The invitation has already been registered. Waiting for a response from the user..."; //<br />" + req.responseText;
			break;
		case "success":
			var new_message = "The invitation was sent. Waiting for the user to respond..."; // <br />" + req.responseText;
			break;
		default:
			new Effect.Fade('allcontent', { duration: 0.3, queue:'end' });
			new Effect.Appear('error_message', { duration: 0.3, from: 0.0, to: 1.0, queue:'end' });
			break;
	}
	
	if (new_message) {
		// display the message
		$('wait_content').innerHTML = new_message;
		
		// register a new timer to check for a response.
		check121Timer = window.setTimeout( 'check121InviteStatus( '+reqBits[1]+' )', _ONETOONE_PING_INTERVAL );
	}
	
	return;
}
function check121InviteStatus( theID )
{
	// issue a request for invite status
	var req = new Ajax.Request("resource/121/check_121.php?iid="+theID+"&us="+getMS(), {method:'post',onComplete:handle121InviteStatus} );
}
function handle121InviteStatus( req )
{
	// req.responseText is <invite status>|<invite id>|<response>|<created chatroom id>
	var reqBits = req.responseText.split('|');
	
	switch (reqBits[0]) {
		
		case "Open":
			// do nothing; re-set the timer
			check121Timer = window.setTimeout( 'check121InviteStatus( '+reqBits[1]+' )', _ONETOONE_PING_INTERVAL );
			break;
			
		case "Accepted":		
			// if the chat is accepted but there's not yet a chatroom id, then rest timer and drop out
			if (reqBits[3]=='') {
				$('wait_content').innerHTML = '<br />Chat request accepted. Waiting for chatroom...';
				check121Timer = window.setTimeout( 'check121InviteStatus( '+reqBits[1]+' )', _ONETOONE_PING_INTERVAL );
				return;
			}
			
			// otherwise open up the chat window!
			new Effect.Parallel(
				[ new Effect.Fade('allcontent', { sync: true, duration: 0.5 }),
				  new Effect.Appear('chat_121_interface', { sync: true, duration: 0.5 }) ], 
				{ duration: 0.5, queue: "end", afterFinish:function() 
														{
															document.cr = parseInt(reqBits[3]);	// chatroom
															init_chat();
														}
				}
			);
			break;
			
		case "Expired":
			// display the "sorry dude!" message
			$('sending').innerHTML = 'This invitation has expired. Please create a fresh one.';
			break;
			
		case "Offline":
			// display the "sorry dude!" message
			$('sending').innerHTML = 'The user you invited has gone offline. Please close this window to return to QUBE.';
			break;
			
		case "Declined":
			// display the "sorry dude!" message
			$('sending').innerHTML = 'The chat invitation was declined by the recipient.';
			if (reqBits[2]!='') $('sending').innerHTML += '<br /><br />The following reason was given:<br /><i>'+reqBits[2]+'</i>';
			break;
			
		default:
			// do nothing; re-set the timer
			check121Timer = window.setTimeout( 'check121InviteStatus( '+reqBits[1]+' )', _ONETOONE_PING_INTERVAL );
			break;
	}
}
function offer121( senderName, heShe, preface, chatID )
{
	var newHTML = 	'<b>QUBE121 Invitation</b><hr /><br />'+
					senderName+' has invited you to a private 121 chat.<br /> ';
					
	// append the preface message if it exists
	if (preface.length>0) {
		newHTML += 	'Review their message below, enter a response and then <b>ACCEPT</b>'+
					' or <b>DECLINE</b> the invitation.<div class="div_121_preface">'+preface+'</div>';
	}
	else newHTML += 'If you wish to enter a response, please do so below and then <b>ACCEPT</b>'+
					' or <b>DECLINE</b> the invitation.';
	
	// append the entry fields
	newHTML += '<div class="div_121_response">Your response:<br /><textarea name="121_response_text" id="121_response_text"></textarea></div>';
	
	// append buttons
	newHTML += 	'<a style="float:right;" href="javascript:void(accept121('+chatID+'));">ACCEPT &raquo;</a>'+
				'<a style="float:left;" href="javascript:void(decline121('+chatID+'));">&laquo; DECLINE</a>';
				
	// clear
	newHTML += '<br style="clear:both;" />';
				
	// show the offer
	return showQUBENotice( newHTML, false, "New Chat Invitation !!" );
}
function accept121( theID ) 
{
	// get the response message
	var response = $('121_response_text').value;
	
	// send the accept message - and reset session timer afterwards
	var req = new Ajax.Request("resource/121/accept_121.php?iid="+theID+"&us="+getMS(), {method:'post',parameters:'response='+response,onComplete:resetSessionTimer } );
	
	// open the chat window - the chat121.php file will instantiate the chatroom if it doesn't exist based on the invite
	raw_popup("chat121.php?iid="+theID, "_blank", true, chat121Width, chat121Height);
	
	// close the notice
	closeQUBENotice();
	
	return false;
}
function decline121( theID )
{
	// get the response message
	var response = $('121_response_text').value;
	
	// send the accept message - and re-permit notices afterwards
	var req = new Ajax.Request("resource/121/decline_121.php?iid="+theID+"&us="+getMS(), {method:'post',parameters:'response='+response,onComplete:resetSessionTimer } );
	
	// close the notice
	closeQUBENotice();
	
	return false;
}
/********************* END 121 Chat functions ***************************/




/********************* qube notice functions *************************/
function showQUBENotice( content, hasCloseBox, windowTitleOverride )
{	
	var objNotice = document.createElement("div");
	objNotice.setAttribute('id','qube_notice_wrapper');
	
	
	var boxHTML = '<table class="height100" width="100%" border="0">'+
					'<tr>'+
						'<td height="100%" width="100%" align="center">'+
							'<div id="qube_notice">';
							
	if (hasCloseBox) boxHTML += '<div class="notice_closebox">'+
									'<a href="javascript:closeQUBENotice(this);">'+
										'<img src="skins/' + document.skin + '/images/icons/x.png" border="0" alt="Close" />'+
									'</a>'+
								'</div>';
								
	boxHTML += 					content+
							'aaa</div>'+
							'<div class=\"qube_ui_nest\">'+
								'<object id="annoying_sound" name="annoying_sound" type="application/x-shockwave-flash" data="files/121_invite_notification.swf" width="2" height="2">'+
									'<param name="movie" value="files/121_invite_notification.swf" />'+
								'</object>'+
							'</div>'+
						'</td>'+
					'</tr>'+
				'</table>';
				
	objNotice.innerHTML = boxHTML;
	
	//objBody.style.overflow = 'hidden';
	objBody.appendChild(objNotice);
	
	new Effect.Fade('container', { duration:0.5,queue:'end',from:1.0,to:0.3, afterFinish:function(){Element.show('qube_notice')} } );

	if (windowTitleOverride!='') {
		startTitleBlinking( windowTitleOverride );
	}

	return;
}
function closeQUBENotice( src )
{
	// stop the title blinking
	stopTitleBlinking();
	
	//$('container').style.display = 'inline-block';
	$('container').setOpacity(1.0)
	//alert($('container').getStyle('opacity'));
	// fade the body back up
	//new Effect.Appear('container', {duration:0.1, queue:'end', from:0.5, to:1.0});
	//Element.setOpacity('container', 1.0);
	
	// following code causes extremely weird scrolling anomalies in IE6, it has to be seen to be believed!
	//objBody.style.overflow = 'scroll';
	// remove the notice from the DOM
	Element.remove( $('annoying_sound') );
	Element.remove( $('qube_notice_wrapper') );

	return;
}
function qubeNoticeExists()
{
	if($('qube_notice_wrapper')) return true;
	else return false;
}
/********************* END qube notice functions *************************/



function blinkWindowTitle( msg )
{
	if (document.title==document.oTitle) {
		document.title = msg;
	}
	else {
		document.title = document.oTitle;
	}
	
	// reset the timer
	titleTimer = window.setTimeout( "blinkWindowTitle( '"+msg+"' )", _TITLE_BLINK_INTERVAL );
}

function startTitleBlinking( msg )
{
	titleTimer = window.setTimeout( "blinkWindowTitle( '"+msg+"' )", _TITLE_BLINK_INTERVAL );
}

function stopTitleBlinking()
{
	window.clearTimeout( titleTimer );
	document.title = document.oTitle;
}



function initRollovers() 
{
	var aPreLoad = new Array();
	var sTempSrc;
	var aImages = document.getElementsByTagName('img');

	for (var i = 0; i < aImages.length; i++) {
		if (aImages[i].className == 'imgover') {
			var src = aImages[i].getAttribute('src');
			var ftype = src.substring(src.lastIndexOf('.'), src.length);
			var hsrc = src.replace(ftype, '_o'+ftype);

			aImages[i].setAttribute('hsrc', hsrc);
			
			aPreLoad[i] = new Image();
			aPreLoad[i].src = hsrc;
			
			aImages[i].onmouseover = function() {
				sTempSrc = this.getAttribute('src');
				this.setAttribute('src', this.getAttribute('hsrc'));
			}
			
			aImages[i].onmouseout = function() {
				if (!sTempSrc) sTempSrc = this.getAttribute('src').replace('_o'+ftype, ftype);
				this.setAttribute('src', sTempSrc);
			}
		}
	}
}

function fixIE6Rollovers() 
{
	var aPreLoad = new Array();
	var sTempSrc;
	var aImages = document.getElementsByTagName('span');

	for (var i = 0; i < aImages.length; i++) {
		if (aImages[i].className == 'imgover') {
			var src = aImages[i].getAttribute('osrc');
			var ftype = src.substring(src.lastIndexOf('.'), src.length);
			var hsrc = src.replace(ftype, '_o'+ftype);

			aImages[i].setAttribute('hsrc', hsrc);
			
			aPreLoad[i] = new Image();
			aPreLoad[i].src = hsrc;
			
			aImages[i].onmouseover = function() {
				sTempSrc = this.getAttribute('osrc');
				this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + this.getAttribute('hsrc') + "\', sizingMethod='scale')";
			}
			
			aImages[i].onmouseout = function() {
				if (!sTempSrc) sTempSrc = this.getAttribute('osrc').replace('_o'+ftype, ftype);
				this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + sTempSrc + "\', sizingMethod='scale')";
			}
		}
	}
}

function resolvePNGs()
{
	for(var i=0; i<document.images.length; i++)
	{
		var img = document.images[i];
		var imgName = img.src.toUpperCase();
		
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText 
			var imgOSrc = "osrc='" + img.src + "' ";
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			var usemap = (typeof(img.getAttribute('usemap')=='undefined')) ? "" : 'usemap="' + img.getAttribute('usemap') + '"';
			var strNewHTML = "<span " + imgID + imgClass + imgTitle + imgOSrc
			+ " style=\"" + 
					"width:" + img.width + "px; " +
					"height:" + img.height + "px;" + imgStyle + "; " +
			 		"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + img.src + "\', sizingMethod='scale');\">"
			+ '<img src="' + _BASE_URL + 'images/spacer.gif" onclick="var h = this.parentNode.parentNode.href; if (typeof(h)!=\'undefined\') { window.location = h; }" width="' + img.width + '" height="' + img.height + '" ' + usemap + ' alt="" /></span>';
			img.outerHTML = strNewHTML;
			i = i-1;
		}
	}
};

/********** news ticker functions **********/
var theCharacterTimeout = 40;
var theStoryTimeout     = 5000;
var theSummaries = new Array();
var theSiteLinks = new Array();
// Ticker startup
function startTicker()
{
	// Define run time values
	theCurrentStory     = -1;
	theCurrentLength    = 0;
	// Locate base objects
	if (document.getElementById) {	
		theAnchorObject = document.getElementById("ticker");
		runTheTicker();
	}
	else return true;
}

// Ticker main run loop
function runTheTicker()
{
	var myTimeout;  
	// Go for the next story data block
	if(theCurrentLength == 0)
	{
		theCurrentStory++;
		theCurrentStory      = theCurrentStory % theItemCount;
		theStorySummary      = theSummaries[theCurrentStory].replace(/&quot;/g,'"');		
		// theTargetLink        = theSiteLinks[theCurrentStory];
		// theAnchorObject.href = theTargetLink;
		// thePrefix 	     = "<span class=\"tickls\">" + theLeadString + "</span>";
	}
	// Stuff the current ticker text into the anchor
	// theAnchorObject.innerHTML = thePrefix + 
	theAnchorObject.innerHTML = theStorySummary.substring(0,theCurrentLength) + whatWidget();
	// Modify the length for the substring and define the timer
	if(theCurrentLength != theStorySummary.length)
	{
		theCurrentLength++;
		myTimeout = theCharacterTimeout;
	}
	else
	{
		theCurrentLength = 0;
		myTimeout = theStoryTimeout;
	}
	// Call up the next cycle of the ticker
	setTimeout("runTheTicker()", myTimeout);
}

// Widget generator
function whatWidget()
{
	if(theCurrentLength == theStorySummary.length) return "";
	if((theCurrentLength % 2) == 1) return "_";
	else return "-";
}
/******************* end news ticker functions ********************/


//DOM  Functions Start
function toggle_Box(id){
	var element = document.getElementById(id);
	if(element.style.display == '') element.style.display = 'none';
	if(element.style.display == 'block')
		element.style.display = 'none';
	else
		element.style.display = 'block';
}
//DOM Functions End



function init()
{
	if (!document.getElementById) return;
	
	// register the objBody
	objBody = document.getElementsByTagName("body").item(0);
	
	// register the original window title
	document.oTitle = document.title;
	
	// inserted modification to allow default form focus to happen
	if (document.ffocus!=undefined && document.forms[0]!=undefined && document.forms[0][document.ffocus]!=undefined) {
		document.forms[0][document.ffocus].focus();
	}
	
	// inserted modification to show scriptonly hidden divs
	var allDivs = document.getElementsByTagName('div');
	for (var i = 0; i < allDivs.length; i++) {		
		if (allDivs[i].className == 'scriptonly') { allDivs[i].style.visibility = "visible"; }
	}
	
	// start rotating
	if (document.rotateLength>0 && document.isIndex) {
		document.c_rotate = 0;
		document.c_ad = 0;
		setTimeout( "loadNew()", 500 );
	}
	
	// create a one-month cookie verifying javascript
	var expireDate = new Date ();
	expireDate.setDate(expireDate.getDate()+30);
	document.cookie = "js_enabled=true; expires=" + expireDate.toGMTString() + "; path=/; domain=" + _DOMAIN;
	
	// set timeout for session tracker if applicable
	if (document.trackSessions) resetSessionTimer();
	
	// init interval for idle checking
	var idleInterval = setInterval( "increaseIdle()", 1000 );
	
	// start the ticker.
	var tickObj = document.getElementById("ticker");
	if (typeof(tickObj)!='undefined' && tickObj!=null) startTicker();
	
	// initialise all image rollovers
	initRollovers();
	
	// if we're using IE <= 6, then resolve PNGs - this will kill some existing rollovers, so run a fixer function after
	if (isIE && !gtIE6) {
		resolvePNGs();
		fixIE6Rollovers();
	}
}

// DOMLoaded script courtesy of Rob Cherny, http://www.cherny.com/webdev/24/domloaded-script
var DomLoaded =
{
	onload: [],
	loaded: function()
	{
		if (arguments.callee.done) return;
		arguments.callee.done = true;
		for (i = 0;i < DomLoaded.onload.length;i++) DomLoaded.onload[i]();
	},
	load: function(fireThis)
	{
		this.onload.push(fireThis);
		if (document.addEventListener) 
			document.addEventListener("DOMContentLoaded", DomLoaded.loaded, null);
		if (/KHTML|WebKit/i.test(navigator.userAgent))
		{ 
			var _timer = setInterval(function()
			{
				if (/loaded|complete/.test(document.readyState))
				{
					clearInterval(_timer);
					delete _timer;
					DomLoaded.loaded();
				}
			}, 10);
		}
		/*@cc_on @*/
		/*@if (@_win32)
		var proto = "src='javascript:void(0)'";
		if (location.protocol == "https:") proto = "src=//0";
		document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
		var script = document.getElementById("__ie_onload");
		script.onreadystatechange = function() {
		    if (this.readyState == "complete") {
		        DomLoaded.loaded();
		    }
		};
		/*@end @*/
	   window.onload = DomLoaded.loaded;
	}
};
window.onload = init;

document.onmousemove = updateIdle;
document.onmousewheel = updateIdle;
document.onkeydown = updateIdle;
