/*
* LabeledMarker Class, v1.1
*
* Copyright 2007 Mike Purvis (http://uwmike.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class extends the Maps API's standard GMarker class with the ability
* to support markers with textual labels. Please see articles here:
*
*       http://googlemapsbook.com/2007/01/22/extending-gmarker/
*       http://googlemapsbook.com/2007/03/06/clickable-labeledmarker/
*/

/**
 * Constructor for LabeledMarker, which picks up on strings from the GMarker
 * options array, and then calls the GMarker constructor.
 *
 * @param {GLatLng} latlng
 * @param {GMarkerOptions} Named optional arguments:
 *   opt_opts.labelText {String} text to place in the overlay div.
 *   opt_opts.labelClass {String} class to use for the overlay div.
 *     (default "LabeledMarker_markerLabel")
 *   opt_opts.labelOffset {GSize} label offset, the x- and y-distance between
 *     the marker's latlng and the upper-left corner of the text div.
 */

function LabeledMarker(latlng, opt_opts){
  this.latlng_ = latlng;
  this.opts_ = opt_opts;

  this.labelClass_ = opt_opts.labelClass || "LabeledMarker_markerLabel";
  this.labelOffset_ = opt_opts.labelOffset || new GSize(0, 0);

  this.clickable_ = opt_opts.clickable || true;
  this.title_ = opt_opts.title;
  this.labelVisibility_  = true;

  this.id_ = opt_opts.id || 0;

  if (opt_opts.draggable) {
  	// This version of LabeledMarker doesn't support dragging.
  	opt_opts.draggable = false;
  }
  this.width_ = opt_opts.width || 0;
  this.height_ = opt_opts.height || 0;

  this.description_ = opt_opts.description || "";
  this.datetime_ = opt_opts.datetime || "";
  this.locationName_ = opt_opts.locationName || "";

  this.labelText_ = opt_opts.labelText || "";
  this.labelType_ = opt_opts.labelType.toLowerCase() || "text";
  this.itemType_ = opt_opts.itemType || "";
  this.itemFilename_ = opt_opts.itemFilename || "";
  this.itemUserAvatarFilename_ = opt_opts.itemUserAvatarFilename || "";
  this.ownerID_ = opt_opts.ownerID || "";
  this.ownerDisplayName_ = opt_opts.ownerDisplayName || "";

  this.labelText2_ = opt_opts.labelText2 || 0;
  this.miniItemWidth_ = opt_opts.miniItemWidth || 0;
  this.miniItemHeight_ = opt_opts.miniItemHeight || 0;
  this.thumbWidth_ = opt_opts.thumbWidth || 0;
  this.thumbHeight_ = opt_opts.thumbHeight || 0;

  this.fadeeffect_;
  this.foldeffect_;

  this.currenttab_ = opt_opts.tab;

  GMarker.apply(this, arguments);
}


// It's a limitation of JavaScript inheritance that we can't conveniently
// inherit from GMarker without having to run its constructor. In order for
// the constructor to run, it requires some dummy GLatLng.
LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));

/**
 * Is called by GMap2's addOverlay method. Creates the text div and adds it
 * to the relevant parent div.
 *
 * @param {GMap2} map the map that has had this labeledmarker added to it.
 */
var tmpimg;
function openShadowbox(img,itemid,itemtype,ownerid,filename,owneravatar,ownerdisplay_name){
	div = img.parentNode;
	Shadowbox.init();
	if(itemtype == "photo"){
		var tmpimg = new Image();
		tmpimg.src = photopath_medium+ownerid+"/"+filename;
		Shadowbox.open({title:div.title, type:'img', content:tmpimg.src});
	}else{
        var content = staticpath+'/static/player/mediaV1.swf?avatar=/asset/avatar/48x48/'+owneravatar+'&video='+staticpath+'/asset/video/flv/'+ownerid+'/'+filename+'.flv&title='+encodeURIComponent(div.title)+'&user='+ownerdisplay_name+'&userid='+ownerid+'&urlfile=/video/view/'+itemid+'&urluser=/videos/'+ownerid+'&swffile='+staticpath+'/static/player/mediaV1.swf&videoid='+itemid+'&videoimg='+staticpath+videopngpath_medium+ownerid+'/'+filename+'.png&urlapi=http://'+window.location.host+'&inpg=true';
		Shadowbox.open({title:'', type:'swf', width:480, height:360, content:content});
	}
}

