﻿var reportWin;
var messageTimer = null;
var reportPageUrl = "report.aspx";

function ShowError( message )
{
    alert( message );
}

// dublicate function...?
/*
function ShowAllowedItems( message )
{
    
}
*/

function createARUpload(status, showARNote) {
	// TODO:
	// !!! Check if the file upload works, nested forms were removed !!!
    var html = '<div class="loader" id="lib-options-loader" style="display: none;"><img src="Content/images/loader-wb.gif" alt="Loading..."></div>';
    html += '<div>';

    if (showARNote) {
        html += '	' + j_ARNote;
    }

    //html += '	<form class="ajaxForm" name="form" action="" method="POST" enctype="multipart/form-data">';
    html += '	<div class="ajaxForm">';
    html += '		<p>';
    html += '			<input id="fileToUpload" type="file" size="12" name="myFile" /><br>';
    html += '			<input type="submit" id="buttonUpload" value="' + j_addARPhotoButton + '" />';
    html += '		</p>';
    html += '	</div>';
    //html += '	</form>';
    html += status;
    html += '	<div>';
	html += '		<a href="'+arHelpUrl+'" target="_blank">' + j_downloadARInstructions + '</a><br>';
    html += '		<a href="#" class="ar-printmarker">' + j_printARmarker + '</a>';
    html += '	</div>';
    html += '</div>';

    html = $(html);
    
    $('#library-options').html(html);
    $('a.ar-printmarker').click(function(){ printARMarker(); return false; });
    $('#buttonUpload').click(function(){ return ajaxFileUpload(); });
}

function createARHelp(showARNote) {
    var html = '<div>';
    if (showARNote) {
        html += '	' + j_ARNote;
    }
    html += '	<a href="'+arHelpUrl+'" target="_blank">' + j_downloadARInstructions + '</a><br>';
    html += '	<a href="#" class="ar-printmarker">' + j_printARmarker + '</a>';
    html += '</div>';

    $('#library-options').html($(html));
    $('a.ar-printmarker').click(function(){ printARMarker(); return false; });
}

// REMOVE THIS?
function showARHelp() {
    window.open(arHelpUrl, 'Download');
}

function printARMarker() {
    window.open(arMarkerUrl, 'Download');
}

function ajaxLogin()
{
    var un = $("#un").val();
    var pw = $("#pw").val();
    var handlerUrl = 'loginHandler.ashx?un=' + un + '&pw=' + pw;

    $("#loading")
    .ajaxStart(function() {
        // $(this).show();
    })
    .ajaxComplete(function() {
        // $(this).hide();
    });

    /*
    prepareing ajax file upload
    url: the url of script file handling the uploaded files
    fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
    dataType: it support json, xml
    secureuri:use secure protocol
    success: call back function when the ajax complete
    error: callback function when the ajax failed
			
    */
	
$.ajax({
    url: handlerUrl,
    type: 'POST',
    dataType: 'html',
    timeout: 1000,
    error:function (xhr, ajaxOptions, thrownError)
    { 
        alert('Error: ' + xhr.responseText); 
        //$("#un").val('');
        $("#pw").val('');
    },
    success: function(response){
        checkLogin(response);
        SendMessage('login');
    }
});
	
	

    return false;
    
}

