//------------------

window.onload = _OnLoadHandler;
var window_loaded=false, on_load_list = [];

function RunOnLoad(code)
{
	on_load_list.push(code);
}

function _OnLoadHandler()
{
	window_loaded = true;
	for(var i=0 ; i<on_load_list.length ; i++)
	{
		if(typeof(on_load_list[i])=='function')
			on_load_list[i]();
		else
			eval(on_load_list[i]);
	}
}

//------------------

function createCookie(name,value,del) {
	if (del) {
		var date = new Date();
		date.setTime(date.getTime()-86400000);
		var expires = "; expires="+date.toGMTString();
	}
	else {
		var date = new Date();
		date.setTime(date.getTime()+2592000000);
		var expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/; domain=.xfire.com";
}

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;
}

function eraseCookie(name) {
	createCookie(name,"",1);
}

//------------------

Function.prototype.Inherits = function(parent)
{
	this.prototype = new parent();
	this.prototype.constructor = this;
	this.prototype.parent = parent.prototype;
}

//------------------
// args are appended to any existing args

function BindMethod(object, method) // [, args][, args]
{
    if(!(method instanceof Function))
		method = object[method];
	if(arguments.length<=2)
	    return function () {return method.apply(object, arguments);}

	var fixed_args = [];
	for(var i=2 ; i<arguments.length ; i++)
	    fixed_args.push(arguments[i]);
    return function ()
	{
		var args = [];
		for(var i=0 ; i<arguments.length ; i++)
		    args.push(arguments[i]);
		for(var i=0 ; i<fixed_args.length ; i++)
		    args.push(fixed_args[i]);
		return method.apply(object, args);
	}
}

//------------------

function GetObjStyle(obj, style)
{
	var value = obj.style[style];
	if(value)
	    return value;
	if(obj.currentStyle)
		value = obj.currentStyle[style];
	else if(document.defaultView.getComputedStyle)
		value = document.defaultView.getComputedStyle(obj, null).getPropertyValue(style);
	return value;
}

//------------------

function GetObjPos(obj)
{
	var x = obj.offsetLeft, y = obj.offsetTop;
	while((obj = obj.offsetParent))
	{
		x += obj.offsetLeft;
		y += obj.offsetTop;
	}
	return [x, y];
}

//------------------

function GetPageScrollX()
{
	var pos;
	if(self.pageXOffset)
		pos = self.pageXOffset;
	else if(document.documentElement && document.documentElement.scrollLeft)	 // ie6 Strict
		pos = document.documentElement.scrollLeft;
	else if(document.body) // ie other
		pos = document.body.scrollLeft;
	return pos;
}

//------------------

function GetPageScrollY()
{
	var pos;
	if(self.pageYOffset)
		pos = self.pageYOffset;
	else if(document.documentElement && document.documentElement.scrollTop)	 // ie6 Strict
		pos = document.documentElement.scrollTop;
	else if(document.body) // ie other
		pos = document.body.scrollTop;
	return pos;
}

//------------------

function GetPageWidth()
{
	return document.body.offsetWidth;
}

function GetPageHeight()
{
	return Math.max(GetViewportHeight(), document.body.clientHeight);
}

function GetViewportWidth()
{
	var width = window.innerWidth || document.documentElement.clientWidth;
	return Math.min(GetPageWidth(), width); // use the smaller to eliminate scrollbars in FF
}

function GetViewportHeight()
{
	return window.innerHeight || document.documentElement.clientHeight;
}

//------------------
// don't use this if you want to show something after obscuring, use CenterAndShow() below
function Center(obj)
{
	obj.style.left = (GetPageScrollX() + (GetViewportWidth()-obj.clientWidth)/2) +"px";
	obj.style.top = (GetPageScrollY() + (GetViewportHeight()-obj.clientHeight)/2) +"px";
}


//------------------
// this also takes care of the firefox 2.0 bug where the zindex is (at least partially) ignored
// use this function to show a window after obscuring.
function CenterAndShow(obj)
{
	if(!window_loaded)
	{
		var browser = navigator.userAgent.toLowerCase();
		if(browser.indexOf('msie')!=-1)
		{
			// ie will crash if we use appendChild() before loaded
			RunOnLoad(function() { CenterAndShow(obj); });
			return;
		}
	}
	
	if(obj.parent)
		obj.parent.removeChild(obj);
	document.body.appendChild(obj);
	obj.style.visibility = 'hidden';
	obj.style.display = 'block';
	Center(obj);
	obj.style.visibility = 'visible';
}

