// create namespace
Ext.ns('Sight');
 
// create util lib
Sight.util = function() {
    // do NOT access DOM from here; elements don't exist yet
    // ----------------------------------- private variables
    // panels of the main window
    // ----------------------------------- public space
    return {
        // public methods
    	applyPatches:function() {
    		// Begin patch
                Ext.override(Ext.form.ComboBox, {
				    setValue : function(v){
				//begin patch
				        // Store not loaded yet? Set value when it *is* loaded.
				        // Defer the setValue call until after the next load.
				        if (this.store.getCount() == 0) {
				            this.store.on('load',
				                this.setValue.createDelegate(this, [v]), null, {single: true});
				            return;
				        }
				//end patch
				        var text = v;
				        if(this.valueField){
				            var r = this.findRecord(this.valueField, v);
				            if(r){
				                text = r.data[this.displayField];
				            }else if(this.valueNotFoundText !== undefined){
				                text = this.valueNotFoundText;
				            }
				        }
				        this.lastSelectionText = text;
				        if(this.hiddenField){
				            this.hiddenField.value = v;
				        }
				        Ext.form.ComboBox.superclass.setValue.call(this, text);
				        this.value = v;
				    }
				});
				// End patch
				Ext.override(Ext.form.Field, 
	{	afterRender : Ext.form.Field.prototype.afterRender.createSequence(function()
		{
			var qt = this.qtip;
		    if (qt)
		    {	
		    	var target=this.getTargetTip();
		    	Ext.QuickTips.register({
		        target:  target,
		        title: '',
		        text: qt,
		        enabled: true,
		        showDelay: 20
		    	});
		    }
		}),
		getTargetTip:function(){
			return this.el;
		}
	});
    	}    	
    	,createStore:function(name, url, fields) {	        
	        var myStore = new Ext.data.Store({						
				storeId:'store_'+name,					
				autoLoad:true,					
				proxy: new Ext.data.HttpProxy({
			   		url: url,
					reader: new Ext.data.JsonReader({
			   				root: 'data',
			   			totalProperty: 'count'},
			   				fields 
			   		)
				})        		
	        });
	        return myStore;
        }
        ,pauseMillis:function(millis) {
			var date = new Date();
			var curDate = null;
			do { curDate = new Date(); } 
				while(curDate-date < millis);
		}
		// Line Splitter Function
        // copyright Stephen Chapman, 19th April 2006
        // you may copy this code but please keep the copyright notice as well
        ,splitLine:function (st,n) {
            var b = '';
            var s = st;
            while (s.length > n) {
                var c = s.substring(0,n);
                var d = c.lastIndexOf(' ');
                var e =c.lastIndexOf('\n');
                if (e != -1)
                    d = e;
                if (d == -1)
                    d = n;
                b += c.substring(0,d) + '\n';
                s = s.substring(d+1);
            }
            return b+s;
        }
        ,
        showError:function (msg, title) {
            title = title || 'Error';
            Ext.Msg.show({
                title:title

                           ,msg:msg

                           ,modal:true

                           ,icon:Ext.Msg.ERROR

                           ,buttons:Ext.Msg.OK
            });
        }

             ,showWarning:function(msg, title) {
            title = title || 'Warning';
            Ext.Msg.show({
                title:title

                           ,msg:msg

                           ,modal:true

                           ,icon:Ext.Msg.WARNING

                           ,buttons:Ext.Msg.OK
            });
        }

             ,showInfo:function(msg, title) {
            title = title || 'Information';
            Ext.Msg.show({
                title:title

                           ,msg:msg

                           ,modal:true

                           ,icon:Ext.Msg.INFO

                           ,buttons:Ext.Msg.OK
            });
        }

             ,onSubmitFailure:function (form, action) {
            var failureMessage='';
            if (action.failureType == Ext.form.Action.LOAD_FAILURE) {
                // Error on the server side will include an error message in
                // the response.
                failureMessage = action.result.message;
            }
            // Failure type returned when a communication error happens when
            // attempting to send a request to the remote server.
            else if (action.failureType == Ext.form.Action.CONNECT_FAILURE) {
                // The XMLHttpRequest object containing the
                // response data. See http://www.w3.org/TR/XMLHttpRequest/ for
                // details about accessing elements of the response.
                failureMessage = "Contact your administrator: " +
                "Status: " + action.response.status +
                ", Message: " + action.response.statusText;
            }
            // Failure type returned when server side validation of the Form fails
            // indicating that field-specific error messages have been returned in
            // the response's errors property.
            else if (action.failureType == Ext.form.Action.SERVER_INVALID) {
                // Validation on the server side will include an error message in
                // the response.
				var object = Ext.util.JSON.decode(response.responseText);
                if (object.errors) {
                    for (var i in object.errors) {
                        failureMessage += i + " : " + object.errors[i] + "<br/>";
                    }
                }
                failureMessage += action.result.message;
            }
            // Failure type returned when client side validation of the Form fails
            // thus aborting a submit action.
            else if (action.failureType == Ext.form.Action.CLIENT_INVALID) {
                failureMessage = "Validation error.";
            }
            // Since none of the failure types handled the error, simply retrieve
            // the message off of the response. The response from the server on a
            // failed submital (application error) is:
            // success: false, message: 'Person was not updated successfully. Please try again.')
            else {
                failureMessage = action.result.message;
            }
						
            Sight.util.showError(failureMessage);
		            		
        } // eo onSubmitFailure

             ,requestFailed:function(response, options) {
            Sight.util.showError("Contact your administrator: " +
                "Status: " + response.status + ", Message: " + response.statusText, 'Error');
        } // eo request failed
        ,
        init: function() {
            try {
            //alert('Init successfully initialized');
            } catch(e) {
                alert('Error: "' + e.message + '" at line: ' + e.lineNumber);
            }
        }
    };
}(); // end of app

// Start the util
Ext.onReady(Sight.util.init, Sight.util);
 
// end of file
