var xmlhttp = false;
var handlerUrl = 'ConfigHandler.ashx';
var waitForContent = false;
var waitForConfigurator = false;
var removingGarbage = false;

try{ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e){}
try{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){}
try{ xmlhttp = new XMLHttpRequest(); } catch(e){}

if( !xmlhttp ) 
    alert('Your browser does not support XMLHTTPRequest!');

function SendMessage( message, parameters )
{   
    // if we are waiting response from configurator OR from content -> bounce back!
    // STA: re-added this to keep config and content requests in sync when web latency!
    //if( waitForConfigurator || (waitForContent && contentLoading) )
    //    return;

    // SHE: if we wait for content we cannot use callback coming from the server..
    if( waitForConfigurator )
        return;
        
    // hide the sticks if they are visible..
    if (message != "prepareReport" ) // no hide if prepareReport (MTV20100324)
    {
        HideMeasures();
    }
    
    var url = handlerUrl + '?CMD=';
    if( parameters == null )
        url += message;
    else
        url += message + ':' + parameters;

	xmlhttp.open( 'GET', url, true );
	
	xmlhttp.onreadystatechange = function()
	{
		if( xmlhttp.readyState == 4 )
			if( xmlhttp.status == 200 )
				ReceiveResponse();
	}
  	
	waitForConfigurator = true;
	xmlhttp.send( null );
	
	// HideMessage();
}

function ReceiveResponse()
{
	var actionReport = xmlhttp.responseXML;

	// config message is handled -> no more waiting!
	waitForConfigurator = false;
	
	handleSessionTimeout(actionReport);
	handleInstallation( actionReport );
	handleRemoveLegality( actionReport );
	handleError( actionReport );
	handleConfirm( actionReport );
	handleInitialize( actionReport );
	handleRemove( actionReport );
	handleShowAllowedItems( actionReport );
	handleBoundingBoxes( actionReport );
	handleUpdateActiveGroups( actionReport );
	handleConfigType( actionReport );
	handleShowConfigInfo( actionReport );
	handleShowAllowedMaterials( actionReport );
	handleShowMessage( actionReport );
	handleWarnIgnoreContent( actionReport );
	handleUpdateContent( actionReport );
	handleShowMeasure(actionReport);

	handlePrepareReport(actionReport);
	handleCheckLegality(actionReport);

	if (engine == "unity") {
	    handleShowMeasureSticks(actionReport);
	}
	
    //library-options div hajoaa MAterialWriterin kanssa, jos handleHtmlWriter on handleCallJSFunc:n jälkeen!
	handleHtmlWriter( actionReport );

	handleCallJSFunc( actionReport );
	handleLoadRoomCount( actionReport );
	handleAutoInstantiateFirstPlacer( actionReport );
	
	// Replace all these...
	handleMainCategories( actionReport );
	handleRoomInfoTexts( actionReport );
	handleDynamicButtons( actionReport );
	// with this:
	//handleHtmlWriter( actionReport );

	handleClientProperties( actionReport );
	handleSaveDone( actionReport );
	handleApplicationMode( actionReport );

	//handleCenterView( actionReport );
	
	handleOpenReport( actionReport );
	
	
	

}

function handleSessionTimeout(actionReport) {

    var message = getMessage('SessionTimeout', actionReport);
    if (message != null) {
        if (confirm(message)) {
            window.location.reload(false);  // reload if agreed..
        }
    }
}

function handleLoadRoomCount (actionReport)
{
    var message = getMessage( 'LoadCombination', actionReport );  
    if( message != null ) {
        ShowMessage(message);
    }
}

function handleAutoInstantiateFirstPlacer( actionReport )
{
    var message = getMessage( 'AutoInstantiateFirstPlacer',actionReport );
    if( message != null && message == '1' )
        SendMessage( 'updateLibrary' );
}

