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

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

// Connection state
var gConnectionSate = 0; // 0 == Offline

// Xmpp server interface
var gXmppPlugin;

// User's own jid
var gOwnJid = "";

// What are you doing text
var gWhatAreYouDoingText = "";

// Original Presence status value
var gOriginalPresenceStatus;

// Current Presence status value
var gPresenceStatus;

// vCard IF
var gVcard = "";

// Settings IF
var gSettings;

// stopping music sharing
gStoppingMusicShare = 0;

// stopping location sharing
gStoppingLocationShare = 0;

// original avatar ( url of actual image file )
var gOrigAvatarImagePath;

// updated avatar in string format for saving it to vCard;
var gUpdatedAvatarInStringFormat = "";

// original avatar in string format
var gOriginalAvatarInStringFormat = "";

// Allowed chars in phone number
var KAllowedCharsInPhoneNumber = "0123456789*+pw#";

// illegal characters in url
var KIllegalCharsInUrl = new Array( 9, 10, 13, 27, 39, 149, 32 );

// illegal characters in email
var KIllegalCharsInEmail = new Array( 9, 10, 13, 27, 39, 149, 32 );

// Max lengths for data input fields
var KMaxStatusTextLength    = 250;
var KMaxPhoneNumberLength   = 50;
var KMaxFirstNameLength     = 50;
var KMaxLastNameLength      = 50;
var KMaxStreetAddressLength = 50;
var KMaxCityNameLength      = 150;
var KMaxCountryNameLength   = 100;
var KMaxHomePageLength      = 150;
var KMaxEmailLength         = 150;

// Mime type of avatar
var KMimeTypeJpg = "image/jpeg";

// last shared music presence text
var gLastMusicPresenceText = "";

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

    switch ( event )
        {
        // update layout
        case 1:
            {
            if ( focusedItemOutOfScreen() )
                {
                //Scroll so that anchor is gLinkFocusOffset pixels from the top of screen
                var anchorRectTopLeftY = absolutePosition( gFocusedElement ).y;
                window.scrollTo( 0, anchorRectTopLeftY - window.innerHeight + 70 );
                }
            }
            break;

        // save changes
        case 2:
            {
            saveData();
            }
            break;

        // undo changes
        case 3:
            {
            undoChanges();
            }
            break;

        // set new avatar
        case 4:
            {
            // update avatar to screen
            updateAvatar( "c:/private/2001a928/title.avatar.img" );

            // save avatar in string format also for saving it to vcard
            // after user selects Done
            readFileHttp( "c:\\private\\2001a928\\avatar_data.txt", saveAvatarInStringFormat );
            }
            break;

        // clear avatar
        case 5:
            {
            // empty avatar for vCard
            gUpdatedAvatarInStringFormat = "";

            // default icon to screen
            updateAvatar( "c:/private/2001a928/qgn_prop_y_default_friend.png" );
            }
            break;

        // set status
        case 6:
            {
            // read selected status and update form
            readFileHttp( "c:\\private\\2001a928\\form_data.txt", setStatus );
            }
            break;

        // stop location sharing
        case 7:
            {
            stopLocationSharing();
            }
            break;

        // start music sharing
        case 9:
            {
            startMusicSharing();
            }
            break;

        // focus current element
        case 10:
            {
            document.getElementById( gFocusedElement + "_input" ).focus();
            }
            break;

        // fetch vCard(s)
        case 11:
            {
            fetchVcard();
            }
            break;

        // edit operation (copy, cut or paste)
        case 12:
            {
            readFileHttp( "c:\\private\\2001a928\\edit_data.txt", handleEditOperation );
            }
            break;

        // scroll to top of page
        case 14:
            {
            gFocusedElement = "whatareyoudoing";
            window.scrollTo( 0, 0 );
            }
            break;

        // stop music sharing
        case 25:
            {
            stopMusicSharing();
            }
            break;

        // Remove CRs and LFs
        case 26:
            {
            removeCrsAndLfs();
            }

        // activity event
        case 28:
            {
            readFileHttp( "c:\\private\\2001a928\\form_data.txt", setActivity );
            }
            break;

        // Activate Loc sharing
        case 29:
            {
            // Activate loc sharing
            activateLocSharing();
            }
            break;
        }
    }

//----------------------------------------------------------------------------
// Check is focused item out of screen
//----------------------------------------------------------------------------
//
function focusedItemOutOfScreen()
    {
    var anchorRectTopLeftY = absolutePosition( gFocusedElement ).y;
    if( anchorRectTopLeftY > window.pageYOffset + window.innerHeight - 60 ||
        anchorRectTopLeftY < window.pageYOffset + 47 )//window includes also tabs and "Write message" label, this causes that magic numbers.
        {
        return true;
        }
    else
        {
        return false;
        }
    }