function checkLogin(messagestring) {
	var messages = new Array();
	messages = messagestring.split(";");
	if (messages[0] == "success") {
		ShowMessage(j_welcome + " " + messages[1]);
		$('#loginDiv,#loginButton').hide();
		
		var html = '<div id="userinfo-area">';
		html += '	<p>';
		html += '		<span class="user-info">';
		html += '			'+j_usernametext + ' ' + messages[1];
		html += '		</span>';
		if ( enableRegistration == "true" && messages[3] == "True" )
			html += '		<a href="#" class="profile-edit-link" onclick="editProfile = window.open( \'registration/user/webuser.aspx\',\'editProfile\', \'scrollbars=1;menubar=1,resizable=0,toolbar=0,location=1,status=1,width=550,height=675\' ); editProfile.focus(); return false;" target="_blank" >'+ j_editprofiletext +'</a>';
		if ( messages[2] == "True" )
			html += '		<a href="#" class="maintenance-link" onclick="maintenanceWin = window.open( \'maintenance2/\',\'maintenanceWin\', \'scrollbars=1;menubar=yes,resizable=yes,toolbar=yes,location=yes,status=yes\' ); maintenanceWin.focus(); return false;" target="_blank" >' + j_maintenancetext + '</a>';
		html += '		<a href="logout.aspx" class="logout">' + j_logouttext + '</a>';
		html += '	</p>';
		html += '</div>';
		
		$('#custom-controls').html($(html));
		
		$("#un, #pw").val('');
	}
	else {
		ShowMessage(j_authfailed);
		$("#pw").val('');
	}

}

function ajaxFileUpload() {

    //starting setting some animation when the ajax starts and completes

    $("#lib-options-loader").ajaxStart(function() {
        $(this).show();
        $('.ajaxForm').hide();
    })
    .ajaxComplete(function() {
        $(this).hide();
        $('.ajaxForm').show();
        // update the library view..
        SendMessage('updateLibrary');
    });

    /*
    prepareing ajax file upload
    url: the url of script file handling the uploaded files
    fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
    dataType: it support json, xml
    secureuri:use secure protocol
    success: call back function when the ajax complete
    error: callback function when the ajax failed
			
    */

    var fileName = $("#fileToUpload").val();
    var handlerUrl = 'ARImageUploader.ashx?file=' + fileName;

    $.ajaxFileUpload
    (
			{
			    url: handlerUrl,
			    secureuri: false,
			    fileElementId: 'fileToUpload',
			    dataType: 'xml',
			    success: function(data, status) {
			        if (typeof (data.error) != 'undefined') {
			            if (data.error != '') {
			                alert(data.error);
			            } else {
			                alert(data.msg);
			            }
			        }

			    },
			    error: function(data, status, e) {
			        alert(e);
			    }
			}
		)

    return false;
}
function ShowReportWindow() {
    if (PrepareReport && PrepareReport.toLowerCase() == 'true') {
        SendMessage( "prepareReport" );
    }
    else {
        ExecuteSceneCapture();
    
        // setTimeout('actualOpenReport()', 450);
        actualOpenReport();
	}
}

function actualOpenReport() {
    if (reportWin != null && !reportWin.closed ) {
        reportWin.location = reportPageUrl;
        reportWin.focus();
    }

    m_prepareCapture = false;
}

/*
function prepareReport()
{
    alert('preparera');
}
*/

function CheckLegality( msg ) {
    var fail = true;
    
    var i = msg.indexOf( ":" );
    if ( i != -1 )
    {
        var status = msg.substring( 0, i );
        if ( status == "success" ) {
            ExecuteSceneCapture();                
            actualOpenReport();
        }
        else if ( status == "warning" ) {
            ExecuteSceneCapture();

            // only warn
            var failmsg = msg.substring( i+1 );
            alert( failmsg );

            actualOpenReport();
        }
        else
        {
            reportWin.close();
            var failmsg = msg.substring( i+1 );
            alert( failmsg );
        }
    }
}

function OpenReport() {
    ExecuteSceneCapture();
    //setTimeout('actualOpenReport()', 450);

    actualOpenReport();
}

/*
function prepareReport(message) {
    alert('preparera');
    
    OpenReport();
}
*/