function handleHtmlWriter (actionReport)
{
    // get all the actions...
    var actionsToHandle = actionReport.getElementsByTagName( "HtmlWriter" );
    
    var data = new Array(actionsToHandle.length);
    for( var i=0; i< actionsToHandle.length; i++ )
    {
        var currentAction = actionsToHandle[ i ];   
        var message = "";
        var messageAttribute = currentAction.attributes[ 1 ];
        var targetTypeAttribute = currentAction.attributes[ 2 ];
        var targetDivAttribute = currentAction.attributes[ 3 ];

        var targetType = "";
        var targetDiv = "";
        
    
        if( messageAttribute.value != "" )
        {
            // Append text only
            message = messageAttribute.value;
        }
        else
        {
            for( var j = 0; j < currentAction.childNodes.length; j++ )
            {
                // Appent xhtml
                var content = currentAction.childNodes[ j ];
                if( content.xml == null ) { // FF
                    var serializer = new XMLSerializer();
                    message += serializer.serializeToString(content);
                }
                else // IE
                    message += content.xml;
            }
        }
        
        if( targetTypeAttribute != null && targetTypeAttribute.value != "" )
        {
            targetType = targetTypeAttribute.value;
        }

        if( targetDivAttribute != null && targetDivAttribute.value != "" )
        {
            targetDiv = targetDivAttribute.value;
        }
        //alert("handleHtmlWriter:\n" + "- targetDiv: " + targetDiv + "\n- message:\n" + message);

        message = message.replace('&amp;','&');
        
        data[i] = [targetDiv, message];

        var cdiv = document.getElementById( targetDiv );
        cdiv.innerHTML = message;
    }
    // This updates Layout (Osku's script)
	setHeight(true);

}

function handleMainCategories (actionReport)
{
    var message = getMessage( 'GenerateHtmlList', actionReport );  
    if( message != null ) {
        GenerateMainCategories( message );
    }
}

function handleShowMeasureSticks(actionReport) {
    var message = getMessage('ShowMeasureSticks', actionReport);
    if (message != null) {
        ShowMeasureSticks(message);
    }
}

function handleCheckLegality(actionReport) {
    var message = getMessage('CheckLegality', actionReport);
    if (message != null) {
        CheckLegality(message);
    }
}


function handleRoomInfoTexts (actionReport)
{
    var message = getMessage( 'ShowRoomInfo', actionReport );  
    if( message != null ) {
        ShowRoomInfo( message );
        //WriteRoomInfo( message );
    }
}

function handleDynamicButtons (actionReport)
{
    var message = getMessage( 'GenerateHtmlTransitions', actionReport );  
    if( message != null ) {
        WriteButtons( message );
    }
}

function handleSaveDone(actionReport)
{
    var message = getMessage( 'SavePuzzle', actionReport );  
    if( message != null ) {
        SaveFinished(message);
    }
}


function handlePrepareReport(actionReport) {
    var message = getMessage('prepareReport', actionReport);
    if (message != null) {
        prepareReport(message);
    }
}

function handleUpdateActiveGroups (actionReport)
{
    var message = getMessage( 'UpdateActiveGroups', actionReport );  
    if( message != null ) {
        UpdateActiveGroups( message );
    }
}

function handleInstallation( actionReport )
{
    var message = getMessage( 'ShowInstallationInfo', actionReport );  
    if( message != null ) {
        //CreateInstallationInfo( message );
    }
}

function handleRemoveLegality( actionReport )
{
    var message = getMessage( 'CheckRemoveLegality', actionReport );  
    if( message != null ) {
        InformRemoveLegality( message );
    }
    
}

function handleConfirm( actionReport )
{
    var message = getMessage( 'ShowConfirm', actionReport );  
    if( message != null ) {
        ShowConfirmDialog( message );
    }
}

function handleError( actionReport )
{
    var message = getMessage( 'ConfigError', actionReport );  
    if( message != null ) {
        message = message.replace('&amp;','&');
        alert( message );
    }
    // Use this to show message instead of alert
    //ShowError(message);
}

