//LK This function will grab an input from the Mapbook DOM object so it can be manipulated
function selectServiceInput(serviceName,inputName) {
	var services = theMapbook.getElementsByTagName('service');
	for(i=0; i<services.length; i++) {
	    var service = services[i];
	    if (service.nodeType === 1) {
		if(service.getAttribute("name") == serviceName) {
			var inputs = service.getElementsByTagName('input');
			for(r=0; r<inputs.length; r++) {
			    var input = inputs[r];
			    if (input.nodeType === 1) {
				if(input.getAttribute("name") == inputName) {
				    var pickme = input;
				}
			    } 
			}
	       }
	    }
	}
	return pickme;
}

GeoMOOSE.Services.InputType.AjaxSelectChoropleth = OpenLayers.Class(GeoMOOSE.Services.InputType, {
	MAPBOOK_NAME: "ajax_select_choropleth",
	input: null,

	initialize: function(input, options) {
		this.options = {
			renderable: true
		};
		this.input = input;

	},

	getOptions: function() {
		var url = OpenLayers.Util.getXmlNodeValue(this.input);
		var formed_opts = [];

		var requestOptions = OpenLayers.Request.POST({
			url: url,
			async: false,
			params: {}
		});

		var response = requestOptions.responseXML;

		var opts = response.getElementsByTagName('option'); 
		for(var i = 0 ; i < opts.length; i++) {
			formed_opts.push({value: opts[i].getAttribute('value'), name: OpenLayers.Util.getXmlNodeValue(opts[i])});
		}
		return formed_opts;	
	},

	getValue: function() {
		return this.input.getAttribute('value');
	},

	setValue: function(v) {
		this.input.setAttribute('value', v);
	},

	updateSettings: function() {
		var fid = this.getElementsByTagName('option')[this.selectedIndex].value;
		
		this.input_obj.setValue(fid);

		var url = "custom/choropleth.php?mode=get_default_breaks"
		var requestOptions = OpenLayers.Request.POST({
			url: url,
			async: false,
			params: {'theme':fid}
		});

		var response = requestOptions.responseXML;
		var opts = response.getElementsByTagName('breaks'); 

		for(var i = 0 ; i < opts.length; i++) {
			document.getElementById("service-input-breaks").value = OpenLayers.Util.getXmlNodeValue(opts[i]);
		}

		var breaks = selectServiceInput('choropleth_map','breaks');
		
		if(breaks.childNodes) {
		    while(breaks.childNodes.length > 0) {
			breaks.removeChild(breaks.childNodes[0]);
		    }
		}	
		breaks.appendChild(breaks.ownerDocument.createCDATASection(document.getElementById("service-input-breaks").value));


	},

	renderHTML: function(parent_id) {
		var p = document.getElementById(parent_id);
		var inputParent = document.createElement('span');
		inputParent.className = 'service-input-parent';
		p.appendChild(inputParent);

		var select = document.createElement('select');
		select.className = 'service-select';
		select.input_obj = this;
		select.id = this.input.getAttribute('name');

		var title = document.createElement('span');
		title.className = 'service-input-title';
		inputParent.appendChild(title);
		title.innerHTML = this.input.getAttribute('title');
		inputParent.appendChild(select);

		var options = this.getOptions();
		var selIndex = 0;
		var val = this.getValue();
		for(var i = 0; i < options.length; i++) {
			if(options[i].value == val) {
				selIndex = i;
			}

			var opt = document.createElement('option');
			opt.selected= false;
			opt.setAttribute('value', options[i].value);
			select.appendChild(opt);
			opt.appendChild(document.createTextNode(options[i].name));
		}

		var selected_option = select.getElementsByTagName('option')[selIndex];

		selected_option.selected = true;
		this.setValue(selected_option.value);
			
		select.onchange = this.updateSettings;
	}

});

