function MPolygonSelector(map,MOptions) {
	MOptions = MOptions ? MOptions : {};
	this.parent = MOptions.container ? MOptions.container : null;
	this.infoContainer = MOptions.infoContainer ? MOptions.infoContainer : null;

	this.self = this;
	this.map = map;
	this.selectedPoly;
	this.polys = Array();
	this.deleted = Array();
	this.highPolys = Array();	
	this.baseIcons = Array();
	this.highPoly;
	this.tlc;
	this.progressControl;
	this.maxZoom = 8;
	this.minZoom = 2;
	this.dir = 'MPolygonSelector';

	this.defaultStyle = {color:'#ff0000',stroke:2, opacity:1, rowColor:'#dddddd'};
	this.editStyle = {color:'#CD12DE',stroke:2, opacity:1, rowColor:'#EFA0F8'};
	this.dataStyle = {color:'#000080',stroke:2, opacity:0.3, rowColor:'#ffffff'};
	this.dataStyleHigh = {color:'#0000BB',stroke:5, opacity:0.5, rowColor:'#FF8080'};

	
	this.createDragControl();
	this.initialize();
};



MPolygonSelector.prototype.dump = function() {
	var str = '<pre>\n';
	for (x in this) {
		if (typeof this[x] != 'function') {
			str += x + ': ' + this[x] + '\n';
		}
	}
	GLog.writeHtml(str);
};




//#################################################################
MPolygonSelector.prototype.createDragControl = function() {
	var self = this.self;
	this.polyDragControl = new MPolyDragControl({map:this.map,type:'rectangle'});
	this.polyDragControl.onPolyAccept = function(){self.getParameters()};
};


MPolygonSelector.prototype.getParameters = function() {
	var params = this.polyDragControl.getParams();
//	var url = 'http://' + window.location.host + '/myServerSideScript.php?' + params;
//	GLog.write(url);

	var poly = this.selectedPoly;
	if (!poly) {
//		this.removeFromArray(this.selectedPoly);
		var poly = this.createPoly(this.polyDragControl.pointsArray,false);
		this.addToArray(poly);
	}
	else {
		this.replacePoints(poly,this.polyDragControl.pointsArray);
	}

	poly.p0 = this.polyDragControl.dragMarker0.getLatLng();
	poly.p1 = this.polyDragControl.dragMarker1.getLatLng();
	poly.type = this.polyDragControl.type;
	poly.isEditing = true;
	poly.changed = 1;
	this.toggleEditMode(poly);
	this.expandChildren(poly);
	
	this.polyDragControl.clear();
};

MPolygonSelector.prototype.setInstructions = function(str) {
	app.cControl.setContent(str);

};
MPolygonSelector.prototype.hideInstructions = function() {
	app.cControl.hide();
};


//#################################################################






MPolygonSelector.prototype.initialize = function(map) {
	var self = this.self;

	this.container = document.createElement('DIV');
	if (this.parent) {
		this.parent.appendChild(this.container);
	}
	else {
		this.map.getContainer().appendChild(this.container);
		this.container.style.position = 'absolute';
	}

	this.setPosition();

//	this.container.style.width = '200px';
	this.container.style.border = '1px solid gray';
	this.container.style.background = '#ffffff';

	

	var buttonsTable = this.createButtons();
	this.container.appendChild(buttonsTable);

	this.franchiseInfo = this.createFranchiseInfo();
	this.container.appendChild(this.franchiseInfo);

	this.polyList = this.createSelectorList();
	if (this.infoContainer) {
		this.infoContainer.appendChild(this.polyList);
	}
	else {
		this.container.appendChild(this.polyList);
	}

	GEvent.addDomListener(this.container, "DOMMouseScroll", function(ev){
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
	});
	GEvent.addDomListener(this.container, "mousewheel", function(ev){
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
	});

	var url = app.serverScript + '&task=lookupData&r=' + Math.random();
	ajaxLoad(url,function(http_request){
		self.processResponse(http_request);
		self.createUnitSelector();
	});
};

MPolygonSelector.prototype.setPosition = function() {
	if (!this.parent) {
		this.container.style.top = '30px';
		this.container.style.left = (this.map.getSize().width - 210) + 'px';
	}
};

MPolygonSelector.prototype.hide = function() {
	this.container.style.display = 'none';
	this.toggleSelectors(false);
};
MPolygonSelector.prototype.show = function() {
	this.container.style.display = '';
	this.toggleSelectors(true);
};

MPolygonSelector.prototype.thinking = function(on) {
	if (this.progressControl) {
		if (on) {
			this.progressControl.show();
		}
		else {
			this.progressControl.hide();
		}
	}
};



//=========================================================================

MPolygonSelector.prototype.getFranchiseId = function() {
	return this.franchiseInfo.fid;
};


MPolygonSelector.prototype.loadStatusList = function(obj,self) {
	var txt = obj.dataStr;
	var rows = txt.split(';');
	var header = rows.shift();
	var fHeaderArray = header.split('|');

	self.statusLabels = Array();	
	for (n = 0 ; n < rows.length ; n++ ) {
		var values = rows[n].split('|');
		var statusLabel = {};
		statusLabel.name = values[fHeaderArray.indexOf('status_name')];
		statusLabel.value = values[fHeaderArray.indexOf('status_id')];
		statusLabel.color = values[fHeaderArray.indexOf('status_color')];
		self.statusLabels.push(statusLabel);
	}
	
//status_color|status_id|status_name
//00C000|1|For sale
//F0BA00|2|Sold
//C00076|3|Resale
//	status_color|status_id|status_name
};




MPolygonSelector.prototype.loadUnits = function(obj,self) {
	var txt = obj.dataStr;
	var rows = txt.split(';');
	var header = rows.shift();
	var fHeaderArray = header.split('|');

	self.franchiseUnits = Array();	
	for (n = 0 ; n < rows.length ; n++ ) {
		var values = rows[n].split('|');
		var obj = {};
		obj.value = values[fHeaderArray.indexOf('unit_id')];
		obj.name = values[fHeaderArray.indexOf('unit_name')];
		obj.minZoom = values[fHeaderArray.indexOf('unit_min_zoom')];
		obj.maxZoom = values[fHeaderArray.indexOf('unit_max_zoom')];
		self.franchiseUnits.push(obj);
	}


//unit_id|unit_name|unit_table|unit_demographic_table|unit_join_fields|unit_min_zoom|unit_max_zoom;
//0|Free||||1|8;
//1|County|counties|k_county_demographics|state_fips,county_fips|1|8;
//2|State|states|k_county_demographics|state_fips|1|8

};



MPolygonSelector.prototype.loadSPIcons = function(obj,self) {
	var txt = obj.dataStr;
	var rows = txt.split(';');
	var header = rows.shift();
	var fHeaderArray = header.split('|');

	self.spIcons = Array();	
	for (n = 0 ; n < rows.length ; n++ ) {
		var values = rows[n].split('|');
		var obj = {};
		obj.name = values[fHeaderArray.indexOf('type_name')];
		obj.description = values[fHeaderArray.indexOf('type_description')];
		obj.value = values[fHeaderArray.indexOf('type_id')];
		obj.iconImage = values[fHeaderArray.indexOf('type_icon')];
		obj.icon = self.createIcon(obj.iconImage,32,32);
		self.spIcons.push(obj);
	}

	app.geocoder.spIcons = self.spIcons;
	app.geocoder.initialize();

};


