
/* global configuration variables */

/* the url of the UA backend we submit drug costs to */
var uaPostUrl = 'PlanDrugCostUpdate.aspx';

/* the innova drug search tool base URL we use to make requests for drug costs */
var drugUrl = 'https://troop.ccrxgroups.com/api/';

/* code is called when the page is fully loaded */
$(document).ready(function () {

	/* see if we have a cookie for zip code set from the front page */
	if ( getCookie('zip') )
	{
		var zip = getCookie('zip');
	}
	else
	{
		var zip = '';
	}
	
	/*
	 * Get the Plans from a cookie set by the frontend.
	 * The plans should be in the format shown below.  The else block is only for
	 * development purposes, there should never be a production case where
	 * there's no "plans" cookie being set.
	 */
	if ( getCookie('plans') )
	{
		var includePlans = getCookie('plans');
	} 
	else
	{
		var includePlans = 'MHRUMAPD|9056010|91700,MHRUPARTB|9056010|95500';
	}
	
	
	/* set up a data store to talk to our drug lookup */
	var drugStore = new Ext.data.JsonStore({
		url: drugUrl + 'druglist', // url to request current list of added drugs
		root: 'drugs', // root item to find data in 
		fields: [ 'ddid', 'display_as', 'uid' ] // fields in the data returned
	});
	
	// load data from the remote source to get any existing drugs they have added
	drugStore.load();
	
	// create a grid to list the drugs
	var drugGrid = new Ext.grid.GridPanel({
		id: 'drug-grid',
		width: 400,
		height: 200,
		enableHdMenu: false,
		store: drugStore,
		columns: [ // just one column in our grid, the drug name
			{ 
				header: 'Drug',
				dataIndex: 'display_as'
			}
		],
		viewConfig: {
		        forceFit: true,
				autoFill: true
		    },
		bbar: [ // add a button bar with a delete item to remove drugs from the list
			'->',
			{ 
				text: 'Delete',
				handler: function() {
					/* handle removing drugs that have already been added */
					var grid = Ext.getCmp('drug-grid'); // get our grid
					var row = grid.getSelectionModel().getSelected(); // get the currently selected row
					
					// if there is no selected row, let them know they need to select one
					if ( ! row )
					{
						Ext.MessageBox.alert('Please select a row', 'Please select a row to remove a drug from your list');
						return;
					}
					
					// remove from the grid
					grid.getStore().remove(row);
					
					// remove from the druglookup session
					Ext.Ajax.request({
						url: drugUrl + 'remove_drug',
						method: 'post',
						params: { uid: row.data.uid }
					});
				} 
			}
		],
		frame: true
	});

	// create a window to house our search box and grid
 drugWindow = new Ext.Window({
            y: 40,
			title: 'Add My Drugs',
			id: 'drug_window',
			modal: true, // modal window dims background and blocks other UI interaction
			width: 450,
                        closable: false,
			items: new Ext.form.FormPanel({ // add a form panel to our window to hold the search box
				id: 'drugs_opt',
				bodyStyle: 'padding: 15px',
				border: false,
				items: [ // our form panel holds a combo box to search for data
					{
						xtype: 'combo', // combo box form element
						store: new Ext.data.Store({ // data store for the combo box which requests autocomplete matches from our drug search
							proxy: new Ext.data.ScriptTagProxy({
								url: drugUrl + 'autocomplete'
							}),
							reader: new Ext.data.JsonReader({
								id: 'drug_id'
							}, [ 'DDID', 'Drug_Name', 'Strength', 'Strength_Unit_of_Measure' ] )
						}),
						tpl: new Ext.XTemplate( // define a template to show the results
							'<tpl for="."><div class="x-combo-list-item">',
								'{Drug_Name} {Strength}{Strength_Unit_of_Measure}', // show the results as drug name strength
								'</div></tpl>'
						),
						name: 'query', // the form element name for this, drug search expects query
						emptyText: 'Enter a drug name', // text to display for an empty form element
						forceSelection: true, // forces the user to select a item from the list rather than allowing them to submit anything
						loadingText: 'Searching', // text to display while the autocomplete is fetching data
						minChars: 3, // minimum number of characters to type before a autocomplete request is made
						displayField: 'Drug_Name', // data store field to display in the box
						typeAhead: false,
						width: 200,
						id: 'drug-combo',
						listWidth: 200,
						hideTrigger: true, // hide the drop down arrow for this combo box
						onSelect: function( record ) {
							// pop open a window when they have selected a drug from the list
							// first make an ajax request to get the dispensing options
							Ext.Ajax.request({
								url: drugUrl + 'dosage',
								params: { ddid: record.data.DDID }, // pass the ddid to the request
								success: function(response) {
									Ext.getCmp('drug-combo').collapse(); // close the combo box drop down options menu
									var win = new Ext.Window({ // create a new window
										title: 'Select options',
										y: 50,
										width: 350,
										modal: true,
										id: 'options_window',
										html: response.responseObject.html, // load the html content the server returned into the window
										buttons: [ 
											{ // add a button to add the drug
												text: 'Add drug',
												handler: function() {
													// handle button click - first, mask the window while we fetch data
													var mask = new Ext.LoadMask('options_window', { msg: 'Loading drug information' } );
													mask.show();
													
													// get our form and append it's options to the request url
													// we cannot submit this as a form as IE get's unhappy
													var form = Ext.getDom('dispensing_amounts');
													var params = Ext.Ajax.serializeForm(form);
													
													// submit our dispensing options to drug search
													
													var separator = '?';
													if (form.action.indexOf('?') != -1)
													{
														separator = '&'
													}
													
													Ext.Ajax.request({
														url: form.action + separator + params, // append form values to the request
														method: form.method,
														success: function( response ) {
															// request returns a list of currently selected drugs, load those into the grid
															var store = Ext.getCmp('drug-grid').getStore();
															store.loadData( response.responseObject );
															mask.hide();
															win.hide();
														},
														failure: function( response ) {
															// requet failed, show an error message
															mask.hide();
															win.hide();
															Ext.MessageBox.alert('Error', 'An error occurred adding the drug');
														}
													});

													win.close();
												}
											} 
										]
									});
								
									win.show();
								}
							});
	
						
					
						},
						fieldLabel: 'Add a drug'
					}, 
					drugGrid // add our drug grid to the window
						
				],
				buttons: [ 
					{ 
						/* final drug submit, posts the data to the UA backend with the plans and costs */
						text: 'Submit',
						handler: function() {
							
							// mask the window with a message while we calculate the costs
							// this is a heavy request and if they have a lot of drugs could take a few seconds
							var mask = new Ext.LoadMask('drug_window', { msg: 'Calculating costs' } );
							mask.show();
							
							// requests our drug costs for their current list of drugs
							Ext.Ajax.request({
								url: drugUrl + 'calculate',
								method: 'post',
								params: { plans: includePlans, zip: zip }, // send a comman separated list of plans we want to calculat drugs for
								success: function( response ) {
									// request returns a list of plans and the costs for drugs for each
									var plans = response.responseObject.plans;
									
									// post the data we get to the backend
									Ext.Ajax.request({
										url: uaPostUrl,
										params: plans,
										success: function( response )
										{
											// update our drug cost table with the result
											var result = response.responseText;
											//Ext.get('results-inner-wrapper').update( result );
											Ext.get('panel_bottom').update( result );
											mask.hide();
											Ext.getCmp('drug_window').hide();
                               addDrugClickHandler();
										},
										failure: function( response )
										{
											Ext.MessageBox.alert('Error', 'An error occurred updating the drug plans');
											mask.hide();
											Ext.getCmp('drug_window').hide();
										}
									});
								}
							});
						}
					},
					{ 
						text: 'Cancel',
						handler: function() {
							Ext.getCmp('drug_window').hide();
						}
					}
				]
			})
		});

		// add our click handler
   addDrugClickHandler();
});

