
//UI for query builder

function IMS2_TaskQuery(id){
	var self = this;
	
	this.id = id;
	this.type = "query";
	this.currentIndex = 1;
    this.isActive = false;
    this.xmlReq;
    
        function Render(){
		var html = "";
		
		html += "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";
		html += "<tr class=\"task\" onmousedown=\"IMS2_Tasks.ActivateTask('" + self.id + "');\" onmouseover=\"this.className='taskOver';\" onmouseout=\"this.className='task';\"><td>Query Builder</td>";
		html += "<td style=\"font-size:xx-small;\" align=\"right\" width=\"35\" onmouseover=\"event.cancelBubble='true';\" onmouseout=\"event.cancelBubble='true';\"><img src=\"images/tasks/close.gif\" onmousedown=\"IMS2_Tasks.Remove(" + self.id + ");event.cancelBubble='true';\" onmouseover=\"this.src='images/tasks/close-over.gif';event.cancelBubble='true';\" onmouseout=\"this.src='images/tasks/close.gif';event.cancelBubble='true';\"/></td></tr>";
		html += "</table>";						
		
		html += "<div id=\"_task_" + self.id + "_pages\" style=\"display:none;\">"
		html += "<div id=\"_task_" + self.id + "_page_1\" class=\"taskPage\">";
		html += "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\">";
		html += "<tr><td class=\"wizLarge\">Step 1:  Select a Layer to Query</td></tr>";
		html += "<tr><td class=\"wizSmall\">&nbsp;</td></tr>";
		html += "<tr><td class=\"wizSmall\"><select onchange=\"IMS2_Tasks.Get('" + self.id + "').ShowSearchFields(this.value,'" + self.id + "');\" style=\"width:100%;border:solid 1px #cccccc;\" id=\"" + self.id + "_page_1_select_1\" size=\"1\"/>";
		html += "<option value=\"\"></option>";
		
		//populate dropdwon with layers that are available for use in query builder
		var maps = IMS2_MapManager.maps;
		var layers = maps[0].layers.layers;
		for(var i = 0; i < layers.length; i++){
			if(layers[i].type == "FeatureClass" && layers[i].useQuery == "True")
				html += "<option value=\"" + layers[i].id + "\">" + layers[i].name + "</option>";
		}
		
		html += "</select></td></tr>";
		
		html += "<tr><td class=\"wizSmall\">&nbsp;</td></tr>";
		html += "<tr><td class=\"wizSmall\">Fields:</td></tr>";
		html += "<tr><td class=\"wizSmall\"><select style=\"width:100%;border:solid 1px #cccccc;font-family: Verdana, sans-serif;font-size: small;\" id=\"" + self.id + "_page_1_select_2\" size=\"5\" ondblclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\" onchange=\"document.getElementById('" + self.id + "_page_1_select_3').options.length=0;\" />";
		html += "</select></td></tr>";
		html += "<tr><td class=\"wizSmall\">&nbsp;</td></tr>";
		
		html += "<tr><td class=\"wizSmall\" align=\"center\">";
		html += "<table cellpadding=\"2\" cellspacing=\"0\" >";
		html += "<tr><td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"&lt;\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"=\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" style=\"padding-right:7px;\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"&gt;\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" style=\"padding: 2px 10px 2px 10px;border-left: 1px solid #cccccc;\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"Lookup Values\" onclick=\"IMS2_Tasks.Get('" + self.id + "').LookupValues();\"></td></tr>";
		
		html += "<tr><td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"IS\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"&lt;=\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" style=\"padding-right:7px;\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"&lt;&gt;\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" rowspan=\"4\" style=\"border-left: 1px solid #cccccc;\">";
		html += "<select style=\"margin:5px;width:150px;border:solid 1px #cccccc;font-family: Verdana, sans-serif;font-size: small;\" id=\"" + self.id + "_page_1_select_3\" size=\"5\" ondblclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\" />";
		html += "</select></td></tr>";
		html += "<tr><td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"&gt;=\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"NULL\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" style=\"padding-right:7px;\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"AND\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td></tr>";
		html += "<tr><td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"OR\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"NOT\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" style=\"padding-right:7px;\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"' '\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td></tr>";
		html += "<tr><td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"%\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"LIKE\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td>";
		html += "<td class=\"tdSmall\" style=\"padding-right:7px;\"><input type=\"button\" class=\"textQueryButton\" onmouseover=\"this.className='textQueryButtonOver';\" onmouseout=\"this.className='textQueryButton';\" value=\"( )\" onclick=\"IMS2_Tasks.Get('" + self.id + "').InsertAtCursor(this.value);\"></td></tr>";
		
		html += "</table>";
		html += "</td></tr>";
		
		html += "<tr><td class=\"wizSmall\">&nbsp;</td></tr>";
		html += "<tr><td class=\"wizSmall\">Query String:</td></tr>";
		html += "<tr><td class=\"wizSmall\"><textarea rows=\"5\" style=\"width:95%;border:solid 1px #cccccc;font-family: Verdana, sans-serif;font-size: small;\" wrap=\"soft\" id=\"" + self.id + "_page_1_text\"></textarea></td></tr>";
				
		html += "<tr><td class=\"wizSmall\">&nbsp;</td></tr>";
		html += "<tr><td class=\"wizSmall\">";
		html += "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\">";
		html += "<tr><td class=\"wizSmall\"><input type=\"button\" class=\"textButton\" onmouseover=\"this.className='textButtonOver';\" onmouseout=\"this.className='textButton';\" value=\"Clear\" onclick=\"document.getElementById('" + self.id + "_page_1_text').value='';\"></td>";
		html += "<td class=\"wizSmall\"><input type=\"button\" value=\"Finish\" class=\"textButton\" onmouseover=\"this.className='textButtonOver';\" onmouseout=\"this.className='textButton';\" onclick=\"IMS2_Tasks.Get('" + self.id + "').Execute();\"></td></tr>";
		html += "</table>";
		html += "</table>";
		html += "</div>";
		html += "</div>";
		
		return(html);
	}
	this.Render = Render;
	
    
    //get fields that are available for query builder
    function ShowSearchFields(layer,id){
		var sel = document.getElementById(id + "_page_1_select_2");
		var sel2 = document.getElementById(self.id + "_page_1_select_3");
		var maps = IMS2_MapManager.maps;
		var layer = maps[0].layers.Get(layer);
		layer.GetFields();
		
		sel.options.length = 0;
		sel2.options.length = 0;
		
		for(var i = 0; i < layer.fieldsCollection.fields.length; i++)
		{
			var f = layer.fieldsCollection.fields[i];
			var ftype = "";
			if(f.useQuery == "False"){
				continue;
			}
			
			if(f.type == 1 ||f.type == 12 ||f.type == 14){
				ftype = " (character)";
			}else if(f.type == -5 || f.type == 4 || f.type == 5 || f.type == 6 || f.type == 8){
				ftype = " (number)";
			}
			
			sel.options[sel.options.length] = new Option(f.alias + ftype,f.name);
		}
		
	}
	this.ShowSearchFields = ShowSearchFields;
	
	function ToggleInfoDisplay(){
        var element = document.getElementById("_task_" + self.id + "_pages");
        if(element){  
            element.style.display == "none"  ? element.style.display = "block" : element.style.display = "none";
            element.childNodes[self.currentIndex - 1].style.display = element.style.display;
            element.style.display == "none"  ? self.isActive = "false" : self.isActive = "true";
        }
    }    
    this.ToggleInfoDisplay = ToggleInfoDisplay;    
    
    //get sample values for a field
    function LookupValues(){
		var mapctl = ((IMS2_MapManager)?(IMS2_MapManager.GetMap("MapControl1")):(null));
		if(!mapctl){
			return;
		}
		var lyr = document.getElementById(self.id + "_page_1_select_1").value;
		var fld = document.getElementById(self.id + "_page_1_select_2").value;
		if(lyr == "" || fld == ""){
			alert("Please select a layer and field.");
			return;
		}
		
		var requestMade = false;
	        
		self.xmlReq = IMS2_createXMLHTTPRequest();
		
		if(self.xmlReq){
			var url = "webservice.asmx/LookupValues";
			self.xmlReq.onreadystatechange = ProcessLookupValues;
			self.xmlReq.open("POST", url, false);//synchronous call
			self.xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			//limit set at 300 sample values in string below
			self.xmlReq.send("servicename=" + mapctl.mapdatasource + "&layerid=" + lyr + "&fieldname=" + fld + "&count=300");
			requestMade = true;
		}
		return(requestMade);
	}
	this.LookupValues = LookupValues;
	
	function ProcessLookupValues(){
        if(self.xmlReq){
            if( self.xmlReq.readyState == 4 )
		    {
			    if( self.xmlReq.status == 200 )
			    {
			        if(self.xmlReq.responseXML.normalize){
			            self.xmlReq.responseXML.normalize();
			        }
			        var root = self.xmlReq.responseXML.documentElement;   
			        
			        if(!root.childNodes[0]){
			            //self.featureResultSet = null;
			        }else{
						var data = null;
						var sel = document.getElementById(self.id + "_page_1_select_3");
						var fld = document.getElementById(self.id + "_page_1_select_2");
						sel.options.length = 0;
			            try{
		                    eval("data = " + root.childNodes[0].nodeValue + ";");
		                    
		                    //add values to dropdown
		                    for(var i = 0; i < data.length; i++){
								if(fld.options[fld.selectedIndex].text.indexOf("(character)") > -1){
									sel.options[sel.options.length] = new Option("\'" + data[i] + "\'","\'" + data[i] + "\'");
								}else{
									sel.options[sel.options.length] = new Option(data[i],data[i]);
								}
		                    }
		                
		                }catch(e){
		                    ;
		                }
			        }
			    }else{
			        alert("Connection error: " + self.xmlReq.status + "\n" + self.xmlReq.statusText + "\n" + self.xmlReq.responseText);
			    }
			    try{
			        self.xmlReq.abort();
			    }catch(e){;}
			    self.xmlReq = null;
			    //self.UpdateLoadingFeedback();
			}
        }
    }
    this.ProcessLookupValues = ProcessLookupValues;
    

   //modify sql string in UI when user clicks character
    function InsertAtCursor(val){
		var sql = document.getElementById(self.id + "_page_1_text");
		var txt = "";
		var surround = false;
		
		switch(val){
			case "''":				
			case "()":
				surround = true;
				break;
			case "%":
			case "_":
				break;
			default:
				val = " " + val + " ";
				break;				
		}
		
		if(IMS2_isMSIE()){
			sql.focus();
			var sel = document.selection.createRange();
			if(surround){
				sel.text = val.substring(0,1) + sel.text + val.substring(1);
			}else{
				sel.text = val;
			}
		}else{
			var startPos = sql.selectionStart;
			var endPos = sql.selectionEnd;
			if(surround){
				sql.value = sql.value.replace(sql.value.substring(startPos,endPos - startPos),val.subtring(0,1) + sql.value.substring(startPos,endPos - startPos) + val.substring(1))
			}else{
				sql.value = sql.value.substring(0,startPos) + val + sql.value.substring(endPos,sql.value.length);
			}
		}
		
		sql.value = sql.value.replace(/  /g," ");
		sql.value = sql.value.replace(/^\s+|\s+$/, ""); 
		
    }
    this.InsertAtCursor = InsertAtCursor;
	  
	  
	//get map object to execute query  
	function Execute(){
        var sql = document.getElementById(self.id + "_page_1_text");
        var lid = document.getElementById(self.id + "_page_1_select_1").value;
        if(sql && lid && "" != lid){
            if(sql.value && "" != sql.value){
                var mapctl = ((IMS2_MapManager)?(IMS2_MapManager.GetMap("MapControl1")):(null));
                if(mapctl){
                    mapctl.DataQueryLayer(sql.value,lid,false);
                    mapctl.RequestSelectedFeaturesDrill2(lid);
                }
            }
        }
    }
    this.Execute = Execute;    
}    