function handleBoundingBoxes( actionReport )
{
    var message = getMessage( 'ResolveBoundingBox', actionReport );
    if( message != null ) {
        AddBoundingBox( message );
    }
}

function handleConfigType( actionReport )
{
    var message = getMessage( 'ResolveConfigType', actionReport );
    if( message != null ) {
        SetConfigType( message );
    }
}

function handleShowConfigInfo( actionReport )
{
    var message = getMessage( 'ShowConfigInfo', actionReport );
    if( message != null ) {
        ShowConfigInfo( message );
    }
}

function handleCallJSFunc( actionReport )
{
    // get all the actions...
    var actionsToHandle = actionReport.getElementsByTagName( "CallJavaScript" );
    
    var data = new Array(actionsToHandle.length);
    for( var i=0; i< actionsToHandle.length; i++ )
    {
        var currentAction = actionsToHandle[ i ];
        var message = currentAction.attributes[ 1 ].value;
        eval( message );
    }
} 


function handleClientProperties( actionReport )
{   
    var message = getMessage( 'SetClientProperties', actionReport );  
    if( message != null ) {
        //WindowResized(); // sent the client parameters to the server.
        StartApplication();
    }
}

function handleInitialize( actionReport )
{   
    var message = getMessage( 'VvoInitializeApp', actionReport );  
    if( message != null ) {
        //WindowResized(); // sent the client parameters to the server.
        StartApplication();
    }
}

function handleShowAllowedMaterials( actionReport )
{
    var message = getMessage( 'GetAllowedMaterials', actionReport );
    if( message != null ){
        
        ShowAllowedItems( message );
    }
}

function handleShowAllowedItems( actionReport )
{
    var message = getMessage( 'ShowAllowedItems', actionReport );
    if( message != null ){
        ShowAllowedItems( message );
    }
}

function handleShowMeasure( actionReport )
{
    var message = getMessage( 'ShowMeasure', actionReport );
    if( message != null ){
        ShowMeasure( message );
    }
}

function handleShowMessage( actionReport )
{
    var message = getMessage( 'ShowMessage', actionReport );
    if( message != null ){ 
        ShowMessage( message ); 
    }
}

function handleWarnIgnoreContent( actionReport )
{
    var message = getMessage( 'WarnIgnoreContent', actionReport );
    if( message != null ){
        ShowErrorMessage( message );
    }
} 

function handleUpdateContent( actionReport )
{
    var message = getMessage( 'UpdateContent', actionReport );
    if( message != null )
    {
        if( message == 'update' )
        {
            waitForContent = true;
            UpdateContent();
        }
        else if( message == 'refresh' )
        {
            waitForContent = true;
            RefreshContent();
        }
    }
}

function handleRemove( actionReport )
{
    var message = getMessage( 'RemoveSelected', actionReport );
    if( message != null ) {
       ShowErrorMessage( message );
    }
}


function handleApplicationMode( actionReport )
{
    var message = getMessage( 'InitApplicationMode', actionReport );
    if( message != null ) {
        //ShowError( message );
        initApplicationMode(message);
    }
}

function handleOpenReport( actionReport )
{
    var message = getMessage( 'OpenReport', actionReport );
    if( message != null ) {
        //ShowError( message );
        OpenReport();
    }
}

function getMessage( key, actionReport )
{
    var actionsToHandle = actionReport.getElementsByTagName( key );
    var message = null;
    
    if( actionsToHandle.length > 0 )
    {
        var messageAttribute = actionsToHandle[ 0 ].attributes[ 1 ];
    
        if( messageAttribute != null )
            message = messageAttribute.value;
        else
            message = actionsToHandle[ 0 ].childNodes[ 0 ].xml;
    }
        
    return message;
}

function ShowFlashMessage(id) {
    var message;
    switch(id) {
        case 1:
            message=FlashmessageText1;
            break;
        case 2:
            message=FlashmessageText3
            break;
        case 3:
            message=FlashmessageText2;
            break;
        default:
            message="messageid not defined!";
    }
    
    ShowMessage(message);
}
