/**
 * (c) COPYRIGHT AVIATION SOFTWARE INC. 2003-2011
 */

/**
 * The heart of the current embeded JSON mechanism. This class deals with any X-JSON snippets 
 * generated by php JSON_Snippet* classes. For example, the status JSON snippets are sent by
 * EmbeddedLoadStatusCtl.php. 
 *
 * JSONSnippetReceiver will look for an action property within the receivedJSON header, and will
 * attempt to match the value of that property to a process[Value] method, where [Value] is the 
 * value found in the action property of the JSON Header Snippet.
 */

top.JSONSnippetReceiver = JSONSnippetReceiver = function JSONSnippetReceiver( transport ) {
    this.transport = transport || null;
}

JSONSnippetReceiver.prototype.process = function() {
    if ( this.transport == null ) return;
    if ( typeof this.transport != 'object' ) throw new JSONReceiverException( 'Transport object not found' );
    var header;
    if ( typeof this.transport.headerJSON == 'object' && this.transport.headerJSON ) {
        header = this.transport.headerJSON;
        var action = header.action || null;
        var payload = header.payload || null;
        this.invoke(action, payload);
    }
    else if ( typeof this.transport.responseJSON == 'object' && this.transport.responseJSON ) {
        body = this.transport.responseJSON;
        var action = body.action || null;
        var payload = body.payload || null;
        this.invoke(action, payload);
    }
    else throw new JSONReceiverException( 'JSON header not found' );
}

JSONSnippetReceiver.prototype.invoke = function( action, payloadObj ) {
    if ( typeof action != 'string' ) throw new JSONReceiverException( 'JSON action not found' );
    if ( typeof payloadObj == 'undefined' || payloadObj == null ) throw new JSONReceiverException( 'JSON payload not found' );
    var actionable = 'process' + capitalize(action);
    var payload = payloadObj;
    if ( typeof this[actionable] == 'function' ) {
        try {
            this[actionable]( payload );
        } catch (e) {
            throw new JSONReceiverException( "Could not complete processing JSON snippet type '" + action + "': " + e);
        }
    } else {
        throw new JSONReceiverException( "Unrecognized JSON snippet type: '" + action + "'" );
    }
}

JSONSnippetReceiver.prototype.processScript = function ( payload ) {
    if ( typeof payload != 'string' ) throw new JSONReceiverException('JSON payload not found');
    try {
        window.eval(payload);
    } catch ( e ) {
        top.problematicJSONscript = payload;
        throw new JSONReceiverException("Script could not be evaluated (for debugging purposes, the problem script is stored in top.problematicJSONscript). Reason: " + e);
    }
}

JSONSnippetReceiver.prototype.processLocation = function ( payload ) {
    if ( typeof payload != 'string' ) throw new JSONReceiverException('JSON payload not found');
    if ( typeof window.document != 'undefined' && typeof window.document.location != 'undefined' ) throw new JSONReceiverException('Cannot acquire document object.');
    try {
        window.document.location = payload;
    } catch ( e ) {
        top.problematicJSONuri = payload;
        throw new JSONReceiverException("Document could not be loaded (for debugging purposes, the problem document uri is stored in top.problematicJSONuri). Reason: " + e);
    }
}

JSONSnippetReceiver.prototype.processStatus = function ( payload ) {
    if ( typeof payload != 'string' ) throw new JSONReceiverException('JSON payload not found');
    try {
        var obj = payload.evalJSON(true);
        if (top.debug && top.debug.log) {
            top.debug.log('token: ' + obj.updaterToken + ' - cur_activity: '+ obj.cur_activity,this);
        }
        var status = obj.cur_activity || '';
        var target = obj.updaterTarget || null;
        var completedSteps = obj.completed_steps || 0;
        var totalSteps = obj.total_steps || 0;
        var percentage = 0;
        try {
            percentage = ( completedSteps / totalSteps ) * 100;
        } catch (e) {
            percentage = 0;
        }
        if (!isFinite(percentage)) percentage = 0;
        if ( typeof target == 'string' ) {
            var pb = new ProgressBar();
            pb.init(target);
            pb.setPercentage(percentage);
            pb.setStatus(status);
        }
    } catch ( e ) {
        top.problematicJSONstatus = payload;
        throw new JSONReceiverException("Status could not be used (for debugging purposes, the problem document uri is stored in top.problematicJSONstatus). Reason: " + e);
    }
}

JSONSnippetReceiver.prototype.processGroup = function ( payload ) {
    if ( ! Object.isArray( payload ) ) throw new JSONReceiverException('JSON payload not found');
    try {
        for ( var i = 0, len = payload.length; i < len; ++i ) {
            var snippet = payload[i];
            if ( typeof snippet != 'object' ) throw new JSONReceiverException('Could not retrieve individual JSON snippet from group.');
            var action = snippet.action || null;
            var payloadObj = snippet.payload || null;
            this.invoke( action, payloadObj );
        }
    } catch ( e ) {
        top.problematicJSONgroup = payload;
        throw new JSONReceiverException("Snippet Group could not be used (for debugging purposes, the problem document uri is stored in top.problematicJSONgroup). Reason: " + e);
    }
}

top.JSONReceiverException = JSONReceiverException = function( message ) {
    this.message = message;
    this.name = 'JSONReceiverException';
}

JSONReceiverException.prototype.toString = function () {
    return this.name + ': ' + this.message + '';
}





