/**
 * @name GMap2
 * @class These are new methods added to the Google Maps API's
 * <a href = 'http://code.google.com/apis/maps/documentation/reference.html#GMap2'>GMap2</a>
 * class.
 */
GMap2.prototype.HC_CONTENT_STYLE = { 
	minimum: 1,  // Short content for small infoWindow
	summary: 2,  // Summary for maximize infoWindow
    maxTitleLen : 50 // Maximal Length of Title in Maximized Window
};

// Old Code, Need to rewrite ASAP
GMap2.prototype.HCRenderMinContent = function ($data) {
	HyperCities.debug("Render Min Data");

	var infoWindow = HyperCities.mainMap.getInfoWindow();
	var contentDom = infoWindow.getContentContainers();

//	HyperCities.debug(contentDom);
	var title     = $($data).find("object > title").text();
	var creator   = $($data).find("object > creator").text();
	var copyright = $($data).find("object > copyright").text();
	var content   = $($data).find("object > content").text();
	var mapYear   = Date.today().toString("yyyy");
	var startTime = Date.parse($($data).find("object > startTime").text());
	var endTime   = Date.parse($($data).find("object > endTime").text());
	var timespan  = "Not specify";
	var htmlMin   = "";
	var htmlFull  = "";
	var maxTitle  = "";
	var parentItem   = $($data).find("parent:first");
	var totalParents = $($data).find("parent").length;
	var parentId  = null;
	var hasPrev   = false;
	var hasNext   = false;
	var params    = {};
	var objectId  = $($data).find("object > id").text();

	// Store Raw Data
	infoWindow.rawData = $data;

	if ( startTime !== null && endTime !== null )
	{
		//timespan = startTime.toString("yyyy") + " - " + endTime.toString("yyyy") ;
		timespan = startTime.getFullYear() + " ~ " + endTime.getFullYear() ;
	}
	else if ( startTime !== null )
	{
		//timespan = startTime.toString("yyyy") + " - " ;
		timespan = startTime.getFullYear().toString() + " ~ " ;
	}
	else if ( endTime !== null && endTime.toString("yyyy") !== "9999" )
	{
		//timespan = " - " + endTime.toString("yyyy") ;
		timespan = " ~ " + endTime.getFullYear().toString() ;
	}

	
	htmlMin += '<div class="HCContentTitle">' + title + '</div>'
		+ '<div class="HCContentMeta">Creator: ' + creator + '</div>'
		//+ '<div class="HCContentMeta">Copyright: ' + copyright + '</div>'
		+ '<div class="HCContentMeta">Time: ' + timespan + '</div>'
		//+ '<div class="HCContentMeta">Map Time: ' + mapYear + '</div>'
		+ '<a href="javascript:void(0);" class="moreLink" onClick="HyperCities.mainMap.maximizeInfoWindow()">more info »</a>'
		+ '</div>';


	$(contentDom).find("div.loading")
		.empty()
		.removeClass("loading")
		.addClass("content")
		.append(htmlMin);
	
};