//----------------------------------------------------------------------------
// Get absolute HTMLElement position in document
//----------------------------------------------------------------------------
//
function absolutePosition( e )
    {
    var x = y = 0;
    var focusElement = document.getElementById( e );
    while( focusElement )
        {
        x += focusElement.offsetLeft;
        y += focusElement.offsetTop;
        focusElement = focusElement.offsetParent;
        }
    return {x:x, y:y};
    }

//----------------------------------------------------------------------------
// Display offline note and disable input fields
//----------------------------------------------------------------------------
//
function setMyStatusOffline()
    {
    if ( 3 == gConnectionSate )
        {
        document.getElementById( "OfflineNoteBox" ).className = "OfflineNote_Online";
        document.getElementById( "header" ).className = "header";

        // set textareas modificable
        // get all textareas
        textAreas = document.getElementsByTagName( 'textarea' );
        for (i = 0; i < textAreas.length; i++)
            {
            if ( textAreas[i].className == 'input_textarea' )
                {
                textAreas[i].readOnly = false;
                }
            }
        // update status text when user goes online.
        setStatus( gSettings.getIntParam( 'PRESENCE-STATUS' ) );
        }
    else
        {
        document.getElementById( "OfflineNoteBox" ).className = "OfflineNote_Offline";
        document.getElementById( "header" ).className = "header_offline";

        // set textareas nonmodificable
        // get all textareas
        textAreas = document.getElementsByTagName( 'textarea' );

        // set them non ediable one by one
        for (i = 0; i < textAreas.length; i++)
            {
            if ( textAreas[i].className == 'input_textarea' )
                {
                textAreas[i].readOnly = true;
                }
            }
        // update status text when user goes offline.
        setStatus( 7 ); // offline

        //clear location + tune
        var tmp = new Object();
        tmp.artist = "";
        tmp.track = "";
        tmp.title = "";
        tmp.loctext = "";
        musicPresenceParsingDone( tmp );
        locationParsingDone( tmp );
        }
    }

//----------------------------------------------------------------------------
// Initialize form
//----------------------------------------------------------------------------
//
function initForm()
    {
    gFocusedElement = "whatareyoudoing";
    document.getElementById( 'whatareyoudoing_input' ).focus();

    // Get Xmpp server interface
    try {
        gXmppPlugin = document.getElementById("nokiaXmppPlugin");
        }
    catch( error )
        {
        }

    if ( gXmppPlugin )
        {
        // save JID
        gOwnJid = document.getElementById( "jid" ).innerHTML.trim();

        // save path of original avatar ( actual image file path )
        gOrigAvatarImagePath = document.getElementById( "avatar_image_img" ).src;

        // get Settings IF
        gSettings = gXmppPlugin.Settings;

        // save original presence statatus
        gOriginalPresenceStatus = gSettings.getIntParam( 'PRESENCE-STATUS' );
        gPresenceStatus  = gOriginalPresenceStatus ;

        // save What are you doing text
        gWhatAreYouDoingText = document.getElementById( "whatareyoudoing_input" ).value;

        // set call back for connection state changes
        gXmppPlugin.onChangeState = connectionStateChanged;
        gXmppPlugin.BuddyList.onChange = informationChanged;

        // set call back for PEP events
        gXmppPlugin.Pep.onEvent = pepEventReceived;
        gXmppPlugin.Pep.subscribe( "http://jabber.org/protocol/geoloc" );
        gXmppPlugin.Pep.subscribe( "http://jabber.org/protocol/tune" );

        // Check if location sharing is NOT active
        if ( 0 == gSettings.getIntParam( 'LKM-BROADCAST-INTERVAL' ) )
            {
            // sharing is not active
            var text = document.getElementById( 'xmppClickToShareText' ).value;
            setTimeout( "setInnerHTML( 'mylocation_a', '"+text+"' )", 10 );
            }
        }
    updateLayout();
    }

//----------------------------------------------------------------------------
// Check page layout and tune header style
//----------------------------------------------------------------------------
//
function updateLayout()
    {
    var windowWidth = window.innerWidth;
    var element = document.getElementById( 'header' );
    element.style.width = windowWidth;

    var imgWidth = document.getElementById( 'avatar_image_img' ).width;
    element = document.getElementById( 'title_nick' );
    element.style.width = windowWidth - imgWidth - 3;
    element = document.getElementById( 'jid' );
    element.style.width = windowWidth - imgWidth - 3;
    }