MPolygonSelector.prototype.createIcon = function(img,W,H) {
	var baseIcon = this.getBaseIcon(W,H);
	var icon = new GIcon(baseIcon, 'images/'+img);
	return icon;
};

MPolygonSelector.prototype.getBaseIcon = function(W,H) {
	for (var n = 0 ; n < this.baseIcons.length ; n++ ) {
		if (this.baseIcons[n].iconSize.x == W && this.baseIcons[n].iconSize.y == H) {
			return this.baseIcons[n];
		}
	};

	// If it doesn't exist, create it
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(W,H);
	baseIcon.iconAnchor = new GPoint(Math.round(W/3),H); //new GPoint(Math.round(W/2),Math.round(H/2));
	baseIcon.infoWindowAnchor = new GPoint(Math.round(W/2),0);
	this.baseIcons.push(baseIcon);
	return baseIcon;
};




MPolygonSelector.prototype.deleteCollection = function() {
	var url = app.serverScript + '&task=delete&cid='+this.franchiseInfo.fid;
	url += '&r=' + Math.random();

	this.clearAll();

	ajaxLoad(url,function(http_request){
		var txt = http_request.responseText;
		eval(txt);
	});
};



MPolygonSelector.prototype.toggleSelectors = function(show) {
	for (var n = 0 ; n < this.polys.length ; n++ ) {
		if (show) {
			this.polys[n].show();
		}
		else {
			this.polys[n].hide();
		}
	}
};

MPolygonSelector.prototype.clearAll = function() {
	while (this.polys.length > 0) {
		this.removeFromArray(this.polys[0]);
	}

	if (this.highPoly) {
		this.map.removeOverlay(this.highPoly);
		this.highPoly = null;
	}

	if (this.tlc) {
		if (this.tlc.overlay) {
			this.map.removeOverlay(this.tlc.overlay);
			this.tlc.overlay = null;
		}
		var removed = this.tlc.parent.removeChild(this.tlc.container);
		removed = null;
		this.tlc = null;
	}

	this.deleted = Array();
	
	this.fInfoChanged = 0;
	this.franchiseInfo.bounds = new GLatLngBounds();
	this.franchiseInfo.fid = 0;
	this.franchiseInfo.units = 0;
	this.franchiseInfo.lastSaved.value = 'NO';
	this.franchiseInfo.name.value = 'New franchise';
	this.franchiseInfo.desc.value = 'Some description';
	this.map.closeInfoWindow();

	this.map.setCenter(app.centerPoint,app.zoom);

};


MPolygonSelector.prototype.buttonClick = function(oImg) {
	var self = this.self;



	this.drawRectImg.src = this.dir + '/images/drawRect.png';
	this.drawCircleImg.src = this.dir + '/images/drawCircle.png';

	if (oImg.id == 'cell_draw_rect') {
		if (this.selectedPoly && this.selectedPoly.isEditing) {
			this.toggleEditMode(this.selectedPoly);
		}
		else if (this.polyDragControl.active) {
			this.polyDragControl.clear();
			this.hideInstructions();
		}
		else {
			this.polyDragControl.enable();
			this.polyDragControl.setType('rectangle');
			this.drawRectImg.src = this.dir + '/images/drawRectH.png';
			var str = 'Click and drag on the map to define a rectangle. When done, click inside the rectangle to accept.';
			this.setInstructions(str);
		}
	}
	else if (oImg.id == 'cell_draw_circle') {
		if (this.selectedPoly && this.selectedPoly.isEditing) {
			this.toggleEditMode(this.selectedPoly);
		}
		else if (this.polyDragControl.active) {
			this.polyDragControl.clear();
			this.hideInstructions();
		}
		else {
			this.polyDragControl.enable();
			this.polyDragControl.setType('circle');
			this.drawCircleImg.src = this.dir + '/images/drawCircleH.png';
			var str = 'Click and drag on the map to define a circle. When done, click inside the circle to accept.';
			this.setInstructions(str);
		}
	}
	else if (oImg.id == 'cell_draw') {
		if (!this.selectedPoly) {
			this.selectedPoly = this.createPoly();
		}
		this.toggleEditMode(this.selectedPoly);
	}
	else if (oImg.id == 'cell_stop_draw') {
		if (this.selectedPoly && this.selectedPoly.isEditing) {
			this.toggleEditMode(this.selectedPoly);
		}
		this.polyDragControl.clear();
		this.hideInstructions();

	}
	else if (oImg.id == 'cell_clear') {
		if (confirm('Clear all?')) {
			this.clearAll();
		}
	}
	else if (oImg.id == 'cell_open') {
		this.showOpenDialog();
	}
	else if (oImg.id == 'cell_save') {
		this.saveCollection();
	}
	else if (oImg.id == 'cell_bounds') {
		if (self.franchiseInfo.bounds && self.franchiseInfo.bounds.getCenter()) {
			self.map.setCenter(self.franchiseInfo.bounds.getCenter(), self.map.getBoundsZoomLevel(self.franchiseInfo.bounds));
		}
	}
};



MPolygonSelector.prototype.setReturnValues = function(cid,lastSaved) {
	this.franchiseInfo.fid = cid;
	this.franchiseInfo.lastSaved.value = lastSaved;
};


MPolygonSelector.prototype.saveCollection = function() {
	var self = this.self;

	if (this.selectedPoly && this.selectedPoly.isEditing) {
		this.toggleEditMode(this.selectedPoly);
	}

	var zoom = this.map.getZoom();
	var changeCount = 0;
	var postData = '';

	postData += 'task=save&franchiseId='+this.franchiseInfo.fid;
	postData += '&franchiseName='+this.franchiseInfo.name.value;
	postData += '&franchiseDesc='+this.franchiseInfo.desc.value;
	postData += '&franchiseUnits='+this.franchiseInfo.units;
	postData += '&fInfoChanged=1';//+this.fInfoChanged;
	postData += '&zoom='+zoom;
	postData += '&tt=1&sPolys=';

	for (var n = 0 ; n < this.polys.length ; n++) {
		if (this.polys[n].changed) {
			changeCount++;
			if (typeof this.polys[n].territoryId == 'undefined') {
				this.polys[n].territoryId = 0;
			}
			var territoryId = typeof this.polys[n].territoryId != 'undefined' ? this.polys[n].territoryId : '0';
			postData += this.getPointString(this.polys[n],6);
			postData += '|' + this.polys[n].name;
			postData += '|' + this.polys[n].id;
			postData += '|' + territoryId;
			postData += '|' + (this.polys[n].status ? this.polys[n].status : '1');
			postData += '|' + this.polys[n].changed;

			if (this.polys[n].type && this.polys[n].p0 && this.polys[n].p1) {
				postData += '|' + this.polys[n].type;
				postData += '*' + this.polys[n].p0;
				postData += '*' + this.polys[n].p1;
			}
			
			postData += '||';
		}
	}
	postData = postData.replace(/\|\|$/,'');
	
	postData += '&deleteIds=';
	for (var n = 0 ; n < this.deleted.length ; n++) {
		postData += this.deleted[n] + ',';
	}
	postData = postData.replace(/,$/,'');
	if (changeCount || this.deleted.length || this.fInfoChanged) {

		var html = 'Saving: ';
		if (this.fInfoChanged) {
			html += '<li>Franchise Information';
		}
		if (changeCount) {
			html += '<li>'+ changeCount + ' polygon(s) changed';
		}
		if (this.deleted.length) {
			html += '<li>' + this.deleted.length + ' polygon(s) deleted';
		}
		this.progressControl.setText(html);
		
		
		
		
		var url = app.serverScript + '&r=' + Math.random();
		this.clearHighlights();
		this.deleted = Array();

//GLog.write(url + '&' + postData);

		ajaxLoad(url,function(http_request){
			self.processResponse(http_request);
	//		self.loadFranchise(self.franchiseInfo.fid,self.userPermissions);
		},postData);

		this.toggleSelectors(this.selectorsCheckbox.checked);

	}
	else {
		var obj = {};
		obj.msg = 'Nothing changed. Nothing to save.';
		this.showMessage(obj,self);
	}

};