GeoMOOSE.Services.InputType.Usertextarea = OpenLayers.Class(GeoMOOSE.Services.InputType, {
	MAPBOOK_NAME: "user_textarea",

	initialize: function(input, options) {
		GeoMOOSE.Services.InputType.prototype.initialize.apply(this, arguments);
		this.options.renderable = true;
	},

	updateServiceSetting: function() {
		//console.log(this.value);
		this.input_obj.setValue(this.value);
	},

	keyCallService: function(event) {
		if(window.event) { event = window.event; }
		var keyCode = null;
		if(event.which) {
			keyCode = event.which;
		} else if(event.keyCode) {
			keyCode = event.keyCode;
		}
		if(keyCode == 13) {
			this.onchange();
			document.getElementById('submit-service').onclick();
		}
	},

	renderHTML: function(parent_id) {
		var p = document.getElementById(parent_id);
		var inputParent = document.createElement('span');
		inputParent.className = 'service-input-parent';
		p.appendChild(inputParent);

		var i = document.createElement('textarea');
		i.className = 'service-input';
		i.input_obj = this;
		i.id = 'service-input-'+this.getName();
		i.rows = 3;
		if(this.input.getAttribute('rows')) {
			i.rows = this.input.getAttribute('rows');
		}		
		if(this.getValue()) {
			i.value = this.getValue();
		}
		i.onchange = this.updateServiceSetting;
		i.onkeypress = this.keyCallService;

		var title = document.createElement('span');
		title.className = 'service-input-title';
		inputParent.appendChild(title);
		title.innerHTML = this.input.getAttribute('title');
		inputParent.appendChild(document.createElement('br'));
		inputParent.appendChild(i);
	}
	
});

//var zoomToSelect;
function startDynamicZoomTo() {

	selected=this.selectedIndex;
	if(selected != 0){
		var dynamicZoomToObject = CONFIGURATION.dynamiczoomto;

		selectedValue = this[selected].value;
		selectedValueArray = new String(selectedValue).split(':');
		type = selectedValueArray[0];

		if(type == 'single') {
			for(var zoomToTitle in dynamicZoomToObject) {
				for(var extentTitle in dynamicZoomToObject[zoomToTitle]) {
					if(dynamicZoomToObject[zoomToTitle][extentTitle][0] == selectedValue) {
						extent = dynamicZoomToObject[zoomToTitle][extentTitle][1];
					}
				}	
			}
			var arr = new String(extent).split(',');
			GeoMOOSE.zoomToExtent(arr[0],arr[1],arr[2],arr[3]);
		}

		else if(type == 'dynamic') {
			for(var zoomToTitle in dynamicZoomToObject) {
				for(var extentTitle in dynamicZoomToObject[zoomToTitle]) {
					if(dynamicZoomToObject[zoomToTitle][extentTitle][0] == selectedValue) {
						layer = dynamicZoomToObject[zoomToTitle][extentTitle][1];				
						qitem = dynamicZoomToObject[zoomToTitle][extentTitle][2];
					}
				}	
			}
			GeoMOOSE.startService('dynamicZoomTo', {'layer':layer,'qitem':qitem} );
		}

		else if(type == 'static') {
			document.getElementById(Tabs.getTab(CONFIGURATION.show_service_settings_in)).innerHTML = null;
			var zoomToParent = document.getElementById(Tabs.getTab(CONFIGURATION.show_service_settings_in));
			zoomToParent.appendChild(document.createTextNode('Zoom To '));

			zoomToSelect = document.createElement('select');
			zoomToSelect.className = 'zoomto-select';
			zoomToSelect.onchange = changeExtentBySelect;
			zoomToParent.appendChild(zoomToSelect);

			for(var zoomToTitle in dynamicZoomToObject) {
				for(var extentTitle in dynamicZoomToObject[zoomToTitle]) {
					if(dynamicZoomToObject[zoomToTitle][extentTitle][0] == selectedValue) {
						layer = dynamicZoomToObject[zoomToTitle][extentTitle][1];				
						qitem = dynamicZoomToObject[zoomToTitle][extentTitle][1];
						for(var extentTitle in qitem) {
							var option = document.createElement('option');
							option.value = qitem[extentTitle][1];
							zoomToSelect.appendChild(option);
							option.appendChild(document.createTextNode(qitem[extentTitle][0]));
						}
					}
				}	
			}
		Tabs.showTab(CONFIGURATION.show_service_settings_in);
		}
		else {
			alert("error");
		}

	}
	this.selectedIndex = 0;
}

