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 (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);

		/*
   	$.ajax({
   		url: url,
   		type: "GET",
   		cache: false,
   		async: false,
   		dataType: 'xml',
   		success: function (xml) {
   			ReceiveResponse(xml);
   		}
   	});
	*/
}

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 );

	handleJavaScriptBlocks(actionReport);
}

function handleJavaScriptBlocks(actionReport) {
	$('script#initScript', actionReport).each(function (index) {
		eval($(this).text());
	});
}

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) {
	$(actionReport).find('HtmlWriter').each(function () {
		var message = $(this).attr('Message');
		if (message == null || message.length == 0) {
			message = ''; // null out the 'undefined'..
			var currentAction = $(this)[0];
			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;
			}
			message = message.replace('&amp;', '&');
		}


		// resolve target..
		var target = $('#' + $(this).attr('TargetName'));

		// resolve type..
		var type = $(this).attr('TargetType');
		if (type == null)
			target.html(message);
		else {
			switch (type) {
				case 'append':
					target.append(message);
					break;

				case 'replace':
					target.replaceWith(message);
					break;

				default:
					target.html(message);
			}
		}
	});

    // update layout.
    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 {
          // ie or non-ie
          if(actionsToHandle[ 0 ].childNodes[ 0 ].textContent == undefined)
            message = actionsToHandle[ 0 ].childNodes[ 0 ].xml;
          else
            message = actionsToHandle[ 0 ].childNodes[ 0 ].textContent;
        }
        
    }
        
    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);
}