MPolygonSelector.prototype.createTLC = function(fid) {
	var controlsContainer = document.getElementById("territoriesTitleDiv");
	if (this.tlc) {
		this.tlc = null;
	}
	this.tlc = new MTileLayerControl({
		map:this.map,
		parent:controlsContainer,
		maxZoom: this.maxZoom,
		minZoom: this.minZoom,
		overlayTheme:fid,
		checked:true,
		sliderWidth: 100,
		value: 35,
		background: '#C0C0FF',
		caption:'Territories'
	});

	this.tlc.overlay.getTileLayer().getTileUrl = function (a,b) {
		var url = '/franchiseTiles3/'+ fid + '/' + b + '/' + a.x + '_' + a.y + '.png?r=' + Math.random();
		var url = '/cgi-bin/getFranchiseTile.pl?fid=' + fid + '&x=' + a.x + '&y=' + a.y + '&z=' + b + '&r=' + Math.random();
//GLog.write(url)
		return url;
	};

	this.tlc.map.addOverlay(this.tlc.overlay);
//	this.tlc.initialize();

};

MPolygonSelector.prototype.loadFranchise = function(fid,permissions) {
	var self = this.self;
	this.userPermissions = permissions;
	this.clearAll();

	var oDiv = document.getElementById('t2');
	app.setTab(oDiv);


	var url = app.serverScript + '&task=loadFranchise&franchiseId='+fid;
	url += '&r=' + Math.random() ;
	this.progressControl.setText('Loading franchise...');
//GLog.write(url)
	ajaxLoad(url,function(http_request){
		self.processResponse(http_request);

		if (self.userPermissions > 1) {
			self.show();
			self.toggleSelectors(self.selectorsCheckbox.checked);
		}
		else {
			self.hide();
		}
		if (self.polys.length) {
			if (self.map.getBoundsZoomLevel(self.franchiseInfo.bounds) == self.map.getZoom() ) {
				self.map.panTo(self.franchiseInfo.bounds.getCenter());
			}
			else {
				self.map.setCenter(self.franchiseInfo.bounds.getCenter(), self.map.getBoundsZoomLevel(self.franchiseInfo.bounds));
			}
		}

		if (!self.tlc) {
			self.createTLC(fid);
		}
	});
};


MPolygonSelector.prototype.loadFranchiseInfo = function(obj,self) {
//	GLog.write(obj.dataStr);

	eval(obj.dataStr);
	self.fInfoChanged = 0;
	self.franchiseInfo.fid = franchise_id;
	self.franchiseInfo.lastSaved.value = savedon;
	self.franchiseInfo.name.value = franchise_name;
	self.franchiseInfo.desc.value = franchise_description;

	self.franchiseInfo.fTypeInput.value = unit_name;

	if (obj.fullUpdate) {
		app.mSelector.loadFranchises();
	}
};


MPolygonSelector.prototype.loadDemographics = function(obj,self) {
	var txt = obj.dataStr;
	var rows = txt.split('\|\|');
	var header = rows.shift();
	var fHeaderArray = header.split('|');

/*
state_fips	
county_fips
county_name
census2000pop
popestimate2009
*/	
	var str = obj.dataStr.replace(/\|\|/g,'\n');
	var str = str.replace(/\|/g,',');

	if (obj.territoryId > 0) {
		var poly = self.getSelectorPolyByTerritoryId(obj.territoryId);
	}
	else if (obj.clientId) {
		var poly = self.getSelectorPolyById(obj.clientId);
	}

	if (poly) {
		if (typeof poly.demoTable == 'undefined') {
			poly.demoTable = new MDataTable();
			poly.demoTable.onRowClick = function(rowObj){self.demoRowClicked(rowObj,poly)};
			if (typeof obj.totalize != 'undefined') {
				poly.demoTable.totalizeIx = obj.totalize;
			}
		}
		poly.infoContainer.appendChild(poly.demoTable.container);
		poly.demoTable.loadFromString(str);
		poly.listRow.scrollIntoView(true);
	}

};



MPolygonSelector.prototype.demoRowClicked = function(rowObj,poly) {
	var self = this.self;
	if (rowObj.selected) {
		var points = Array();
		var p = new GLatLng(parseFloat(rowObj.rowData.s),parseFloat(rowObj.rowData.w));
		points.push(p);

		var p = new GLatLng(parseFloat(rowObj.rowData.n),parseFloat(rowObj.rowData.w));
		points.push(p);

		var p = new GLatLng(parseFloat(rowObj.rowData.n),parseFloat(rowObj.rowData.e));
		points.push(p);

		var p = new GLatLng(parseFloat(rowObj.rowData.s),parseFloat(rowObj.rowData.e));
		points.push(p);

		var p = new GLatLng(parseFloat(rowObj.rowData.s),parseFloat(rowObj.rowData.w));
		points.push(p);

		this.setHighPoly(points,poly);
		if (poly.territoryBounds) {
			this.map.setCenter(poly.territoryBounds.getCenter(),this.map.getBoundsZoomLevel(poly.territoryBounds));
		}
	}
	else {
		this.setHighPoly(null,poly);
	}
};

MPolygonSelector.prototype.setHighPoly = function(points,poly) {
	var self = this.self;
	if (this.highPoly) {
		this.map.removeOverlay(this.highPoly);
		this.highPoly = null;
	}

	if (points) {
		this.highPoly = new GPolygon(points,this.dataStyleHigh.color,this.dataStyleHigh.stroke,this.dataStyleHigh.opacity);
		
		GEvent.addListener(this.highPoly,'click',function(){
			poly.demoTable.selectRow(null);
			this.hide();
		});

		this.map.addOverlay(this.highPoly);
	}
};



MPolygonSelector.prototype.loadTerritory = function(obj,self) {
	eval(obj.dataStr);
	var sPoints = selector_poly.split(/,/);
	
	var points = Array();
	for (var p = 0 ; p < sPoints.length ; p++ ) {
		var pair = sPoints[p].split(/ /);
		var pt = new GLatLng(
			parseFloat(pair[1]),
			parseFloat(pair[0]));
		points.push(pt);
	}

	if (points.length > 2) {
		if (selector_params) {
			var poly = self.createPoly(points,false);
		}
		else {
			var poly = self.createPoly(points,true);
		}

		poly.name = territory_name;
		poly.territoryId = territory_id;
		poly.status = territory_status;
		poly.isEditing = false;
		self.addToArray(poly);
		poly.changed = 0;

		if (selector_params) {
			var params = selector_params.split('*');
			poly.type = params[0];
			poly.p0 = eval('new GLatLng' + params[1]);
			poly.p1 = eval('new GLatLng' + params[2]);
		}




	// These are the bounds of the selected territory, NOT of the selector poly.
		poly.territoryBounds = new GLatLngBounds();
		var p = new GLatLng(parseFloat(s),parseFloat(w));
		poly.territoryBounds.extend(p);
		self.franchiseInfo.bounds.extend(p);
		var p = new GLatLng(parseFloat(n),parseFloat(e));
		poly.territoryBounds.extend(p);
		self.franchiseInfo.bounds.extend(p);


		if (service_point) {
			var lonlat = service_point.split(/ /);
			var point = new GLatLng(parseFloat(lonlat[1]),parseFloat(lonlat[0]));
			self.setServicePoint(poly,point,service_address_parsed,service_point_type);
		}
	}
};