//LK So the geocode results show a marker instead of a popup
function addMark(y,x) {
	var markers = new OpenLayers.Layer.Markers( "Markers" );
	Map.addLayer(markers);

	var size = new OpenLayers.Size(20,34);
	var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
	var icon = new OpenLayers.Icon('http://openlayers.org/dev/img/marker-gold.png',size,offset);
	markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(y,x),icon));
	markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(y,x),icon.clone()));
}

GeoMOOSE.Services.InputType.Text = OpenLayers.Class(GeoMOOSE.Services.InputType, {
	MAPBOOK_NAME: "text",

	initialize: function(input, options) {
		GeoMOOSE.Services.InputType.prototype.initialize.apply(this, arguments);
		this.options.renderable = true;
	},

	renderHTML: function(parent_id) {
		var p = document.getElementById(parent_id);
		var inputParent = document.createElement('span');
		inputParent.className = 'service-input-parent';
		p.appendChild(inputParent);

		var text = document.createElement('span');
		text.className = 'service-input-text';
		inputParent.appendChild(text);
		text.innerHTML = OpenLayers.Util.getXmlNodeValue(this.input);
	}
	
});

GeoMOOSE.Services.InputType.Date = OpenLayers.Class(GeoMOOSE.Services.InputType, {
	MAPBOOK_NAME: "date",

	initialize: function(input, options) {
		GeoMOOSE.Services.InputType.prototype.initialize.apply(this, arguments);
		this.options.renderable = true;
	},

	updateServiceSetting: function() {
		//console.log(this.value);
		this.input_obj.setValue(this.value);
	},

	getValue: function() {
		var obj = document.getElementById('service-input-'+this.getName());

		if(obj) {
			return obj.value;
		}
	},

	keyCallService: function(event) {
		if(window.event) { event = window.event; }
		var keyCode = null;
		if(event.which) {
			keyCode = event.which;
		} else if(event.keyCode) {
			keyCode = event.keyCode;
		}
		if(keyCode == 13) {
			this.onchange();
			document.getElementById('submit-service').onclick();
		}
	},

	datepick: function() {
		var id = this.id;
		id = id.replace("calendar-","service-input-");
		var cal3 = new calendar2(document.getElementById(id));
		cal3.popup();
	},

	renderHTML: function(parent_id) {
		var p = document.getElementById(parent_id);
		var inputParent = document.createElement('span');
		inputParent.className = 'service-input-parent';
		p.appendChild(inputParent);

		var calIcon = document.createElement('img');
		calIcon.id = 'calendar-'+this.getName();
		calIcon.src = "images/cal.gif";
		calIcon.onclick = this.datepick;
		calIcon.className = 'calIcon';
		
		var i = document.createElement('input');
		i.className = 'service-input';
		i.input_obj = this;
		i.id = 'service-input-'+this.getName();

		if(this.getValue()) {
	//		i.value = this.getValue();
		}
	
		i.onchange = this.updateServiceSetting;
		i.onkeypress = this.keyCallService;

		var title = document.createElement('span');
		title.className = 'service-input-title';
		inputParent.appendChild(title);
		inputParent.appendChild(document.createElement('br'));
		title.innerHTML = this.input.getAttribute('title');
		inputParent.appendChild(i);
		inputParent.appendChild(calIcon);
	}
	
});

GeoMOOSE.Services.InputType.Mapsize = OpenLayers.Class(GeoMOOSE.Services.InputType, {
	MAPBOOK_NAME: "mapsize",

	getValue: function() {
		return Map.getSize().w + ','+Map.getSize().h;
	}
});

