/*
 * CdmClient
 * 
 * @description: populate a select element with results from a rest service call.
 * @author: Chris Hill
 * 
 * service: path to cdmService 
 * client_code: client or campus code (CustNum)
 * param, value options: '', '' - returns all programs.
 * 					   categories, all - returns DegreeLevel and Category.
 * 					   category, * - returns program info for category with name=value.
 * 					   degree, degree_level% - returns all programs with degree_level if only the 1st char is passed 
 * 											   (eg. degree=B returns BA, BS etc..,) or degree type if all chars.
 * 
 * elt_name: name of select element. put element inside a div/span and name it 'elt'_select. (eg. program_select)
 * elt_value: field to use to populate the value of the element
 * elt_text: field(s) to use to populate the text node of the element
 * delim: optional delimiter for concatenating field(s)
 * handler: config object used when attaching an event handler. 
 * label, vlabel: labels for select and validation messages.
 * 					   
 */

CdmClient = function() {
	var url = '/global/cdm-server.php?path=http://ulm.datamark.com/cdm';
	//var url = '/global/cdm-server.php?path=http://ulm.datamark.com/cdm';

	var response, handler, config, debug;
	var configs = new Array();

	var buildSelect = function() {
		/**
		* Trying to fix a bug that happens when zipcode pasted in.
		* Basically if there isn't anything in the first value,
		* don't enable and print options.
		*/
		if (response.body[0] == null) {
			dispForm(false);
			return;
		}
		
		if (!response.body[0][config.elt_value]) {
			return;			
		}
		
		var e = '<span class="ie-select-width-fix" style="vertical-align:middle; position:relative; top:-1px; padding-bottom:4px;" >';
		e += '<select name="'+config.elt_name+'" id="'+config.elt_name+'" dtmk:validation="{required:true,message:\' '+config.vlabel+'.\'}">';
		e += '<option value="">'+config.label+'</option>';

		for(var i = 0; i < response.body.length; i++) {
			var r =  response.body[i];

			// construct text and value for element with an array of values and an optional delimiter
			if(config.elt_text.length > 1 && config.delim != '') { 
				r[config.elt_text] = r[config.elt_text[0]] + config.delim + r[config.elt_text[1]];
			} else {
				r[config.elt_text] = r[config.elt_text[0]]; 
			}
			if(config.elt_value.length > 1 && config.delim != '') { 
				r[config.elt_value] = r[config.elt_value[0]] + config.delim + r[config.elt_value[1]];
			} else {
				r[config.elt_value[0]]; 
			}
			e += '<option value="' + r[config.elt_value] + '"';
			
			if(response.body.length == 1) { e += ' selected="Selected"'; }
			
			e += '">' + r[config.elt_text] + '</option>';
		}
		e += '</select></span>';

		Ext.getDom(config.container).innerHTML = e;	

		var expand_select1 = new YAHOO.dtmk.FixIESelectWidth(config.elt_name);

		if(config.handler) { CdmClient.attachHandler(config.handler); }
	};
	
	return {
		init: function(c) {
			// service url override
			if(c[0].url) { url = c[0].url; } 
			// set config or store configs in an array
			if(c.length == 1) {
				config = c[0];
			} else {
				for(var i = 0; i < c.length; i++) {
					configs[i] = c[i];
				}
			}
		},
		setConfig: function(config_num) {
			config = configs[config_num];
			// if no validation label has been set, use label.
			if(!config.vlabel) { config.vlabel = config.label; } 
		},
		callService: function(value) {
			if(value) { config.value = value; }	
			// build query string from params/values
			var path = url + '/' + config.service + '?';
			var query_string = ''; 
			if (config.param) {
				if (config.param.length > 1) {
					for (var i = 0; i < config.param.length; i++) {
						query_string += config.param[i] + '=' + config.value[i] + '&';
					}
				} else {
					query_string = config.param[0] + '=' + config.value[0]
				}
			}
			if(config.debug) {
				console.log(url + '/' + config.service);
				console.log(query_string);
				console.log(config);
			}
			Ext.Ajax.request({
				method: 'GET', 
				url: path,
				params: query_string,
				success: function(r){
					response = Ext.util.JSON.decode(r.responseText);
					buildSelect();
				}
			});
		},
		attachHandler: function(handler) {		
			var elt_name = config.elt_name;		
			// set config based on value in handler param
			CdmClient.setConfig(handler);
			
			Ext.get(elt_name).on('change', function() {
				Ext.getDom(config.container).innerHTML = "<select name='campus_code' id='campus_code' dtmk:validation=\"{required:true,message:'Please select a campus.'}\" disabled><option value=''>Loading................................</option></select>";
				// replace {campus_code} with the CustNum of the selected campus.
				if (Ext.getDom('program_code').selectedIndex != 0) {
					config.service = 'corinthian/campuses';
					config.value = new Array(Ext.getDom('postal_code').value, Ext.getDom('program_code').value, 'Name');
					
					CdmClient.callService();
				}
				else {
					Ext.getDom(config.container).innerHTML = "<select name='campus_code' id='campus_code' dtmk:validation=\"{required:true,message:'Please select a campus.'}\" disabled><option value=''>Please select a program</option></select>";
				}

			});
		}	
	}
}();