function GenerateMainCategories( message )
{
    var splitted = message.split( ';' );
    var selectedId = splitted[splitted.length-1];
    var html = "<ul>";

    for (i=0; i< splitted.length-1; i++)
    {
        var categoryInfo = splitted[i].split(',');
        if (i == selectedId)
        {
            html += "<li><a href=\"#\" title=\"Valitse huone/tuote kirjastosta\" onclick=\"CategorySelected('" + categoryInfo[0] + "')\" class=\"current\" >" + categoryInfo[1] + "</a></li>";
        }        
        else
        {
            html += "<li><a href=\"#\" title=\"Näytä "+categoryInfo[1]+"\" onclick=\"CategorySelected('" + categoryInfo[0] + "'\)\" >" + categoryInfo[1] + "</a></li>";
        }
    }
    html += "</ul>";

    //alert(html);
    document.getElementById( 'categories' ).innerHTML = html;
}

function WriteRoomInfo( message )
{
    var html = message;
    document.getElementById( 'roominfo' ).innerHTML = html;
}

function WriteButtons( message )
{
    var splitted = message.split( '?' );
    var ulparams = splitted[0].split(":");
    var html = "<ul id=\"" + ulparams[0] + "\" class=\""+ ulparams[1] + "\">\n";

    var buttonsData = splitted[1].split(";");
    for (i=0; i< buttonsData.length; i++)
    {
        var buttonInfo = buttonsData[i].split('#');
        if (buttonInfo[0] != "")
        {
            var funk = "";
            if (buttonInfo[2].indexOf("js:") == 0)
            {
                funk = buttonInfo[2].split(":")[1] + "(";
                if (buttonInfo[3] != null)
                    funk += "'" + buttonInfo[3] + "'";
                funk += ")";
            }
            else
            {
                funk = "SendMessage(\'" + buttonInfo[2] + "\', '" + buttonInfo[3] + "')";
            }
            html += "\t<li id=\"" + buttonInfo[0] + "\"><a href=\"#\" onmouseover=\"showMouseoverInfo('"+buttonInfo[2]+"')\" onmouseout=\"releaseMouseoverInfo('"+buttonInfo[2]+"')\" onclick=\""+ funk + "\">" + buttonInfo[1] + "</a></li>\n";
        }
    }
    html += "</ul>\n\n";
    
    html += "<ul id=\"extra-functions-right\" class=\"extra-functions\">\n" +
                    "\t<li id=\"cameracenter-function\"><a href=\"#\" onmouseover=\"showMouseoverInfo('centerView')\" onmouseout=\"releaseMouseoverInfo('centerView')\" onclick=\"CenterView();\" title=\"Keskitä näkymä\">Keskitä näkymä</a></li>\n" +
					"\t<li id=\"screenshot-function\"><a href=\"#\" onmouseover=\"showMouseoverInfo('picture')\" onmouseout=\"releaseMouseoverInfo('picture')\" onclick=\"ExecuteClientCapture();\" title=\"Tallenna kuva omalle koneellesi\">Ota kuva</a></li>\n" +
					"\t<li id=\"help-function\"><a href=\"#\" onclick=\"window.open('" + portalAddess + "node/9#Ohjeet\', '_blank', 'width=800,height=600,location=0,menubar=0,directories=0,resizable=1')\" onmouseover=\"showMouseoverInfo('help')\" onmouseout=\"releaseMouseoverInfo('help')\" title=\"Avaa Unelmien Palapelin käyttöohjeet\">Ohje</a></li>\n" +
				"</ul>";
				
    html += "<span id=\"tbbottom\">&nbsp;</span>"; 
    //alert(html);
    document.getElementById( 'toolbox' ).innerHTML = html;

}

function ShowInstallInfo()
{
    var installDiv = document.getElementById( 'InstallLayer' );
    installDiv.style.visibility = 'visible';
}