LabeledMarker.prototype.initialize = function(map) {
  // Do the GMarker constructor first.
  GMarker.prototype.initialize.apply(this, arguments);

  this.map_ = map;
  this.div_ = document.createElement("div");
  this.div_.className = this.labelClass_;
  this.div_.style.position = "absolute";

  if(this.labelType_ == "bigmarker"){
  	if(!isIE){
	  	this.div_.setOpacity(0.0);
		this.div_.style.visibility = 'hidden';
  	}
	var itemid = this.id_+this.itemType_;
	if(this.currenttab_ == 'public')itemid = this.ownerID_+this.itemType_;
	
  	var imglink = this.itemType_=="photo"?photopath_thumb+this.ownerID_+"/"+this.itemFilename_:videopngpath_thumb+this.ownerID_+"/"+this.itemFilename_+".png";
  	this.div_.innerHTML =
			'<div class="bigmarker" id="bigmarker_imgid'+itemid+'" title="'+this.title_+'" onmouseover="showElement(&quot;bigmarker_closebtn'+this.id_+this.itemType_+'&quot;)" onmouseout="hideElement(&quot;bigmarker_closebtn'+this.id_+this.itemType_+'&quot;)"> ' +
				'<img class="bigmarker_img" src="'+imglink+'" onclick="openShadowbox(this,&quot;'+this.id_+'&quot;,&quot;'+this.itemType_+'&quot;,&quot;'+this.ownerID_+'&quot;,&quot;'+this.itemFilename_+'&quot;'+',&quot;'+this.itemUserAvatarFilename_+'&quot;,&quot;'+encodeURIComponent(this.ownerDisplayName_)+'&quot;)" alt=""/>' +
				'<div class="iteminfo"> <a href="/profiles/'+this.ownerID_+'" target="_blank"><img class="avatar" src="/asset/avatar/30x30/'+this.itemUserAvatarFilename_+'" alt="" /></a>' +
					'<p><strong>'+this.title_+'</strong><br />' +
					_('Date')+': '+this.datetime_+'<br />' +
					_('Location')+': '+this.locationName_+'<br />' +
					'<a href="#" onclick="openInfoPane(this.parentNode.parentNode.parentNode.id.substring(15),60000);return false;">'+_("Detail")+'</a></p>' +
				'</div>' +
				'<div id="bigmarker_closebtn'+this.id_+this.itemType_+'" class="deleteoverlay deleteicon" onclick="closeBigMarker()"/>'+
			'</div>';
  }else if(this.labelType_ == "smallmarker"){
	var itemid = this.id_+this.itemType_;
	if(this.currenttab_ == 'public')itemid = this.ownerID_+this.itemType_;
  	//setopacity(this.div_,1);
  	var imglink = this.itemType_=="photo"?photopath_mini+this.ownerID_+"/"+this.itemFilename_:videopngpath_mini+this.ownerID_+"/"+this.itemFilename_+".png";
	this.div_.innerHTML = '<div class="smallmarker" id="smallmarker_imgid'+itemid+'"><img src="'+imglink+'" onclick="delayCloseBigMarker(this.parentNode.id.substring(17),10000)" alt="" /></div>'
  }else if(this.labelType_ == "place"){
	this.div_.innerHTML = "<img id='"+this.id_+"' onclick='openPlaceInfoWindow(this)' src='"+this.labelText_+"' style='width:"+this.width_+"px; height:"+this.height_+"px;'></img>";
  }
  //this.div_.style.cursor = "pointer";
  //this.div_.title = this.title_;

  map.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);
  if(isFirefox3){
	this.oldStyle_ = {
		top: this.div_.getStyle('top'),
		left: this.div_.getStyle('left'),
		width: this.div_.getStyle('width'),
		height: this.div_.getStyle('height')
	};
  }
  if (this.clickable_) {
    /**
     * Creates a closure for passing events through to the source marker
     * This is located in here to avoid cluttering the global namespace.
     * The downside is that the local variables from initialize() continue
     * to occupy space on the stack.
     *
     * @param {Object} object to receive event trigger.
     * @param {GEventListener} event to be triggered.
     */
    function newEventPassthru(obj, event) {
      return function() {
        GEvent.trigger(obj, event);
      };
    }

    // Pass through events fired on the text div to the marker.
    var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
    for(var i = 0; i < eventPassthrus.length; i++) {
      var name = eventPassthrus[i];
      GEvent.addDomListener(this.div_, name, newEventPassthru(this, name));
    }
  }
}