//----------------------------------------------------------------------------
// Callback about connection state change
//----------------------------------------------------------------------------
//
function connectionStateChanged( state )
    {
    // save new connection state
    gConnectionSate = state;
    setMyStatusOffline();

    // inform native side about connectionstate change
    if ( 3 == gConnectionSate )
        {
        // Connected
        return prompt( "online_state" );
        }
    else
        {
        // NOT connected
        return prompt( "offline_state" );
        }
    }

//----------------------------------------------------------------------------
// Callback about connection state change
//----------------------------------------------------------------------------
//
function informationChanged( jid, infoType )
    {
    if ( jid == gOwnJid )
        {
        if ( KBuddyListVCardReceived == infoType )
            {
            // update v-card information
            gVcard = gXmppPlugin.getVcard( gOwnJid );
            gOriginalAvatarInStringFormat = gVcard.avatar;
            gUpdatedAvatarInStringFormat = gOriginalAvatarInStringFormat;

            // undo all changes, ie. set new v-card information
            undoChanges();

            // set presence information as it's wrong after undo operation
            var ownPresence = gXmppPlugin.getBuddy( gOwnJid );
            setStatus( ownPresence.presenceStatus );
            gWhatAreYouDoingText = ownPresence.detailedStatus.escapeHTML();
            document.getElementById( "whatareyoudoing_input" ).value = gWhatAreYouDoingText;
            }
        if ( BuddyListStatusChanged == infoType )
            {
            var ownPresence = gXmppPlugin.getBuddy( gOwnJid );
            setStatus( ownPresence.presenceStatus );
            gWhatAreYouDoingText = ownPresence.detailedStatus.escapeHTML();
            document.getElementById( "whatareyoudoing_input" ).value = gWhatAreYouDoingText;
            }
        }
    }

//----------------------------------------------------------------------------
// Callback about file reading completion
//----------------------------------------------------------------------------
//
function setStatus( status )
    {
    // Get icon and text according to presence state
    if ( !isNaN( parseInt( status ) ) )
        {
        // save status
        gPresenceStatus = status;

        var textAndIcon = get_presenseStateTextAndIcon( status );

        // Set icon
        document.getElementById( "mystatus_src" ).src = textAndIcon.img;

        // set text
        setTimeout( "setInnerHTML( 'mystatus_a', '"+document.getElementById( textAndIcon.txt ).value+"' )", 10 );

        // notify native side about status update
        prompt( "status_updated" );
        }
    }

//----------------------------------------------------------------------------
// Saves data to xmpp server
//----------------------------------------------------------------------------
//
function saveData()
    {
    // get first name and last name that are mandatory fields
    var fName = document.getElementById( "contactinfo_firstname_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_firstname_input" ).value = fName;
    var lName = document.getElementById( "contactinfo_lastname_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_lastname_input" ).value = lName;

    // check if data is valid
    var validData = validateData();

    if ( validData == "ok" )
        {
        //*** Data can be saved because mandatory data was found from form.
        // first name
        gVcard.firstName = fName;

        // lastname
        gVcard.lastName = lName;

        // status text
        var statusText = document.getElementById( "whatareyoudoing_input" ).value.removeLFsAndCRs();
        document.getElementById( "whatareyoudoing_input" ).value = statusText;
        if ( statusText )
            {
            gSettings.setParam( 'PRESENCE-STATUS-FREE-TEXT', statusText );
            }
        else
            {
            gSettings.setParam( 'PRESENCE-STATUS-FREE-TEXT', '' );
            }

        // presence state
        gSettings.setIntParam( 'PRESENCE-STATUS', parseInt( gPresenceStatus ) );

        //send data over network
        gXmppPlugin.sendPresence( parseInt( gPresenceStatus ), statusText );

        // nickname
        var nickname = document.getElementById( "contactinfo_nickname_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_nickname_input" ).value = nickname;
        gVcard.fullName = nickname;

        // update nickname to page also
        if ( 0 < nickname.length )
            {
            // If nick given use it
            document.getElementById( "title_nick_span" ).innerText = nickname;
            }
        else
            {
            // Use firstname
            document.getElementById( "title_nick_span" ).innerText = fName;
            }

        // address
        var address = document.getElementById( "contactinfo_address_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_address_input" ).value = address;
        gVcard.address = address;

        // city
        var city = document.getElementById( "contactinfo_city_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_city_input" ).value = city;
        gVcard.city = city;

        // state
        var state = document.getElementById( "contactinfo_state_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_state_input" ).value = state;
        gVcard.state = state;

        // country
        var country = document.getElementById( "contactinfo_country_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_country_input" ).value = country;
        gVcard.country = country;

        // mobile number
        var mobile = document.getElementById( "contactinfo_phone_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_phone_input" ).value = mobile;
        gVcard.phoneNumber = mobile;

        // email
        var email = document.getElementById( "contactinfo_email_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_email_input" ).value = email;
        gVcard.email = email;

        // homepage
        var homePage = document.getElementById( "contactinfo_homepage_input" ).value.removeLFsAndCRs();
        document.getElementById( "contactinfo_homepage_input" ).value = homePage;
        gVcard.homePage = homePage;

        // avatar
        gVcard.avatarType = KMimeTypeJpg;
        gVcard.avatar = gUpdatedAvatarInStringFormat;
        gOriginalAvatarInStringFormat = gUpdatedAvatarInStringFormat;
        gOrigAvatarImagePath = document.getElementById( "avatar_image_img" ).src;

        // commit changes to vcard
        gVcard.commit();

        // save completed
        document.getElementById( "whatareyoudoing_input" ).focus();
        prompt( "save", "ok" );
        }
    else
        {
        // non valid data found inform client
        prompt( "save", validData );
        }
    }

