﻿// get rid of 'Secure and unsecure content' warning under SSL connection
//Ext.BLANK_IMAGE_URL = "./resources/images/gray/s.gif";
Ext.BLANK_IMAGE_URL = "./img/pixel.gif";
Ext.LOADING_ANIM_IMG_URL = './img/search_anim_tr.gif';
Ext.COMMUNICATION_FAILURE_STATUS  = 0;
Ext.COMMUNICATION_FAILURE_MESSAGE = 'Communication failure.' // No response from web-server
Ext.COMMUNICATION_ABORT_STATUS = -1;
Ext.COMMUNICATION_ABORT_MESSAGE = 'Transaction aborted.'; // Ajax request aborted

if ( !Ext.isIE ) {
    Ext.enableGarbageCollector = false;    
} else {
    try { var href = document.location.href; } catch (e) { document.location.reload(); } 
}
Ext.namespace('Veeam');

// DataProxy for jayrock
Veeam.RpcDataProxy = function( config ) {
    Ext.apply ( this, config );
    Veeam.RpcDataProxy.superclass.constructor.apply(this, arguments);
};

Ext.extend( Veeam.RpcDataProxy, Ext.data.DataProxy, {
    initComponent : function() {
        Veeam.RpcDataProxy.superclass.initComponent.call(this);
    },
    
    load : function(params, reader, callback, scope, arg){
        if(this.fireEvent("beforeload", this, params) !== false){
            var  o = { 
                params : params || {},
                request: { callback : callback, scope : scope,  arg : arg },
                reader: reader,
                callback : this.loadResponse,
                scope: this
            };
            CommonDataHandler.rpc[this.method]( params, this.processResponce.createDelegate( this, [o], true ) ).call(ext_channel);
    
        }else{
            callback.call(scope||this, null, arg, false);
        }
    },
    
    processResponce : function(result , o) {
        if ( !result ) return;
        if (result.success == false){
            this.fireEvent('exception', this, 'remote', null, o, result);
        } else {
            var r = o.reader.readRecords( result );       
            this.fireEvent("load", this, o, o.request.arg);
            o.request.callback.call(o.request.scope, r, o.request.arg, true);
        }
    }
});

// TreeLoader for jayrock
Veeam.RpcTreeLoader = function(config) {
    Veeam.RpcTreeLoader.superclass.constructor.apply(this, arguments);

    this.rpcProxy = CommonDataHandler;
    this.dataUrl = '.'; // little hack
};

Ext.extend(Veeam.RpcTreeLoader, Ext.tree.TreeLoader, {

    // override base mathod so it can work with jayrock
    requestData : function(node, callback) {
        
        if(this.fireEvent("beforeload", this, node, callback) === false){
            return 
        }

        var attr = this.nodeAttr || "id",
            decode = Ext.util.Format.htmlDecode;

        var params = { node : decode(node.attributes[attr] || node.id) };
        Ext.apply( params, this.baseParams );
    
        this.rpcProxy.rpc[this.method]( params,
            this.handleResponse.createDelegate(this, [node, callback], true )  
        ).call(ext_channel);    
    },

    // create  node from json object with subnodes
    _createNodeTree : function(node, json) {
        var newnode = this.createNode(json);
        if (newnode) 
            node.appendChild(newnode); 
        
        if ( !node.leaf && json.children ) {
            for(var i = 0, len = json.children.length; i < len; i++) {
                this._createNodeTree( newnode, json.children[i] );
            } 
        }
       /*
        if (newnode instanceof Ext.tree.AsyncTreeNode){
            newnode.loaded = false;
        } else {
            newnode.loaded = true;
        }
        
        newnode.loading = false;
        */
    },
    
    
    // need to write own response processing
    handleResponse : function(result, node, callback) {
        this.transId = false;
        if ( !result ) return;
        if (result.success === false){
            // handle error
            this.fireEvent("loadexception", this, node, result);
            return
        }

        node.beginUpdate();
        for(var i = 0, len = result.length; i < len; i++) {
            this._createNodeTree( node, result[i] );
        }
        node.endUpdate();
        if (typeof(node.loadCompete) == 'function') { 
            node.loadComplete(); 
        }
        if(typeof callback == "function") { callback(this, node); }
        //this.fireEvent("load", this, node, result);
    }
});