MPolygonSelector.prototype.setServicePoint = function(poly,point,address,service_point_type) {
	var self = this.self;
	if (poly.servicePoint) {
		this.map.removeOverlay(poly.servicePoint);
		poly.servicePoint = null;
	}

	if (point) {
		var spObj = this.getSPObject(service_point_type);
		poly.servicePoint = new this.createMarker(point,spObj,address,self);
		poly.servicePoint.address = address;
		poly.servicePoint.typeId = service_point_type;
		this.map.addOverlay(poly.servicePoint);
	}
};

MPolygonSelector.prototype.getSPObject = function(id) {
	for (var n = 0 ; n < this.spIcons.length ; n++ ) {
		if (this.spIcons[n].value == id) {
			return this.spIcons[n];
		}
	}

};

MPolygonSelector.prototype.createMarker = function(point,spObj,service_address_parsed,self) {
	var title = service_address_parsed;
//	title +=  '\n' + spObj.name + ' : ' + spObj.description;

	var marker = new GMarker(point,{title:title,icon:spObj.icon});

	if (typeof self.onMarkerClick == 'function') {
		GEvent.addListener(marker,'click',function(){
			self.onMarkerClick(marker);
		});
	}

	return marker;
};

MPolygonSelector.prototype.updateDemographics = function(obj,self) {
	if (obj.territoryId > 0) {
		var poly = self.getSelectorPolyByTerritoryId(obj.territoryId);
		poly.colorRef.style.background =  '#' + self.statusLabels[poly.status-1].color;
	}
	
	
	var url = app.serverScript + '&task=demographics&franchiseId='+self.franchiseInfo.fid+'&territoryId='+obj.territoryId;
	url += '&r=' + Math.random() ;
	ajaxLoad(url,function(http_request){
		self.processResponse(http_request);
	});
};

MPolygonSelector.prototype.partialDemographics = function(poly) {
	var self = this.self;
	var territoryId = (typeof poly.territoryId != 'undefined') ? poly.territoryId : '0';
	var postData = 'poly=';
	postData += this.getPointString(poly,6);
	postData += '&task=pdemographics';
	postData += '&franchiseId='+this.franchiseInfo.fid;
	postData += '&territoryId='+territoryId;
	postData += '&clientId='+poly.id;
	postData += '&units='+this.franchiseInfo.units;
	
	var url = app.serverScript;
	url += '&r=' + Math.random() ;
	ajaxLoad(url,function(http_request){
		self.processResponse(http_request);
	},postData);
};

MPolygonSelector.prototype.reloadFranchise = function(obj,self) {
	self.loadFranchise(obj.dataStr);
};

MPolygonSelector.prototype.setTerritoryId = function(obj,self) {
	var poly = self.getSelectorPolyById(obj.clientId);
	poly.territoryId = obj.territoryId;
};


MPolygonSelector.prototype.showMessage = function(obj,self) {
	self.thinking(false);
	alert(obj.msg);
};

MPolygonSelector.prototype.reloadTiles = function(obj,self) {
// Reload tiles is called after save operations, so reset the changed flag for all selector polygons.	
	
	for (var n = 0 ; n < self.polys.length ; n++ ) {
		self.polys[n].changed = 0;
	}
	if (self.tlc) {
		self.map.removeOverlay(self.tlc.overlay);
		self.map.addOverlay(self.tlc.overlay);
	}
	else {
		self.createTLC(self.franchiseInfo.fid);
	}
};

MPolygonSelector.prototype.highlightArea = function(obj,self){
	self.clearHighlights();
	var points = Array();
	var pairs = obj.rect.split(',');
	for (var n = 0 ; n < pairs.length ; n++) {
		var lonlat = pairs[n].split(' ');
		points.push(new GLatLng(parseFloat(lonlat[1]), parseFloat(lonlat[0])));
	}

	var highPoly = new GPolygon(points, '#ff0000', 2, 1, '#ff0000', 0.5);
	self.highPolys.push(highPoly);
	self.map.addOverlay(highPoly);
};


MPolygonSelector.prototype.clearHighlights = function() {
	while (this.highPolys.length > 0) {
		var poly = this.highPolys.shift();
		this.map.removeOverlay(poly);
		poly = null;
	}
	this.highPolys = Array();
};

MPolygonSelector.prototype.processResponse = function(http_request){
	var self = this.self;
	var txt = http_request.responseText;
//GLog.write(txt);

	eval(txt);

	for (var n = 0 ; n < response.length ; n++ ) {
		var responseObj = response[n];
		var func = eval('self.' + responseObj.action);

		if (typeof func == 'function') {
			func(response[n],self);
		}
		else {
//			GLog.write(func + '(' + 'self.' + responseObj.action + ') Not a function')
		}
	}
	self.thinking(false);
};


MPolygonSelector.prototype.getSelectorPolyByTerritoryId = function(id) {
	for (var n = 0 ; n < this.polys.length ; n++ ) {
		if (this.polys[n].territoryId == id) {
			return this.polys[n];
		}
	}
};

MPolygonSelector.prototype.getSelectorPolyById = function(id) {
	for (var n = 0 ; n < this.polys.length ; n++ ) {
		if (this.polys[n].id == id) {
			return this.polys[n];
		}
	}
};



MPolygonSelector.prototype.replacePoints = function(poly,points) {
	ix = poly.getVertexCount()-1;
	for (var n = 0 ; n < points.length ; n++ ) {
		poly.insertVertex(ix,points[n]);
		poly.deleteVertex(0);
	}


};

MPolygonSelector.prototype.createPoly = function(points,clickable) {
	var self = this.self;
	points = points ? points : [];
	clickable = (typeof clickable != 'undefined') ? clickable : true;


	var poly = new GPolygon(points,this.defaultStyle.color,this.defaultStyle.stroke,this.defaultStyle.opacity,null,null,{clickable:clickable});
	poly.isEditing = false;
	poly.changed = 1;


	GEvent.addListener(poly,'cancelline',function(){
		this.isEditing = true;
		self.toggleEditMode(this);
	});


	GEvent.addListener(poly,'endline',function(){
		self.polyImg.src = this.dir + '/images/drawFree.png';
		self.hideInstructions();

		if (poly.getArea() > 0) {
			self.addToArray(this);
			self.toggleEditMode(this);
			self.expandChildren(this);
		}
		else {
			this.isEditing = true;
			self.toggleEditMode(this);
		}
	});

	GEvent.addListener(poly,'lineupdated',function(){
		this.changed = 1;
		if (poly.getVertexCount() > 2) {
			//If first and last verteces are equal (polygon is closed)
			if (poly.getVertex(0).toUrlValue() == poly.getVertex(poly.getVertexCount()-1).toUrlValue()) {
				self.partialDemographics(poly);
			}
		}
	});

	if (clickable) {
		GEvent.addListener(poly,'click',function(){
			self.toggleEditMode(this);
			if (this.isEditing) {
				self.expandChildren(this);
			}
			this.listRow.scrollIntoView(true);
		});
	}

	this.map.addOverlay(poly);
	
	return poly;
};