function ShowControlToolTip( cmdData )
{
    var cmd_data = cmdData.split(":");
    
    var cState = cmd_data[0];
    var command = cmd_data[1];
    
    var texts = new Array("", "", "");
    if (cState == 0)
    {
        texts[0] = PalettemessageroomText1;
        texts[1] = PalettemessageroomText2;
        texts[2] = PalettemessageroomText3;
    }
    if (cState == 1)
    {
        texts[0] = PalettemessageelementText1;
        texts[1] = PalettemessageelementText2;
        texts[2] = PalettemessageelementText3;
    }

    if (command == "move")
        showMessageText( PalettemessagemoveText + texts[1], false, false );
    if (command == "rotate")
        showMessageText( PalettemessagerotateText + texts[1], false, false );
    if (command == "zoom")
        showMessageText( PalettemessagezoomText + texts[2], false, false );
    if (command == "design")
        showMessageText( PalettemessagemodifyText + texts[1], false, false );
    if (command == "remove")
        showMessageText(PalettemessageremoveText + texts[0], false, false );
}

function HideControlToolTip( message )
{
    HideMessage();
}

function ShowMessage( message )
{
    showMessageText( message, false );
}

function ShowErrorMessage( message )
{
    showMessageText( message, true );
}
function HideMessage()
{
	document.getElementById('info').innerHTML = '';
	//document.getElementById('infoImage').style.visibility = 'hidden';
}


var oldmessage = '';
function showMessageText2( message, isError, keepold )
{
	if( message == null || message.length == 0 )
	    return;
	
	if( messageTimer != null )
		clearTimeout( messageTimer );

    var infoText = document.getElementById('info');
    if( isError )
        infoText.style[ 'color' ] = '#ff0000';
    else
        infoText.style[ 'color' ] = '#A29B86';
	
	//document.getElementById('infoImage').style.visibility = 'visible';
	if ( keepold )
	    oldmessage = infoText.innerHTML;
	else 
	    oldmessage = '';
	    
    infoText.innerHTML = message;

    if( isError )
	    messageTimer = setTimeout( 'HideMessage();',8000 );

}

function showMouseoverInfo( controlid )
{
    if ( controlid == 'save' )
    {
        showMessageText2( 'Tallenna unelmasi Unelmien Palapeli portaaliin', false, true );
    }
    else if ( controlid == 'report' )
    {
        showMessageText2( 'Näytä yhteenveto unelmasi huoneista ja huonekaluista', false, true );
    } 
    else if ( controlid == 'picture' )
    {
        showMessageText2( 'Tallenna kuva unelmasta omalle koneellesi', false, true );
    } 
    else if ( controlid == 'help' )
    {
        showMessageText2( 'Avaa Unelmien Palapelin käyttöohjeet', false, true );
    }   
    else if ( controlid == 'MyFlashUI2' )
    {
        showMessageText2( 'Navigaatioympyrällä voi siirtää, pyörittää, kalustaa ja muokata huonetta.', false, true );    
    } 
    else if ( controlid == 'MyFlashUI2' )
    {
        showMessageText2( 'Navigaatioympyrällä voi siirtää, pyörittää huonekalua. Suurennuslasilla pääset rakentamaan huonekalua.', false, true );    
    } 
    else if ( controlid == 'zoomOutGroup' )
    {
        showMessageText2( 'Siirry takaisin ylemmälle tasolle', false, true );    
    }     
    else if ( controlid == 'js:ToggleDesignMode' )
    {
        showMessageText2( 'Siirry huoneen muokkaukseen. Siellä voit myös lisätä ja poistaa ovia ja ikkunoita', false, true );    
    }     
    else if ( controlid == 'js:Remove' )
    {
        showMessageText2( 'Poista valittu elementti. Valitse ensin elementti kokoonpanosta ja paina sitten \'Poista\' painiketta', false, true );    
    }     
    else if ( controlid == 'zoomToRoomState' )
    {
        showMessageText2( 'Siirry takaisin ylemmälle tasolle', false, true );    
    }     
    else if ( controlid == 'centerView' )
    {
        showMessageText2( 'Keskitä näkymä', false, true );    
    }     
    else 
    {
    alert ( controlid);
    }
     
}

function releaseMouseoverInfo( controlid )
{
    showMessageText2( oldmessage, false, false );
}