Veeam.AsyncRcpTreeLoader = Ext.extend(Veeam.RpcTreeLoader, {

        constructor: function(cfg)
        {
            var cfg = Ext.apply({
              taskManager: new Ext.util.TaskRunner(),
              pendingTasks: new Ext.util.MixedCollection(),
              updateInterval: 2000,
              updateMethod: "checkState"
            }, cfg);
            Veeam.AsyncRcpTreeLoader.superclass.constructor.call(this, cfg);
        },

        createTask: function(serverTaskObj, node, callback)
        {
           var taskObj = {
               taskId : serverTaskObj.uuid,
               node: node,
               cb: callback
           };

           var runTask = {
               run: this.checkTaskState,
               args: [ taskObj ],
               scope: this,
               interval: this.updateInterval,
               duration: 10*60*1000 // 10 min timeout
           };

            this.taskManager.start(runTask);
            this.pendingTasks.add( taskObj.taskId, runTask);

        },

        taskCallback: function(response, task)
        {
           if (response == null)
               return  // Task is still running - do nothing


           if (response.success == false)
           {
               this.fireEvent("loadexception", this, task.node, response);
           }



            // remove task
            if (this.pendingTasks){
                var t = this.pendingTasks.get(task.taskId);
                if (t && this.taskManager){
                    //log('Stoping check task. id' + task.taskId);
                    this.taskManager.stop(t);
                }
                this.pendingTasks.removeKey(task.taskId);

            }

            //log("Task complete. Task " + task.taskId);
           // Task complete - update UI
            if (response.items) {
                task.node.beginUpdate();
                if (response.totalCount >= 1000){
                    Veeam.Msg.warning({ msg: "Returned dataset is too large. Displaying top 1000 records only." });
                    response.items.length = 1000;
                }

                this._createNodeTree( task.node, response.items );

                task.node.endUpdate();

                if (typeof(task.node.loadComplete) == 'function') {
                    task.node.loadComplete();
                }

                if (typeof task.callback == "function" )
                    task.callback(this, task.node);
            }
            task = null;
        },

        _createNodeTree: function(node, data){
             var nodeData = [].concat(data),
                 nodes = [];

             for (var i = 0, len = nodeData.length; i < len; i++)
                nodes[i] = this.createNode(nodeData[i]);

            node.appendChild(nodes);

        },

        checkTaskState: function(  task ){
            if (!task.taskId)
                throw Error("Task id is empty.");

            var params = Ext.apply({
                taskId: task.taskId
            }, this.baseParams);

            //log("Checking task state. Task " + task.taskId);
            this.rpcProxy.rpc[this.updateMethod]( params, this.taskCallback.createDelegate(this, [task], true) ).call(ext_channel);
        },

        handleResponse : function(result, node, callback) {
            this.transId = false;

            if (result.success === false){
                // handle error
                this.fireEvent("loadexception", this, node, result);
                return
            }

            if (!result.uuid)
                throw new Error("Failed to get task id from server.");

            this.createTask( result, node, callback );
    },

    onDestroy: function()
    {
        if (this.taskManager)
            this.taskManager.stopAll();

        if (this.pendingTasks)
            this.pendingTasks.removeAll();

        Veeam.AsyncRcpTreeLoader.superclass.onDestroy.call(this)
    }
});

// Common combobox with tree. Uses Veeam.RpcTreeLoader to load tree.
// config = { rpcMethod: ..., /etc./ }
Veeam.TreeComboBox = function(config) {

    this.nodeClickable = true;  // if true then each node is clickable, otherwise only leafs
    this.pathDepth = 100; // number of full names in path
    this.pathSeparator = '/';
    this.pathElipses = '..';
    this.includeRootInPath = false;
    this.selectedNode = null;
            
    this.treeContainerId = Ext.id() + '-tree';    
    
    config = Ext.applyIf( config, {
	    store: new Ext.data.SimpleStore({fields:[],data:[[]]}),
        maxHeight: 300,
        tpl: String.format('<div style="height:200px;" id="{0}"></div>', this.treeContainerId ),
        mode: 'local',
        forceSelection: true,
        selectOnFocus: true,
        triggerAction: 'all'
        //width: 200
    });  
    
    config.treeConfig = Ext.applyIf( (config||{}).treeConfig||{}, {
        rootVisible: true,
        border: false,
        lines: true,
        containerScroll: true, 
        loader: new Veeam.RpcTreeLoader( Ext.apply({  method : config.rpcMethod, clearOnLoad: false }) )
    });
    
    config.treeConfig.root = Ext.applyIf(  ((config||{}).treeConfig||{}).root||{} ,{        
        nodeType:'async',
        text: 'Root',
        expanded:true,                                                          
        draggable:false
    });
    
    Ext.apply( this, config );
    Veeam.TreeComboBox.superclass.constructor.apply(this, arguments);
    
    this.on('expand', this.expandHandler.createDelegate(this));
    this.on('collapse', this.collapseHandler.createDelegate(this));

    this.theTree = new Ext.tree.TreePanel( this.treeConfig );
    this.theTree.on('load', this.nodeLoaded.createDelegate(this));
    this.theTree.on('click', this.nodeClick.createDelegate(this));
    this.theTree.on('beforeclick', (function(node) { return this.nodeClickable || node.leaf;} ).createDelegate(this));
};