//----------------------------------------------------------------------------
// undoChanges ( gets data from xmpp server )
//----------------------------------------------------------------------------
//
function undoChanges()
    {
    // revert status text changes to saved values
    setStatus( gSettings.getIntParam( 'PRESENCE-STATUS' ) );
    var gStatusText = gSettings.getParam('PRESENCE-STATUS-FREE-TEXT' ) ;
    document.getElementById( "whatareyoudoing_input" ).value = gStatusText;

    // set first name
    if ( gVcard.firstName )
        {
        document.getElementById( "contactinfo_firstname_input" ).value = gVcard.firstName.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_firstname_input" ).value = "";
        }

    // set last name
    if ( gVcard.lastName )
        {
        document.getElementById( "contactinfo_lastname_input" ).value = gVcard.lastName.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_lastname_input" ).value = "";
        }

    // set nickname
    if ( gVcard.fullName )
        {
        document.getElementById( "contactinfo_nickname_input" ).value = gVcard.fullName.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_nickname_input" ).value = "";
        }

    // set address
    if ( gVcard.address )
        {
        document.getElementById( "contactinfo_address_input" ).value = gVcard.address.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_address_input" ).value = "";
        }

    // set city
    if ( gVcard.city )
        {
        document.getElementById( "contactinfo_city_input" ).value = gVcard.city.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_city_input" ).value = "";
        }

    // set state
    if ( gVcard.state )
        {
        document.getElementById( "contactinfo_state_input" ).value = gVcard.state.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_state_input" ).value = "";
        }

    // set country
    if ( gVcard.country )
        {
        document.getElementById( "contactinfo_country_input" ).value = gVcard.country.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_country_input" ).value = "";
        }

    // set mobile number
    if ( gVcard.phoneNumber )
        {
        document.getElementById( "contactinfo_phone_input" ).value = gVcard.phoneNumber.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_phone_input" ).value = "";
        }

    // set email
    if ( gVcard.email )
        {
        document.getElementById( "contactinfo_email_input" ).value = gVcard.email.escapeHTML();
        }
    else
        {
         document.getElementById( "contactinfo_email_input" ).value = "";
        }

    // set homepage
    if ( gVcard.homePage )
        {
        document.getElementById( "contactinfo_homepage_input" ).value = gVcard.homePage.escapeHTML();
        }
    else
        {
        document.getElementById( "contactinfo_homepage_input" ).value = "";
        }

    // avatar
    gUpdatedAvatarInStringFormat = gOriginalAvatarInStringFormat;

    // set original avatar to page
    if ( 1 >= gXmppPlugin.getVcard( gOwnJid ).avatar.length )
        {
        // set default avatar
        updateAvatar( "c:/private/2001a928/qgn_prop_y_default_friend.png" );
        }
    else
        {
        // take original avatar from vCard and set it to page
        var originalAvatar = "data:" + gXmppPlugin.getVcard( gOwnJid ).avatarType + ";base64," + gXmppPlugin.getVcard( gOwnJid ).avatar;
        var avatarImg = document.getElementById( "avatar_image_img" );
        if ( avatarImg )
            {
             avatarImg.src = originalAvatar;
            }
        }
    }