function showMessageText( message, isError )
{   
    showMessageText2( message, isError, false );
}



function CreateInstallationInfo( message )
{
/*
    var installDiv = document.getElementById( 'InstallText' );
    if( VMPSupported() ) {
        var splitted = message.split( ';' );
        var buttonText = splitted[ 0 ];
        var installInfo = splitted[ 1 ];
    
        installDiv.innerHTML  = '<p>' + installInfo + '</p><br/><br/>';
        installDiv.innerHTML += '<input type="button" onclick="StartDownload();" value="'+ buttonText +'" />';
    }
    else {
        installDiv.innerHTML =  '<p>Valitettavasti tietokoneesi ei ole tuettujen laitteiden listalla. Tuettuja laitteita ovat:</p>';
        installDiv.innerHTML += '<li>Windows 2000/XP/Vista Internet Explorer 6.0+ & FireFox 1.0+';
        installDiv.innerHTML += '<li>Mac OSX 10.4 Safari 1.5+ & FireFox 1.5+';
    }
*/
}

function EnableIntro( enabled )
{
    if( enabled )
    {
        document.getElementById( 'IntroImage' ).style.visibility = 'visible';
		document.getElementById( 'ViewpointArea' ).style.visibility = 'hidden';
    }
    else
    {
        document.getElementById( 'IntroImage' ).style.visibility = 'hidden';
		document.getElementById( 'ViewpointArea' ).style.visibility = 'visible';
    }
}

function ShowAllowedItems( str )
{   
    var html='<table width="210">';
    var started=false;
    var count=0;

    var items = str.split( ';' );
    for( var i = 0; i < items.length; i++ )
    {
        if(count == 2) {
            html+= '</tr>';
            count = 0;
        }
        if(count == 0) {
            html += '<tr>';
        }
            
        if(items[i].indexOf('$') == 0) {
            if(started) {
                if(count == 1) {
                  html+='<td>&nbsp;</td>'
                  count=0;
                }
                html += '</tr><tr><td colspan="2">';
            }
            html += '<h3><a href="#" class="open">' + items[i].substr(1) + '</a></h3></td></tr>';
            //html += '<ul class="clearfix" >';
            started=true;
        } else {
            var params = items[ i ].split( ',' );
            if( params.length > 2 )
                html += '<td style="font-size: 1.2em; vertical-align:top;" ><img onclick="LibraryItemSelected(\''+ params[ 0 ] +'\');" src="'+ params[ 2 ]+'" class="lib-icon" /><br />'+ params[ 1 ]+'</td>';
                count++;
        }
    }

    html += '</table>';
    
    document.getElementById( 'library-contents' ).innerHTML = html;
    
    //alert(html);
    //document.getElementById("db").value = html;
}

function loadSavedConfiguration( webid )
{   
    SendMessage( 'loadSavedConfiguration', 'configid=' + webid );

}

function loadSavedConfigurationPC( webid )
{   
    SendMessage( 'loadSavedConfigurationPC', 'configid=' + webid );

}

function TakeScreenShot() {
    if (pluginInstalled) {
        ExecuteClientCapture();
        window.open('ImageRetriever.ashx?StorageId=ScreenShotImage&download=1', '', 'scrollbars=1;menubar=yes,height=100,width=100,resizable=no,toolbar=no,location=no,status=no');
        this.blur();
    }
    return false;
}

function ShowReport() {
    if (pluginInstalled) {
        m_prepareCapture = true;
        reportWin = window.open('about:blank', 'reportWin_' + sessionId, 'scrollbars=1;menubar=yes,height=750,width=800,resizable=yes,toolbar=no,location=no,status=no');
        ShowReportWindow();
    }
    return false;
}

function ShowHelp() {
    window.open(helpUrl, 'Help', 'scrollbars=1;menubar=yes,height=750,width=800,resizable=yes,toolbar=no,location=no,status=no');
}