//------------------
// Form-related functions

function FormSetChecked(form, name_prefix, checked)
{
	for(var i=0 ; i<form.length ; i++)
	{
	    var element = form.elements[i];
	    var name = element.getAttribute('name');
	    if(name)
			name = name.substring(0, name_prefix.length);
	    if(name!=name_prefix)
	        continue;
		element.checked = checked;
	}
}

//-------------------------

function SetBlockVisible( block_name )
{
	block_object = document.getElementById( block_name );
	
	block_object.style.display = 'block';
}

function SetBlockHidden( block_name )
{
	block_object = document.getElementById( block_name );
	
	block_object.style.display = 'none';
}

//--------------------------------------

function HideSelects(form, hide)
{
	var o = form.getElementsByTagName('select');
	for(var i=0; i<o.length; i++)
	{
		o[i].style.visibility = (hide? 'hidden' : '');
	}
}

//--------------------------------------

function GetElements(obj, tag, name)
{
	if(!obj.getElementsByTagName)
	    return null;
	var bytag = obj.getElementsByTagName(tag);
	var byname = [];
	for(var i=0 ; i<bytag.length ; i++)
	{
	    if(bytag[i].getAttribute('name')==name)
		    byname.push(bytag[i]);
	}
	return byname;
}

//--------------------------------------

function GetFirstChild(obj, tag, name)
{
	for(var i=0 ; i<obj.childNodes.length ; i++)
	{
	    var child = obj.childNodes[i];
	    if(!tag || (child.tagName && child.tagName==tag))
	    {
		    if(!name || (child.getAttribute('name')==name))
		    {
		        return child;
		    }
	    }
	    var grandchild = GetFirstChild(child, tag, name);
	    if(grandchild)
	        return grandchild;
	}
	return null;
}

//--------------------------------------
// ads
var hide_ads_nest = 0;

function HideAds(auto)
{
	if(!auto)
		hide_ads_nest++;
	else if(hide_ads_nest==0)
		return;
	if(hide_ads_nest>1)
	    return;
	if(!auto && !window_loaded)
	{
		setTimeout("HideAds(1);", 500);
		RunOnLoad("HideAds(1);");
		return;
	}
	var list = GetElements(document, 'DIV', 'advert');
	for(var i=0 ; i<list.length ; i++)
	{
	    var obj = list[i];
	    obj.style.display = 'none';
	}
}

//------------------

function ShowAds()
{
	hide_ads_nest--;
	if(hide_ads_nest>0)
	    return;
	var list = GetElements(document, 'DIV', 'advert');
	for(var i=0 ; i<list.length ; i++)
	{
	    var obj = list[i];
	    obj.style.display = '';
	}
}

//--------------------------------------
// PAGE OBSCURER: opacity=0.0-1.0, fade_time=ms
var obsc_id, obsc_close_callback, obsc_opacity, obsc_fade_time,
	obsc_fader, obsc_hiding;

function obsc_Show(opacity, fade_time, close_callback, obj_id)
{
	obsc_id = obj_id;
	if(!obsc_id)
	    obsc_id = "obsc_default";
	obsc_opacity = opacity;
	obsc_fade_time = fade_time;
	obsc_close_callback = close_callback;
	obsc_ShowObj();
}

//------------------

function obsc_ShowObj()
{
	var obj = document.getElementById(obsc_id);
	if(!obj)
	{
		if(!window_loaded)
		{
			var browser = navigator.userAgent.toLowerCase();
			if(browser.indexOf('msie')!=-1)
			{
			    // ie will crash if we use appendChild() before loaded
				RunOnLoad(obsc_ShowObj);
				return;
			}
		}
	    obj = document.createElement("div");
		obj.id = obsc_id;
		obj.onclick = obsc_Hide;
		document.body.appendChild(obj);
	}
	obj.style.height = GetPageHeight()+"px";
	obj.style.display = 'block';
	obsc_fader = 0;
	obsc_Fade(true);
	// expand after page loads
	if(!window_loaded)
	{
	    var code = "document.getElementById('"+obsc_id+"').style.height = GetPageHeight()+'px';";
		setTimeout(code, 2000);
		RunOnLoad(code);
	}

	/* FF2.0 hack! zIndex is ignored, must re-append the chooser after the obscurer in the dom - laaaaame. -Van http://bugs.corp.xfire.com/show_bug.cgi?id=10388 */
	/* This hack is now done more generically with CenterAndShow() */
}