GMap2.prototype.HCRenderMaxContent = function ($data) {
	HyperCities.debug("Render Max Data");

	var infoWindow = HyperCities.mainMap.getInfoWindow();
//	var contentDom = infoWindow.getContentContainers();
	var summaryDom = HyperCities.mainMap.getMapInstance().getTabbedMaxContent().summaryNode_;

//	HyperCities.debug(summaryDom);
	var title     = $($data).find("object > title").text();
	var creator   = $($data).find("object > creator").text();
	var copyright = $($data).find("object > copyright").text();
	var content   = $($data).find("object > description > ExtendedData > content").text();
	var mapYear   = Date.today().toString("yyyy");
	var startTime = Date.parse($($data).find("object > startTime").text());
	var endTime   = Date.parse($($data).find("object > endTime").text());
	var timespan  = "Not specify";
	var htmlMin   = "";
	var htmlFull  = "";
	var maxTitle  = "";
	var parentItem   = $($data).find("parent:first");
	var totalParents = $($data).find("parent").length;
	var parentId  = null;
	var hasPrev   = false;
	var hasNext   = false;
	var params    = {};
	var objectId  = $($data).find("object > id").text();
        var permalink = HyperCities.linkController.generatePermalink('object', objectId);
        HyperCities.collectionList.addCitations(objectId, $($data).find("object > description > ExtendedData > citationlist"));

	// Store Raw Data
	infoWindow.rawData = $data;

	if ( startTime !== null && endTime !== null )
	{
		//timespan = startTime.toString("yyyy") + " - " + endTime.toString("yyyy") ;
		timespan = startTime.getFullYear() + " ~ " + endTime.getFullYear() ;
	}
	else if ( startTime !== null )
	{
		//timespan = startTime.toString("yyyy") + " - " ;
		timespan = startTime.getFullYear().toString() + " ~ " ;
	}
	else if ( endTime !== null && endTime.toString("yyyy") !== "9999" )
	{
		//timespan = " - " + endTime.toString("yyyy") ;
		timespan = " ~ " + endTime.getFullYear().toString() ;
	}

	htmlFull += '<div class="HCContentTitle">' + title + '</div>'
		+ '<div class="HCContentMeta">Creator: ' + creator + '</div>'
		//+ '<div class="HCContentMeta">Copyright: ' + copyright + '</div>'
		+ '<div class="HCContentMeta">Time: ' + timespan + '</div>'
		//+ '<div class="HCContentMeta">Map Time: ' + mapYear + '</div>'
		+ '<div class="HCContentMeta">Link to this object: ' + permalink + '</div>'
		+ '</div>';
	
	$(summaryDom).find(".HCMaxInfoSummary div.loading")
		.empty()
		.removeClass("loading")
		.addClass("content")
		.append(htmlFull);
	
	var contentDom = HyperCities.mainMap.getMapInstance().getTabbedMaxContent().getTab(0).getContentNode();

	var ImageSubId = 0;
	var ImagePanelObject = {id: objectId, title: title};

//	HyperCities.debug(contentDom);
	$(contentDom)
		.html(content)
		.find("a")
		.css("color", "#2200FF")
		.attr("target", "_blank").end()
		.find("img")
		.each(function() {
                    

				var imageId = ImagePanelObject.id + "_" + ImageSubId++;

				var imageObject = { 
						id: imageId,
						title: ImagePanelObject.title,
						sourceURL: $(this).attr("src"),
						height: 200,
						width: 320
					};

				var image = new Image();
				image.onload = function () { 
						imageObject.height = this.height;
						imageObject.width  = this.width; 
					};
				image.src = $(this).attr("src");

				var anchorNode = $(this).parent().get(0);

				if ( anchorNode.nodeName === "A" && anchorNode.href !== "" ) {
					$(this).css("border", "0px");
					return;
				} else {
					$(this).css("cursor", "pointer")
						.click(HyperCities.mainMap.overlayImageBox(imageObject));
				}
			});
        $(contentDom).find("a").each(function () {
            if ($(this).hasClass('citationLink')) {
                $(this).removeAttr('target');
                var refCode = $(this).find('citation:first').attr('ref');
                //HyperCities.debug("RefCode" + refCode);
                var title = $(this).find('citation:first').text();
                
                $(this).attr('onClick',
                    'javascript:HyperCities.mainMap.showCitation(' +objectId + ',"' + refCode + '","' + title + '");');
                $(this).wrap(document.createElement("sup"));
            }
        });

	HyperCities.mainMap.getMapInstance().getTabbedMaxContent().selectTab(0);
};