/* override connection functionality to handle cross domain ajax requests - should not be modified */
Ext.lib.Ajax.isCrossDomain = function(u) {
	var match = /(?:(\w*:)\/\/)?([\w\.]*(?::\d*)?)/.exec(u);
	if (!match[1]) return false; // No protocol, not cross-domain
	return (match[1] != location.protocol) || (match[2] != location.host);
};

Ext.override(Ext.data.Connection, {

    request : function(o){
        if(this.fireEvent("beforerequest", this, o) !== false){
            var p = o.params;

            if(typeof p == "function"){
                p = p.call(o.scope||window, o);
            }
            if(typeof p == "object"){
                p = Ext.urlEncode(p);
            }

            if(this.extraParams){
                var extras = Ext.urlEncode(this.extraParams);
                p = p ? (p + '&' + extras) : extras;
            }

            var url = o.url || this.url;
            if(typeof url == 'function'){
                url = url.call(o.scope||window, o);
            }

            if(o.form){
                var form = Ext.getDom(o.form);
                url = url || form.action;
				
                var enctype = form.getAttribute("enctype");
                if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
                    return this.doFormUpload(o, p, url);
                }
                var f = Ext.Ajax.serializeForm(form);

                p = p ? (p + '&' + f) : f;
            }

            var hs = o.headers;
            if(this.defaultHeaders){
                hs = Ext.apply(hs || {}, this.defaultHeaders);
                if(!o.headers){
                    o.headers = hs;
                }
            }

            var cb = {
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: {options: o},
                timeout : this.timeout
            };

            var method = o.method||this.method||(p ? "POST" : "GET");

            if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
                url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
            }

            if(typeof o.autoAbort == 'boolean'){ // options gets top priority
                if(o.autoAbort){
                    this.abort();
                }
            }else if(this.autoAbort !== false){
                this.abort();
            }
            if((method == 'GET' && p) || o.xmlData || o.jsonData){
                url += (url.indexOf('?') != -1 ? '&' : '?') + p;
                p = '';
            }
            if (o.scriptTag || this.scriptTag || Ext.lib.Ajax.isCrossDomain(url)) {
               this.transId = this.scriptRequest(method, url, cb, p, o);
            } else {
               this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
            }
            return this.transId;
        }else{
            Ext.callback(o.callback, o.scope, [o, null, null]);
            return null;
        }
    },
    
    scriptRequest : function(method, url, cb, data, options) {
        var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
        var trans = {
            id : transId,
            cb : options.callbackName || "stcCallback"+transId,
            scriptId : "stcScript"+transId,
            options : options
        };

        url += (url.indexOf("?") != -1 ? "&" : "?") + data + String.format("&{0}={1}", options.callbackParam || this.callbackParam || 'callback', trans.cb);

        var conn = this;
        window[trans.cb] = function(o){
            conn.handleScriptResponse(o, trans);
        };

//      Set up the timeout handler
        trans.timeoutId = this.handleScriptFailure.defer(cb.timeout, this, [trans]);

        var script = document.createElement("script");
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", trans.scriptId);
        document.getElementsByTagName("head")[0].appendChild(script);
		
        return trans;
    },

    handleScriptResponse : function(o, trans){
        this.transId = false;
        this.destroyScriptTrans(trans, true);
        var options = trans.options;
        
//      Attempt to parse a string parameter as XML.
        var doc;
        if (typeof o == 'string') {
            if (window.ActiveXObject) {
                doc = new ActiveXObject("Microsoft.XMLDOM");
                doc.async = "false";
                doc.loadXML(o);
            } else {
                doc = new DOMParser().parseFromString(o,"text/xml");
            }
        }

//      Create the bogus XHR
        response = {
            responseObject: o,
            responseText: (typeof o == "object") ? Ext.util.JSON.encode(o) : String(o),
            responseXML: doc,
            argument: options.argument
        }
        this.fireEvent("requestcomplete", this, response, options);
        Ext.callback(options.success, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, true, response]);
    },
    
    handleScriptFailure: function(trans) {
        this.transId = false;
        this.destroyScriptTrans(trans, false);
        var options = trans.options;
        response = {
            argument:  options.argument,
            status: 500,
            statusText: 'Server failed to respond',
            responseText: ''
        };
        this.fireEvent("requestexception", this, response, options, {
            status: -1,
            statusText: 'communication failure'
        });
        Ext.callback(options.failure, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, false, response]);
    },
    
    // private
    destroyScriptTrans : function(trans, isLoaded){
        document.getElementsByTagName("head")[0].removeChild(document.getElementById(trans.scriptId));
        clearTimeout(trans.timeoutId);
        if(isLoaded){
            window[trans.cb] = undefined;
            try{
                delete window[trans.cb];
            }catch(e){}
        }else{
            // if hasn't been loaded, wait for load to remove it to prevent script error
            window[trans.cb] = function(){
                window[trans.cb] = undefined;
                try{
                    delete window[trans.cb];
                }catch(e){}
            };
        }
    }
});


/* fix ie combobox rendering glitch */
Ext.form.TriggerField.override({
    afterRender : function(){
        Ext.form.TriggerField.superclass.afterRender.call(this);
        var y;
        if(Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())){
            this.el.position();
            this.el.setY(y);
        }
    }
});


function addDrugClickHandler()
{
		Ext.select('a.add_drugs').on('click', function( event ) {
			drugWindow.show(); // show the drug window
			Ext.getCmp('drug-combo').focus(); // focus the search box
		});
}