//------------------

function obsc_Hide()
{
	if(obsc_hiding)
	{
		obsc_hiding = 2;
	    return;
	}
    obsc_hiding = 1;
	if(obsc_close_callback)
	{
	    obsc_close_callback();
	}
	// only hide if the callback called hide
	if(!obsc_close_callback || obsc_hiding==2)
	{
		obsc_Fade(false);
		obsc_close_callback = null;
	}
    obsc_hiding = 0;
}

//------------------

function obsc_Fade(fade_in)
{
	var obj = document.getElementById(obsc_id);
	if(!obj)
		return;
	var adjust = obsc_opacity*(obsc_fade_time? 5000/24/obsc_fade_time : 1);
	if(fade_in)
	{
		obsc_fader += adjust;
		if(obsc_fader>obsc_opacity)
			obsc_fader = obsc_opacity;
	}
	else
	{
		obsc_fader -= adjust;
		if(obsc_fader<=0)
		{
			obj.style.display = 'none';
			return;
		}
	}
	obj.style.opacity = obsc_fader; // FF
	obj.style.filter = "alpha(opacity="+parseInt(obsc_fader*100)+")"; // IE
	if(fade_in && obsc_fader==obsc_opacity);
	else if(!obsc_fade_time);
	else
		setTimeout("obsc_Fade("+fade_in+")", 5000/24);
}

//--------------------------------------
// DEBUGGING
var dbg_dump_win, dbg_dump_parents=false, dbg_dump_functions=true, dbg_dump_nest=0, dbg_dump_nest_max=4;

function DBG_Dump()
{
	dbg_dump_win = window.open();
	dbg_dump_win.document.open();
	dbg_dump_win.document.write("<b>DBG_Dump() called by:</b><br>"+DBG_Dump.caller.toString().replace(/\n/g, '<br>').replace(/    /g, '&nbsp; &nbsp; ').replace(/DBG_Dump/g, '<b>DBG_Dump</b>'));
	dbg_dump_win.document.write("<hr>");
	for(var i=0 ; i<arguments.length ; i++)
	{
	    var item = arguments[i];
		DBG_Dumper(item, '');
	    if(!dbg_dump_win)
	        break;
	}
	if(dbg_dump_win)
	{
		dbg_dump_win.document.close();
		dbg_dump_win.focus();
		dbg_dump_win.close;
		dbg_dump_win = null;
	}
}

function DBG_Dumper(item, name)
{
	try
	{
		var output='';
		dbg_dump_nest++;

	    switch(typeof(item))
		{
		case 'object':
			var prefix = (name? "[<b>"+name+"</b>] = " : "") + "(OBJECT)";
			if(dbg_dump_nest>=dbg_dump_nest_max)
			{
				output += prefix;
			    break;
			}
			if(!dbg_dump_parents && (name=='all' || name=='document' || name=='ownerDocument' || name=='parentElement' || name=='parentNode' || name=='parentTextEdit' || name=='offsetParent'))
			{
				output += prefix;
			    break;
			}
			var any;
			// objects come last
			for(var objects=0 ; objects<2 ; objects++)
			{
		        for(key in item)
		        {
		            if(!any)
		            {
		                any = true;
						output += "<b>"+prefix+"</b><br>";
						output += "<blockquote style='border:1px solid black; margin:6px; padding:4px; margin-left:40px;'>";
					}
		            try
		            {
		                if(objects!=(typeof(item[key])=="object"))
		                    continue;
		                if(!dbg_dump_functions && typeof(item[key])=="function")
		                    continue;
						dbg_dump_win.document.write(output);
						output = "";
						DBG_Dumper(item[key], key);
						if(typeof(item[key])=="undefined")
						    continue;   // can change...?
						output += "<br>";    // newline here
		            }
					catch(e)
		            {
				    	output += "["+key+"] ? [<i>UNABLE TO EVALUATE:"+e.message+"</i>]<br>";
						dbg_dump_win.document.write(output);
						output = "";
		            }
		        }
			}
            if(any)
				output += "</blockquote>";
			else
				output += prefix;
	        break;

		case 'function':
			output += item;
	    	break;

		case 'string':
	    	output += "["+name+"] = \""+item.replace(/</g, "&lt;")+"\"";
	    	break;

		case 'number':
		case 'boolean':
	    	output += "["+name+"] = "+item;
	    	break;

		default:
			output += "["+name+"]("+typeof(item)+") = "+item;
	    	break;
		}
		if(output)
			dbg_dump_win.document.write(output);
		output = "";
		dbg_dump_nest--;
	}
	catch(e)
	{
		output += "<hr>ABNORMAL TERMINATION";
		dbg_dump_win.document.write(output);
		output = "";
		dbg_dump_win.document.close();
		dbg_dump_win.focus();
		dbg_dump_win.close;
		dbg_dump_win = null;
	}
}