Ext.extend( Veeam.TreeComboBox, Ext.form.ComboBox, {

    expandHandler: function() {
        if ( !this.theTree.rendered )
    	    this.theTree.render( this.treeContainerId );
    	    
        var root = this.getTree().getRootNode();
        if ( !root.isLoaded() && !root.isLoading() && this.toSel )
            this.getTree().getLoader().load(root);
    },
    
    collapseHandler: function() {
    },
    
    _updateText : function(node) {
        var value = node.text;
        var parent = node.parentNode;
        this.selectedNode = node;
        var c = 1;
        while ( parent!=null && !( parent.isRoot && !this.includeRootInPath )  ) {
            value = (c>=this.pathDepth ? this.pathElipses : parent.text) + this.pathSeparator + value;
            parent = parent.parentNode;
            c += 1;
        }
	    this.setValue(value);
    },
    
    nodeClick : function(node) {
        this._updateText(node);
	    this.collapse();
    },
    
    nodeLoaded : function (node) 
    {
        if (!this.toSel) return;
        var n = this.findNodeBy( this.toSel.attrname, this.toSel.value, this.getTree().getRootNode() );
        if ( n ) { 
            this.getTree().expandPath( n.getPath() );
            n.select(); 
        };
    },
    
    getTree : function() {
        return this.theTree;
    },

    findNodeBy : function( attrname, value, node ) {
        if ( node.attributes[attrname] == value )
            return node;

        var cn = node.childNodes;
        for ( var i = 0; i < cn.length; i++ ) {
            var n = this.findNodeBy(attrname, value, cn[i] );
            if ( n != null ) return n;
        }
        return null;
    },
    
    selectNodeBy : function( attrname, value ) {
        if ( this.selectedNode ) {
            this.selectedNode.unselect();
            this.setValue('');
            this.selectedNode = null;
        }
        
        var root =  this.getTree().getRootNode();
        if ( root.isLoaded()  ) {
            var n = this.findNodeBy( attrname, value, root );   
            if ( n ) {
                this.getTree().expandPath( n.getPath() );
                n.select(); 
            }
        } else {
            this.toSel = { attrname: attrname, value: value };
        }
    }
});

/*
    SimpleComboBox
*/    
Veeam.SimpleComboBox = function(config) {
    var store = new Ext.data.SimpleStore({ 
        fields:['value','text'], 
        data: config.data || [] 
    });
    
    config = Ext.apply(config||{}, {    
        store : store,
        valueField: 'value', 
        displayField: 'text',                        
        typeAhead: true,
        triggerAction: 'all',
        shadow:false,
        editable:false,
        mode: 'local'
    });
       
    Veeam.SimpleComboBox.superclass.constructor.apply(this, [config] );
};
Ext.extend(Veeam.SimpleComboBox, Ext.form.ComboBox, {
    forceWidth : function(w) {
        if (this.rendered === true){
            this._forceWidth(w);
        } else {
            this.addListener('afterrender', function(){
                this._forceWidth(w);
            }, this);
        
        }
    },
    _forceWidth: function(w){
        this.wrap.setWidth( w ); 
        this.el.setWidth( w-17 );
    }
});
Ext.reg('vm.ui.combobox', Veeam.SimpleComboBox);


// Veeam.CenterLayout
Veeam.CenterLayout = Ext.extend(Ext.layout.FitLayout, {
    setItemSize : function(item, size){
        this.container.addClass('ux-layout-center');
        item.addClass('ux-layout-center-item');
        if(item && size.height > 0) {
            if(item.width){ size.width = item.width; }
            item.setSize(size);
        }
    }
});
Ext.Container.LAYOUTS['vm.center'] = Veeam.CenterLayout; 