//----------------------------------------------------------------------------
// stop location sharing
//----------------------------------------------------------------------------
//
function stopLocationSharing()
    {

    // set flag to indicate that sharing must be stopped
    gStoppingLocationShare = 1;

    // send empty location to remove event from client's views
    gXmppPlugin.Pep.publish( "http://jabber.org/protocol/geoloc",
        "<geoloc xmlns='http://jabber.org/protocol/geoloc'>" +
            "" +
        "</geoloc>", true );

    // sharing interval has to be set to zero to disable sharing
    gSettings.setIntParam( 'LKM-BROADCAST-INTERVAL', 0 );

    // Set click to share text to form
    var text = document.getElementById( 'xmppClickToShareText' ).value;
    setTimeout( "setInnerHTML( 'mylocation_a', '"+text+"' )", 10 );
    }

//----------------------------------------------------------------------------
// stop music sharing
//----------------------------------------------------------------------------
//
function stopMusicSharing()
    {
    // set flag to indicate that sharing must be stopped
    gStoppingMusicShare = 1;

    // store old music presence text and do fail safe check for presence text
    var currentmusicpresence = document.getElementById( 'nowplaying_a' ).innerHTML;
    if ( currentmusicpresence == document.getElementById( 'xmppClickToShareText' ).value )
        {
        gLastMusicPresenceText = document.getElementById( 'xmppNotPlayingText' ).value;
        }
    else
        {
        gLastMusicPresenceText = currentmusicpresence;
        }

    var lastMusicPresenceText = gLastMusicPresenceText;

    // send empty tune to remove event from client's views
    gXmppPlugin.Pep.publish( "http://jabber.org/protocol/tune",
        "<tune xmlns='http://jabber.org/protocol/tune'>" +
            "<title></title>" +
        "</tune>", true );

    // stop sharing
    gSettings.setIntParam( 'IS-MUSIC-PUB-ENABLED', 0 );

    // store last music presence incase that pec sdk works so fast that it
    // overrides presence value by doing empty tune callback
    gLastMusicPresenceText = lastMusicPresenceText;

    // Set text to form
    var text = document.getElementById( 'xmppClickToShareText' ).value;
    setTimeout( "setInnerHTML( 'nowplaying_a', '"+text+"' )", 10 );
    }

//----------------------------------------------------------------------------
// start music sharing
//----------------------------------------------------------------------------
//
function startMusicSharing()
    {
    // add previous music presence text to form
    if ( gLastMusicPresenceText == "" ||
        gLastMusicPresenceText == document.getElementById( 'xmppClickToShareText' ).value )
        {
        gLastMusicPresenceText = document.getElementById( 'xmppNotPlayingText' ).value;
        }
    setTimeout( "setInnerHTML( 'nowplaying_a', '"+gLastMusicPresenceText+"' )", 10 );

    // start sharing
    gSettings.setIntParam( 'IS-MUSIC-PUB-ENABLED', 1 );

    // get published tune
    gXmppPlugin.Pep.subscribe( "http://jabber.org/protocol/tune" );
    }

//----------------------------------------------------------------------------
// Callback about PEP events
//----------------------------------------------------------------------------
//
function pepEventReceived( jid, eventType, content )
    {
    // Check if the change happened user's own profile
    if ( gOwnJid == jid )
        {
        switch( eventType )
            {
            case KLocationPepEvent:
                {
                // Add dummy element around received data, needed in parsing
                var modifiedContent = "<location>" + content + "</location>";

                // Get location from event data and set it to html
                parsePepGeoloc( modifiedContent, locationParsingDone );

                break;
                }
            case KMusicPresencePepEvent:
                {
                // Add dummy element around received data, needed in parsing
                var modifiedContent = "<music>" + content + "</music>";

                // Get music pres. from event data and set it to html
                parsePepTune( modifiedContent, musicPresenceParsingDone );

                break;
                }
            }
        }
    }