/**
 * Move the text div based on current projection and zoom level, call the redraw()
 * handler in GMarker.
 *
 * @param {Boolean} force will be true when pixel coordinates need to be recomputed.
 */
LabeledMarker.prototype.redraw = function(force) {
  GMarker.prototype.redraw.apply(this, arguments);

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var p = this.map_.fromLatLngToDivPixel(this.latlng_);
  var z = GOverlay.getZIndex(this.latlng_.lat());

  // Now position our div based on the div coordinates of our bounds
  this.div_.style.left = (p.x + this.labelOffset_.width) + "px";
  this.div_.style.top = (p.y + this.labelOffset_.height) + "px";
  this.div_.style.zIndex = z; // in front of the marker
}

/**
 * Remove the text div from the map pane, destroy event passthrus, and calls the
 * default remove() handler in GMarker.
 */
 LabeledMarker.prototype.remove = function() {
  GEvent.clearInstanceListeners(this.div_);
  if (this.div_.outerHTML) {
    this.div_.outerHTML = ""; //prevent pseudo-leak in IE
  }
  if (this.div_.parentNode) {
    this.div_.parentNode.removeChild(this.div_);
  }
  this.div_ = null;
  GMarker.prototype.remove.apply(this, arguments);
}

/**
 * Return a copy of this overlay, for the parent Map to duplicate itself in full. This
 * is part of the Overlay interface and is used, for example, to copy everything in the
 * main view into the mini-map.
 */
LabeledMarker.prototype.copy = function() {
  return new LabeledMarker(this.latlng_, this.opt_opts_);
}


/**
 * Shows the marker, and shows label if it wasn't hidden. Note that this function
 * triggers the event GMarker.visibilitychanged in case the marker is currently hidden.
 */
LabeledMarker.prototype.show = function() {
  GMarker.prototype.show.apply(this, arguments);
  if(this.div_){
	  if (this.labelVisibility_) {
	  	if(isIE){
	  		this.showLabel();
	  	}else{
		  	if(this.fadeeffect_) this.fadeeffect_.cancel();
			if(this.foldeffect_){
				this.foldeffect_.cancel();
				this.div_.undoClipping().setStyle(this.oldStyle_);
				this.redraw();
			}
	
			var options = Object.extend({
				from: (this.div_.getStyle('display') == 'none' ? 0.0 : this.div_.getOpacity() || 0.0),
				to:   1.0,
				afterFinishInternal: function(effect) {
					effect.element.forceRerendering();
				},
				beforeSetup: function(effect) {
					effect.element.setOpacity(effect.options.from);
					effect.element.style.visibility = 'visible';
				}
			});
	
			this.fadeeffect_ = new Effect.Opacity(this.div_,options);
	  	}
	  } else {
	  	if(isIE){
	  		this.hideLabel();
	  	}else if(isFirefox3 && this.div_.style.visibility=='visible'){
			this.fold();
		}else{
		  	if(this.fadeeffect_) this.fadeeffect_.cancel();
			if(this.foldeffect_){
				this.foldeffect_.cancel();
				this.div_.undoClipping().setStyle(this.oldStyle_);
				this.redraw();
			}
	
			var options = Object.extend({
				from: this.div_.getOpacity() || 1.0,
				to: 0.0,
				afterFinishInternal: function(effect) {
					effect.element.style.visibility = 'hidden';
				}
			});
	
			this.fadeeffect_ = new Effect.Opacity(this.div_,options);
	  	}
	  }
  }
}