//------------------
var dbg_log='', dbg_log_start=null;

function DBG_LogReset(show)
{
	if(show)
	    alert(dbg_log);
	dbg_log = '';
	dbg_log_start = null;
}

function DBG_Log(text)
{
	var date = new Date(), now = date.getTime();
	if(!dbg_log_start)
        dbg_log_start = now;
	dbg_log += parseInt(now-dbg_log_start)+": "+text+"\n";
}

//------------------
// PAGE-SPECIFIC FUNCTIONS

function FilterGameList(obj, estid, filter)
{
	var ul = obj;
	while(ul!=null && ul.tagName!='UL')
	{
	    ul = ul.parentNode;
	}
	
	if(!ul)
	    return;

	var total = ul.childNodes.length;
	for(var i = 0 ; i < total ; i++)
	{
	    var li = ul.childNodes[i];
	    if(li.tagName!='LI')
	        continue;
		if(li.className!='game_overview_filters_disabled')
			li.className = '';
	}
	obj.className = 'game_overview_filters_on';

	Est_FilterRows(estid, filter);
}

function DebugShowAllProperties( object )
{
	var msg = "", i = 0;
	for( var property in image )
	{
		msg += "" + property + " = " + image[property] + "\t\t\t";
		if( i++ > 1 )
		{
			i = 0;
			msg += "\n";
		}
	}
	alert( msg );
	return;
}

//------------------

// sets the img width= tag to enable scaling ONLY when desired size is smaller (downscampling is okay).
// Otherwise, leaves it alone to avoid upsampling (too blocky)
function SetImageSizeConditional( image, maxSize, autoHCenter )
{
	var width, height;
	
	// get image width
	if( typeof( image.naturalWidth ) != "undefined" )
		width = parseInt( image.naturalWidth );
	else width = parseInt( image.width );
	
	if( typeof( image.naturalHeight ) != "undefined" )
		height = parseInt( image.naturalHeight );
	else height = parseInt( image.height );
	
	if( ( width == 0 || height == 0 ) && image.complete == false )
	{
		// IE7 fires image.onload() too soon. Physician, loop thyself.
		// bug #10388
		imageID = image.id;
		setTimeout( "SetImageSizeConditional( document.getElementById( '" + imageID + "' ), " + maxSize + ", " + autoHCenter + " );", 250 );
		return;
	}

	// scale if image exceeds max in either direction
	greater = Math.max( width, height );
	if( greater > maxSize )
	{
		// trigger downsampling
		scale = maxSize / greater;
		width = Math.round( width * scale );
		height = Math.round( height * scale );
		image.width = "" + width;
		image.height = "" + height;
		//alert( "s" + scale + " nw" + width + " nh" + height +  " w" + image.width + " h" + image.height + " max" + maxSize );
	}

	// if width (either original, or re-computed) is under the limit now
	if( width < maxSize && autoHCenter == 1 )
	{
		// auto-hcenter within target size, since we're undersized
		margin = (maxSize - width ) / 2;
		image.style.marginLeft = "" + margin  + "px";
	}
}

// This function will resize images if they are larger than the parent and insert a message above the image
var imageIDCounter = 0;