//----------------------------------------------------------------------------
// Callback about completed music presence parsing
//----------------------------------------------------------------------------
//
function musicPresenceParsingDone( item )
    {
    var musicPresence = "";

    // Create string

    // Artist
    if ( "" != item.artist )
        {
        musicPresence += item.artist;
        }

    // Track
    if ( "" != item.track )
        {
        if ( "" != item.artist )
            {
            musicPresence += "-"
            }
        musicPresence += item.track ;
        }

    // Title
    if ( "" != item.title )
        {
        if ( ( "" != item.track  )  || ( "" == item.track && "" != item.artist ) )
            {
            musicPresence += "-"
            }
        musicPresence += item.title ;
        }

    // set last music presence to be as current presence if it's empty
    if ( gLastMusicPresenceText == "" && musicPresence != "" )
        {
        gLastMusicPresenceText = musicPresence;
        }

    // set item visible/invisible
    var musicPubSub = gSettings.getIntParam('IS-MUSIC-PUB-ENABLED' );
    if ( musicPresence == "" || !musicPubSub )
        {
        // set last music presence text to current music if we get new presence while stopped
        if ( musicPresence != "" && !musicPubSub && gStoppingMusicShare )
            {
            gLastMusicPresenceText = musicPresence;
            }

        // set no playing song / click to share text to form
        if ( ( !gStoppingMusicShare && musicPubSub ) || ( musicPresence == "" && musicPubSub && gStoppingMusicShare ) )
            {
            var notplaying = document.getElementById( 'xmppNotPlayingText' ).value;
            if ( gLastMusicPresenceText == "" )
                {
                gLastMusicPresenceText = notplaying;
                }

            setTimeout( "setInnerHTML( 'nowplaying_a', '" + notplaying + "' )", 10 );
            gStoppingMusicShare = 0;
            }
        else
            {
            setTimeout( "setInnerHTML( 'nowplaying_a', '" + document.getElementById( 'xmppClickToShareText' ).value + "' )", 10 );
            }
        }
    else
        {
        if ( gLastMusicPresenceText != musicPresence )
            {
            gLastMusicPresenceText = musicPresence;
            }

        // Set Music pres. to page
        setTimeout( "setInnerHTML( 'nowplaying_a', '"+musicPresence+"' )", 10 );
        }
    }

//----------------------------------------------------------------------------
// Callback about completed location data parsing
//----------------------------------------------------------------------------
//
function locationParsingDone( item )
    {
    // Create location string
    var location = "";

    if ( "" != item.loctext )
        {
        location = item.loctext;
        }

    // set item visible/invisible
    if ( "" == location && !gStoppingLocationShare )
        {
        // set unknown text to form if sharing is active
        if ( 0 != gSettings.getIntParam( 'LKM-BROADCAST-INTERVAL' ) )
            {
            setTimeout( "setInnerHTML( 'mylocation_a', '" + document.getElementById( 'xmppNoLandmarkText' ).value +"' )", 10 );
            }
        else
            {
            // Set Click to share to form to page
            setTimeout( "setInnerHTML( 'mylocation_a', '"+document.getElementById( 'xmppClickToShareText' ).value+"' )", 10 );
            }
        }
    else
        {
        // check if location sharing was just deactivated,
        // if it was does not use received location info
        if ( gStoppingLocationShare )
            {
             // Set Click to share to form to page
            setTimeout( "setInnerHTML( 'mylocation_a', '"+document.getElementById( 'xmppClickToShareText' ).value+"' )", 10 );
            }
        else
            {
            // Set Location to page if sharing is active otherwise click_to_share is shown
            if ( location.length && 0 != gSettings.getIntParam( 'LKM-BROADCAST-INTERVAL' ) )
                {
                setTimeout( "setInnerHTML( 'mylocation_a', '"+location+"' )", 10 );
                }
            else
                {
                // Set Click to share to form to page
                setTimeout( "setInnerHTML( 'mylocation_a', '"+document.getElementById( 'xmppClickToShareText' ).value+"' )", 10 );
                }
            }
        }
   gStoppingLocationShare = 0;
   }

//----------------------------------------------------------------------------
// Update avatar image
//----------------------------------------------------------------------------
//
function updateAvatar( imageFile )
    {
    var avatarImg = document.getElementById( "avatar_image_img" );
    if ( avatarImg )
        {
        // get time and add it image src to force image loading
        var time =  new Date().getTime();
        avatarImg.src = imageFile + '?' + time;
        }
    }

//----------------------------------------------------------------------------
// Callback about completed reading of avatar in string format from file.
//----------------------------------------------------------------------------
//
function saveAvatarInStringFormat( avatarString )
    {
    if ( avatarString )
        {
        gUpdatedAvatarInStringFormat = avatarString;
        }
    }
