var AddMediaControl = function() {

	//private variables
	//constant
	var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
	["blue", "#000080"], ["purple", "#800080"]];

	var _colorIndex = 0;
	//
	var _editObjectModeFlag = false;	//add new media or update existing media
	var _objectId = null;	//save update object id
	var _submit_flag = false;

	var _type = null;
	var _latlng = new Array();
	var _poly = null;	//polygon or polyline added to map
	var _beforeDrawing = false;	//before drawing polyline and polygon
	var _content = null;
	var _yearCounter=0;
	var _oldAddTo = null;
	var _addMediaListeners = new Array();

	//info window objects, these are jQuery objects
	var html_1 = null;
	var html_2 = null;
	var html_3 = null;
	var html_4 = null;
	var importKmlFrame = null;
	
	//add media control buttons
	var container = null;
	var hand_b = null;
	var marker_b = null;
	var line_b = null;
	var shape_b = null;
	var kml_b = null;

	//private methods
	//these are auxiliary function
	function _printArray($array)
	{
		HyperCities.debug("[_printArray]");
		for (i in $array)
			HyperCities.debug(i+": "+$array[i]);
	}
	function _hasBindedEvent($eventType)
	{
		//HyperCities.debug("[_hasBindedEvent] _addMediaListeners["+$eventType+"]="+_addMediaListeners[$eventType]);

		if ( typeof(_addMediaListeners[$eventType]) !== 'undefined'
			&& _addMediaListeners[$eventType] !== null)
			return true;

		return false;
	}
	
	/* add listener to _addMediaListeners
	* _addMediaListeners store only one handler for each event
	* _addMediaListeners store key value pairs: ($eventType, $eventHandler)
	*
	*/	
	function _addListener($eventType, $eventHandler)
	{
		var prevHandle = _hasBindedEvent($eventType);
		var map = HyperCities.mainMap.getMapInstance();
		
		//overwrite any existing handle
		if (prevHandle)
		{
			//HyperCities.debug($eventType+" handle has existed. Remove old one first.");
			//remove existing handle
			_removeListener($eventType);
		}
		//add new handle
		_addMediaListeners[$eventType] = GEvent.addListener(map, $eventType, $eventHandler);		
		//HyperCities.debug("[_addListener] _addMediaListeners["+$eventType+"]="+_addMediaListeners[$eventType]);
		//return _addMediaListeners[$eventType];
	}
	function _removeListener($eventType)
	{
		if (_hasBindedEvent($eventType))
		{
			//HyperCities.debug("[_removeListener] _addMediaListeners["+$eventType+"]="+_addMediaListeners[$eventType]);
			var handle = _addMediaListeners[$eventType];
			GEvent.removeListener(handle);
			_addMediaListeners[$eventType] = null;
		}
	}
	function _removeAllListener()
	{
		for (i in _addMediaListeners)	
		{
			if (typeof(_addMediaListeners[i]) !== 'undefined'
				&& _addMediaListeners[i] !== null)
				GEvent.removeListener(_addMediaListeners[i]);
		}
		_addMediaListeners = new Array();
	}
	
	function _infoWindowOpenHandler($treeRoot, $oldAddTo, $objectId, $isCollection) {
		editor.setupEditor(_content);
		
		if ($("#tree").children().length === 0)
		{
			_oldAddTo = [];
			var tree = HyperCities.util.loadCollectionTree($treeRoot, _oldAddTo, $objectId, $isCollection);
		}
	}
	
	function _infoWindowBeforeCloseHandler() {
		_content = $("#dsrte").contents().find("body").html();
		editor.removeEditor();
	}
	
	//infoWindowCloseHanlder for polyline and polygon
	function _infoWindowCloseHandler($poly, $infoWindow) {
		if( _submit_flag)
		{
			HyperCities.mainMap.removeOverlay($poly);
			resetParams();
			select("hand_b");
			return;
		}
		//var response = confirm("Do you want to leave without saving?");
        var response = confirm("Are you sure you want to exit without saving this object?");
		if (response) {
			HyperCities.mainMap.removeOverlay($poly);
			resetParams();
			select("hand_b");
		}else{
			HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] , $infoWindow, {maxWidth: 550, noCloseOnClick:true });
		}
	}
	function _addPolyListener($poly, $infoWindow, $treeRoot, $oldAddTo, $objectId, $isCollection)
	{
		HyperCities.mainMap.addOverlay($poly);
		$poly.enableEditing({onEvent: "mouseover"});
		$poly.disableEditing({onEvent: "mouseout"});
		
		_addListener("infowindowopen", function() {_infoWindowOpenHandler($treeRoot, $oldAddTo, $objectId, $isCollection); });
		_addListener("infowindowbeforeclose",_infoWindowBeforeCloseHandler);
		_addListener("infowindowclose", function(){
			_infoWindowCloseHandler($poly, $infoWindow);
		});

		GEvent.addListener($poly, "lineupdated", function() {
			//HyperCities.debug("lineupdated");
			_latlng = new Array();
			var VertexCount = $poly.getVertexCount();
			for(var i=0; i< VertexCount; i++)
			{
				_latlng.push($poly.getVertex(i));
			}
			HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] ,$infoWindow,{maxWidth: 550, noCloseOnClick:true});
		});
		
		GEvent.addListener($poly, "click", function(latlng, index) {
			//HyperCities.debug("click");
			if (typeof(index)== "number") {
				$poly.deleteVertex(index);
				HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] ,$infoWindow,{maxWidth: 550, noCloseOnClick:true});
			} 
			else
			{
				_yearCounter =0;
				HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] ,$infoWindow,{maxWidth: 550, noCloseOnClick:true});
			}
		});
		
		GEvent.addListener($poly, "mouseover", function(){
			HyperCities.debug("mouse over");
			//save rich text editor content
			_content = $("#dsrte").contents().find("body").html();
			_removeListener("infowindowclose");
			_removeListener("infowindowbeforeclose");
			HyperCities.mainMap.closeInfoWindow();
		});

		GEvent.addListener($poly, "mouseout", function(){
			HyperCities.debug("mouse out");
			_addListener("infowindowopen", function() {_infoWindowOpenHandler($treeRoot, $oldAddTo, $objectId, $isCollection);});
			_addListener("infowindowbeforeclose",_infoWindowBeforeCloseHandler);
			_addListener("infowindowclose", function(){
				//HyperCities.debug("$poly="+$poly);
				_infoWindowCloseHandler($poly, $infoWindow);
			});
		});
		
		GEvent.addListener($poly, "cancelline", function(){
			HyperCities.debug("cancel line");
			//calling removeOverlay on an editable shape before it has been completely finalized prevents the overlay from being removed
			//so use a timeout to execute it a little afterwards
			setTimeout(function(){
				$poly.disableEditing();
				HyperCities.mainMap.removeOverlay($poly);
				$poly = null;	//set $poly to null, beware _poly is not null
			}, 500);
		});
	}
	
	function _initAddMediaInfoWindow($addMediaControlFrame)
	{	
		/*
		$.ajax({
			url: 'editorFrame.html',
			dataType: 'html',
			type: 'GET',
			async: true,
			success: function(message) {
          		_editor_frame_content = $(message);
        	}
		});
		*/
		var editorFrame = $addMediaControlFrame.find("#editorFrame");
		var bottomBar = $addMediaControlFrame.find("#bottomBar");
		
		html_1 = $(document.createElement("div"));
		html_1.attr("id", "html_1");
		html_1.append($addMediaControlFrame.find("#add_media_form").clone());
		html_1.find("br:first").after(editorFrame);
		html_1.append(bottomBar.clone());
		html_1.find("#bottomBar > a").click(cancelAddMedia);
		html_1.find("#bottomBar > input").click(function() {selectLabel(1);});
		$("#author", html_1).val(HyperCities.user.getNickname());

		html_2 = $(document.createElement("div"));
		html_2.attr("id", "html_2");
		html_2.append($addMediaControlFrame.find("#add_year_form"));
		html_2.find("#add_time_From0").click(function() {toggle_time_detail(this);});
		html_2.find("#add_time_To0").click(function() {toggle_time_detail(this);});
		html_2.find("#add_another_year a").click(function() {_addTimespan();});
		html_2.append(bottomBar.clone());
		html_2.find("#bottomBar > a").click(cancelAddMedia);
		html_2.find("#bottomBar > input").click(function(){selectLabel(2);});
		
		html_3 = $(document.createElement("div"));
		html_3.attr("id", "html_3");
		html_3.append($addMediaControlFrame.find("#add_to_form"));
		html_3.find("#add_a_new > a").click(add_new_collection);
		html_3.append(bottomBar.clone());
		html_3.find("#bottomBar > a").click(cancelAddMedia);
		html_3.find("#bottomBar > input").click(load_preview);
		
		html_4 = $(document.createElement("div"));
		html_4.attr("id", "html_4");
		html_4.append($addMediaControlFrame.find("#preview_form"));
		html_4.append(bottomBar.clone());
		html_4.find("#bottomBar > a").click(cancelAddMedia);
		html_4.find("#bottomBar > input").click(_submitAddMedia);
		html_4.find("#bottomBar > input").attr("value", "submit");
		
		importKmlFrame = $(document.createElement("div"));
		importKmlFrame.attr("id", "importKmlFrame");
		importKmlFrame.append($addMediaControlFrame.find("#add_media_form").clone());
		importKmlFrame.find("br:first").after($addMediaControlFrame.find("#importKmlFrame").get(0));
		importKmlFrame.append(bottomBar.clone());
		importKmlFrame.find("#bottomBar > a").click(cancelAddMedia);
		importKmlFrame.find("#bottomBar > input").click(function() {selectLabel(1);});
	}
	
	function _init()
	{
		container = document.createElement("div");
		container.style.width = "32px";

		hand_b = $(document.createElement("div"));
		hand_b.attr("id", "hand_b");
		hand_b.click(function() {hideShowAllButtons();});

		marker_b = $(document.createElement("div"));
		marker_b.attr("id", "marker_b");
		marker_b.css("display", "none");
		marker_b.click(function() {_placeMarker();});

		line_b = $(document.createElement("div"));
		line_b.attr("id", "line_b");
		line_b.css("display", "none");
		line_b.click(function() {_startPoly("line");});

		shape_b = $(document.createElement("div"));
		shape_b.attr("id", "shape_b");
		shape_b.css("display", "none");
		shape_b.click(function() {_startPoly("polygon");});

		kml_b = $(document.createElement("div"));
		kml_b.attr("id", "kml_b");
		kml_b.css("display", "none");
		kml_b.click(function() {importKml();});
		
		container.appendChild(hand_b.get(0));
		container.appendChild(marker_b.get(0));
		container.appendChild(line_b.get(0));
		container.appendChild(shape_b.get(0));
		container.appendChild(kml_b.get(0));

		//initialize addMediaInfoWindow
		/*
		$.ajax({
			url: 'addMediaControlFrame.html',
			dataType: 'html',
			type: 'GET',
			async: true,
			success: function(message) {
				_initAddMediaInfoWindow($(message));
          		//addMediaControlFrame = $(message);
        	}
		});
		*/
		$.get("addMediaControlFrame.html", null, function(message) {
				_initAddMediaInfoWindow($(message));
          		//addMediaControlFrame = $(message);
        	}, "html");
	}
	
	function _createInfoWindow($html_1, $html_2, $html_3, $html_4)
	{
		//tabInfoWindow variables
		var label_1 = "1. Content";
		var label_2 = "2. Time";
		var label_3 = "3. Add To";
		var label_4 = "4. Preview";

		var tabList = [	new GInfoWindowTab(label_1, $html_1.get(0)),
						new GInfoWindowTab(label_2, $html_2.get(0)),
						new GInfoWindowTab(label_3, $html_3.get(0)),
						new GInfoWindowTab(label_4, $html_4.get(0))	];
		//tabInfoWindow event handler
		tabList[3].onclick = load_preview;
		tabList[0].onclick = close_preview;
		
		return tabList;
	}

	function _createMarker($latlng, $infoWindow, $treeRoot, $oldAddTo, $objectId, $isCollection)
	{
		var marker = new GMarker($latlng,{draggable: true});

		var infoWindowCloseHandler = function() {
			if( _submit_flag){
				HyperCities.mainMap.removeOverlay(marker);
				//resetParams();
				select("hand_b");
				return;
			}
			//var response = window.confirm("Do you want to leave without saving?");
			var response = window.confirm("Are you sure you want to close this window without saving your changes?");
			if (response) {
				marker.closeInfoWindow();
				HyperCities.mainMap.removeOverlay(marker);
				//resetParams();
				select("hand_b");
			}else{
				marker.openInfoWindowTabsHtml($infoWindow,{maxWidth: 550, noCloseOnClick:true});
			}
		};

		//add event listener
		var clickHandle = GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowTabsHtml($infoWindow, {maxWidth: 550, noCloseOnClick:true});
		});
		
		var infoWindowOpenHandle = GEvent.addListener(marker, "infowindowopen", function() {_infoWindowOpenHandler($treeRoot, $oldAddTo, $objectId, $isCollection);});
		var infoWindowBeforeCloseHandle = GEvent.addListener(marker, "infowindowbeforeclose", _infoWindowBeforeCloseHandler);
		var infoWindowCloseHandle = GEvent.addListener(marker, "infowindowclose", infoWindowCloseHandler);
		
		var dragstartHandle = GEvent.addListener(marker, "dragstart", function() {
			//save the rich text editor content
			_content = $("#dsrte").contents().find("body").html();
			
			//remove these two listener so that popup confirm window won't show up
			GEvent.removeListener(infoWindowCloseHandle);
			GEvent.removeListener(infoWindowBeforeCloseHandle);
			marker.closeInfoWindow();
		});
		var dragendHandle = GEvent.addListener(marker, "dragend", function() {
			var latlng = marker.getPoint();
			_latlng[0] = latlng;
			//restore these two listener
			infoWindowCloseHandle = GEvent.addListener(marker, "infowindowclose", infoWindowCloseHandler);
			infoWindowBeforeCloseHandle = GEvent.addListener(marker, "infowindowbeforeclose", _infoWindowBeforeCloseHandler);
			marker.openInfoWindowTabsHtml($infoWindow, {maxWidth: 550, noCloseOnClick:true});
		});
		
		return marker;
	}
	
	_editMarker = function($latlng, $title, $creator, $copyright, $content, $timespan, $inCollectionArray, $objectId, $ownerId, $parentId) {
		HyperCities.mainMap.enableSync(false);
		_editObjectModeFlag  = true;
		_type = "marker";

		//load object attributes
		var newHtml1 = html_1.clone(true);
		newHtml1.find("#title").val($title);
		newHtml1.find("#author").val($creator);
		newHtml1.find("#copyright").val($copyright);
		if (HyperCities.user.hasDeletePrivilege($objectId, $ownerId))
		{
			_addDelBtn(newHtml1.find("#bottomBar"), $objectId, $parentId);
		}

		//load timespan
		var newHtml2 = html_2.clone(true);
		_loadTimespan(newHtml2, $timespan);
		
		//
		var newHtml3 = html_3.clone(true);
		//HyperCities.util.loadCollectionList(newHtml3, $inCollectionArray);

		var infoWindow = _createInfoWindow(newHtml1, newHtml2, newHtml3, html_4.clone(true));
		var marker = _createMarker($latlng, infoWindow, $("#tree", newHtml3), _oldAddTo, $objectId, false);

		//save content, save user's change
		//because everytime info window is opened the editor is reload
		_content = $content;
		_latlng[0] = $latlng;
		//add marker overlay
		HyperCities.mainMap.addOverlay(marker);
		//open info window
		marker.openInfoWindowTabsHtml(infoWindow,{maxWidth: 550, noCloseOnClick:true});
	};
	
	_editPoly = function($type, $latlngs, $title, $creator, $copyright, 
						$content, $timespan, $inCollectionArray, $objectId, $ownerId, $parentId)
	{
		HyperCities.mainMap.enableSync(false);
		_editObjectModeFlag  = true;
		
		_content = $content;
		_latlng = $latlngs;
		var color = getColor(false);
		
		if ($type === "line")
		{
			_type = "line";
			_poly = new GPolyline($latlngs, color);
		}
		else if ($type === "polygon")
		{
			_type = "polygon";
			_poly = new GPolygon($latlngs, color);
		}
		
		
		//set original object info
		var newHtml1 = html_1.clone(true);
		newHtml1.find("#title").val($title);
		newHtml1.find("#author").val($creator);
		newHtml1.find("#copyright").val($copyright);
		if (HyperCities.user.hasDeletePrivilege($objectId, $ownerId))
		{
			_addDelBtn(newHtml1.find("#bottomBar"), $objectId, $parentId);
		}

		//load timespan
		var newHtml2 = html_2.clone(true);
		_loadTimespan(newHtml2, $timespan);

		var newHtml3 = html_3.clone(true);
		//HyperCities.util.loadCollectionList(newHtml3, $inCollectionArray);
		
		var infoWindow = _createInfoWindow(newHtml1, newHtml2, newHtml3, html_4.clone(true));
		
		_addPolyListener(_poly, infoWindow, $("#tree", newHtml3), _oldAddTo, $objectId, false);
		HyperCities.mainMap.openInfoWindow("tabsHtml", $latlngs[0] ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
	};

	_editKmlLink = function($title, $creator, $copyright, $link, $timespan, $inCollectionArray, $objectId, $ownerId, $parentId) {
		HyperCities.mainMap.enableSync(false);
		_editObjectModeFlag  = true;
		_type = "kml";
		
		var kmlHtml4 = html_4.clone(true);
		//unbind original click handler
		kmlHtml4.find("#bottomBar input").unbind("click");
		//bind new click handler
		kmlHtml4.find("#bottomBar input").click(submitKml);
		
		//hide upload kml file div and kml form title
		var newImportKmlFrame = importKmlFrame.clone(true);
		newImportKmlFrame.find("#uploadKmlFileDiv").hide();
		newImportKmlFrame.find("#kmlDesc").hide();
		
		//set up each field of kml
		newImportKmlFrame.find("#title").val($title);
		newImportKmlFrame.find("#author").val($creator);
		newImportKmlFrame.find("#copyright").val($copyright);
		newImportKmlFrame.find("#kmlLink").val($link);

		if (HyperCities.user.hasDeletePrivilege($objectId, $ownerId))
		{
			_addDelBtn(newImportKmlFrame.find("#bottomBar"), $objectId, $parentId);
		}
		
		//load timespan
		var newHtml2 = html_2.clone(true);
		_loadTimespan(newHtml2, $timespan);

		//load own and other collection lists
		var newHtml3 = html_3.clone(true);
		$("#add_a_new", newHtml3).remove();
		//HyperCities.util.loadCollectionList(newHtml3, $inCollectionArray);

		//add info window event listener
		var infoWindow = _createInfoWindow(newImportKmlFrame, newHtml2, newHtml3, kmlHtml4);
		var infoWindowOpenHandle = _addListener("infowindowopen", function() {
			_oldAddTo = [];
			var tree = HyperCities.util.loadCollectionTree($("#tree", newHtml3), _oldAddTo, $objectId, false);
		});
		var infoWindowCloseHandle = _addListener( "infowindowclose", function() {
			if( _submit_flag)
			{
				//HyperCities.mainMap.restoreSync();
				select("hand_b");
				resetParams();
				return;
			}
			//var response = confirm("Do you want to leave without saving?");
			var response = confirm("Are you sure you want to close this window without saving your changes?");
			if (response) {
				//HyperCities.mainMap.restoreSync();
				select("hand_b");
				resetParams();
			}else{
				HyperCities.mainMap.openInfoWindow("tabsHtml", HyperCities.mainMap.getCenter() ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
			}
		});

		HyperCities.mainMap.openInfoWindow("tabsHtml", HyperCities.mainMap.getCenter() ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
	};

	function _addDelBtn($container, $objectId, $parentId)
	{
		var delBtn = $("<a href='javascript:void(0)' style='float:left'><img src='./images/trashcan.gif' width='16px' height='16px' /></a>");	
	
		delBtn.click(function(){

			response = window.confirm("Are you sure you want to delete this item?");
			if ( !response ) {
				return false;
			}

			// Call Delete Object Function
			var params = {
				objectId: $objectId,
				parentId: $parentId 
			};

			$.post("./deleteObject.php", params, function($response){
				_ajaxReport($response)
			}, "xml");		
		});

		$container.prepend(delBtn);
	}

	function _placeMarker(){
		HyperCities.mainMap.enableSync(false);
		select("marker_b");
		_type = "marker";
		
		_addListener("click",function(overlay, latlng)
		{
			if (latlng) {
				_latlng[0] = latlng;
				_removeListener("click");
				

				var newHtml3 = html_3.clone(true);
				//HyperCities.util.loadCollectionList(newHtml3);
				
				var infoWindow = _createInfoWindow(html_1.clone(true), html_2.clone(true), newHtml3, html_4.clone(true));
				var marker = _createMarker(latlng, infoWindow, $("#tree", newHtml3), null, null, false);

				HyperCities.mainMap.addOverlay(marker);
				//_yearCounter =0;//for add year form
				marker.openInfoWindowTabsHtml(infoWindow,{maxWidth: 550, noCloseOnClick:true});
			}
		});
		
	}
	
	//drawing polyline and polygon
	function _startPoly($type){
		HyperCities.mainMap.enableSync(false);

		var color = getColor(false);
		
		if ($type === "line")
		{
			_type = "line";
			select("line_b");
			_poly = new GPolyline([], color);
		}
		else if ($type === "polygon")
		{
			_type = "polygon";
			select("shape_b");
			_poly = new GPolygon([], color, 2, 0.7, color, 0.2);
		}
		
		var newHtml3 = html_3.clone(true);
		//HyperCities.util.loadCollectionList(newHtml3);

		var infoWindow = _createInfoWindow(html_1.clone(true), html_2.clone(true), newHtml3, html_4.clone(true));
				
		_startDrawing(_poly, color, infoWindow, $("#tree", newHtml3), null, null, false);
	}

	function _startDrawing(poly, color, infoWindow, $treeRoot, $oldAddTo, $objectId, $isCollection) {
		//_printArray(_addMediaListeners);
		_beforeDrawing = true;
		HyperCities.mainMap.addOverlay(poly);
		poly.enableDrawing({});
		poly.enableEditing({onEvent: "mouseover"});
		poly.disableEditing({onEvent: "mouseout"});
		GEvent.addListener(poly, "endline", function(latlng) {
			_beforeDrawing = false;
			//_yearCounter =0;
			_latlng = new Array();
			var VertexCount = poly.getVertexCount();
			for(var i=0; i< VertexCount; i++)
			{
				_latlng.push(poly.getVertex(i));
			}
			
			//HyperCities.debug(_printArray(_addMediaListeners));
			_addListener("infowindowopen", function(){_infoWindowOpenHandler($treeRoot, $oldAddTo, $objectId, $isCollection);});
			_addListener("infowindowbeforeclose",_infoWindowBeforeCloseHandler);
			_addListener("infowindowclose", function(){
				//HyperCities.debug("poly="+poly);
				_infoWindowCloseHandler(poly, infoWindow);
			});

			HyperCities.mainMap.openInfoWindow("tabsHtml", latlng ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
			
			GEvent.addListener(poly, "lineupdated", function() {
				//HyperCities.debug("lineupdated");
				_latlng = new Array();
				var VertexCount = poly.getVertexCount();
				for(var i=0; i< VertexCount; i++)
				{
					_latlng.push(poly.getVertex(i));
				}
				HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
			});
			
			GEvent.addListener(poly, "click", function(latlng, index) {
				//HyperCities.debug("click");
				if (typeof(index)== "number") {
					poly.deleteVertex(index);
					HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
				} 
				else
				{
					//_yearCounter =0;
					HyperCities.mainMap.openInfoWindow("tabsHtml", _latlng[0] ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
				}
			});
			
			GEvent.addListener(poly, "mouseover", function(){
				//HyperCities.debug("mouse over");
				//save rich text editor content
				_content = $("#dsrte").contents().find("body").html();
				_removeListener("infowindowclose");
				_removeListener("infowindowbeforeclose");
			});

			GEvent.addListener(poly, "mouseout", function(){
				//HyperCities.debug("mouse out");
				_addListener("infowindowopen", function(){_infoWindowOpenHandler($treeRoot, $oldAddTo, $objectId, $isCollection);});
				_addListener("infowindowbeforeclose",_infoWindowBeforeCloseHandler);
				_addListener("infowindowclose", function(){
					//HyperCities.debug("poly="+poly);
					_infoWindowCloseHandler(poly, infoWindow);
				});
			});
		});
		
		GEvent.addListener(poly, "cancelline", function(){
			//HyperCities.debug("cancel line");
			//calling removeOverlay on an editable shape before it has been completely finalized prevents the overlay from being removed
			//so use a timeout to execute it a little afterwards
			setTimeout(function(){
				poly.disableEditing();
				HyperCities.mainMap.removeOverlay(poly);
				poly = null;	//set poly to null, beware _poly is not null
			}, 500);
		});
	}
	/*end of line drawing*/

	//import a kml link or upload a kml file
	function importKml() {
		HyperCities.mainMap.enableSync(false);
		
		//resetParams();
		_type = "kml";
		select("kml_b");

		var kmlHtml4 = html_4.clone(true);
		//unbind original click handler
		kmlHtml4.find("#bottomBar input").unbind("click");
		//bind new click handler
		kmlHtml4.find("#bottomBar input").click(submitKml);
		
		var newImportKmlFrame = importKmlFrame.clone(true);
		
		newImportKmlFrame.find("#uploadKmlForm").submit(function(){
			$("#loadingMessage").fadeIn("fast");
			_submit_flag = true;
			
			//bind ready event here when iframe finished loading
			//Use jquery ready instead of jquery load() because Safari hangs
			//change back to load because sometimes ready event fire earlier than dom ready
			$("#upload_target").load(function (){
				//set a short delay so that jQuery can traverse returned message
				setTimeout(function() {
					var message = $("#upload_target").contents().find("body").html();
					HyperCities.mainMap.closeInfoWindow();
					alert(message);
					HyperCities.collectionList.update(null, null, true);
					$("#loadingMessage").fadeOut("fast");
				}, 1000);
			});
			
			return true;
		});
		
		//load own and other collection lists
		var newHtml3 = html_3.clone(true);
		//HyperCities.util.loadCollectionList(newHtml3);

		var infoWindow = _createInfoWindow(newImportKmlFrame, html_2.clone(true), newHtml3, kmlHtml4);

		var infoWindowOpenHandle = _addListener("infowindowopen", function() {
			_oldAddTo = [];
			var tree = HyperCities.util.loadCollectionTree($("#tree", newHtml3), null, null, false);
		});
		var infoWindowCloseHandle = _addListener( "infowindowclose", function() {
			if( _submit_flag)
			{
				//HyperCities.mainMap.restoreSync();
				select("hand_b");
				resetParams();
				return;
			}
			//var response = confirm("Do you want to leave without saving?");
			var response = confirm("Are you sure you want to exit without saving this object?");
			if (response) {
				//HyperCities.mainMap.restoreSync();
				select("hand_b");
				resetParams();
			}else{
				HyperCities.mainMap.openInfoWindow("tabsHtml", HyperCities.mainMap.getCenter() ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
			}
		});

		HyperCities.mainMap.openInfoWindow("tabsHtml", HyperCities.mainMap.getCenter() ,infoWindow,{maxWidth: 550, noCloseOnClick:true});
	}
	
	function _ajaxReport($response) {
		var success = $($response).find("Success > Message").text();
		var error   = $($response).find("Error > Message").text();
		
		if ( success.length > 0 ) {
			alert(success);
			_submit_flag = true;
			HyperCities.mainMap.closeInfoWindow();
			HyperCities.collectionList.update(null, null, true);
		}
		else if ( error.length > 0 ) {
			alert(error);
		}
	}

	function submitKml() {

		var metadata = {};
		var addTo = new Array();
		metadata.objectId = _objectId;
		metadata.type = _type;
		metadata.title =  document.getElementById("title").value;
		metadata.creator = document.getElementById("author").value;
		metadata.copyright = document.getElementById("copyright").value;
		metadata.yearCounter = _yearCounter;
		metadata.oldAddTo = _oldAddTo.toString();

		if (!metadata.title) { alert("Please specify a title for the item"); return;}		
		if(!$("#yearFrom0").val() && !$("#yearTo0").val() ) { alert("Please specify a year for the item"); return;}

		for (i=0; i<= _yearCounter; i++)
		{
			metadata["bcFrom"+i] = 0;
			metadata["bcTo"+i] = 0;
			if( $("#bcFrom" + i).attr('checked') ) metadata["bcFrom"+i] = 1;
			if( $("#bcTo" + i).attr('checked') ) metadata["bcTo"+i] = 1;

			/*
			metadata["yearFrom"+i] = $("#yearFrom" + i).val();
			metadata["monthFrom"+i] = $("#monthFrom" + i).val();
			metadata["dateFrom"+i] = $("#dateFrom" + i).val();
			metadata["hourFrom"+i] = $("#hourFrom" + i).val();
			metadata["minFrom"+i] =  $("#minFrom" + i).val();
			metadata["yearTo"+i] = $("#yearTo" + i).val();
			metadata["monthTo"+i] = $("#monthTo" + i).val();
			metadata["dateTo"+i] = $("#dateTo" + i).val();
			metadata["hourTo"+i] = $("#hourTo" + i).val();
			metadata["minTo"+i] =  $("#minTo" + i).val();
			*/
			var yearFrom = $("#yearFrom"+i).val();
			if (yearFrom === "")
			{
				yearFrom = "9999";
				metadata['bcFrom'+i] = 1;
			}
			var monthFrom = ($("#monthFrom"+i).val() == "") ? "01" : $("#monthFrom"+i).val();
			var dateFrom = ($("#dateFrom"+i).val() == "") ? "01" : $("#dateFrom"+i).val();
			var hourFrom = ($("#hourFrom"+i).val() == "") ? "00" : $("#hourFrom"+i).val();
			var minFrom = ($("#minFrom"+i).val() == "") ? "00" : $("#minFrom"+i).val();
			var yearTo = ($("#yearTo"+i).val() == "") ? "9999" : $("#yearTo"+i).val();
			var monthTo = ($("#monthTo"+i).val() == "") ? "12" : $("#monthTo"+i).val();
			var dateTo = ($("#dateTo"+i).val() == "") ? "31" : $("#dateTo"+i).val();
			var hourTo = ($("#hourTo"+i).val() == "") ? "23" : $("#hourTo"+i).val();
			var minTo = ($("#minTo"+i).val() == "") ? "59" : $("#minTo"+i).val();

			var fullDateFrom =  yearFrom + "-"
									+ monthFrom + "-"
									+ dateFrom + " "
									+ hourFrom + ":"
									+ minFrom + ":"
									+"00";

			var fullDateTo =  yearTo + "-"
									+ monthTo + "-"
									+ dateTo + " "
									+ hourTo + ":"
									+ minTo + ":"
									+"00";

			if (HyperCities.util.validateDate(fullDateFrom))
				metadata["dateFrom"+i] = fullDateFrom;
			else
			{
				alert("Begin date is not a valid date.");
				return false;
			}

			if (HyperCities.util.validateDate(fullDateTo))
				metadata["dateTo"+i] = fullDateTo;
			else
			{
				alert("End date is not a valid date.");
				return false;
			}
		}
		/*
		if( $("#new_collection_input").val()!=="" 
			&& typeof($("#new_collection_input").val())!== 'undefined'
			&& $("#new_collection_input").val()!== null) 
			metadata.newcollection = $("#new_collection_input").val();

		$("#own_collections input[name=ownOption]:checked").each(function() {
			collections.push($(this).data("collectionId"));
		});
		$("#other_collections input[name=otherOption]:checked").each(function() {
			collections.push($(this).data("collectionId"));
		});
		*/

		$(".checkboxChecked").next().each(function(){
			addTo.push($(this).attr("id"));	
		});

		if(!$("#new_collection_input").val() && addTo.length === 0)
		{
			alert("Please choose at least one collection for the item"); return;
		}
		metadata.addTo= addTo.toString();
		
		var uploadKml = function() {
			var metaString = "";
			for (i in metadata)
			{
				metaString = metaString + i+"="+metadata[i]+"&";
			}
			metaString = metaString.substr(0, metaString.length-1);
			$("#uploadKmlForm #metadata").val(metaString);
			$("#importKmlFrame #uploadKmlForm").submit();
		};
		
		var importKml = function() {
			
			var earth = HyperCities.earth.getEarth();
			if (earth === null)
			{
				alert("This feature requires Google Earth.\nPlease install Google Earth first.");
				return;
			}
			var url = $.trim($("#kmlLink").val());
			//replace network link with kml file
			var regExp = new RegExp("output=nl");
			url = url.replace(regExp, "output=kml");

			metadata.link = url;
			metadata.threeDCollection = (( $("#threeDCollection").attr('checked'))? 1:0);
			
			//calculate the boundary
			if (!metadata.threeDCollection)
			{
				var geoXml = new GGeoXml(url);
				GEvent.addListener( geoXml, "load", function( ) {
					if ( geoXml.loadedCorrectly( ))
					{
						HyperCities.debug("geoXml.getDefaultBounds()="+geoXml.getDefaultBounds());
						var bound = geoXml.getDefaultBounds();
						metadata.ne_lat = bound.getNorthEast().lat();
						metadata.ne_lon = bound.getNorthEast().lng();
						metadata.sw_lat = bound.getSouthWest().lat();
						metadata.sw_lon = bound.getSouthWest().lng();
						
						if (_editObjectModeFlag)
						{
							$.ajax({
								url: 'updateKmlLink.php',
								data: metadata,
								dataType: 'xml',
								type: 'POST',
								success: function($response){
									_ajaxReport($response);
								}
							});
						}
						else
						{
							$.ajax({
								url: 'importKmlLink.php',
								data: metadata,
								dataType: 'xml',
								type: 'POST',
								success: function($response){
									_ajaxReport($response);
								}
							});
						}
					}
					else
					{
						var msg  = "Cannot fetch KML file from "+ url + "!\n";
						//msg += "Please check if it a valid URL of KML file.";
						msg += "Please check if it is a valid URL, and also a valid KML file.";
						alert(msg);
						return;
					}
				} ); 
			}
			else
			{
				HyperCities.earth.fetchKml(url, function($kmlObj){
					
					if ($kmlObj === null)
					{
						var msg  = "Cannot fetch KML file from "+ url + "!\n";
						msg += "Please check if it a valid URL of KML file.";
						alert(msg);
						return;
					}
						
					var extent = HyperCities.earth.getFeatureExtent(earth, $kmlObj);
	
					if (extent === null)
					{
						/*var response = window.confirm("Cannot acquire the boundary of KML\n"+
										"Do you still want to import this KML?");*/
						var response = window.confirm("Cannot determine the boundaries of this KML file.\n"+
										"Do you still want to import it?");
						if (!response)
							return;
					}
					else
					{
						metadata.ne_lat = extent.getNorth();
						metadata.ne_lon = extent.getEast();
						metadata.sw_lat = extent.getSouth();
						metadata.sw_lon = extent.getWest();
					}
					
					if (_editObjectModeFlag)
					{
						$.ajax({
							url: 'updateKmlLink.php',
							data: metadata,
							dataType: 'xml',
							type: 'POST',
							success: function($response){
								_ajaxReport($response);
							}
						});
					}
					else
					{
						$.ajax({
							url: 'importKmlLink.php',
							data: metadata,
							dataType: 'xml',
							type: 'POST',
							success: function($response){
								_ajaxReport($response);
							}
						});
					}
				});
			}
		};

		//upload kml or import kml link
		HyperCities.debug('$("#uploadKmlFile").val()='+$("#uploadKmlFile").val());
		if ( typeof($("#uploadKmlFile").val()) !== 'undefined' && 
			$("#uploadKmlFile").val() !== null && $("#uploadKmlFile").val() !== "")
			uploadKml();
		else
			importKml();
	}

	function getColor(named) {
		return COLORS[(_colorIndex++) % COLORS.length][named ? 0 : 1];
	}
	function resetParams(){

		_submit_flag = false;
		_yearCounter =0;	//for add year form
		_latlng = new Array();
		_poly = null;
		_beforeDrawing = false;
		_content = null;
		_objectId = null;
		_editObjectModeFlag = false;
		
		_removeAllListener();
		HyperCities.mainMap.restoreSync();
	}
	

	function cancelAddMedia()
	{
		HyperCities.mainMap.closeInfoWindow();
	}
	
	/**
	 * Load timespan to info window when updating object
	 * @param jQuery object $html: html content of info window
	 * @param array $timespan: array of timespans
	 */
	function _loadTimespan($html, $timespan){
		
		for (var i=1; i<$timespan.length; i++)
		{
			_addTimespan($html);
		}
		
		for (var i=0; i<$timespan.length; i++)
		{
			var dateFrom = $timespan[i].dateFrom;
			var dateTo = $timespan[i].dateTo;
			var bcFrom = parseInt($timespan[i].bcFrom);
			var bcTo = parseInt($timespan[i].bcTo);
			
			if (dateFrom !== null)
			{
				$("#yearFrom"+i, $html).val(dateFrom.getFullYear());
				$("#monthFrom"+i, $html).val(dateFrom.getMonth()+1);
				$("#dateFrom"+i, $html).val(dateFrom.getDate());
				$("#hourFrom"+i, $html).val(dateFrom.getHours());
				$("#minFrom"+i, $html).val(dateFrom.getMinutes());
				if (bcFrom)
					$("#bcFrom"+i, $html).attr("checked","checked");
			}

			if (dateTo !== null)
			{
				$("#yearTo"+i, $html).val(dateTo.getFullYear());
				$("#monthTo"+i, $html).val(dateTo.getMonth()+1);
				$("#dateTo"+i, $html).val(dateTo.getDate());
				$("#hourTo"+i, $html).val(dateTo.getHours());
				$("#minTo"+i, $html).val(dateTo.getMinutes());
				if (bcTo)
					$("#bcTo"+i, $html).attr("checked","checked");
			}
		}
	}
	
	function _addTimespan($html){
		
		if (typeof($html) === "undefined" || $html === null)
			$html = $("#html_2");
		
		
		// max years is eight
		//HyperCities.debug("_yearCounter="+_yearCounter);
		
		var yearCounter = $("#add_year_form", $html).children().length-1;
		HyperCities.debug("yearCounter="+yearCounter);
		//if(yearCounter == 3) {alert("you already reach the maximum years"); return; }
		if(yearCounter == 3) {alert("An object can have a maximum of three timespans."); return; }
		//_yearCounter++;
		
		//remove add year button first
		$("#add_another_year", $html).remove();
		
		//retrieve timespan form and change id of year, month, date, etc.
		var newTimespan = html_2.find("#form_pair_item").clone(true);
		var addYearBtn = html_2.find("#add_another_year").clone(true);
		addYearBtn.find("a").click(function(){_addTimespan($html);});
		$("#yearFrom0", newTimespan).attr("id", "yearFrom"+yearCounter);
		$("#monthFrom0", newTimespan).attr("id", "monthFrom"+yearCounter);
		$("#dateFrom0", newTimespan).attr("id", "dateFrom"+yearCounter);
		$("#hourFrom0", newTimespan).attr("id", "hourFrom"+yearCounter);
		$("#minFrom0", newTimespan).attr("id", "minFrom"+yearCounter);
		$("#bcFrom0", newTimespan).attr("id", "bcFrom"+yearCounter);
		
		$("#yearTo0", newTimespan).attr("id", "yearTo"+yearCounter);
		$("#monthTo0", newTimespan).attr("id", "monthTo"+yearCounter);
		$("#dateTo0", newTimespan).attr("id", "dateTo"+yearCounter);
		$("#hourTo0", newTimespan).attr("id", "hourTo"+yearCounter);
		$("#minTo0", newTimespan).attr("id", "minTo"+yearCounter);
		$("#bcTo0", newTimespan).attr("id", "bcTo"+yearCounter);
		
		$("#add_year_form", $html).append(newTimespan).append(addYearBtn);
	}


	function load_preview(){
		var preview_form = document.getElementById("preview_form");
		while (preview_form.hasChildNodes())
		{
			preview_form.removeChild(preview_form.firstChild);
		}
		//var tinyMCEContent= tinyMCE.activeEditor.getContent({format : 'raw'});
		var tmpContent = $('#dsrte').contents();
		$(tmpContent).find('img.Itemshockwave').replaceWith('<object></object>','shockwave');
		$(tmpContent).find('img.Itemaudio').replaceWith('<object></object>','audio');
		preview_form.innerHTML = tmpContent.find('body').html();

		//preview_form.appendChild(tinyMCEContent);

		selectLabel(3);
	}
	function close_preview(){
		$('#dsrte').contents().find('object.audio').replaceBack('<img></img>','audio');
		$('#dsrte').contents().find('object.shockwave').replaceBack('<img></img>','shockwave');
		selectLabel(0);
	}
	
	/*Step3  Add to Collection Label */
	function add_new_collection()
	{
		var new_from =  document.getElementById("add_a_new");
		var label = document.createElement("label");
		label.innerHTML = "Name:";
		var input = document.createElement("input");
		input.setAttribute("id", "new_collection_input");
		input.setAttribute("type", "text");
		input.setAttribute("size", "20");
		//new_from.appendChild(document.createElement("BR"));
		new_from.appendChild(label);
		new_from.appendChild(input);
	}
	
	/*Step2  Add Year Label */
	function toggle_time_detail(obj){
		$(this).blur();
		if ( $(obj).width() > 100 )
		{
			$(obj).stop().animate({width: "30px", left: "350px"}, 1000, "linear", function() {
			$(this).html("Less");} ).html("");
		}
		else
		{
			$(obj).stop().animate({width: "190px", left: "185px"}, 1000, "linear", function() {
			$(this).html("More");} ).html("");
		}
	}
	
	function _setMetadata()
	{
		var metadata = {};
		var addTo =new Array();

		if (_editObjectModeFlag)
			metadata.objectId = _objectId;
		metadata.creator = document.getElementById("author").value;
		metadata.title =  document.getElementById("title").value;
		metadata.copyright = document.getElementById("copyright").value;
		metadata.content = document.getElementById("preview_form").innerHTML;
		metadata.oldAddTo = _oldAddTo.toString();
		metadata.yearCounter = _yearCounter;
		metadata.type = _type;
		metadata.lat = "";
		metadata.lng = "";

		if (!metadata.title) 
		{
			alert("Please specify a title for the item"); return false;
		}
		if(!$("#yearFrom0").val() && !$("#yearTo0").val() ) 
		{
			alert("Please specify a year for the item");
			return false;
		}
		else
		{
			
		}

		for (i=0; i<= _yearCounter; i++)
		{
			metadata["bcFrom"+i] = 0;
			metadata["bcTo"+i] = 0;
			if( $("#bcFrom" + i).attr('checked') ) metadata["bcFrom"+i] = 1;
			if( $("#bcTo" + i).attr('checked') ) metadata["bcTo"+i] = 1;

			/*
			metadata["yearFrom"+i] = $("#yearFrom" + i).val();
			metadata["monthFrom"+i] = $("#monthFrom" + i).val();
			metadata["dateFrom"+i] = $("#dateFrom" + i).val();
			metadata["hourFrom"+i] = $("#hourFrom" + i).val();
			metadata["minFrom"+i] =  $("#minFrom" + i).val();
			metadata["yearTo"+i] = $("#yearTo" + i).val();
			metadata["monthTo"+i] = $("#monthTo" + i).val();
			metadata["dateTo"+i] = $("#dateTo" + i).val();
			metadata["hourTo"+i] = $("#hourTo" + i).val();
			metadata["minTo"+i] =  $("#minTo" + i).val();
			*/
			var yearFrom = $("#yearFrom"+i).val();
			if (yearFrom === "")
			{
				yearFrom = "9999";
				metadata['bcFrom'+i] = 1;
			}
			var monthFrom = ($("#monthFrom"+i).val() == "") ? "01" : $("#monthFrom"+i).val();
			var dateFrom = ($("#dateFrom"+i).val() == "") ? "01" : $("#dateFrom"+i).val();
			var hourFrom = ($("#hourFrom"+i).val() == "") ? "00" : $("#hourFrom"+i).val();
			var minFrom = ($("#minFrom"+i).val() == "") ? "00" : $("#minFrom"+i).val();
			var yearTo = ($("#yearTo"+i).val() == "") ? "9999" : $("#yearTo"+i).val();
			var monthTo = ($("#monthTo"+i).val() == "") ? "12" : $("#monthTo"+i).val();
			var dateTo = ($("#dateTo"+i).val() == "") ? "31" : $("#dateTo"+i).val();
			var hourTo = ($("#hourTo"+i).val() == "") ? "23" : $("#hourTo"+i).val();
			var minTo = ($("#minTo"+i).val() == "") ? "59" : $("#minTo"+i).val();

			var fullDateFrom =  yearFrom + "-"
									+ monthFrom + "-"
									+ dateFrom + " "
									+ hourFrom + ":"
									+ minFrom + ":"
									+"00";

			var fullDateTo =  yearTo + "-"
									+ monthTo + "-"
									+ dateTo + " "
									+ hourTo + ":"
									+ minTo + ":"
									+"00";

			if (HyperCities.util.validateDate(fullDateFrom))
				metadata["dateFrom"+i] = fullDateFrom;
			else
			{
				alert("Begin date is not a valid date.");
				return false;
			}

			if (HyperCities.util.validateDate(fullDateTo))
				metadata["dateTo"+i] = fullDateTo;
			else
			{
				alert("End date is not a valid date.");
				return false;
			}
		}
		
		if(_type == "marker"){
			HyperCities.debug("_latlng[0]="+_latlng[0]);
			metadata.lat = _latlng[0].lat();
			metadata.lng = _latlng[0].lng();
		}else {
			for(var i=0;i< _latlng.length;i++)
			{
				metadata.lat += _latlng[i].lat() ;
				metadata.lng += _latlng[i].lng() ;
				if(i != _latlng.length-1)
				{
					metadata.lat += ",";
					metadata.lng += ",";
				}
			}
		}

		/*
		if( $("#new_collection_input").val()!=="" 
				&& typeof($("#new_collection_input").val())!== 'undefined'
				&& $("#new_collection_input").val()!== null) 
				metadata.newcollection = $("#new_collection_input").val();
		
		$("#own_collections input[name=ownOption]:checked").each(function() {
			addTo.push($(this).data("collectionId"));
		});

		$("#other_collections input[name=otherOption]:checked").each(function() {
			addTo.push($(this).data("collectionId"));
		});
		*/
		$(".checkboxChecked").next().each(function(){
			addTo.push($(this).attr("id"));	
		});
				
		
		if( !$("#new_collection_input").val() && addTo.length === 0)
		{
			//alert("Please choose at least a collection for the item"); return false;
			alert("Please choose at least one collection to put the item in."); return false;
		}
		metadata.addTo = addTo.toString();
		
		return metadata;
	}
	
	function _submitAddMedia(){
		//HyperCities.debug("_editObjectModeFlag="+_editObjectModeFlag);
		var metadata = _setMetadata();
		if (!metadata)
			return;

		_submit_flag = true;
		if(_editObjectModeFlag)
		{
			$.ajax({
				url: 'updateObject.php',
				data: metadata,
				type: "POST",
				success: function($response){

					_ajaxReport($response);
					//alert("Media object successfully updated!");
					//HyperCities.mainMap.closeInfoWindow();
					//HyperCities.collectionList.update(null, null, true);
					//resetParams();
				}
			});
		}
		else
		{
			$.ajax({
				url: 'addObject.php',
				data: metadata,
				type: "POST",
				success: function($response){
				
					_ajaxReport($response);
					//alert("Media object successfully added!");
					//HyperCities.mainMap.closeInfoWindow();
					//HyperCities.collectionList.update(null, null, true);
					//resetParams();
				}
			});	
		}
	}
		//hide or show all add media buttons
	function hideShowAllButtons() {
		select("hand_b");
	}

        var _ciationInsert = function () {
            // open panel
        };

        var _citationSave = function () {
            var displayText = $("#citationDisplayText").text();
            var citationText = $("#citationText").text();
            var textToInsert = '<citation><displaytext>'+displayText+'</displayText><citationText>'+citationText+'</citationText></citation>';
            // insert text
        };

	/*make the  button selected  or not  */
	function select($buttonId) {
		var selectedButton = $("#"+$buttonId);

		if ($buttonId == "hand_b")
		{
			//remove poly if it is not null
			if (_poly !== null)
			{
				HyperCities.debug("_beforeDrawing="+_beforeDrawing);
				if (_beforeDrawing)
				{
					//info window is not opened
					//HyperCities.mainMap.removeOverlay(_poly);
					GEvent.trigger(_poly, "cancelline");
					resetParams();
		
					if(marker_b.css("display") == "none" || line_b.css("display") == "none" ||
					shape_b.css("display") == "none" || kml_b.css("display") == "none")
					{
						//show
						hand_b.attr("class", "selected");
						marker_b.css("display", "block");
						line_b.css("display", "block");
						shape_b.css("display", "block");
						kml_b.css("display", "block");
						marker_b.attr("class", "unselected");
						line_b.attr("class", "unselected");
						shape_b.attr("class", "unselected");
						kml_b.attr("class", "unselected");
						enableAddMediaControl("marker_b", 1);
						enableAddMediaControl("line_b", 1);
						enableAddMediaControl("shape_b", 1);
						enableAddMediaControl("kml_b", 1);
					}else{
						//hide
						hand_b.attr("class", "unselected");
						marker_b.css("display", "none");
						line_b.css("display", "none");
						shape_b.css("display", "none");
						kml_b.css("display", "none");
						marker_b.attr("class", "unselected");
						line_b.attr("class", "unselected");
						shape_b.attr("class", "unselected");
						kml_b.attr("class", "unselected");
						//enableAddMediaControl("all", 2);
					}
				}
				else
				{
					HyperCities.mainMap.closeInfoWindow();
				}
			}
			else
			{
				resetParams();
		
				if(marker_b.css("display") == "none" || line_b.css("display") == "none" ||
				shape_b.css("display") == "none" || kml_b.css("display") == "none")
				{
					//show
					hand_b.attr("class", "selected");
					marker_b.css("display", "block");
					line_b.css("display", "block");
					shape_b.css("display", "block");
					kml_b.css("display", "block");
					marker_b.attr("class", "unselected");
					line_b.attr("class", "unselected");
					shape_b.attr("class", "unselected");
					kml_b.attr("class", "unselected");
					enableAddMediaControl("marker_b", 1);
					enableAddMediaControl("line_b", 1);
					enableAddMediaControl("shape_b", 1);
					enableAddMediaControl("kml_b", 1);
				}else{
					//hide
					hand_b.attr("class", "unselected");
					marker_b.css("display", "none");
					line_b.css("display", "none");
					shape_b.css("display", "none");
					kml_b.css("display", "none");
					marker_b.attr("class", "unselected");
					line_b.attr("class", "unselected");
					shape_b.attr("class", "unselected");
					kml_b.attr("class", "unselected");
					//enableAddMediaControl("all", 2);
				}
			}
		}
		else
		{
			marker_b.css("display", "none");
			line_b.css("display", "none");
			shape_b.css("display", "none");
			kml_b.css("display", "none");
			marker_b.attr("class", "unselected");
			line_b.attr("class", "unselected");
			shape_b.attr("class", "unselected");
			kml_b.attr("class", "unselected");

			selectedButton.css("display", "block");
			selectedButton.attr("class", "selected");
			//enableAddMediaControl("hand_b", 3);
			enableAddMediaControl($buttonId, 3);
		}
	}
	
	function selectLabel(index)
	{
		HyperCities.mainMap.getInfoWindow().selectTab(index);
	}
	
	function enableAddMediaControl($buttonId, $flag) {
		var closeInfoWindowAlert = function()
		{
			alert("Please close the Add Media window first.");
		};
		
		var enableSingleButton = function($buttonId, $flag)
		{
			if ($flag == 1)
			{
				//HyperCities.debug("Enable "+$buttonId+" button");
				$("#"+$buttonId).unbind("click");
				if ($buttonId === 'marker_b')
					$("#"+$buttonId).click(_placeMarker);
				else if ($buttonId === 'line_b')
					$("#"+$buttonId).click(function(){_startPoly("line");});
				else if ($buttonId === 'shape_b')
					$("#"+$buttonId).click(function(){_startPoly("polygon");});
				else if ($buttonId === 'kml_b')
					$("#"+$buttonId).click(importKml);
				else if ($buttonId === 'hand_b')
					$("#"+$buttonId).click(hideShowAllButtons);
			}
			else if ($flag == 2)
			{
				//HyperCities.debug("Disable "+$buttonId+" button with alert.");
				$("#"+$buttonId).unbind("click");
				$("#"+$buttonId).click(closeInfoWindowAlert);
			}
			else if ($flag ==3)
			{
				//HyperCities.debug("Disable "+$buttonId+" button without alert.");
				$("#"+$buttonId).unbind("click");
			}
		};
		
		if ($buttonId === 'all')
		{
			enableSingleButton("hand_b", $flag);
			enableSingleButton("marker_b", $flag);
			enableSingleButton("line_b", $flag);
			enableSingleButton("shape_b", $flag);
			enableSingleButton("kml_b", $flag);
		}
		else
		{
			enableSingleButton($buttonId, $flag);
		}
	}

	//previledge methods
	this.getContainer = function() {
		return container;
	};
	
	this.setEditObjectMode = function($value){
		_editObjectModeFlag = $value;
	};
	
	this.getEditObjectMode = function(){
		return _editObjectModeFlag;
	};
	
	this.showUpdateWindow = function($id, $parentId) {

		_objectId = $id;
		
		$.ajax({
			url: 'queryObject.php',
			data: { object_id: $id},
			dataType: 'xml',
			type: 'POST',
			success: function($data){

				var inCollectionArray = [];
				var title     = $($data).find("object > title").text();
				var creator   = $($data).find("object > creator").text();
				var copyright = $($data).find("object > copyright").text();
				var ownerId   = $($data).find("object > ownerId").text();
				var content   = $($data).find("object > content").text();
				content = content.replace(/&amp;/g, "&").replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace (/&gt;/g, ">");
				var lat  = $($data).find("object > lat").text();
				var lon = $($data).find("object > lon").text();
				var link = $($data).find("object > timelines > timeline > kml:first").text();
				var objectTypeId = parseInt($($data).find("object > objectTypeId").text());
				var markerStyleId = parseInt($($data).find("object >  timelines > timeline > markerStyleId").text());
				
				var type = 0;
				if (objectTypeId == "4" || objectTypeId == "5")
					type = objectTypeId;
				else
					type = markerStyleId;
				HyperCities.debug("type="+type);
			
				var index = 0;
				var timespan = [];
				
				//set up timespan
				$($data).find("object > timelines > timeline").each( function(){

					timespan[index] = {
						dateFrom : Date.parse($("dateFrom", this).text()),
						dateTo   : Date.parse($("dateTo", this).text()),
						bcFrom   : $("bcFrom", this).text(),
						bcTo     : $("bcTo", this).text()
					};
					index++;
				});
				
				//set up inCollectionArray
				$($data).find("object > collections > id").each( function(){
					inCollectionArray.push($(this).text());
				});
				
			
				if (type == 1)
				{
					_editMarker(new GLatLng(lat, lon), title, creator, copyright, content, timespan, inCollectionArray, _objectId, ownerId, $parentId);
				}
				else if (type == 2 || type == 3)
				{
					var latlngs = Array();
					var latArray = (new String(lat)).split(",");
					var lngArray = (new String(lon)).split(",");
					for (var i=0; i<latArray.length; i++)
					{
						latlngs.push(new GLatLng(parseFloat(latArray[i]), parseFloat(lngArray[i])));
					}
					
					if (type == 2)
						_editPoly("line", latlngs, title, creator, copyright, content, timespan, inCollectionArray, _objectId, ownerId, $parentId);
					else if (type == 3)
						_editPoly("polygon", latlngs, title, creator, copyright, content, timespan, inCollectionArray, _objectId, ownerId, $parentId);
						
				}
				else if (type == 4 || type == 5)
					_editKmlLink(title, creator, copyright, link, timespan, inCollectionArray, _objectId, ownerId, $parentId);
				else
					HyperCities.debug(id + " has unknown object type.");				
			}//end of success
		});
	};
	
	//constructor code
	_init();
};

AddMediaControl.prototype = new GControl();

AddMediaControl.prototype.initialize = function(map) {

	var container = this.getContainer();

	map.getContainer().appendChild(container);
	return container;
};

AddMediaControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 5));
};

/*replace item back  when user closes the preview window*/
jQuery.fn.replaceBack = function(replacement,type) {
	return this.each(function(){
		if(type == "audio"){
			element = $(this);
			$(this)
			.after(replacement).next()
			.attr('width','20')
			.attr('height','20')
			.attr('_moz_resizing','true')
			.attr('src','./images/WAV.png')
			.attr('mce_src','./images/WAV.png')
			.attr('class','Itemaudio')
			.attr('title','src:'+element.find('embed').attr('src'))
			.prev().remove();
		}else if(type =="shockwave"){
			element = $(this);
			$(this)
			.after(replacement).next()
			.attr('width','20')
			.attr('height','20')
			.attr('_moz_resizing','true')
			.attr('src','./images/shockwave.gif')
			.attr('mce_src','./images/shockwave.gif')
			.attr('class','Itemshockwave')
			.attr('title','src:'+element.find('embed').attr('src'))
			.prev().remove();
		}
	});
};
jQuery.fn.replaceWith = function(replacement,type) {
	return this.each(function(){
		if(type == "audio"){
			element = $(this);
			$(this)
			.after(replacement).next()
			.attr('width','2000')
			.attr('height','36')
			.attr('ID','RVOCX')
			.attr('class','audio')
			.attr('CLASSID',"clsid:6bf52a52-394a-11d3-b153-00c04f79faa6")
			.attr('codebase',"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701")
			.append('<embed  height="36" width="200"  src="'+element.attr('title').substring(4)+'" type="application/x-mplayer2" autoplay="false" />')
			.prev().remove();
		}else if(type =="shockwave"){
			element = $(this);
			$(this)
			.after(replacement).next()
			//             .attr('width','200')
			//             .attr('height','150')
			.attr('class','shockwave')
			.append('<param value="'+element.attr('title').substring(4)+'" name="movie"/>')
			.append('<param value="200" name="width"/> <param value="150" name="height"/><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>')
			.append('<embed  height="230" align="" width="400"  src="'+element.attr('title').substring(4)+'" type="application/x-shockwave-flash"  allowscriptaccess="always" allowfullscreen="true"/>')
			.prev().remove();
		}
	});
};