MPolygonSelector.prototype.toggleEditMode = function(poly) {
	if (poly.isEditing) {
//		this.toggleSelectors(false);
		this.toggleSelectors(this.selectorsCheckbox.checked);

		if (poly.type == 'rectangle') {
			this.drawRectImg.src = this.dir + '/images/drawRect.png';
			this.polyDragControl.clear();
			this.hideInstructions();
		}		
		else if (poly.type == 'circle') {
			this.drawCircleImg.src = this.dir + '/images/drawCircle.png';
			this.polyDragControl.clear();
			this.hideInstructions();
		}
		else {
			this.polyImg.src = this.dir + '/images/drawFree.png';
			this.hideInstructions();
		}		
		poly.disableEditing();
		poly.isEditing = false;
		this.selectedPoly = null;
		this.setEditStyle(poly);
		// If the polygon is not closed, then close it automatically.
		if (poly.getArea() > 0) {
			if (poly.getVertex(0).toUrlValue() != poly.getVertex(poly.getVertexCount()-1).toUrlValue()) {
				poly.insertVertex(poly.getVertexCount(),poly.getVertex(0));
				this.addToArray(poly);
			}
		}
		else {
//			alert('The area of the polygon must be greater than zero');
			this.map.removeOverlay(poly);
			poly = null;
		}
	}
	else {
		this.toggleSelectors(true);
		poly.isEditing = true;
		this.selectedPoly = poly;
		this.setEditStyle(poly);

		if (poly.type == 'rectangle') {
			this.polyDragControl.setType(poly.type);
			this.polyDragControl.setPoints(poly.p0,poly.p1);
			this.drawRectImg.src = this.dir + '/images/drawRectH.png';
			var str = 'Drag the white markers to adjust the rectangle. When done, click inside the rectangle to accept.';
			this.setInstructions(str);

//			poly.hide();
		}		
		else if (poly.type == 'circle') {
			this.polyDragControl.setType(poly.type);
			this.polyDragControl.setPoints(poly.p0,poly.p1);
			this.drawCircleImg.src = this.dir + '/images/drawCircleH.png';
			var str = 'Drag the white markers to adjust the circle. When done, click inside the circle to accept.';
			this.setInstructions(str);
//			poly.hide();
		}
		else {
			this.polyImg.src = this.dir + '/images/drawFreeH.png';		
			if (poly.getVertexCount() > 2) {
				if (poly.getVertex(0).toUrlValue() == poly.getVertex(poly.getVertexCount()-1).toUrlValue()) {
					poly.enableEditing();
					return;
				}
			}
			poly.enableDrawing();
			var str = 'Click the map to add points to a new polygon or move existing ones to edit';
			this.setInstructions(str);
		}
	}
};


MPolygonSelector.prototype.setEditStyle = function(poly) {
	if (poly.isEditing) {

		poly.setStrokeStyle(this.editStyle);
		if (poly.titleRow) {
			poly.titleRow.style.background = this.editStyle.rowColor;
		}
	}
	else {
		poly.setStrokeStyle(this.defaultStyle);
		if (poly.titleRow) {
			poly.titleRow.style.background = '';//this.defaultStyle.rowColor;
		}
	}
};


MPolygonSelector.prototype.getPointString = function(poly,dec) {
	dec = dec ? dec : 6;
	var str = '';;
	if (poly.getVertexCount() > 2) {
		for (var n = 0 ; n < poly.getVertexCount() ; n++ ) {
			str += poly.getVertex(n).lng().toFixed(dec) + ' ' + poly.getVertex(n).lat().toFixed(dec) + ',';
		}
		str = str.replace(/,$/,'');
	}
	return str;
};


/*
this.polys[n].id
this.polys[n].name
this.polys[n].isEditing
this.polys[n].listRow
this.polys[n].listRow.ecIcon

this.polys[n].childContainer.cRows
this.polys[n].childContainer.cRows[r].poly.state
this.polys[n].childContainer.cRows[r].poly.county
this.polys[n].childContainer.cRows[r].poly.name
this.polys[n].childContainer.cRows[r].poly.selectorID
*/





//////////////////////////////////////////////////////////
// Add selector polygon to internal array and create display rows in list
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.addToArray = function(poly) {
	poly.id = poly.id ? poly.id : (this.polys.length + 1);
	poly.name = poly.name ? poly.name : 'Territory ' + (this.polys.length + 1);
	poly.status = poly.status ? poly.status : 1;

	poly.listRow = this.createSelectorRow(poly);
	this.polyList.listContainer.appendChild(poly.listRow);

//	poly.childContainer = this.createChildContainer(4);
//	this.polyList.listContainer.appendChild(poly.childContainer);

	this.polys.push(poly);
};



//////////////////////////////////////////////////////////
// Remove selector polygon from internal array and remove list entries
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.removeFromArray = function(poly) {
	for (var n = 0 ; n < this.polys.length ; n++ ) {
		if (this.polys[n] == poly) {
			if (poly.isEditing) {
				this.toggleEditMode(poly);
			}

			if (poly.servicePoint) {
				this.map.removeOverlay(poly.servicePoint);
				poly.servicePoint = null;
			}

//			this.removeSelectedPolys(poly);
			if (poly.listRow) {
				var removed = poly.listRow.parentNode.removeChild(poly.listRow);
				removed = null;
			}
//			var removed = poly.childContainer.parentNode.removeChild(poly.childContainer);
//			removed = null;
			this.polys.splice(n,1);
			this.map.removeOverlay(poly);

			if (poly.territoryId) {
				this.deleted.push(poly.territoryId)
			}
			poly = null;
			return;
		}
	}
};


MPolygonSelector.prototype.removeSelectedPolys = function(poly) {
	while (poly.childContainer.cRows.childNodes.length > 0) {
		this.map.removeOverlay(poly.childContainer.cRows.childNodes[0].poly);
		poly.childContainer.cRows.childNodes[0].poly = null;
		var removed = poly.childContainer.cRows.removeChild(poly.childContainer.cRows.childNodes[0]);
		removed = null;
	}
};



//////////////////////////////////////////////////////////
// Add information for one selected polygon, (county), to the list of children
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.addChildInfo = function(poly) {
	var self = this.self;
	var selectorPoly = this.getSelectorPolyById(poly.selectorID);
	var childRow = this.createChildRow(poly);
	selectorPoly.childContainer.cRows.appendChild(childRow);
	selectorPoly.listRow.ecIcon.src = this.dir + '/images/plus2.png';
	selectorPoly.listRow.ecIcon.style.cursor = 'pointer';

	GEvent.addListener(poly,'click',function(){
		self.toggleHighlight(childRow);
	});
};


//////////////////////////////////////////////////////////
// Row to hold one selector polygon
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createSelectorRow = function(poly) {
	var self = this.self;
	var sRow = document.createElement('TR');
	sRow.style.background = '#dddddd';

// ------ Expand/collapse icons

	var iCell = document.createElement('TD');
	sRow.appendChild(iCell);

	sRow.ecIcon = document.createElement('IMG');

	if (this.userPermissions > 1) {
		sRow.ecIcon.src = this.dir + '/images/plus2.png';
		sRow.ecIcon.style.cursor = 'pointer';
		sRow.ecIcon.onclick = function(){
			self.toggleChildren(poly)
		};
	}
	else {
		sRow.ecIcon.src = this.dir + '/images/dot2.png';
	}
	
	iCell.appendChild(sRow.ecIcon);
	iCell.setAttribute('vAlign','top');
	iCell.style.lineHeight = '6px';
	iCell.style.width = '16px';
	iCell.style.border = '1px solid white';

	var sCell = document.createElement('TD');
	sRow.appendChild(sCell);

// Row holds a single cell with multiple tables

	var iTable = document.createElement('TABLE');
	sCell.appendChild(iTable);
	iTable.setAttribute('width','100%');
	iTable.setAttribute('cellSpacing',0);
	iTable.setAttribute('cellPadding',1);

	var oTBody = document.createElement('TBODY');
	iTable.appendChild(oTBody);

	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);
	poly.titleRow = oRow;