// 
var ext_channel = function(call)
{
    if (typeof(call.callback) !== 'function')
        throw new Error("The EXT channel does not support synchronous methods.");        

    var requestTimeout = Veeam.Defaults && Veeam.Defaults.requestTimeout ? Veeam.Defaults.requestTimeout : 60000;
    
    var srpc = Ext.encode(call.request);
    
    call.yuiconn = Ext.Ajax.request ({
            timeout: requestTimeout,
            url: call.url , 
            params: { "JSON-RPC": srpc }, 
            method:'POST',
            success: function(response, options) {
                if ( !response.responseText )       
                    alert( "Enterprise Manager service did not respond in a timely manner." );
                else {                    
                    var o = Ext.decode(response.responseText);
                    if ( o.error ) {
                        if ( o.error.redirectUrl ) {
                            var l = document.location;
                            l.href = l.protocol+'//' + l.host + decodeURI(o.error.redirectUrl);
                        }
                        else if ( o.error.redirectLogin ) {
                            var l = document.location;
                            var url = l.pathname + l.search;
                            l.href = l.protocol+'//' + l.host + o.error.redirectLogin + '?' + url;
                        }
                        else                        
                            alert("responseText=" + response.responseText);
                    } else {
    				    call.callback(o.result);
    		        }
    		    }
			},      
		    failure: function(response, options) {
		        // Handle http error
		        if (response.isAbort == true)
		            if (response.isTimeout == true)
		                alert("Enterprise Manager service did not respond in a timely manner.");
                    return // do not show error if request was aborted by client
                var message;
                if (response.status == Ext.COMMUNICATION_ABORT_STATUS){
                    message = Ext.COMMUNICATION_ABORT_MESSAGE;
                } else if (response.status == Ext.COMMUNICATION_FAILURE_STATUS){
                    message = Ext.COMMUNICATION_FAILURE_MESSAGE;
                } else {
                    message = String.format("[{0}] {1}", response.status,  response.statusText || "Unexpected Error");
                }

                Ext.Msg.alert('Error', message);
            }   
        }
    );
    return call ; 
};

/* Add label next to formfield */

Veeam.BoxLabelPlugin = Ext.extend(Ext.util.Observable, {
    init: function(field){
        this.field = field;
        if (this.field.initialConfig.boxLabel){
            this.boxLabelText = this.field.initialConfig.boxLabel;
            field.afterMethod('onRender', this.doRender, this);
        }
    },

    doRender: function(ct, position){
            this.field.container.createChild({ 
                tag: 'div',
                html: this.boxLabelText,
                cls: 'x-formfield-boxlabel',
                style: 'display: inline; padding-left: 5px;'
            });
            if (Ext.isIE){
                this.field.wrap.applyStyles('display: inline;');   
            } else {
                this.field.wrap.applyStyles('display: inline-block;'); 
            }     
    }
});



log  = function (){
     if (typeof(console) != 'undefined' && console.log){
        console.log('[DEBUG]' + Array.prototype.shift.call(arguments), arguments);
     }   

}


// Add daterange validation
Ext.apply(Ext.form.VTypes, {
	daterange : function(val, field) {
		var date = field.parseDate(val);
 
		if(!date){
			return true;
		}
		if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
			var start = Ext.getCmp(field.startDateField);
			start.setMaxValue(date);
			this.dateRangeMax = date;
			start.validate();
		} 
		else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
			var end = Ext.getCmp(field.endDateField);
			end.setMinValue(date);
			this.dateRangeMin = date;
			end.validate();
		}
		/*
		 * Always return true since we're only using this vtype to set the
		 * min/max allowed values (these are tested for after the vtype test)
		 */
		return true;
	}
});


Veeam.ObjectHelper = {
   /*
    *	Create object from class name (e.q. Veeam.Plugins.MetaPlugin)
    */
   create: function (className) {
        var current,
                parts,
                constructorName,
                plugin;

        parts = className.split('.');
        constructorName = parts[parts.length - 1];
        current = window;
        for (var i = 0; i < parts.length - 1; i++) {
            current = current[parts[i]];
        }

        return new current[constructorName]();
    }
};


Veeam.VmDateField = function (cnf) {
    var c = cnf || {};

    c = Ext.applyIf(c, {
        format: Veeam.Defaults.dateFormat
    });

    Veeam.VmDateField.superclass.constructor.apply(this, [c]);
}

Ext.extend(Veeam.VmDateField, Ext.form.DateField, {
    forceWidth: function (w) { this.wrap.setWidth(w); this.el.setWidth(w - 17); }
});

Ext.reg('vm.ui.datefield', Veeam.VmDateField);