function SetImageWidthConditional( image )
{
	if( image.complete == false )
	{
		image.setAttribute("id", "img" + imageIDCounter++);
		setTimeout( "SetImageWidthConditional( document.getElementById( '" + image.id + "' ));", 250 );
		return;
	}
	var width, height;
	
	var parent = image.parentNode;
	while(parent.offsetWidth == 0)
		parent = parent.parentNode;
	var parentWidth = parent.offsetWidth;
	image.style.display = "";
	
	if( typeof( image.naturalWidth ) != "undefined" )
		width = parseInt( image.naturalWidth );
	else width = parseInt( image.width );

	if( typeof( image.naturalHeight ) != "undefined" )
		height = parseInt( image.naturalHeight );
	else height = parseInt( image.height );
	
	// scale if image exceeds max in either direction
	var newWidth = parentWidth - 20;
	if( width > newWidth )
	{
		// trigger downsampling
		scale = newWidth / width;
		width = Math.round( width * scale );
		height = Math.round( height * scale );
		image.width = "" + width;
		image.height = "" + height;
		
		var warning_div = document.createElement('div');
		var warning_span = document.createElement('span');
		var warning_a = document.createElement('a');
		
		var warning_txt_node = document.createTextNode("This image has been resized from ");
		var warning_href_txt_node = document.createTextNode("the original");
		
		warning_span.appendChild(warning_txt_node);
		warning_a.appendChild(warning_href_txt_node);
		
		warning_div.appendChild(warning_span);
		warning_div.appendChild(warning_a);

		image.parentNode.insertBefore(warning_div, image);
		warning_div.style.width = (image.width - 10)+ "px";
		warning_div.className = "resized_image_header";
		warning_a.href = image.src;
		warning_a.target = "_blank";
	}

}

//------------------

// Make sure the user is sure they want to make their clan unlimited
function UnlimitedConfirmation()
{
	var form = document.getElementById('clan_prefs');
	if( form )
	{
		// check to see if the user changed their mind and unchecked the box
		// if so, let them without interference.
		if( form['pref_unlimited'] && !form['pref_unlimited'].checked )
			return;
		
    	HideSelects( form, true);
	}
	
    	
	var conf_box = document.getElementById('unlimited_confirmation');
	if( conf_box )
	{
		obsc_Show( 0.5, 75, UnlimitedCancelled );
	    CenterAndShow(conf_box);
	}
}

// This cancels the unlimited selection
function UnlimitedCancelled( box_to_uncheck, box_to_check )
{
	var conf_box = document.getElementById('unlimited_confirmation');
	if( conf_box )
	{
		conf_box.style.display = 'none';
		obsc_Hide();
	}
	var form = document.getElementById('clan_prefs');
	if( form )
	{
		HideSelects( form, false);
		var box = form[box_to_uncheck];
		if( box )
			box.checked = '';
		if ( box_to_check != '' )
		{
			var box = form[box_to_check];
			if ( box )
				box.checked = 'checked';
		}
	}
}

// This confirms the unlimited selection, they are crazy!
function UnlimitedConfirm( other_option_to_check )
{
	var conf_box = document.getElementById('unlimited_confirmation');
	if( conf_box )
	{
		conf_box.style.display = 'none';
		obsc_Hide();
	}
	var form = document.getElementById('clan_prefs');
	if( form )
	{
		HideSelects( form, false);
		var box = form['pref_unlimited'];
		if( box )
			box.checked = 'checked';
		if ( other_option_to_check != '' )
		{
			var box = form[other_option_to_check];
			if ( box )
				box.checked = 'checked';
		}
	}
}

// This makes sure the invite-only/auto-accept options are in line with each other
function InviteOnlyCheck()
{
	var form = document.getElementById('clan_prefs');
	if( form )
	{
		var io = form['pref_invite_only'];
		var aa = form['pref_auto_accept'];
		
		if( io && aa)
		{
			if( io.checked )
			{
				aa.checked = '';
				aa.disabled = 'disabled';

				var aal = document.getElementById('auto_accept_label');
				if( aal )
					aal.className = 'disabled';
			}
			else
			{
				aa.disabled = '';

				var aal = document.getElementById('auto_accept_label');
				if( aal )
					aal.className = '';
			}
		}
	}
}

function ToggleHideShowID(elementID)
{
	var element = document.getElementById(elementID);
	if (element.style.display == 'none')
		element.style.display = '';
	else
		element.style.display = 'none';
}