//	oRow.style.background = this.defaultStyle.rowColor;


// ------ poly name cell
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);

	oCell.style.width = '12px';

	poly.colorRef = document.createElement('DIV');
	poly.colorRef.style.height = '12px';
	poly.colorRef.style.background =  '#' + this.statusLabels[poly.status-1].color;
	oCell.appendChild(poly.colorRef);
//	oCell.style.border = '1px solid gray';

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.paddingLeft = '6px';

	if (this.userPermissions > 1) {
		oCell.style.cursor = 'text';
		oCell.style.lineHeight = '6px';

		var oInput = document.createElement('INPUT');
		oCell.appendChild(oInput);
		oInput.style.border = '1px solid gray';
		oInput.style.width = '200px';
	//	oInput.style.background = '#ffffff';
		oInput.style.font = 'normal 10px verdana';
		oInput.value = poly.name;
		oInput.onclick = function(ev){
			try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		};
		oInput.onchange = function(ev){
			poly.changed = 1;
			poly.name = this.value;
		};
	
	}


	
	// ------ Zoom to territory Icon cell	
	var oZoomCell = document.createElement('TD');
	oRow.appendChild(oZoomCell);

	var oIcon = document.createElement('IMG');
	oZoomCell.appendChild(oIcon);
	oZoomCell.style.lineHeight = '6px';
	oZoomCell.style.width = '16px';

	oIcon.src = this.dir + '/images/bounds.png';
	oIcon.style.width = '16px';
	oIcon.style.margin = '0px';
	oIcon.style.cursor = 'pointer';
	oIcon.title = 'Center and zoom to this territory';
	oIcon.onclick = function(){
		if (poly.territoryBounds) {
			var zoom = self.map.getBoundsZoomLevel(poly.territoryBounds);
			if (zoom == self.map.getZoom()) {
				self.map.panTo(poly.territoryBounds.getCenter());
			}
			else {
				self.map.setCenter(poly.territoryBounds.getCenter(), zoom);
			}
		}
	};

		
	if (this.userPermissions > 1) {

	// ------ Edit Icon cell	
		var oCell = document.createElement('TD');
		oRow.appendChild(oCell);

		var oIcon = document.createElement('IMG');
		oCell.appendChild(oIcon);
		oCell.style.lineHeight = '6px';
		oCell.style.width = '16px';

		oIcon.src = this.dir + '/images/edit.png';
		oIcon.style.width = '16px';
		oIcon.style.margin = '0px';
		oIcon.style.cursor = 'pointer';
		oIcon.title = 'Edit this polygon...';

		GEvent.bindDom(oIcon, 'click', poly, function(){
			if (poly.territoryBounds) {
				self.map.panTo(poly.territoryBounds.getCenter());
			}
			self.toggleEditMode(poly);
		});

		
	// ------ Delete Icon cell	
		var oCell = document.createElement('TD');
		oRow.appendChild(oCell);

		var oIcon = document.createElement('IMG');
		oCell.appendChild(oIcon);
		oCell.style.lineHeight = '6px';
		oCell.style.width = '16px';

		oIcon.src = this.dir + '/images/delete.png';
		oIcon.style.width = '16px';
		oIcon.style.margin = '0px';
		oIcon.style.cursor = 'pointer';
		oIcon.title = 'Delete this item...';
		oIcon.onclick = function(){
			if (confirm('Are you sure that you want to delete polygon "'+poly.name+'"?')) {
				self.removeFromArray(poly);
//				self.saveCollection();
			}
		};
	}
	else {
		oCell.innerHTML += poly.name + ' (' + this.statusLabels[poly.status-1].name + ')';
	}

// End of first inner table
//==============================

	var iTable = document.createElement('TABLE');
	iTable.setAttribute('width','100%');
	iTable.setAttribute('cellSpacing',0);
	iTable.setAttribute('cellPadding',0);

	var oTBody = document.createElement('TBODY');
	iTable.appendChild(oTBody);

	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);

// ------ Expand/collapse icons
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);

	if (this.userPermissions > 1) {
		var oTable2 = this.createInnerTable(this.statusLabels.length*2);
		oCell.appendChild(oTable2);
		oTable2.style.marginTop = '2px';
		oTable2.style.marginBottom = '2px';
//		oTable2.style.border = '1px solid gray';
	// --------- Radio buttons -------------
		poly.statusSelector = this.createInputSet(this.statusLabels,'radio','territoryStatus',poly);

		for (var n = 0 ; n < poly.statusSelector.length ; n++ ) {
			oTable2.tCells[n*2].appendChild(poly.statusSelector[n]);
			oTable2.tCells[n*2].style.background = '#' + this.statusLabels[n].color;
			oTable2.tCells[n*2].style.width = '10px';
//			oTable2.tCells[n*2+1].style.width = '62px';
			oTable2.tCells[n*2+1].style.textAlign = 'left';
	//		oTable2.tCells[n*2].style.border = '2px solid gray';
			oTable2.tCells[n*2+1].innerHTML = this.statusLabels[n].name;
		}
	}


// Set as properties of the poly for toggling
	poly.infoContainer = document.createElement('DIV');
	sCell.appendChild(poly.infoContainer);
	poly.infoContainer.appendChild(iTable);
	poly.infoContainer.style.display = 'none';
	return sRow;
};


//////////////////////////////////////////////////////////
// Edit the name of the selector polygon
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.editPolyName = function(oCell,poly) {
	this.textInput.style.top = oCell.clientTop;
	this.textInput.style.left = oCell.clientLeft;
	this.textInput.value = poly.name;
	this.textInput.style.display = '';
};


//////////////////////////////////////////////////////////
// Row to hold selected polygons, (counties), for one selector polygon
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createChildRow = function(poly) {
	var self = this.self;
	var oRow = document.createElement('TR');

// ------ FIPS cell
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.innerHTML = poly.state + poly.county;
	oCell.style.font = 'normal 10px verdana';
	oCell.style.lineHeight = '10px';
	oCell.style.cursor = 'pointer';
	oCell.style.textAlign = 'left';

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.innerHTML = poly.name;
	oCell.style.font = 'normal 10px verdana';
	oCell.style.lineHeight = '10px';
	oCell.style.cursor = 'pointer';
	oCell.style.textAlign = 'left';

	oRow.poly = poly;

	GEvent.bindDom(oRow, 'click', poly, function(){self.toggleHighlight(oRow)});
	
	return oRow;
};




//////////////////////////////////////////////////////////
// Toggle highlight of selected polygons (counties)
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.toggleHighlight = function(oRow) {
	if (oRow.highlighted) {
		oRow.poly.setFillStyle(this.dataStyle);
		oRow.poly.setStrokeStyle(this.dataStyle);
		oRow.style.background = this.dataStyle.rowColor;
		oRow.highlighted = false;
	}
	else {
		oRow.poly.setFillStyle(this.dataStyleHigh);
		oRow.poly.setStrokeStyle(this.dataStyleHigh);
		oRow.style.background = this.dataStyleHigh.rowColor;
		oRow.scrollIntoView(false);
		oRow.highlighted = true;
	}
};

