/*Save the map

-Loop through all global objects and pull out necessary values
-Discard all null objects (i.e. deleted panels and controls)



Ojbect -map-
	general
		controls
		layers
		
		
Object -divs-
-div control object is tied to control
-panels are independent - will have to loop through and determine which are panels and which aren't

TODO
-Save Map
-Save Layers
-Save Controls
-Save Panels / Controls

*/	
var finalMapOptions;
var generatedCode = "";
var preGenCode = "";
var cssGenCode = "";
var finalMap = {};
var finalControlOptions = [];
window.addEvent('domready', function(){

	$('saveMapButton').addEvent('click', function(event){
		if(numActiveLayers < 1){
			$('siteAlerts').setStyle('display', 'block');
			$('siteAlerts').setStyle('opacity',0);
			$('siteAlerts').fade(1);
			$('siteAlerts').innerHTML = "At least one layer needs to be created";

		}
		else{
			/*Fade any alerts*/
			if( $('siteAlerts').getStyle('opacity') > 0 )
				$('siteAlerts').fade(0);
		
			/*-------------------
			| Generate Map code
			|--------------------*/
			finalMapOptions = ""
			preGenCode = "<script type='text/javascript' src='http://openlayers.org/api/OpenLayers.js'></script>\n";
			
			for(var i in map){
				if(i != "controls" && i != "layers" && i != 'CLASS_NAME' && i != 'title' && i != 'lat' && i != 'lon' && i != 'zoom' && i != 'dragging' && i != 'projection' && i != 'MaxExtentMinX' && i != 'MaxExtentMinY' && i != 'MaxExtentMaxX' && i != 'MaxExtentMaxY' && i != 'MinExtentMinX' && i != 'MinExtentMinY' && i != 'MinExtentMaxX' && i != 'MinExtentMaxY' && i != 'createDiv' && i != 'defaultControls'){/*do not check for values specified above (i.e. i != "controls" will ensure 'controls' is skipped*/
					if(hasQuotes(map[i]) == true)
						finalMapOptions += "\n" + i + ":" + map[i] + ","; //no quotes if int
					else
						finalMapOptions += "\n" + i + ": '" + map[i] + "',";
				}
				if( i == 'projection')//Custom options
					finalMapOptions += "\n" + i + ": new OpenLayers.Projection('" + map[i] + "'),";
				if( i == 'MaxExtentMinX'){
					if(map['MaxExtentMinX'] && map['MaxExtentMinY'] && map['MaxExtentMaxX']&& map['MaxExtentMaxY'])
						finalMapOptions += "\n maxExtent: new OpenLayers.Bounds(" +  map['MaxExtentMinX'] + "," + map['MaxExtentMinY'] + "," + map['MaxExtentMinY'] + ","  +  map['MaxExtentMaxY'] + "),";
				}
				if( i == 'MinExtentMinX'){
					if(map['MinExtentMinX'] && map['MinExtentMinY'] && map['MinExtentMaxX']&& map['MinExtentMaxY'])
						finalMapOptions += "\n minExtent: new OpenLayers.Bounds(" +  map['MinExtentMinX'] + "," + map['MinExtentMinY'] + "," + map['MinExtentMaxX'] + ","  +  map['MinExtentMaxY'] + "),";
				}
				//if default controls are not to be shown
				if( i == "defaultControls"){
					if(map['defaultControls']){
						if(map['defaultControls'] == 'False')
							finalMapOptions += "controls: [],";
					}
				}
			}
			
		
		
		
			/*Generate skeleton map code*/
			var mapDiv = "map";
			if(map.div != null || map.div != undefined)
				mapDiv = map.div;
			
			
			generatedCode = "<script type='text/javascript'>\n"
							+	"/*Configure the map*/\n";
			
			/*remove commas*/
			if(finalMapOptions == '')
				generatedCode += "var map = new OpenLayers.Map('" + mapDiv + "'); \n";
			else{
				if (finalMapOptions.substr(finalMapOptions.length - 1) == ",")
					finalMapOptions = finalMapOptions.substr(0, finalMapOptions.length - 1) //get rid of the trailing comma
				generatedCode += "var map = new OpenLayers.Map('" + mapDiv + "',{" + finalMapOptions + "}); \n\n";
			}
		
			/*-------------------
			| Generate Layer code
			|--------------------*/
			//Only add current layers
			finalMap = {
				"layers": [],
				"controls": [],
				"panels": []
			}

			/*store the layers to generate the code*/
			for(i = 0; i < map.layers.length; i++){
				if(map.layers[i] != null){
					finalMap.layers.push(map.layers[i]);
				}
			}
			
			/*generate the code*/
			var finalLayerParams = "";
			var finalLayerOptions = "";
			
			
			//Loop through all the valid layers
			for(i = 0; i < finalMap.layers.length; i++){							
				finalLayerOptions = '';
				finalLayerParams = '';
				generatedCode += '\n/*Layers*/\n';
				/*-------------------
				| Google / Yahoo / VE
				|--------------------*/
				if(finalMap.layers[i].CLASS_NAME == 'OpenLayers.Layer.Google' || finalMap.layers[i].CLASS_NAME == 'OpenLayers.Layer.Yahoo' || finalMap.layers[i].CLASS_NAME == 'OpenLayers.Layer.VirtualEarth'){
					/*---------Add in script for google API-----------*/
					if(finalMap.layers[i].CLASS_NAME == 'OpenLayers.Layer.Google'){
						preGenCode +="<!-- change this to your own google api code. Don't have one? go to http://code.google.com/apis/maps/signup.html  -->  \n" 
						+ "<script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ'></script>\n\n";
					}
					
					/*---------Add in script for yahoo API-----------*/
					if(finalMap.layers[i].CLASS_NAME == 'OpenLayers.Layer.Yahoo'){
						preGenCode += "<script src='http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=euzuro-openlayers'></script>\n\n";
					}
					
					/*---------Add in script for ve API-----------*/
					if(finalMap.layers[i].CLASS_NAME == 'OpenLayers.Layer.VirtualEarth'){
						preGenCode +="<script src='http://dev.virtualearth.net/mapcontrol/v3/mapcontrol.js'></script>\n\n";
					}
					
					/*---------Get all the layer properties for the current layer-----------*/
					/*TODO - extend this?*/
					for(var j in finalMap.layers[i]){
						if(j != "id" && j != "CLASS_NAME" && j != "name"){
							if( hasQuotes(finalMap.layers[i][j]) == true || j == 'type' )
								finalLayerOptions += "\n" + j + ":" + finalMap.layers[i][j] + ","; //no quotes if int
							else
								finalLayerOptions += "\n" + j + ": '" + finalMap.layers[i][j] + "',";
						}
					}				
					
					//remove commas
					if (finalLayerOptions.substr(finalLayerOptions.length - 1) == ",")
						finalLayerOptions = finalLayerOptions.substr(0, finalLayerOptions.length - 1) 
						
						
					/*GENERATE CODE*/
					generatedCode += "layer" + finalMap.layers[i].id + " = new " + finalMap.layers[i].CLASS_NAME + "( '"
								+ finalMap.layers[i].name + "'";
					if(finalLayerOptions != '')
						generatedCode += "\n,{" + finalLayerOptions + "}" ;
					generatedCode += ");\n";			
				}
				/*-------------------
				/*WMS, WFS, TileCahce
				/*-------------------*/
				else if(finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.WMS" || finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.WFS" || finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.TileCache" || finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.MapServer"){
					/*Get all the layer properties for the current layer*/
					for(var j in finalMap.layers[i]){
						if(j != "id" && j != "CLASS_NAME" && j != "name" && j != "url" && j != "srs" && j != "typenameO" && j != 'tmsimgtype'){
							
							if(j != "layers" && j != "exceptions" && j != "format" && j != "map" && j != "alpha" && j != "typename" && j != "maxfeatures"){
								if( hasQuotes(finalMap.layers[i][j]) == true || j == 'type' )
									finalLayerOptions += "\n" + j + ":" + finalMap.layers[i][j] + ",";
								else
									finalLayerOptions += "\n" + j + ": '" + finalMap.layers[i][j] + "',";
							}	
							else{
								if( hasQuotes(finalMap.layers[i][j]) == true || j == 'type' )
									finalLayerParams += "\n" + j + ":" + finalMap.layers[i][j] + ",";
								else
									finalLayerParams += "\n" + j + ": '" + finalMap.layers[i][j] + "',";
									
							}
						}
						//Custom options
						if( j == "srs")
							finalLayerOptions += "\n projection: new OpenLayers.Projection('" +  finalMap.layers[i][j] + "'),";
						if( j == "typenameO")
							finalLayerOptions += "\n typename: '" + finalMap.layers[i][j] + "',";
						if(finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.TMS" && j == "tmsimgtype"){
							var imgType = finalMap.layers[i][j].replace("image/", "");
							finalLayerOptions += "\n type: '" + imgType + "',";
						}
					}
					
					
					/*GENERATE CODE*/		
					if (finalLayerOptions.substr(finalLayerOptions.length - 1) == ",")
						finalLayerOptions = finalLayerOptions.substr(0, finalLayerOptions.length - 1) //get rid of the trailing comma	
					if (finalLayerParams.substr(finalLayerParams.length - 1) == ",")
						finalLayerParams = finalLayerParams.substr(0, finalLayerParams.length - 1) //get rid of the trailing comma	
						
					generatedCode += "layer" + finalMap.layers[i].id + " = new " + finalMap.layers[i].CLASS_NAME + "( '"
								+ finalMap.layers[i].name + "', \n"
								+ "'" + finalMap.layers[i].url + "',{"
								+ finalLayerParams + "},{"
								+ finalLayerOptions + "});\n";
					
				}
				/*-------------------
				/*TMS
				/*-------------------*/
				else if(finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.TMS"){
					/*Get all the layer properties for the current layer*/
					for(var j in finalMap.layers[i]){
						if(j != "id" && j != "CLASS_NAME" && j != "name" && j != "url" && j != "srs" && j != "typenameO" && j != 'tmsimgtype'){
							if( hasQuotes(finalMap.layers[i][j]) == true || j == 'type' )
								finalLayerOptions += "\n" + j + ":" + finalMap.layers[i][j] + ",";
							else
								finalLayerOptions += "\n" + j + ": '" + finalMap.layers[i][j] + "',";	
						}
						//Custom options
						if( j == "srs")
							finalLayerOptions += "\n projection: new OpenLayers.Projection('" +  finalMap.layers[i][j] + "'),";
						if( j == "typenameO")
							finalLayerOptions += "\n typename: '" + finalMap.layers[i][j] + "',";
						if(j == "tmsimgtype"){
							var imgType = finalMap.layers[i][j].replace("image/", "");
							finalLayerOptions += "\n type: '" + imgType + "',";
						}
					}
					
					
					/*GENERATE CODE*/		
					if (finalLayerOptions.substr(finalLayerOptions.length - 1) == ",")
						finalLayerOptions = finalLayerOptions.substr(0, finalLayerOptions.length - 1) //get rid of the trailing comma	
			
					generatedCode += "layer" + finalMap.layers[i].id + " = new " + finalMap.layers[i].CLASS_NAME + "( '"
								+ finalMap.layers[i].name + "', \n"
								+ "'" + finalMap.layers[i].url + "',{"
								+ finalLayerOptions + "});\n";
					
				}
				
				/*-------------------
				/* Image Layer
				/*-------------------*/
				else if(finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.Image"){
						for(var j in finalMap.layers[i]){
							if(j != "id" && j != "CLASS_NAME" && j != "name" && j != "url" && j != "srs" && j != "typenameO" && j != 'sizeH' && j != 'sizeW' && j != 'MaxExtentMinX' && j != 'MaxExtentMinY' && j != 'MaxExtentMaxX' && j != 'MaxExtentMaxY'  ){
								if( hasQuotes(finalMap.layers[i][j]) == true || j == 'type' )
									finalLayerOptions += "\n" + j + ":" + finalMap.layers[i][j] + ",";
								else
									finalLayerOptions += "\n" + j + ": '" + finalMap.layers[i][j] + "',";
							}
							if(j == 'MaxExtentMinX'){
								if(finalMap.layers[i]['MaxExtentMinX'] && finalMap.layers[i]['MaxExtentMinY'] && finalMap.layers[i]['MaxExtentMaxX']&& finalMap.layers[i]['MaxExtentMaxY'])
									var imageBounds = "\n new OpenLayers.Bounds(" +  finalMap.layers[i]['MaxExtentMinX'] + "," + finalMap.layers[i]['MaxExtentMinY'] + "," + finalMap.layers[i]['MaxExtentMaxY'] + ","  +  finalMap.layers[i]['MaxExtentMaxY'] + ")";
							}
							if(j == 'sizeW'){
								if(finalMap.layers[i]['sizeW'] && finalMap.layers[i]['sizeH'])
									var imageSize = "\n new OpenLayers.Size(" +  finalMap.layers[i]['sizeW'] + "," + finalMap.layers[i]['sizeH'] + ")";
							}
								
						}
						
				/*GENERATE CODE*/		
				if (finalLayerOptions.substr(finalLayerOptions.length - 1) == ",")
					finalLayerOptions = finalLayerOptions.substr(0, finalLayerOptions.length - 1) //get rid of the trailing comma	
					
				generatedCode += "layer" + finalMap.layers[i].id + " = new " + finalMap.layers[i].CLASS_NAME + "( '"
							+ finalMap.layers[i].name + "', \n"
							+ "'" + finalMap.layers[i].url + "',"
							+ imageBounds + ","
							+ imageSize + ",{"
							+ finalLayerOptions + "});\n";
						
				}
				
				
				/*-------------------
				/* Vector Layer
				/*-------------------*/
				else if(finalMap.layers[i].CLASS_NAME == "OpenLayers.Layer.Vector"){
						for(var j in finalMap.layers[i]){
							if(j != "id" && j != "CLASS_NAME" && j != "name" && j != "url" && j != "srs" && j != "typenameO" && j != 'sizeH' && j != 'sizeW' && j != 'MaxExtentMinX' && j != 'MaxExtentMinY' && j != 'MaxExtentMaxX' && j != 'MaxExtentMaxY'  ){
								if( hasQuotes(finalMap.layers[i][j]) == true || j == 'type' )
									finalLayerOptions += "\n" + j + ":" + finalMap.layers[i][j] + ",";
								else
									finalLayerOptions += "\n" + j + ": '" + finalMap.layers[i][j] + "',";
							}
						}
						
				/*GENERATE CODE*/		
				if (finalLayerOptions.substr(finalLayerOptions.length - 1) == ",")
					finalLayerOptions = finalLayerOptions.substr(0, finalLayerOptions.length - 1) //get rid of the trailing comma	
					
				generatedCode += "layer" + finalMap.layers[i].id + " = new " + finalMap.layers[i].CLASS_NAME + "( '"
							+ finalMap.layers[i].name + "', \n {"
							+ finalLayerOptions + "});\n";
						
				}
			}//end loop
			
			/*Add layers to map*/
			generatedCode += "map.addLayers([";
			var layersToAdd = ''
			var curLayerID = ''
			for(i=0; i < $('layerListItems').getChildren().length; i++){
					curLayerID = $('layerListItems').getChildren()[i].id;
					curLayerID = curLayerID.match(/[0-9]*$/)
					layersToAdd += "layer" + curLayerID + ",";
			}
			if (layersToAdd.substr(layersToAdd.length - 1) == ",")
					layersToAdd = layersToAdd.substr(0, layersToAdd.length - 1) //get rid of the trailing comma
			generatedCode += layersToAdd;
			generatedCode += "]);\n\n\n/*Controls*/";
			

			/*-------------------
			|
			| Generate Control code
			|
			|--------------------*/
			
			/*store the controls*/
			for(i = 0; i < divs.div.length; i++){
				for(j = 0; j < map.controls.length; j++){
					if(map.controls[j] != null){
						if(divs.div[i].cID == map.controls[j].id){
							finalMap.controls.push(map.controls[j]);
							//For now, save the values directly.  Rewrite the save method in dragDrop
							if(finalMap.controls[i] != null){
								finalMap.controls[i].topP = divs.div[i].topP;
								finalMap.controls[i].leftP = divs.div[i].leftP;
								finalMap.controls[i].widthP = divs.div[i].widthP;
								finalMap.controls[i].heightP = divs.div[i].heightP;
							}
						}
					}
				}
				
				/*store panels*/
				for(j = 0; j < panels.panels.length; j++){
					if(panels.panels[j] != null){
						if(divs.div[i].pID == panels.panels[j].id){

							finalMap.panels.push(panels.panels[j]);
							//For now, save the values directly.  Rewrite the save method in dragDrop
							if(finalMap.panels[i] != null){
								finalMap.panels[i].topP = divs.div[i].topP;
								finalMap.panels[i].leftP = divs.div[i].leftP;
								finalMap.panels[i].widthP = divs.div[i].widthP;
								finalMap.panels[i].heightP = divs.div[i].heightP;
							}
						}
					}
				}
			}		
			
			/*-------------------
			| Set CSS Class
			|--------------------*/
			/*--------CONTROL------------*/
			for(i = 0; i < finalMap.controls.length; i++){
				//remove whitespace to check that a valid value has been entered
				finalMap.controls[i].displayClass = finalMap.controls[i].displayClass.trim();
				if(finalMap.controls[i].displayClass == ""){
						//set a default display class
						finalMap.controls[i].displayClass = "control_" + finalMap.controls[i].CLASS_NAME.replace("OpenLayers.Control.", "") + "_" + finalMap.controls[i].id;
				}	
			}	
			/*--------PANEL------------*/
			for(i = 0; i < finalMap.panels.length; i++){
				//remove whitespace to check that a valid value has been entered
				finalMap.panels[i].displayClass = finalMap.panels[i].displayClass.trim();
				if(finalMap.panels[i].displayClass == ""){
						//set a default display class
						finalMap.panels[i].displayClass = "panel_" + finalMap.panels[i].CLASS_NAME.replace("OpenLayers.Control.", "") + "_" + finalMap.panels[i].id;
				}	
			}	
			
			
			
			/*---------CONTROL-----------*/
			/*Get all the control properties for the current control*/
			/*extend this?*/
			
			/*GENERATE OPTIONS*/
			
			/*--------CONTROL OPTIONS------------*/
			finalControlOptions = [];
			var controlPreParams = [];
			for(i = 0; i < finalMap.controls.length; i++){
				finalControlOptions[i] = '';
				for(j in finalMap.controls[i]){
					//skip these options
					if(j != "id" && j != "CLASS_NAME" && j != "id" && j != "panelID" && j != "xPos" && j != "yPos" && j != "width" && j != "height" && j != "base" && j != "vectorLayer" && j != "ovMapOptions" && j!= "maximize" && j != "minButton" && j != "width" && j != "height" && j != "topP" && j != "leftP" && j != "widthP" && j != "heightP" &&  j != "displayClass"){
						if( hasQuotes(finalMap.controls[i][j]) == true) //check to see if the current item has quotes
							finalControlOptions[i] += "\n" + j + ":" + finalMap.controls[i][j] + ","; //no quotes if int
						else
							finalControlOptions[i] += "\n" + j + ": '" + finalMap.controls[i][j] + "',";
					}
					
					//overview map options
					if( j == 'ovMapOptions' ){
						if(finalMap.controls[i]['ovMapOptions'] == 'True'){
							finalControlOptions[i] += finalMapOptions + ",";
						}
					}
					
					//For now, don't give the editing toolbar a custom class
					if( j == 'displayClass' && 	finalMap.controls[i].CLASS_NAME != "OpenLayers.Control.EditingToolbar"){
						if( hasQuotes(finalMap.controls[i][j]) == true) //check to see if the current item has quotes
								finalControlOptions[i] += "\n" + j + ":" + finalMap.controls[i][j] + ","; //no quotes if int
						else
							finalControlOptions[i] += "\n" + j + ": '" + finalMap.controls[i][j] + "',";
					}
					
					if( j == 'base' )
							controlPreParams[i] = "'" + finalMap.controls[i].base + "'";
					
					//store the vector layer name for the editing toolbar
					if( j == 'vectorLayer')
						controlPreParams[i] = "layer" + finalMap.controls[i].vectorLayer + ","; 
					
				}
				if (finalControlOptions[i].substr(finalControlOptions[i].length - 1) == ",")
							finalControlOptions[i] = finalControlOptions[i].substr(0, finalControlOptions[i].length - 1) //get rid of the trailing comma			
			}
		
			
			/*--------PANEL OPTIONS------------*/
			/*Get all the panel properties for the current panel*/
			/*extend this?*/
			var finalPanelOptions = [];
			for(i = 0; i < finalMap.panels.length; i++){
				finalPanelOptions[i] = '';
				for(j in finalMap.panels[i]){
					if(j != "id" && j != "CLASS_NAME" && j != "id" && j != "panelID" && j != "title" && j != "xPos" && j != "yPos" && j != "width" && j != "height" && j!= "maximize" && j != "minButton" && j != "topP" && j != "leftP" && j != "widthP" && j != "heightP"){
						if( hasQuotes(finalMap.panels[i][j]) == true)
							finalPanelOptions[i] += "\n" + j + ":" + finalMap.panels[i][j] + ","; //no quotes if int
						else
							finalPanelOptions[i] += "\n" + j + ": '" + finalMap.panels[i][j] + "',";
					}
				}		
			}
			
			/*GENERATE NEW CONTROL / PANEL CODE*/
			var controlName = "";
			var cTitle = "";

			/*--------CONTROL------------*/
			//Loop through all the valid controls
			for(i = 0; i < finalMap.controls.length; i++){											
				generatedCode += '\n';
				cTitle = finalMap.controls[i].title.replace(/\s+/g,'');
				generatedCode += "var control_" +  cTitle + "_" + finalMap.controls[i].id + " = new " + finalMap.controls[i].CLASS_NAME + "("; 
				
				if(controlPreParams[i] != null)
				 	generatedCode += controlPreParams[i];
				 	
				generatedCode	+= "{"
						+ finalControlOptions[i] + "});\n"; 

				if(finalMap.controls[i].panelID == null){ //only add the control to the map if it does not have a panel
					generatedCode += "\nmap.addControl(control_" +  cTitle + "_" + finalMap.controls[i].id + ");";
				}
				
				/*ADDITIONAL CONTROL OPTIONS*/
				for(j in finalMap.controls[i]){ //loop through to get additional options, i.e. maximizeControl
					if(finalMap.controls[i][j] == "OpenLayers.Control.OverviewMap") {
						if( finalMap.controls[i].maximize != 'False')
							generatedCode += "\ncontrol_" +  cTitle + "_" + finalMap.controls[i].id + ".maximizeControl();";
					}
				}
			}
			
			/*--------PANEL-----------*/
			generatedCode += '\n';
			var cToPanel = ''; //controls to panel
			var pTitle = ''; //panel title 
			//Loop through all the valid panels
			for(i = 0; i < finalMap.panels.length; i++){							
				pTitle = finalMap.panels[i].title.replace(/\s+/g,''); //remove spaces
				
				/*ADD ANY DEFAULT CONTROLS*/
				if($('panel' + i + 'ListItems') != null){
					if($('panel' + i + 'ListItems').childNodes[0] != null){
						var defaultControl = $('panel' + i + 'ListItems').childNodes[0].id.replace("tb1Control",'');
						if(finalMap.controls[defaultControl] != null){
							cTitle = finalMap.controls[defaultControl].title.replace(/\s+/g,'');
							finalPanelOptions[i] += "defaultControl: control_" +  cTitle + "_" + finalMap.controls[defaultControl].id;
						}
					}	
				}
				
				if (finalPanelOptions[i].substr(finalPanelOptions[i].length - 1) == ",")
					finalPanelOptions[i] = finalPanelOptions[i].substr(0, finalPanelOptions[i].length - 1) //get rid of the trailing comma
				
				
				
				//create the panel
				generatedCode += "var panel_" +  pTitle + "_" + finalMap.panels[i].id + " = new " + finalMap.panels[i].CLASS_NAME + "({"
					+ finalPanelOptions[i] + "});\n"; //create the panel
				
				//add controls the panel
				generatedCode += "panel_" +  pTitle + "_" + finalMap.panels[i].id + ".addControls([";
				cToPanel = '';
				for(j = 0; j < finalMap.controls.length; j++){
					cTitle = finalMap.controls[j].title.replace(/\s+/g,'');
					if(finalMap.controls[j].panelID == finalMap.panels[i].id){
						cToPanel += "control_" +  cTitle + "_" + finalMap.controls[j].id + ","; //add control to the panel
					}
				}
									
				/*get rid of trailing comma*/
				if (cToPanel.substr(cToPanel.length - 1) == ","){
					cToPanel = cToPanel.substr(0, cToPanel.length - 1) //get rid of the trailing comma
					//cToPanel += "\n"; //add the break
				}
				
				generatedCode += cToPanel + "]);"
				+	"\nmap.addControl(panel_" +  pTitle + "_" + finalMap.panels[i].id + ");\n\n"; //add the panel
			}	

			/*-------------------
			| Generate Addition code
			|--------------------*/		
						
			/*Set map center*/
			if(map.lat != null && map.lon != null){
				generatedCode += "\n/*Set the map center*/\nmap.setCenter(new OpenLayers.LonLat(" + map.lon + ", " + map.lat + ")"; //Use lat lon if specified
				if (map.zoom != null)
					generatedCode += ", " + map.zoom;
				if(map.dragging != null)
					generatedCode += ", " + map.dragging;
				generatedCode += ");";
			}
			else //set to max extent
				generatedCode += "\n/*Set the map center*/\nmap.zoomToMaxExtent();"; //No center set
			
			generatedCode += "\n</script>"; //close the script
			
			
			/*-------------------
			|
			|  Generate CSS Code
			|
			|--------------------*/
			/*STORE CSS INFORMATION*/
			/*--------CONTROL------------*/
			var cssControlCode = [];  //Create an array for both the control and panel code
			var cssPanelCode = [];
			var curClassName = "";
			var cssExists = false; //used to determine if any css has been created
			cssGenCode = "<style>\n";
			for(i = 0; i < finalMap.controls.length; i++){
				curClassName = finalMap.controls[i].displayClass = "control_" + finalMap.controls[i].CLASS_NAME.replace("OpenLayers.Control.", "") + "_" + finalMap.controls[i].id;
				cssControlCode[i] = "";
				cssControlCode[i] += "." + curClassName + "{"; //Selector
				if(finalMap.controls[i].panelID == null){
					if(finalMap.controls[i].leftP != "" || finalMap.controls[i].leftP != null)
						cssControlCode[i] += "left: " + Math.round(finalMap.controls[i].leftP) + "% !important; "; //width
					if(finalMap.controls[i].heightP != "" || finalMap.controls[i].heightP != null)
						cssControlCode[i] += "height: " + Math.round(finalMap.controls[i].heightP) + "% !important; "; //width
					cssControlCode[i] += "position: absolute; "; //buttons are positioned absolutely within a panel
					if(finalMap.controls[i].topP != "" || finalMap.controls[i].topP != null)
						cssControlCode[i] += "top: " + Math.round(finalMap.controls[i].topP) + "% !important; "; //width
					if(finalMap.controls[i].widthP != "" || finalMap.controls[i].widthP != null)
						cssControlCode[i] += "width: " + Math.round(finalMap.controls[i].widthP) + "% !important; "; //width
				}
				else{
					cssControlCode[i] += "float:left; height: " + finalMap.controls[i].height + "px; position: relative; width: " + finalMap.controls[i].width + "px;" //buttons are positioned absolutely within a panel	
				}
				cssControlCode[i] += "}\n ";
				cssExists = true;
				
				if(finalMap.controls[i].panelID != null){
					/*INACTIVE BUTTON*/
					cssControlCode[i] += "." + curClassName + "ItemInactive{"; //Selector
					cssControlCode[i] += "background-color:#cd3434; float:left; height: " + finalMap.controls[i].height + "px; position: relative; width: " + finalMap.controls[i].width + "px;" //buttons are positioned absolutely within a panel	
					cssControlCode[i] += "}\n ";
					
					
					/*ACTIVE BUTTON*/
					cssControlCode[i] += "." + curClassName + "ItemActive{"; //Selector
					cssControlCode[i] += "background-color:#efefef; float:left; height: " + finalMap.controls[i].height + "px; position: relative; width: " + finalMap.controls[i].width + "px;" //buttons are positioned absolutely within a panel	
					cssControlCode[i] += "}\n ";
				}
								
				if(finalMap.controls[i].CLASS_NAME == "OpenLayers.Control.OverviewMap"){ //set the minimize button
					if(finalMap.controls[i].minButton != null){
						//minbutton
						cssControlCode[i] += "." + curClassName + "MinimizeButton {";		
						if(finalMap.controls[i].minButton == "bottomright")
							cssControlCode[i] += "bottom: 0px; position:absolute; right:0px; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "bottomleft")
							cssControlCode[i] += "bottom: 0px; left:0px; position:absolute; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topright")
							cssControlCode[i] += "position:absolute; right:0px; top: 0px; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topleft")
							cssControlCode[i] += "left:0px;position:absolute; top: 0px; z-index: 999999;}\n";
						
						//maxbutton
						cssControlCode[i] += "." + curClassName + "MaximizeButton {";		
						if(finalMap.controls[i].minButton == "bottomright")
							cssControlCode[i] += "bottom: 0px; position:absolute; right:0px; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "bottomleft")
							cssControlCode[i] += "bottom: 0px; left:0px; position:absolute; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topright")
							cssControlCode[i] += "position:absolute; right:0px; top: 0px; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topleft")
							cssControlCode[i] += "left:0px;position:absolute; top: 0px; z-index: 999999;}\n";
							
						//set the viewPort to the width / height
						cssControlCode[i] += ".olMapViewport {\n";
						cssControlCode[i] += "height:100%; width: 100%;}\n";
						
						
						//Set the OV map window to 100%.  OpenLayers can specifiy a pixel width / height for the OVMap, but not percentage
						//The following code is very ugly.  It loops up to 999 and tries to get the overview map id.  As far as I can tell, the ID number is random.  This should be cleaned up
						generatedCode += "\n <br /><script type='text/javascript'>for(i = 0; i < 999; i++){"
										+	"/*set the overview map width and height to 100%*/if(document.getElementById('overviewMap' + i) != null){"
										+		"document.getElementById('overviewMap' + i).style.width='100%';"
										+		"document.getElementById('overviewMap' + i).style.height='100%';"
										+	"};"
										+"};</script>"
										
						cssExists = true;
					}
				}
				
				
				if(finalMap.controls[i].CLASS_NAME == "OpenLayers.Control.LayerSwitcher"){ //set the minimize button
					if(finalMap.controls[i].minButton != null){
						//minbutton
						cssControlCode[i] += "#OpenLayers_Control_MaximizeDiv {";
						cssControlCode[i] += "visibility:visible !important;";						
						if(finalMap.controls[i].minButton == "bottomright")
							cssControlCode[i] += "position:absolute; right:0px; top: 99%  !important; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "bottomleft")
							cssControlCode[i] += "left:0px; position:absolute; top: 99%  !important; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topright")
							cssControlCode[i] += "position:absolute; right:0px; top: 0px; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topleft")
							cssControlCode[i] += "left:0px;position:absolute; top: 0px; z-index: 999999;}\n";
						
						//maxbutton
						cssControlCode[i] += "#OpenLayers_Control_MinimizeDiv {";		
						cssControlCode[i] += "visibility:visible !important;";
						if(finalMap.controls[i].minButton == "bottomright")
							cssControlCode[i] += "position:absolute; right:0px; top: 99%  !important; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "bottomleft")
							cssControlCode[i] += "left:0px; position:absolute; top: 99%  !important; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topright")
							cssControlCode[i] += "position:absolute; right:0px; top: 0px; z-index: 999999;}\n";
						if(finalMap.controls[i].minButton == "topleft")
							cssControlCode[i] += "left:0px;position:absolute; top: 0px; z-index: 999999;}\n";
						
						cssControlCode[i] += "#layersDiv {"
											+ "padding-top:5px!important;padding-bottom:0px!important;padding-left:5px!important;padding-right:5px!important; visibility:visible !important; }";
											
						cssControlCode[i] += "." + curClassName + "{ visibility: hidden !important; }"; //Selector
						
						cssExists = true;
					}
				}
				
				
			}
			
			/*--------PANEL---------*/
			for(i = 0; i < finalMap.panels.length; i++){
				curClassName = finalMap.panels[i].displayClass = "panel_" + finalMap.panels[i].CLASS_NAME.replace("OpenLayers.Control.", "") + "_" + finalMap.panels[i].id;
				cssPanelCode[i] = "";
				cssPanelCode[i] += "." + curClassName + "{"; //Selector
				if(finalMap.panels[i].leftP != "" || finalMap.panels[i].leftP != null)
					cssPanelCode[i] += "left: " + Math.round(finalMap.panels[i].leftP) + "%; "; //width
				if(finalMap.panels[i].heightP != "" || finalMap.panels[i].heightP != null)
					cssPanelCode[i] += "height: " + Math.round(finalMap.panels[i].heightP) + "%; "; //width
				cssPanelCode[i] += "position: absolute; "; //buttons are positioned absolutely within a panel
				if(finalMap.panels[i].topP != "" || finalMap.panels[i].topP != null)
					cssPanelCode[i] += "top: " + Math.round(finalMap.panels[i].topP) + "%; "; //width
				if(finalMap.panels[i].widthP != "" || finalMap.panels[i].widthP != null)
					cssPanelCode[i] += "width: " + Math.round(finalMap.panels[i].widthP) + "%; "; //width
				cssPanelCode[i] += "}\n ";
				cssExists = true;
			}	
			
			/*GENERATE CSS CODE*/	
			/*PANELS*/
			for(i = 0; i < cssPanelCode.length; i++){
				if(cssPanelCode[i] != null)
					cssGenCode += cssPanelCode[i];
				cssExists = true;
			}
			/*CONTROLS*/
			for(i=0; i < finalMap.controls.length; i++){
				//if the control belongs to a panel, prefix the panel
				if(finalMap.controls[i].panelID != null){	
					var pID = finalMap.controls[i].panelID;
					if(finalMap.panels[pID]!= null && finalMap.panels[pID].CLASS_NAME != null){
						var curPanelName = "panel_" + finalMap.panels[pID].CLASS_NAME.replace("OpenLayers.Control.", "") + "_" + finalMap.panels[pID].id;
						cssGenCode += "." + curPanelName + " " + cssControlCode[i];
					}
				}
				else{
					cssGenCode += cssControlCode[i];
				}				
				cssExists = true;
			}
			cssGenCode += "\n</style>\n\n";
			
			if(cssExists == false){
				cssGenCode = '';
			}
			$('mapContainer').innerHTML = "Not sure how to use this? <a onclick=\"javascript:window.open('instructions.htm', 'Instructions', 'width=500,height=400,scrollbars=yes');\" href='#'>Instructions</a><br />"
				+ "<form action='sample.php' method='post' target='_blank'>"
				+ "	<input type='submit' value='Launch a Preview'>"
				+ "	<input type='hidden' value=\"" + cssGenCode + preGenCode + generatedCode + "\" name='genCode'>"
				+ "</form>"
				+ "<div style='padding:10px; height:400px; width:98%;'><textarea readOnly id='genCode' class='genCodeBlock'>" + cssGenCode + preGenCode + generatedCode + "</textarea></div>";
			//console.log(finalLayerParams);
			/*Generate the code in JS, save the code to the DB in php*/
			//var jsonRequest = new Request({url: "includes/generatedCode.php"}).post(generatedCode);

		}		
	});


});