/**
 * Hides the marker and label if it is currently visible. Note that this function
 * triggers the event GMarker.visibilitychanged in case the marker is currently visible.
 */
LabeledMarker.prototype.hide = function() {
  GMarker.prototype.hide.apply(this, arguments);
  if(this.div_){
  	if(isIE){
  		this.hideLabel();
  	}else if(isFirefox3 && this.div_.style.visibility=='visible'){
		this.fold();
	}else{
	  	if(this.fadeeffect_) this.fadeeffect_.cancel();
		if(this.foldeffect_){
			this.foldeffect_.cancel();
			this.div_.undoClipping().setStyle(this.oldStyle_);
			this.redraw();
		}

		var options = Object.extend({
			from: this.div_.getOpacity() || 1.0,
			to: 0.0,
			afterFinishInternal: function(effect) {
				effect.element.style.visibility = 'hidden';
			}
		});

		this.fadeeffect_ = new Effect.Opacity(this.div_,options);
  	}
  }
}

/**
 * Sets the visibility of the label, which will be respected during show/hides.
 * If marker is visible when set, it will show or hide label appropriately.
 */
LabeledMarker.prototype.setLabelVisibility = function(visibility) {
  this.labelVisibility_ = visibility;
  if (!this.isHidden()) { // Marker showing, make visible change
    if (this.labelVisibility_) {
	  	this.showLabel();
    } else {
    	this.hideLabel();
    }
  }
}

/**
 * Returns whether label visibility is set on.
 * @return {Boolean}
 */
LabeledMarker.prototype.getLabelVisibility = function() {
  return this.labelVisibility_;
}


/**
 * Hides the label of the marker.
 */
LabeledMarker.prototype.hideLabel = function() {
  this.div_.style.visibility = 'hidden';
}


/**
 * Shows the label of the marker.
 */
LabeledMarker.prototype.showLabel = function() {
  this.div_.style.visibility = 'visible';
}

LabeledMarker.prototype.fold = function(){
	var oldStyle = this.oldStyle_;

	if(this.foldeffect_) this.foldeffect_.cancel();
	this.div_.makeClipping();
	this.foldeffect_ = new Effect.Scale(this.div_, 20,
		Object.extend({
			scaleContent: false,
			scaleY: false,
			afterFinishInternal: function(effect) {
				new Effect.Scale(effect.element, 1, {
					scaleContent: false,
					scaleX: false,
					afterFinishInternal: function(effect) {
						effect.element.style.visibility = 'hidden';
					},
					duration: 0.5
				});
				new Effect.Move(effect.element, {
					x:0,
					y:parseInt(oldStyle.height),
					afterFinishInternal: function(effect) {
						effect.element.style.visibility = 'hidden';
					},
					duration:0.5
				});
			},
			duration: 0.5
		})
	);

	if(this.fadeeffect_) this.fadeeffect_.cancel();
	this.fadeeffect_ = new Effect.Opacity(this.div_,
		Object.extend({
			from: this.div_.getOpacity() || 1.0,
			to: 0.0,
			afterFinishInternal: function(effect) {
				effect.element.style.visibility = 'hidden';
			}
		})
	);
}
