var History;

(function(window,undefined)
{
	History = window.History; // Note: We are using a capital H instead of a lower h
	// Establish Variables
	var State = History.getState();
//	var $log = $('#log');

	// Log Initial State
//	History.log('initial:', State.data, State.title, State.url);

	// Bind to State Change
	History.Adapter.bind(window,'statechange',function()
	{ // Note: We are using statechange instead of popstate
//		// Log the State
		var StateObj = History.getState(); // Note: We are using History.getState() instead of event.state
//		alert( "location: " + document.location + ", state: " + JSON.stringify( StateObj )); 
//		alert( State.data.contentId );
		loadContent( StateObj.data.contentId, StateObj.data.contentURL, 0 );
//		$.get( State.url + '.js' + "?direction=" + direction, function(){}, 'script');
//		History.log('statechange:', State.data, State.title, State.url);
//		alert( 'test2' );
	});
})(window);

function dialog( url )
{
	window.open( url, 'destination', 'width=650,height=500' );
}

function commit()
{
//	window.opener.location.reload();
//	window.opener.frugalform.submit();
//	window.opener.update();
	window.close();
}

function setClass( id, color )
{
	var node = document.getElementById( id );
	node.className=color;
}

//function onChangeDestination( inPage, inDestinationId )
//{
//	var url = "summary.php";
	
//	if( inDestinationId != "-1" )
//	{
//		url = inPage + "?destination=" + inDestinationId;
//	}
		
//	window.location=url;
//}

/*==========================================================================#
# * Function for adding a Filter to an Input Field                          #
# * @param  : [filterType  ] Type of filter 0=&gt;Alpha, 1=&gt;Num, 2=&gt;AlphaNum   #
# * @param  : [evt         ] The Event Object                               #
# * @param  : [allowDecimal] To allow Decimal Point set this to true        #
# * @param  : [allowCustom ] Custom Characters that are to be allowed       #
#==========================================================================*/
function filterInput( filterType, evt, allowDecimal, allowCustom )
{
	var keyCode, Char, inputField, filter = '';
	var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var num = '0123456789';

	// Get the Key Code of the Key pressed if possible else - allow
	if( window.event )
	{
		keyCode = window.event.keyCode;
		evt = window.event;
	}
	else if( evt )
	{
		keyCode = evt.which;
	}
	else
	{
		return true;
	}

	// Setup the allowed Character Set
	if( filterType == 0 ) { filter = alpha; }
	else if( filterType == 1 ) { filter = num; }
	else if( filterType == 2 ) { filter = alpha + num; }
	if( allowCustom ) { filter += allowCustom; }
	if( filter == '' ) { return true; }

	// Get the Element that triggered the Event
	inputField = evt.srcElement ? evt.srcElement : evt.target || evt.currentTarget;
	// If the Key Pressed is a CTRL key like Esc, Enter etc - allow
	if( keyCode == null || keyCode == 0 || keyCode == 8 || keyCode == 9 || keyCode == 13 || keyCode == 27 )
	{
		return true;
	}
	// Get the Pressed Character
	Char = String.fromCharCode( keyCode );
	// If the Character is a number - allow
	if( ( filter.indexOf( Char ) > -1 ) )
	{
		return true;
	}
	// Else if Decimal Point is allowed and the Character is '.' - allow
	else if( filterType == 1 && allowDecimal && ( Char == '.' ) && inputField.value.indexOf( '.' ) == -1 )
	{
		return true;
	}
  else { return false; }
}

function postCommand( inURL, inData )
{
	var request = null;
	if( window.XMLHttpRequest ) // If IE7, Mozilla, Safari, and so on: Use native object.
	{
		request = new XMLHttpRequest();
	}
	else if( window.ActiveXObject ) // ...otherwise, use the ActiveX control for IE5.x and IE6.
	{
		request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
	}
	
	request.open( "post", inURL, true );
	
	request.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
	request.setRequestHeader( "Content-length", inData.length );
	request.setRequestHeader( "Connection", "close" );

	request.onreadystatechange = function()
	{
		if( request.readyState == 4 )
		{
			alert( request.responseText );
		}
	}
	request.send( inData );
}

function loadContent( inContentId, inURL, inAddWait, inHistoryData )
{
	var contentPane = document.getElementById( inContentId );
	
	// Show the wait indicator...
	if( inAddWait != 0 )
	{
		contentPane.innerHTML += '<div style="position:absolute;top:5px;left:5px;"><img src="/static/site/wait16.gif"/></div>';
	}

	var request = new XMLHttpRequest();
	request.open( "get", inURL, true );
	
//	alert( inURL );
	
//	request.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
//	request.setRequestHeader( "Content-length", inData.length );
//	request.setRequestHeader( "Connection", "close" );

	request.onreadystatechange = function()
	{
		if( request.readyState == 4 )
		{
//			var node = document.getElementById( inContentId );
//			alert( node );
//			alert( request.responseText );
			contentPane.innerHTML=request.responseText;
			
			if( inHistoryData )
			{
//				alert( inHistoryURL );
		
//				History.log('initial:', State.data, State.title, State.url);
				var stateObj = { contentId: inContentId, contentURL: inURL };
//				History.pushState( stateObj, "Problem Test", inHistoryURL );
				if( inHistoryData.replace )
				{
					History.replaceState( stateObj, inHistoryData.title, inHistoryData.url ); // logs {state:1,rand:"some random value"}, "State 1", "?state=1"',
				}
				else
				{
					History.pushState( stateObj, inHistoryData.title, inHistoryData.url ); // logs {state:1,rand:"some random value"}, "State 1", "?state=1"',
				}
			}
		}
	}
	request.send();
}

// Menu functions
var timeout	= 250;
var closetimer	= 0;
var ddmenuitem	= 0;

function mopen(id)
{	
	mcancelclosetime();

	if( ddmenuitem ) ddmenuitem.style.visibility = 'hidden';

	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';
}

function mclose()
{
	if( ddmenuitem ) ddmenuitem.style.visibility = 'hidden';
}

function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 

/*

Resize map div.

*/
function sizeMap( inReservedWidth, inDestination )
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' )
  { //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  }
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
  { //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  }
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
  { //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  if( myWidth < 800 )
	{
		myWidth = 800;
	}

	var headerHeight = 85;
	if( inDestination )
	{
		headerHeight += 24;
	}
  
	mapDiv = document.getElementById( "map" );
	mapDiv.style.height = ( myHeight - headerHeight ) + "px"	;
	mapDiv.style.width = ( myWidth - inReservedWidth ) + "px"	;
}

function sizeProblemNavigator()
{
	navDiv = document.getElementById( "problemNav" );
	if( null != navDiv )
	{
		var myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' )
		{ //Non-IE
			myHeight = window.innerHeight;
		}
		else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
		{ //IE 6+ in 'standards compliant mode'
			myHeight = document.documentElement.clientHeight;
		}
		else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
		{ //IE 4 compatible
			myHeight = document.body.clientHeight;
		}

		// 85 = header, 24 = destination header, 34 = filter.
		var headerHeight = 85 + 24 + 34;

		navDiv = document.getElementById( "problemNav" );
		navDiv.style.height = ( myHeight - headerHeight ) + "px"	;
	}
}

function toggleSends( inCheckBox, inTextBox )
{
	var checkBox = document.getElementById( inCheckBox );
	var textBox = document.getElementById( inTextBox );
	if( checkBox.checked )
	{
		textBox.innerHTML = "1";
		textBox.disabled= false;
	}
	else
	{
		textBox.innerHTML = "0";
		textBox.disabled = true;
	}
}