//////////////////////////////////////////////////////////
// Toggle the list of selected polygons (counties)
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.toggleChildren = function(poly) {
	if (poly.listRow.ecIcon.src.match(/minus2.png/)) {
		this.collapseChildren(poly);
	}
	else if (poly.listRow.ecIcon.src.match(/plus2.png/)) {
		this.expandChildren(poly);
		if (poly.territoryBounds) {
			this.map.panTo(poly.territoryBounds.getCenter());
		}
	};
};

MPolygonSelector.prototype.expandChildren = function(poly) {
	poly.infoContainer.style.display = '';
	poly.listRow.scrollIntoView(true);
	poly.listRow.ecIcon.src = this.dir + '/images/minus2.png';
};
MPolygonSelector.prototype.collapseChildren = function(poly) {
	poly.infoContainer.style.display = 'none';
	poly.listRow.ecIcon.src = this.dir + '/images/plus2.png';
};


//////////////////////////////////////////////////////////
// Table holding the list of selected polygons (counties)
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createChildContainer = function(cols) {
	var self = this.self;
	var childContainer = document.createElement('TR');
	
	var oCell = document.createElement('TD');
	childContainer.appendChild(oCell);
	oCell.setAttribute('colSpan',cols);

	childContainer.style.display = 'none';
	
	var oDiv = document.createElement('DIV');
	oCell.appendChild(oDiv);
	oDiv.style.height = '100px';
	oDiv.style.overflow = 'auto';
	
	var oTable = document.createElement('TABLE');
	oDiv.appendChild(oTable);
	if (document.all) {
		oTable.style.width = '160px';
	}
	else {
		oTable.setAttribute('width','100%');
	}
	oTable.setAttribute('cellSpacing',0);
	oTable.setAttribute('cellPadding',2);

	childContainer.cRows = document.createElement('TBODY');
	oTable.appendChild(childContainer.cRows);
	
	return childContainer;
};




//////////////////////////////////////////////////////////
// Table holding the list of selector polygons
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createSelectorList = function() {
	var self = this.self;	
	
	var oTable = document.createElement('TABLE');
	if (!document.all) {
		oTable.setAttribute('width','100%');
	}
	oTable.setAttribute('cellSpacing',2);
	oTable.setAttribute('cellPadding',0);
//	oTable.style.marginLeft = 'auto';
//	oTable.style.marginRight = 'auto';

	oTable.listContainer = document.createElement('TBODY');
	oTable.appendChild(oTable.listContainer);

//	oTable.style.border = '1px solid gray';


	return oTable;
};


//////////////////////////////////////////////////////////
// Table holding the info for the current franchise
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createFranchiseInfo = function() {
	var self = this.self;	
	
	var fInfoTable = document.createElement('TABLE');
	fInfoTable.setAttribute('width','100%');
	fInfoTable.setAttribute('cellSpacing',2);
	fInfoTable.setAttribute('cellPadding',2);

	oTBody = document.createElement('TBODY');
	fInfoTable.appendChild(oTBody);



// ------ collection name row
	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);
	oRow.style.background = this.defaultStyle.rowColor;

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.font = 'normal 10px verdana';
	oCell.style.lineHeight = '6px';
	oCell.innerHTML = 'Name:';

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.lineHeight = '6px';

	fInfoTable.name = document.createElement('INPUT');
	oCell.appendChild(fInfoTable.name);
	fInfoTable.name.style.border = 'none';
	fInfoTable.name.style.width = '100%';
	fInfoTable.name.style.font = 'normal 10px verdana';
	fInfoTable.name.value = 'New franchise';
	fInfoTable.name.onchange = function(ev){
		self.fInfoChanged = 1;
	};


// ------ collection.desc row
	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);
	oRow.style.background = this.defaultStyle.rowColor;

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.font = 'normal 10px verdana';
	oCell.style.lineHeight = '6px';
	oCell.innerHTML = 'Desc:';

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.lineHeight = '6px';

	fInfoTable.desc = document.createElement('TEXTAREA');
	oCell.appendChild(fInfoTable.desc);
	fInfoTable.desc.style.border = 'none';
	fInfoTable.desc.style.width = '100%';
	fInfoTable.desc.style.font = 'normal 10px verdana';
	fInfoTable.desc.value = 'Some Description - (255 characters max.)';
	fInfoTable.desc.onchange = function(ev){
		self.fInfoChanged = 1;
	};


// ------ collection.type row
	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);
	oRow.style.background = this.defaultStyle.rowColor;

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.font = 'normal 10px verdana';
	oCell.style.lineHeight = '6px';
	oCell.innerHTML = 'Unit:';

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);

	fInfoTable.fTypeInput = document.createElement('INPUT');
	oCell.appendChild(fInfoTable.fTypeInput);
	fInfoTable.fTypeInput.style.border = 'none';
	fInfoTable.fTypeInput.style.width = '100%';
	fInfoTable.fTypeInput.style.font = 'normal 10px verdana';
	fInfoTable.fTypeInput.value = '0';
	fInfoTable.fTypeInput.setAttribute('readonly','true');



// ------ last saved name row
	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);
	oRow.style.background = this.defaultStyle.rowColor;

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.font = 'normal 10px verdana';
	oCell.style.lineHeight = '6px';
	oCell.innerHTML = 'Saved:';


	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.style.lineHeight = '6px';

	fInfoTable.lastSaved = document.createElement('INPUT');
	oCell.appendChild(fInfoTable.lastSaved);
	fInfoTable.lastSaved.style.border = 'none';
	fInfoTable.lastSaved.style.width = '100%';
	fInfoTable.lastSaved.style.font = 'normal 10px verdana';
	fInfoTable.lastSaved.value = 'NO';
	fInfoTable.lastSaved.setAttribute('readonly','true');

// ----- Collection ID (not shown on screen)
	fInfoTable.fid = 0;

	return fInfoTable;
};


//////////////////////////////////////////////////////////
// Table holding the buttons of the control
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createButtons = function() {
	var self = this.self;	
	
	var oTable = document.createElement('TABLE');
//	oTable.setAttribute('width','100%');
	oTable.setAttribute('cellSpacing',2);
	oTable.setAttribute('cellPadding',0);
//	oTable.setAttribute('border',1);
	oTable.style.marginLeft = 'auto';
	oTable.style.marginRight = 'auto';

	oTBody = document.createElement('TBODY');
	oTable.appendChild(oTBody);

	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);

// ------------- Irregular poly
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	this.polyImg = document.createElement('IMG');
	oCell.appendChild(this.polyImg);
	this.polyImg.id = 'cell_draw';
	this.polyImg.src = this.dir + '/images/drawFree.png';
	this.polyImg.title = 'Irregular Polygon';
	this.polyImg.style.cursor = 'pointer';
	this.polyImg.onclick =  function(ev) {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};


// --------------- Rectangle
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	this.drawRectImg = document.createElement('IMG');
	oCell.appendChild(this.drawRectImg);
	this.drawRectImg.id = 'cell_draw_rect';
	this.drawRectImg.src = this.dir + '/images/drawRect.png';
	this.drawRectImg.title = 'Rectangle';
	this.drawRectImg.style.cursor = 'pointer';
	this.drawRectImg.onclick =  function(ev) {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};