GeoMOOSE.Services.InputType.Radio = OpenLayers.Class(GeoMOOSE.Services.InputType, {
	MAPBOOK_NAME: "radio",
	input: null,

	initialize: function(input, options) {
		this.options = {
			renderable: true
		};
		this.input = input;
	},

	getOptions: function() {
		var opts = this.input.getElementsByTagName('option');
		var formed_opts = [];
		for(var i = 0 ; i < opts.length; i++) {
			formed_opts.push({value: opts[i].getAttribute('value'), name: opts[i].getAttribute('name'), checked: opts[i].getAttribute('checked')});
		}
		return formed_opts;
	},

	getValue: function() {
		return this.input.getAttribute('value');
	},

	setValue: function(v) {
		this.input.setAttribute('value', v);
	},

	updateSettings: function() {
		var p = this.parentNode.parentNode;
		var inputs = p.getElementsByTagName('input');
		for(var i = 0; i < inputs.length; i++) {
			if(inputs[i].type == 'radio') {
				inputs[i].value = 'false';
				inputs[i].input_obj.setValue(inputs[i].value);
				this.value = 'true';
				this.input_obj.setValue(this.value);
			}	
		}


	},

	renderHTML: function(parent_id) {
		var p = document.getElementById(parent_id);
		var inputParent = document.createElement('span');
		inputParent.className = 'service-input-parent';
		p.appendChild(inputParent);

//		var selIndex = 0;
//		var val = this.getValue();
		var radio = document.createElement('input');
		radio.name = 'eatmeie';
		radio.type = 'radio';
		radio.id = this.input.getAttribute('name');
		radio.value = this.input.getAttribute('name');
		var title = document.createElement('span');
//		title.className = 'service-input-title';
		title.innerHTML = this.input.getAttribute('name');
		p.appendChild(radio);
		p.appendChild(title);

		radio.input_obj = this;
		radio.input_obj.setValue('false');
		if(this.input.getAttribute('checked') == "true") {
			radio.checked = true;
			radio.input_obj.setValue('true');
		}
		radio.onchange = this.updateSettings;
	}

});


function toggle_search_panel() {
	var sp = document.getElementById('search_panel');
	var className = new String(sp.className);
	var img = document.getElementById('openCloseIcon')
	if(className.match('collapsed')) {
		sp.className = className.replace('collapsed','expanded');
		img.src = "/images/draw-triangle3.png";
	} else {
		sp.className = className.replace('expanded','collapsed');
		img.src = "/images/draw-triangle4.png";
	}
	manageLayout();
}

function open_search_panel() {
	var sp = document.getElementById('search_panel');
	var className = new String(sp.className);
	if(className.match('collapsed')) {
		sp.className = className.replace('collapsed','expanded');
	} 
	manageLayout();
}

function highlight(geojson,style) {
	var featurecollection = {
		'type': 'FeatureCollection', 
		'features': 
			[{'geometry': 
				{'type': 'GeometryCollection', 
					'geometries': [geojson
					]
				},
				'type': 'Feature',
				'properties': {}
				}
			]};
	var geojson_format = new OpenLayers.Format.GeoJSON();
	Map.getLayersByName('highlightlayer')[0].addFeatures(geojson_format.read(featurecollection));

}

function highlightClear() {
	Map.getLayersByName('highlightlayer')[0].removeFeatures(Map.getLayersByName('highlightlayer')[0].features);
	Map.getLayersByName('/drawinglayer')[0].removeFeatures(Map.getLayersByName('/drawinglayer')[0].features);
}

function startSelect() {
	GeoMOOSE.startService('select',{
		'minx':'min lon',
		'miny':'min lat',
		'maxx':'max lon',
		'maxy':'max lat',
		'shape':''},false);
	open_search_panel();
	highlightClear();
	selectTool();
	var olDiv=document.getElementById('mapContainer_OpenLayers_ViewPort');
	olDiv.style.cursor='auto';
}

//LK User Extension for customizing the User Interface
CustomUi = new OpenLayers.Class(GeoMOOSE.UX.Extension, {
	initialize: function() {
	},
	afterMapbookLoad: function() {
		//LK Adds a spinner GIF when AJAX request is processing.  Also need to add CSS, spinner.gif and calls to toggleSpinner in compiled.js		
		var spinner = document.createElement('div');
		spinner.id = "spinner"
		spinner.className = "Hidden"
		var img = document.createElement('img');
		img.src = "images/spinner.gif";
		document.getElementById('middle').appendChild(spinner);
		document.getElementById('spinner').appendChild(img);
	},
 	toggleSpinner: function(visibility) {
		var element = document.getElementById('spinner');
		if(element && visibility=="hide") {
			element.className = element.className.replace('Visible','Hidden');
		}
		else if(element && visibility=="show") {
			element.className = element.className.replace('Hidden','Visible');
		}
	},
	CLASS_NAME: "CustomUi"
});
GeoMOOSE.UX.register("CustomUi");

var customUi = new CustomUi();

function hideResults() {
	$("#results").hide('slide',{ direction: 'down'});
}