//----------------------------------------------------------------------------
// validates data
// @return "ok" if data is valid othervise string telling what was wrong
//----------------------------------------------------------------------------
//
function validateData()
    {
    var ret = "ok";

    // read needed data
    var firstName = document.getElementById( "contactinfo_firstname_input" ).value;
    var lastName = document.getElementById( "contactinfo_lastname_input" ).value;
    var sText = document.getElementById( "whatareyoudoing_input" ).value;
    var addrs = document.getElementById( "contactinfo_address_input" ).value;
    var city = document.getElementById( "contactinfo_city_input" ).value;
    var state = document.getElementById( "contactinfo_state_input" ).value;
    var country = document.getElementById( "contactinfo_country_input" ).value;
    var mobile = document.getElementById( "contactinfo_phone_input" ).value;
    var email = document.getElementById( "contactinfo_email_input" ).value;
    var homePage = document.getElementById( "contactinfo_homepage_input" ).value;

    // **** Validata firstname
    if ( ret == "ok" && !firstName )
        {
        document.getElementById( "contactinfo_firstname_input" ).focus();
        ret = "missing_first_name";
        }

    // **** Validata lastname
    if ( ret == "ok" && !lastName )
        {
        document.getElementById( "contactinfo_lastname_input" ).focus();
        ret = "missing_last_name";
        }

    // **** Validata data lengths

    // free text
    if ( ret == "ok" && KMaxStatusTextLength < sText.length )
        {
        document.getElementById( "whatareyoudoing_input" ).focus();
        ret = "too_long_field_data:" + KMaxStatusTextLength;
        }

    // first name
    if ( ret == "ok" && KMaxFirstNameLength < firstName.length )
        {
        document.getElementById( "contactinfo_firstname_input" ).focus();
        ret = "too_long_field_data:" + KMaxFirstNameLength;
        }

    // last name
    if ( ret == "ok" && KMaxLastNameLength < lastName.length )
        {
        document.getElementById( "contactinfo_lastname_input" ).focus();
        ret = "too_long_field_data:" + KMaxLastNameLength;
        }

    // street address
    if ( ret == "ok" && KMaxStreetAddressLength < addrs.length )
        {
        document.getElementById( "contactinfo_address_input" ).focus();
        ret = "too_long_field_data:" + KMaxStreetAddressLength;
        }

    // city
    if ( ret == "ok" && KMaxCityNameLength < city.length )
        {
        document.getElementById( "contactinfo_city_input" ).focus();
        ret = "too_long_field_data:" + KMaxCityNameLength;
        }

    // country
    if ( ret == "ok" && KMaxCountryNameLength < country.length )
        {
        document.getElementById( "contactinfo_country_input" ).focus();
        ret = "too_long_field_data:" + KMaxCountryNameLength;
        }

    // phone number
    if ( ret == "ok" && KMaxPhoneNumberLength < mobile.length )
        {
        document.getElementById( "contactinfo_phone_input" ).focus();
        ret = "too_long_field_data:" + KMaxPhoneNumberLength;
        }

    // homepage
    if ( ret == "ok" && KMaxHomePageLength < homePage.length )
        {
        document.getElementById( "contactinfo_homepage_input" ).focus();
        ret = "too_long_field_data:" + KMaxHomePageLength;
        }

    // email
    if ( ret == "ok" && KMaxEmailLength < email.length )
        {
        document.getElementById( "contactinfo_email_input" ).focus();
        ret = "too_long_field_data:" + KMaxEmailLength;
        }

    // **** Validata phonenumber
    if ( ret == "ok" && mobile )
        {
        // check that number does not contain illegal chars
        var illegalCharFound = "false";
        for ( var index = 0; illegalCharFound != "true" && index < mobile.length; index++  )
            {
            if ( -1 == KAllowedCharsInPhoneNumber.indexOf( mobile.charAt( index ) ) )
                {
                // Illegal char found
                document.getElementById( "contactinfo_phone_input" ).focus();
                ret = "invalid_phone_number" + ":" + mobile.charAt( index );
                illegalCharFound = "true";
                }
            }
        }

    // **** Validata email
    if ( ret == "ok" && email )
        {
        // validate format on some level using regexp
        var rExp = new RegExp("(\\w{1,})+(@)+(\\w{1,})+(\\.)+(\\w{2,})");
        if( !rExp.test( email,"" ) )
            {
            document.getElementById( "contactinfo_email_input" ).focus();
            ret = "invalid_email";
            }

        // check that there are no illegal chars in address
        if ( ret == "ok" )
            {
            var illegalCharFound = "false";
            for ( var index = 0; illegalCharFound != "true" && index < email.length; index++  )
                {
                if ( -1 != KIllegalCharsInEmail.indexOf( email.charCodeAt( index ) ) )
                    {
                    // illegal char found
                    document.getElementById( "contactinfo_email_input" ).focus();
                    ret = "invalid_email";
                    }
                }
            }
        delete rExp;
        }

    // **** Validata url
    if ( ret == "ok" && homePage )
        {
        // validat format on some level using regexp
        var rExp = new RegExp("(\\w{1,})+(\\w{1,})+(\\.)+(\\w{2,})");
        if( !rExp.test( homePage,"" ) )
            {
            document.getElementById( "contactinfo_homepage_input" ).focus();
            ret = "invalid_url";
            }

        // check that url does not contain illegal chars
        if ( ret == "ok" )
            {
            var illegalCharFound = "false";
            for ( var index = 0; illegalCharFound != "true" && index < homePage.length; index++  )
                {
                if ( -1 != KIllegalCharsInUrl.indexOf( homePage.charCodeAt( index ) ) )
                    {
                    // illegal char found
                    document.getElementById( "contactinfo_homepage_input" ).focus();
                    ret = "invalid_url";
                    }
                }
            }
        }

    return ret;
    }