// ------------- Circle
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	this.drawCircleImg = document.createElement('IMG');
	oCell.appendChild(this.drawCircleImg);
	this.drawCircleImg.id = 'cell_draw_circle';
	this.drawCircleImg.src = this.dir + '/images/drawCircle.png';
	this.drawCircleImg.title = 'Circle';
	this.drawCircleImg.style.cursor = 'pointer';
	this.drawCircleImg.onclick =  function(ev) {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};


// ------------- Hand
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	var oImg = document.createElement('IMG');
	oCell.appendChild(oImg);
	oImg.id = 'cell_stop_draw';
	oImg.src = this.dir + '/images/Bsu.png';
	oImg.title = 'Stop drawing';
	oImg.style.cursor = 'pointer';
	oImg.onclick =  function(ev) {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};


// ------------- Zoom to extent
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	var oImg = document.createElement('IMG');
	oCell.appendChild(oImg);
	oImg.id = 'cell_bounds';
	oImg.src = this.dir + '/images/bounds.png';
	oImg.style.cursor = 'pointer';
	oImg.title = 'Zoom to franchise extent';
	oImg.onclick = function(ev){
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};


// ------------- Separator

	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	var separator = document.createElement('DIV');
	oCell.appendChild(separator);
	separator.style.borderLeft = '2px solid gray';
	separator.style.marginLeft = '5px';
	separator.style.marginRight = '5px';
	separator.style.height = '31px';
//	separator.style.width = '2px';

// ------------- Save
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	var oImg = document.createElement('IMG');
	oCell.appendChild(oImg);
	oImg.id = 'cell_save';
	oImg.src = this.dir + '/images/save.png';
	oImg.title = 'Save ...';
	oImg.style.cursor = 'pointer';
	oImg.onclick =  function(ev) {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};
	
	
// ------------- CLR
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('align','center');

	var oImg = document.createElement('IMG');
	oCell.appendChild(oImg);
	oImg.id = 'cell_clear';
	oImg.src = this.dir + '/images/clr.png';
	oImg.title = 'Clear';
	oImg.style.cursor = 'pointer';
	oImg.onclick =  function(ev) {
		try{ev.stopPropagation()}catch(e){event.cancelBubble=true};
		self.buttonClick(this);
	};



//==============================
// Second row - Toggle selectors

	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);

// ------------- 
	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);

	var checked = 'checked';
	if (document.all && !window.opera && document.createElement) {
		this.selectorsCheckbox = document.createElement('<input type="checkbox" '+checked+'>');
	}
	else {
		this.selectorsCheckbox = document.createElement('INPUT');
		this.selectorsCheckbox.type = 'checkbox';
		if (checked) {
			this.selectorsCheckbox.setAttribute('checked',checked);
		}
	}
	oCell.appendChild(this.selectorsCheckbox);
	this.selectorsCheckbox.onclick = function(){self.toggleSelectors(this.checked)};


	var oCell = document.createElement('TD');
	oRow.appendChild(oCell);
	oCell.setAttribute('colSpan',7);
	oCell.innerHTML = 'Show selector polygons';

//==============================

	return oTable;
};


//////////////////////////////////////////////////////////
// Table holding the radio status selectors for one territory
//////////////////////////////////////////////////////////
MPolygonSelector.prototype.createInnerTable = function(cellCount) {
	var iTable = document.createElement('TABLE');
	iTable.setAttribute('width','100%');
	iTable.setAttribute('cellSpacing',0);
	iTable.setAttribute('cellPadding',2);
	iTable.style.marginLeft = 'auto';
	iTable.style.marginRight = 'auto';
	iTable.tCells = Array();

	var oTBody = document.createElement('TBODY');
	iTable.appendChild(oTBody);

	var oRow = document.createElement('TR');
	oTBody.appendChild(oRow);


//----------------
	for (var c = 0 ; c < cellCount ; c++ ) {
		var oCell = document.createElement('TD');
		oRow.appendChild(oCell);
		oCell.style.font = 'normal 10px verdana';
		oCell.style.lineHeight = '10px';
		oCell.style.textAlign = 'center';
		iTable.tCells.push(oCell);
	}
	
	return iTable;
};


MPolygonSelector.prototype.createInputSet = function(eArray,type,name,poly) {
	var self = this.self;
	var checkedIndex = poly.status;

	var inputSet = Array();
	for (var n = 0 ; n < eArray.length ; n++ ) {
		var obj = eArray[n];

		var checked = '';
		if (checkedIndex == obj.value) {
			var checked =  'checked';
		}

		if (document.all && !window.opera && document.createElement) {
			var oInput = document.createElement('<input type="'+type+'" name="'+name+poly.id+'" value="'+obj.value+'" '+checked+'>');
		}
		else {
			var oInput = document.createElement('INPUT');
			oInput.type = type;
			oInput.name = name + poly.id;
			oInput.value = obj.value;
			if (checked) {
				oInput.setAttribute('checked',checked);
			}
		}
		oInput.style.margin = '0px';
		oInput.onclick = function(){
			self.inputClick(this,poly);
		};
		inputSet.push(oInput);
	}

	return inputSet;
};

MPolygonSelector.prototype.inputClick = function(oInput,poly) {
	poly.status = oInput.value;
	poly.changed = 1;
};


MPolygonSelector.prototype.createUnitSelector = function() {
	var self = this.self;
	var oDiv = document.createElement('DIV');
//	oDiv.style.border = '1px solid gray';
	oDiv.style.background = '#ffffff';
//--------------
	var oDivTitle = document.createElement('DIV');
	oDiv.appendChild(oDivTitle);
	oDivTitle.style.background = 'navy';
	oDivTitle.style.color = 'white';
	oDivTitle.style.padding = '2px';
	oDivTitle.style.textAlign = 'center';
	oDivTitle.innerHTML = 'Please select a unit type for this franchise';
//--------------

	var oDivChoices = document.createElement('DIV');
	oDiv.appendChild(oDivChoices);
	oDivChoices.style.textAlign = 'center';

	for (var n = 0 ; n < this.franchiseUnits.length ; n++) {
		var optDiv = document.createElement('DIV');
		optDiv.style.border = '1px solid gray';
		optDiv.style.background = '#bbbbbb';
		optDiv.style.width = '200px';
		optDiv.style.cursor = 'pointer';
		optDiv.style.margin = '1px';
		optDiv.style.marginLeft = '50px';
		optDiv.style.padding = '2px';
		optDiv.innerHTML = this.franchiseUnits[n].name;
		optDiv.value = this.franchiseUnits[n].value;
		optDiv.onclick = function(){self.setFranchiseType(this)};
		optDiv.onmouseover = function(){this.style.background = '#FFA921'};
		optDiv.onmouseout = function(){this.style.background = '#bbbbbb'};
		oDivChoices.appendChild(optDiv);
	}

	this.modalDialog = new MModalDialog(null,300,200);
	this.modalDialog.contentDiv.appendChild(oDiv);

};


MPolygonSelector.prototype.setFranchiseType = function(inputObj) {
	this.clearAll();
	this.fInfoChanged = 1;
	this.franchiseInfo.units = inputObj.value;
	this.franchiseInfo.fTypeInput.value = inputObj.innerHTML; 
	this.modalDialog.hide();
	this.show();

	var oTab = document.getElementById('t2');
	app.setTab(oTab);

};


MPolygonSelector.prototype.newFranchise = function() {
	this.modalDialog.show();
};

