//----------------------------------------------------------------------------
// Globals
//----------------------------------------------------------------------------
//

// current page width. Needed in layout setting.
var gCurrentWidth = 0;

// currently focused element
var gFocusedElement = "";

//----------------------------------------------------------------------------
// Reads a file from local filesystem and notifies callback on completion.
// Notice that this function is also on common.js, but it should not be
// included into search view in order to shorten load time.
//----------------------------------------------------------------------------
function readFileHttp( fname, callback )
    {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
        {
        callback( xmlhttp.responseText );
        }
    xmlhttp.open( "GET", fname, true );
    xmlhttp.send( null );
    }

//----------------------------------------------------------------------------
// Send element click command to client
//----------------------------------------------------------------------------
//
function elementClicked( element )
    {
    return prompt( "click", element.id );
    }

//----------------------------------------------------------------------------
// Send element focused command to client
//----------------------------------------------------------------------------
//
function elementFocuced( element )
    {
    gFocusedElement = element.id;
    return prompt( "focus", element.id );
    }

//----------------------------------------------------------------------------
// Callback handles requests from client-side
//----------------------------------------------------------------------------
//
function onClientRequest( keyEvent )
    {
    keyEvent  = keyEvent ? keyEvent : window.event;
    var event = keyEvent.keyCode ? keyEvent.keyCode : keyEvent.which;

    switch ( event ) // layout update
        {
        // update layout
        case 1:
            {
            updateLayout();
            }
            break;

        // Get domain text
        case 2:
            {
            prompt( "value_domain", document.getElementById( "domain" ).value );
            }
            break;

        // Get search text
        case 3:
            {
            prompt( "value_search", document.getElementById( "keyword" ).value );
            }
            break;

        // Get username
        case 4:
            {
            prompt( "value_username", document.getElementById( "username" ).value );
            }
            break;

        // Set service selection
        case 5:
            {
            // read selected status
            readFileHttp( "c:\\private\\2001a928\\form_data.txt", setServiceSelection );
            }
            break;

        // Clear Username field
        case 6:
            {
            // Clear Username field
            clearTextArea( 'username' );
            }
            break;

        // reset all input areas to default values
        case 7:
            {
            clearTextArea( 'username' );
            clearTextArea( 'keyword' );
            document.getElementById( 'keyword' ).focus();
            }
            break;

        // edit operation (copy, cut or paste)
        case 12:
            {
            readFileHttp( "c:\\private\\2001a928\\edit_data.txt", handleEditOperation );
            }
            break;
            
        // Clear Search text field
        case 14:
            {
            // Clear Search text field
            clearTextArea( 'keyword' );
            }
            break;
            
        // Remove LFs and CRs from data fields
        case 25:
            {
            document.getElementById( 'domain' ).value =  document.getElementById( 'domain' ).value.removeLFsAndCRs();
            document.getElementById( 'keyword' ).value =  document.getElementById( 'keyword' ).value.removeLFsAndCRs();
            document.getElementById( 'username' ).value =  document.getElementById( 'username' ).value.removeLFsAndCRs();
            }
            break;

        }
    }

//----------------------------------------------------------------------------
// Initialize form
//----------------------------------------------------------------------------
//
function initForm()
    {
    gFocusedElement = "keyword";
    updateLayout();
    document.getElementById( "keyword" ).focus();
    }

//----------------------------------------------------------------------------
// Switch element's style
//----------------------------------------------------------------------------
//
function changeStyle( el, newstyle )
    {
    var e = document.getElementById( el );
    if ( e )
        e.className = newstyle;
    }

//----------------------------------------------------------------------------
// Check page layout and tune header style
//----------------------------------------------------------------------------
//
function updateLayout()
    {
    if ( window.innerWidth != gCurrentWidth )
        {
        gCurrentWidth = window.innerWidth;

        var orientation = document.getElementById( "xmppSelectServiceLR" ).value;
        if ( gCurrentWidth > window.innerHeight )
            {
            changeStyle( 'input_headline_service','headline_container_landscape_' + orientation );
            changeStyle( 'input_headline_username','headline_container_landscape_' + orientation );
            changeStyle( 'input_headline_search','headline_container_landscape_' + orientation );
            changeStyle( 'selectservice','selectservice_landscape' );
            changeStyle( 'body', 'body_landscape_' + orientation );
            var myarr = document.getElementsByName('divider');
            for ( i = 0; i<myarr.length; i++ )
                {
                myarr[i].className = 'divider_landscape';
                }
            }
        else
            {
            changeStyle( 'input_headline_service','headline_container_portrait' );
            changeStyle( 'input_headline_username','headline_container_portrait' );
            changeStyle( 'input_headline_search','headline_container_portrait' );
            changeStyle( 'selectservice','selectservice_portrait' );
            changeStyle( 'body', 'body_portrait_' + orientation );
            var myarr = document.getElementsByName('divider');
            for ( i = 0; i<myarr.length; i++ )
                {
                myarr[i].className = 'divider_portrait';
                }
            }
        }
    }

//----------------------------------------------------------------------------
// Callback about file reading completion
//----------------------------------------------------------------------------
//
function setServiceSelection( service )
    {
    // Get icon and text according to service selection
    if ( service )
        {
        var data = getServiceSelectionTextAndIcon( service );

        // Set icon
        document.getElementById( "selectservice_img" ).src = data.img;
        document.getElementById( "domain" ).value = data.domain;
        document.getElementById( "selectservice_txt" ).innerHTML = document.getElementById( data.txt ).value;

        // notify native side about service update
        prompt( "service_updated" );
        }
    }