GMap2.prototype.getHCContent = function ($type, $contentId) {
		
	var content = '';

	if ( $type === this.HC_CONTENT_STYLE.minimum ) { 
		content = '<div class="HCInfoWindow"><span class="banner"></span>'
			+ '<div class="addthis_toolbox addthis_default_style">'
			+ '<a class="addthis_button_email" title="Email"><span class="at300bs at15t_email"/></a>'
			+ '<a class="addthis_button_favorates" title=Add to Bookmarks""><span class="at300bs at15t_favorites"/></a>'
			+ '<a class="addthis_button_twitter" title="Tweet This"><span class="at300bs at15t_twitter"/></a>'
			+ '<a class="addthis_button_facebook" title="Share to Facebook"><span class="at300bs at15t_facebook"/></a>'
			+ '</div>'
			+ '<div class="loading"> Loading... </div></div>';
	}
	else if ( $type === this.HC_CONTENT_STYLE.summary ) {
		content = '<div class="HCMaxInfoSummary"><span class="banner"></span>'
			+ '<div class="addthis_toolbox_max addthis_default_style">'
                        + '<a href="javascript: HyperCities.session.saveSnapshot();" ><img src="./images/camera.gif" width="16" height="16" /></a>'
			/*+ '<a class="addthis_button_email" title="Email"><span class="at300bs at15t_email"/></a>'
			+ '<a class="addthis_button_favorates" title=Add to Bookmarks""><span class="at300bs at15t_favorites"/></a>'
			+ '<a class="addthis_button_twitter" title="Tweet This"><span class="at300bs at15t_twitter"/></a>'
			+ '<a class="addthis_button_facebook" title="Share to Facebook"><span class="at300bs at15t_facebook"/></a>'
			+ '<a class="addthis_button_myspace" title="Share to MySpace"><span class="at300bs at15t_myspace"/></a>'
			+ '<a class="addthis_button_stumbleupon" title="StumbleUpon"><span class="at300bs at15t_stumbleupon"/></a>'
			+ '<a class="addthis_button_digg" title="Digg This"><span class="at300bs at15t_digg"/></a>'*/
			+ '</div>'
			+'<div class="loading"> Loading... </div></div>';
	}

	return content;
};

GMap2.prototype.getHCMaxTitle = function ($title) {

	var newTitle    = $title,
		oldTitleLen = $title.length,
		maxTitleLen = this.HC_CONTENT_STYLE.maxTitleLen,
		titleHtml   = [ '<div class="HCMaxInfoTitle"><span class="prevLink">« Previous</span>',
						'<span class="nextLink">Next »</span>',
						'<span class="maxTitle" title="', $title, '">', $title, "</span></div>"],
		c;

	// Truncate Max Title
	while (maxTitleLen < oldTitleLen) {
		c = $title.charAt(maxTitleLen);
		if (c.match(/\s/)) {
			newTitle = $title.substring(0, maxTitleLen);
			titleHtml[5] = newTitle;
			titleHtml[6] = "...</span></div>";
			break;
		}
		maxTitleLen--;
	}

	return titleHtml.join ('');
};

GMap2.prototype.closeHCInfoWindow = function ($restoreCenter) {
	var restore = !($restoreCenter === false); // Default to true
        
	// unbind Event Listeners
	GEvent.clearListeners(this, 'infowindowopen');
	GEvent.clearListeners(this, 'infowindowbeforeclose');
	GEvent.clearInstanceListeners(this.getInfoWindow());

	// Reset HyperCities related variable
	HyperCities.session.set("infoWin", null);
	if ( this.HCOldBaseMap !== null ) {
		HyperCities.session.set("baseMap", this.HCOldBaseMap);
	}
	// panTo original center, if necessary
	if ( restore && (this.getCurrentMapType() !== G_SATELLITE_3D_MAP) ) {
		HyperCities.mainMap.panTo(this.HCOldLatLng);
	} 
	else { // Seve the new Center
		HyperCities.mainMap.updateCenter(this.getCenter());
	}

	// Clean up HyperCities Variables
	this.HCOldBaseMap = null;
	this.HCOldLatLng = null;
	this.getInfoWindow().rawData = null;

//	this.maxContent_ = null;
	this.closeInfoWindow();
};
/**
 * Opens an info window with maximizable content at the given {@link latlng}.
 * The infowindow displays the content in the {@link minNode} in the 
 * minimized state, and then displays the content in the {@link summaryNode}
 * along with the array of {@link tabs} in the maximized state.
 * Additional options can be sent in {@link opt_maxOptions}.
 * @param {GLatLng} latlng
 * @param {number} collection Id in HyperCities DB
 * @param {MaxContentOptions} opt_maxOptions
 */