//----------------------------------------------------------------------------
// Fetches vGard if it has not already been fetched
//----------------------------------------------------------------------------
//
function fetchVcard()
    {
    if (  "" == gVcard )
        {
        // get vCard IF
        gVcard = gXmppPlugin.getVcard( gOwnJid );

        // store original avatar
        gOriginalAvatarInStringFormat = gVcard.avatar;

        // set updated avatar to be the same as the original
        gUpdatedAvatarInStringFormat = gOriginalAvatarInStringFormat;
        }
    }

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

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

//----------------------------------------------------------------------------
// Removes CRs and LF from inputs edit operation
//----------------------------------------------------------------------------
//
function removeCrsAndLfs()
    {
    document.getElementById( "contactinfo_firstname_input" ).value = document.getElementById( "contactinfo_firstname_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_lastname_input" ).value = document.getElementById( "contactinfo_lastname_input" ).value.removeLFsAndCRs();
    document.getElementById( "whatareyoudoing_input" ).value = document.getElementById( "whatareyoudoing_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_nickname_input" ).value = document.getElementById( "contactinfo_nickname_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_address_input" ).value = document.getElementById( "contactinfo_address_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_city_input" ).value = document.getElementById( "contactinfo_city_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_state_input" ).value = document.getElementById( "contactinfo_state_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_country_input" ).value = document.getElementById( "contactinfo_country_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_phone_input" ).value = document.getElementById( "contactinfo_phone_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_email_input" ).value = document.getElementById( "contactinfo_email_input" ).value.removeLFsAndCRs();
    document.getElementById( "contactinfo_homepage_input" ).value = document.getElementById( "contactinfo_homepage_input" ).value.removeLFsAndCRs();
    }

//----------------------------------------------------------------------------
// Set activity by subscribing or unsubscribing from pep events
//----------------------------------------------------------------------------
//
function setActivity( data )
    {
    if ( data )
        {
        if ( "0" == data )
            {
            gXmppPlugin.Pep.onEvent = pepEventReceived;
            gXmppPlugin.Pep.unsubscribe( "http://jabber.org/protocol/geoloc" );
            gXmppPlugin.Pep.unsubscribe( "http://jabber.org/protocol/tune" );
            }
        else
            {
            gXmppPlugin.Pep.onEvent = pepEventReceived;
            gXmppPlugin.Pep.subscribe( "http://jabber.org/protocol/geoloc" );
            gXmppPlugin.Pep.subscribe( "http://jabber.org/protocol/tune" );
            }
        }
    }

//----------------------------------------------------------------------------
// Activate location sharing
//----------------------------------------------------------------------------
//
function activateLocSharing()
     {
     // Is any landmarks shared
     if ( gSettings.getParam( 'LANDMARK-IDS' ) && gSettings.getParam( 'LANDMARK-IDS' ).length > 0 )
        {
        // Landsmarks shared
        if ( document.getElementById( 'mylocation_a' ).innerHTML == document.getElementById( 'xmppClickToShareText' ).value )
            {
            var text = document.getElementById( 'xmppGettingLocationText' ).value;
            setTimeout( "setInnerHTML( 'mylocation_a', '"+text+"' )", 10 );
            }

        // set default interval to location broadcasting
        gSettings.setIntParam( 'LKM-BROADCAST-INTERVAL', 1200 );
        }
    else
        {

        // No landmarks shared
        // set interval to zero
        gSettings.setIntParam( 'LKM-BROADCAST-INTERVAL', 0 );

        var text = document.getElementById( 'xmppClickToShareText' ).value;
        setTimeout( "setInnerHTML( 'mylocation_a', '"+text+"' )", 10 );
        }
    }