//----------------------------------------------------------------------------
// Resolves service selection icon and text
//----------------------------------------------------------------------------
//
function getServiceSelectionTextAndIcon( service )
    {
    var map =
        [
        { txt : "xmppSelectServiceTextOvi",   img : "qgn_prop_service_ovi.png",   domain : "ovi.com" },
        { txt : "xmppSelectServiceTextGTalk", img : "qgn_prop_service_gtalk.png", domain : "gmail.com" },
        { txt : "xmppSelectServiceTextOther", img : "img.spacer.png",             domain : "" }
        ]

    return map[service];
    }

// --- Search Button ---

//----------------------------------------------------------------------------
// Handles search button image change when input field is in focus
//----------------------------------------------------------------------------
//
function activateSearchButton()
    {
    var searchButton = document.getElementById( 'search_by_name_button_id' );
    if ( searchButton )
        {
        searchButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_search_active.png" );
        }
    }

//----------------------------------------------------------------------------
// Handles search button image change when input field is not in focus
//----------------------------------------------------------------------------
//
function disableSearchButton()
    {
    var searchButton = document.getElementById( 'search_by_name_button_id' );
    if ( searchButton )
        {
    var item = document.getElementById( 'keyword' );
    if( item.value.length == 0 )
        {
            searchButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_search_inact.png" );
            }
        }
    }

//----------------------------------------------------------------------------
// Handles search button image "onmousedown" event
//----------------------------------------------------------------------------
//
function initiateSearch()
    {
    var searchButton = document.getElementById( 'search_by_name_button_id' );
    if ( searchButton )
        {
    var item = document.getElementById( 'keyword' );
    if( item.value.length > 0 )
            {
        searchButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_search_pressed.png" );
            }
    }
    }

//----------------------------------------------------------------------------
// Handles search button image "onmouseup" event and activates search process
//----------------------------------------------------------------------------
//
function startSearch( e )
    {
    var item = document.getElementById( 'keyword' );
    if( item.value.length > 0 )
        {
        var searchButton = document.getElementById( 'search_by_name_button_id' );
        if ( searchButton )
            {
            searchButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_search_active.png" );
            }

        elementClicked( e );
        }
    }


// --- Send Invitation Button ---

//----------------------------------------------------------------------------
// Handles invitation button image change when input field is in focus
//----------------------------------------------------------------------------
//
function activateInviteButton()
    {
    var inviteButton = document.getElementById( 'sendbutton_img_id' );
    if ( inviteButton )
        {
        inviteButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_send_active.png" );
        }
    }

//----------------------------------------------------------------------------
// Handles invitation button image change when input field is not in focus
//----------------------------------------------------------------------------
//
function disableInviteButton()
    {
    var inviteButton = document.getElementById( 'sendbutton_img_id' );
    if ( inviteButton )
        {
    var item = document.getElementById( 'username' );
    if( item.value.length == 0 )
        {
        inviteButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_send_inact.png" );
            }
        }
    }

//----------------------------------------------------------------------------
// Handles invite button image "onmousedown" event
//----------------------------------------------------------------------------
//
function initiateInvite()
    {
    var inviteButton = document.getElementById( 'sendbutton_img_id' );
    if ( inviteButton )
        {
    var item = document.getElementById( 'username' );
    if( item.value.length > 0 )
            {
        inviteButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_send_pressed.png" );
            }
         }
    }

//----------------------------------------------------------------------------
// Handles invite button image "onmouseup" event and activates invitation process
//----------------------------------------------------------------------------
//
function startInvite( e )
    {
    var item = document.getElementById( 'username' );
    if( item.value.length > 0 )
        {
        var inviteButton = document.getElementById( 'sendbutton_img_id' );
        if ( inviteButton )
            {
            inviteButton.setAttribute( "src", "c:/private/2001a928/qgn_graf_btn_send_active.png" );
            }

        elementClicked( e );
        }
    }

//----------------------------------------------------------------------------
// Clears content of text area
//----------------------------------------------------------------------------
//
function clearTextArea( fieldId )
    {
    document.getElementById( fieldId ).value = "";
    }

//----------------------------------------------------------------------------
// Handles edit operation (copy, cut, paste)
//----------------------------------------------------------------------------
//
function handleEditOperation( data )
    {
    if ( data )
        {
        command = data.substring( 0, 1 );

        // copy
        if ( "0" == command )
            {
            prompt( "value", document.getElementById( gFocusedElement ).value );
            }
        // cut
        else if ( "1" == command )
            {
            textValue = document.getElementById( gFocusedElement ).value;
            document.getElementById( gFocusedElement ).value = "";
            prompt( "value", textValue );
            }
        // paste
        else if ( "2" == command )
            {
            document.getElementById( gFocusedElement ).value = data.substr( 1 );
            }
        }
    }

// ---------------------------------------------------------------------------
// Extends String.prototype with method for removing LFs and CRs from
// the string
// ---------------------------------------------------------------------------
//
String.prototype.removeLFsAndCRs = function() {
    var returnedStr = "";
    var i = 0;
    var ch = 0;

    while ( i < this.length )
        {
        if ( ( 13 != this.charCodeAt( i ) ) && // CR
             ( 10 != this.charCodeAt( i ) ) )  // LF
            {
            returnedStr += String.fromCharCode( this.charCodeAt( i ) );
            }
        i++;
        }
    return returnedStr;
    }