GMap2.prototype.openHCInfoWindow = function ($item, $opts) {
	var oldInfoWin   = null,
		isCollection = false,
		isMaximized  = false,
		objectId     = $item.id,
		objectTitle  = $item.name,
		objectLatLng = $item.overlay.getLatLng(),
		collectionId = null,
		infoWindow   = null,
		infoWinOpts  = {},
		shortContent = null,
		longContent  = null,
		tabs         = [],
		opts         = $opts || {},
		self         = this;

	// Save Current Status and restore when infoWindow close
	this.HCOldLatLng  = this.getCenter();
	this.HCOldBaseMap = HyperCities.session.get("baseMap");

	// Check if another infoWindo was opened
	oldInfoWin = HyperCities.session.get("infoWin");
	if ( oldInfoWin !== null ) {
		if ( oldInfoWin === objectId ) { // correct infoWindow already opened
//			HyperCities.debug(_id + "InfoWindow already opened");
			return;
		}
		else { // Another InfoWindow opened, close old InfoWindow, but not panTo old Center
//			HyperCities.debug(_id + "Another InfoWindow opened");
			this.closeHCInfoWindow(false);
		}
	}

	// Check if Item is a collection
	if (opts.isCollection === true) {
		isCollection = true;
	}
	// Check if Parent Id is given
	if (typeof(opts.collectionId) !== 'undefined' ) {
		collectionId = opts.collectionId;
	}

        // handles call from opening snapshot
        if ((typeof(opts.maximize) == 'boolean')) {
            HyperCities.debug("Opts maximized: " + opts.maximize);
            isMaximized = opts.maximize;
        } else {
            isMaximized = HyperCities.session.get("maxInfoWin");
        }
        
	// Store Current InfoWindow Id
	HyperCities.session.set("infoWin", objectId);

	// Prepare InfoWindow
	infoWinOpts = { maxTitle: this.getHCMaxTitle(objectTitle), maximized: isMaximized };
	shortContent = this.getHCContent(this.HC_CONTENT_STYLE.minimum, objectId);
	longContent = this.getHCContent(this.HC_CONTENT_STYLE.summary, objectId);
	tabs = [ new MaxContentTab('Description', 'Description Content'),
			 new MaxContentTab('StreeView', 'StreeView Window'),
			 new MaxContentTab('Comment', 'User comments') ];

	// Open InfoWindow
	this.openMaxContentTabsHtml(objectLatLng, shortContent, longContent, tabs, infoWinOpts);

	// Bind event listener for InfoWindow
	infoWindow = this.getInfoWindow();

	GEvent.addListener(infoWindow, 'maximizeend', function() {
			HyperCities.debug("Maximizeend InfoWindow");
			HyperCities.session.set("maxInfoWin", true);
			if ( !isMaximized ) {
				self.HCRenderMaxContent(self.getInfoWindow().rawData);
			}
		});

	GEvent.addListener(infoWindow, 'restoreend', function() {
			HyperCities.debug("Restoreend InfoWindow");
			HyperCities.session.set("maxInfoWin", false);
			if ( isMaximized ) {
				self.HCRenderMinContent(self.getInfoWindow().rawData);
			}
		});

	GEvent.addListener(this, 'infowindowopen', function() {

			//var params = {cid: objectId};
			var params = { object_id: objectId};

			if ( collectionId !== null ) {
				//params.pid = collectionId;
				params.parent_id = collectionId;
			}
 
			if ( isMaximized ) {
				HyperCities.debug("Load Max Data");
				//$.post("./getContent.php", params, self.HCRenderMaxContent, "xml");
				$.post("./queryContent.php", params, self.HCRenderMaxContent, "xml");
			}
			else {
				HyperCities.debug("Load Min Data");
				//$.post("./getContent.php", params, self.HCRenderMinContent, "xml");
				$.post("./queryContent.php", params, self.HCRenderMinContent, "xml");
			}
		});

	GEvent.addListener(this, "infowindowbeforeclose", function() {
			HyperCities.debug("Close InfoWindow");
			this.closeHCInfoWindow(true);
		});
/*
					if ( _currentCollectionId > 0 )
						params = { object_id: $id, parent_id: _currentCollectionId};
					else
						params = { object_id: $id };

					if ( $type == "object" || $type == "polygon" || $type === 'polyline' ) {
						//HyperCities.debug("Show Info Windows of "+$type+" " + $id);
						_infoWindowId = $id;
						// Query the Object Content
						$.post("./queryContent.php", params, _renderContent, "xml");
					} else {
						HyperCities.debug("Show Info Windows of Cluster " + $id);
						_infoWindowId = $id;

						_cluster[_infoWindowId].overlay.gmarkers[0].openInfoWindowHtml(_cluster[_infoWindowId].html);
					}
*/
};

