/**** script/tooltip.js ****/
function Tooltip (link) {
	this.link = link;
	this.body = $("#body")
	this.key = this.link.attr("class");
	this.showText = L("tooltip_show_text");
	this.hideText = L("tooltip_hide_text");
	this.name = this.link.text();
	this.mapDescContainer = $("#map .mapDescriptionContainer");
	this.options = {
		leftClass: 'leftOriented',
		rightClass: 'rightOriented',
		tooltipClass: 'tooltip'
	}	
	this.createTooltipContainers();
	this.initEventHandlers();
}

Tooltip.prototype.createTooltipContainers = function() {
	this.tooltipContainer = $('<div style="display:none"></div>');
	this.tooltipContainer.addClass(this.options.leftClass)
					     .addClass(this.options.tooltipClass)
						 .appendTo("body")
}

Tooltip.prototype.initEventHandlers = function() {
	var that = this;
	this.link.mouseover(function(){
		that.showTooltip();
	})
	this.link.mouseout(function(event){
		that.hideTooltip();
	})
}

Tooltip.prototype.showTooltip = function() {

	var text = this.link.hasClass('active') ? this.hideText : this.showText;
	this.tooltipContainer.text(text + " " + this.name);

	var bodyWidth = $("body").outerWidth();
	var linkWidth = this.link.outerWidth();
	var linkLeftOffset = this.link.offset().left;
	var linkRightOffset = bodyWidth - linkWidth - linkLeftOffset;

	this.tooltipContainer.css({
		top: this.mapDescContainer.offset().top - 30,
		left: linkLeftOffset,
		right: ""
	})
	this.tooltipContainer.show();
	
	var tooltipWidth = this.tooltipContainer.outerWidth();
	
	
	if (!((tooltipWidth + linkLeftOffset) < bodyWidth - 50)) {
		this.tooltipContainer.css({
			top: this.mapDescContainer.offset().top - 30,
			right: linkRightOffset,
			left: ""
		})
	}

}

Tooltip.prototype.hideTooltip = function() {
	this.tooltipContainer.hide();
}

;

/**** script/controls.js ****/
var commonControls = {
	/**
	 * Switcher control (i.e. currency switcher)
	 * @param string|array Switchers
	 * @param string Active element class name
	 * @param string Inactive element class name
	 * @param function Callback function
	 */
	switcher: function (control, activeClass, inactiveClass, callback, hiddenInput) {
		$(control).each(function() {
			if ((this.tagName).toLowerCase() == "ul") {
				// hidden switcher value
				if (hiddenInput) {
					var hidden = hiddenInput;
				} else {
					var hidden = $(this).next("input");
				}
				// current option
				var current = null;
				$("li", this).each(function() {
					// hidden option value
					var hiddenValue = $("input:first", this).val();
					// set current option
					if (!current && $(this).children("a:first").hasClass(activeClass)) current  = this;
					//disabling a element click handler
					$("a", this).click(function(e){
						return false;
					})
					// option click handler					
					$(this).mousedown(function(e) {
						// if can activate
						if (!$(this).hasClass(activeClass) && (e.button == 0 || e.button == 1)) {
							// previous switcher value
							var prevValue = hidden.val();
							// deselect siblings
							$(this).siblings().children("a").removeClass(activeClass).addClass(inactiveClass);
							// select this option
							$("a", this).removeClass(inactiveClass).addClass(activeClass);
							// set hidden field
							if (hidden) {
								hidden.val(hiddenValue);
							}
							// call function
							var justClickedItem = this;
							if ($.isFunction(callback)) callback.call(this, current, justClickedItem);
							// change current item link
							current = this;
						}
						return false;
					});
				});
			}
		});
		if (hiddenInput) {
			hiddenInput.val($(control).children('li:first').children('input:first').val());
		}	
	}, 
	
	customSwitcher: function(control, activeClass, hiddenInput, callback) {
		this.switcher(control, activeClass, null, callback, hiddenInput);
	}
}
;

/**** script/object-map.js ****/
/**
 * GMap control constructor. This class is singletone
 *
 * @return ObjectMap
 */
function ObjectMap(fullMapContainer, previews, photos) {
	//if class has not been instantiated yet
	if (!this.constructor.prototype.instance) {
		if ($.isFunction(window.GMap2) && fullMapContainer) {
			
			this.previews = previews;
			this.photos = photos;
			this.fullMapContainer = fullMapContainer;
			this.mainContainer = this.fullMapContainer.parent();
			this.center = null;
			this.frequency = null;
			this.fullMap = null;
			this.fullMapControls = $("#mapControls");
			
			this.center = this.getCenter();
			this.initMapPreview();
			this.initFullMap();

		} else {
			return null;
		}
		// store instance in prototype
		this.constructor.prototype.instance = this;
	}
	// return instance
	return this.constructor.prototype.instance;
}


ObjectMap.prototype.getCenter = function() {
	var data = String(this.mainContainer.attr("class"));
	var lat = data.match(/lat_(\-?\d+(?:\.\d+)?)/);
	lat = lat ? parseFloat(lat[1]) : null;
	var lng = data.match(/lng_(\-?\d+(?:\.\d+)?)/);
	lng = lng ? parseFloat(lng[1]) : null;
	if (lat && lng) {
		return new GLatLng(lat, lng);
	} else {
		return null;
	}	
}

ObjectMap.prototype.initMapPreview = function() {
	var that = this;
	this.previews.filter(".card-map").each(function(){
		var previewMapContainer = $(this).children("div:first");
		if (previewMapContainer) {				
			// create preview map
			var previewMap = new GMap2(previewMapContainer[0]);
			previewMap.disableDragging();
			previewMap.disableDoubleClickZoom()
			previewMap.setCenter(that.center, 14);				
			//creating icon
			var options = {};
			var icon = new GIcon();
			icon.iconSize = new GSize(16, 16);
			icon.iconAnchor = new GPoint(5, 2);		
			icon.image = "/img/gmap/house_object.gif";
			options.icon = icon;
			var marker = new GMarker(that.center, options);
			previewMap.addOverlay(marker);				
			//preview maps handlers
			if (that.previews.length) {
				var item = $(this);
				GEvent.addListener(marker, "click", function() {
					item.click();
				});
				// set handlert to select map
				$(this).click(function() {
					that.initFullMap();
				});
			}
			if (!that.photos.length) {
				//if map object is the only one in preview list
				$(this).trigger('click')
			}			
		}
	})

}

ObjectMap.prototype.initFullMap = function() {
	if (!this.fullMap && this.center) {
		this.fullMap = new GMap2(this.fullMapContainer[0]);
		this.fullMap.setCenter(this.center, 14);
		this.initFullMapControls();
		this.addObjectToMap();
		this.initPostLoad();
		this.initMapLegend();
	} else if (this.fullMap) {
		this.mainContainer.show();
		this.fullMap.checkResize();
		this.fullMap.setCenter(this.center, 14);
		this.loadInfraItems();
	}
}

ObjectMap.prototype.initFullMapControls = function() {
	// If no container found, then no need to add custom control, use default
	if (!this.fullMapControls[0]) {
		this.fullMap.addControl(new GSmallMapControl());
		return;
	}
	
	var control = this;
	
	//defining the function
	function CustomControl() {
	}
	
	//creating a subclass of GControl
	CustomControl.prototype =  new GControl();
	
	/**
	 * @return DOMElement
	 */
	CustomControl.prototype.initialize = function(map) {
		//DOM element to be returned
		var container = control.fullMapControls[0];
		
		//binding click handler to map areas of navigation block image
		var zoomControlContainer = $(container).find('#zoomControl')
		var left = zoomControlContainer.find('.left');
		var top = zoomControlContainer.find('.top');
		var right = zoomControlContainer.find('.right');
		var down = zoomControlContainer.find('.down');
		var center = zoomControlContainer.find('.center');
		right.click(function(){
				control.map.panDirection(-1, 0);
			})
			.mouseover(function(){
				zoomControlContainer.attr("style","background-position: 0 -88px");
			 })
			.mouseout(function(){
				zoomControlContainer.attr("style","");
			})
		left.click(function(){
				control.fullMap.panDirection(1, 0);
			})
			.mouseover(function(){
				zoomControlContainer.attr("style","background-position: 0 -176px");
			 })
			.mouseout(function(){
				zoomControlContainer.attr("style","");
			})
		top.click(function(){
				control.fullMap.panDirection(0, 1);
			})
			.mouseover(function(){
				zoomControlContainer.attr("style","background-position: 0 -44px");
			 })
			.mouseout(function(){
				zoomControlContainer.attr("style","");
			})
		down.click(function(){
				control.fullMap.panDirection(0, -1);
			})
			.mouseover(function(){
				zoomControlContainer.attr("style","background-position: 0 -132px");
			 })
			.mouseout(function(){
				zoomControlContainer.attr("style","");
			})
		center.click(function(){
				control.fullMap.returnToSavedPosition();
			})
			.mouseover(function(){
				zoomControlContainer.attr("style","background-position: 0 -220px");
			 })
			.mouseout(function(){
				zoomControlContainer.attr("style","");
			})
			
		
		//binding click handlers to slider control
		var sliderControl = $("#sliderControl");
		var zoomIn = sliderControl.find('.zoomIn');
		var zoomOut = sliderControl.find('.zoomOut');
	
		zoomIn.click(function(){
				control.fullMap.zoomIn();
			})
		zoomOut.click(function(){
			control.fullMap.zoomOut();
		})
		
		zoomOut.mouseover(function(){
			   		$(this).attr("style","background-position: 0 -25px");
			  	})
			  	.mouseout(function(){
			     	$(this).attr("style","");
			    })
		
		zoomIn.mouseover(function(){
			   		$(this).attr("style","background-position: 0 -31px");
			  	})
			  	.mouseout(function(){
			     	$(this).attr("style","");
			    })
		
		container.style.zIndex = 10;
		
		return container;
	}
	
	//setting the position of custom control
	CustomControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20, 20));
	}
	
	control.fullMap.addControl(new CustomControl());	
}


ObjectMap.prototype.addObjectToMap = function() {
	if (this.center) {
		var options = {};
		var icon = new GIcon();
		icon.iconSize = new GSize(16, 16);
		icon.iconAnchor = new GPoint(0, 0);
		icon.infoWindowAnchor = new GPoint(9, 2);
		icon.image = "/img/gmap/house_object.gif";
		options.icon = icon;
		var marker = new GMarker(this.center, options);
		this.fullMap.addOverlay(marker);
	}
}

ObjectMap.prototype.initMapLegend = function() {
	var that = this;
	this.infraLegendList = that.mainContainer.find("ul.map-descr:first");
	this.infraItems = this.mainContainer.find(".map-descr li");
	
		
	this.infraItems.each(function(){
		var infraItem = $(this);
		var infraLink = $("a", this);
		var infraTypeID = (id = String($(this).attr("class")).match(/type_(\d+)/)) ? id[1] : null;
		if (infraTypeID) {
			this.infraTypeID = infraTypeID;
			new Tooltip (infraLink);
			infraLink.click(function(e) {
				if (!that.infraLegendList.hasClass('loading')) {
					if (!infraItem.children("a").hasClass("active")) {
						// load and show markers
						infraItem.children("a").addClass("active");
						that.infraLegendList.addClass('loading');
						that.addObjectType(infraTypeID);
					} else {
						// switch off button
						infraItem.children("a").removeClass("active");
						// hide markers
						that.removeObjectType(infraTypeID);
					}
				}
			});
		}
		
	})
}

ObjectMap.prototype.loadInfraItems = function() {
	var that = this;
	this.infraItems.each(function(){
		that.addObjectType(this.infraTypeID);
		$("a", this).addClass("active");
	})
}


ObjectMap.prototype.initPostLoad = function() {
	var that = this;
	this.loadTimeout = null;
	this.bounds = this.fullMap.getBounds();
	// Map interaction start
	GEvent.addListener(this.fullMap, "movestart", function start() {
		// stop previous loading
		if (that.loadTimeout) clearTimeout(that.loadTimeout);
	});
	// Map interaction end
	GEvent.addListener(this.fullMap, "moveend", function() { that.postLoad(); });
	GEvent.addListener(this.fullMap, "zoomend", function() { that.postLoad(); });
}

ObjectMap.prototype.getAjaxUrl = function(exBounds) {
	// objects limit
	var limit  = this.getLimit();
	// visible objects
	var objects = []
	// get objects limits for each type 
	var needle = [];
	// process each object type
	var that = this;
	$.each(this.getObjectTypes(), function() {
		// get objects by type
		list = that.getVisibleObjects(this);
		// merge objects lists
		objects = objects.concat(list);
		// check their count
		if (list.length < limit) {
			if (this == '0') {
				needle.push("limit[" + this + "]= 0");
			} else {
				needle.push("limit[" + this + "]=" + (limit - list.length));
			}
		}
	});
	// return null if map is full
	if (!needle.length) {
		return null;
	}
	// compile url
	var params = [];
	// current map viewport bounds
	var bounds = this.fullMap.getBounds();
	params.push("bs=" + bounds.getSouthWest().lat());
	params.push("bw=" + bounds.getSouthWest().lng());
	params.push("bn=" + bounds.getNorthEast().lat());
	params.push("be=" + bounds.getNorthEast().lng());
	// exclude bounds
	if ((exBounds instanceof GLatLngBounds) && !(exBounds.containsBounds(bounds))) {
		params.push("es=" + exBounds.getSouthWest().lat());
		params.push("ew=" + exBounds.getSouthWest().lng());
		params.push("en=" + exBounds.getNorthEast().lat());
		params.push("ee=" + exBounds.getNorthEast().lng());
	}
	// objects limit
	$.each(needle, function() { params.push(this); });
	// exclude existing objects
	var excludeObjs = [];
	$.each(objects, function() { excludeObjs.push(this.getId()); });
	params.push("exclude=" + excludeObjs.join(","));
	// base url
	var url = this.getFormAction();
	if (params) {
		url += (url.indexOf("?") < 0 ? "?" : "&") + params.join("&");
	}
	return url;
}

ObjectMap.prototype.postLoad = function(typeOfInfraObject) {
	var that = this;
	//set frequency if it hasnt been done yet
	if (!this.frequency) this.setFrequency();
	// stop previous loading
	if (this.loadTimeout) clearTimeout(this.loadTimeout);
	// set timeout to load items
	this.loadTimeout = setTimeout(function() {
		// url for get objects request
		var url = that.getAjaxUrl(that.bounds);	
		if (url !== null) {
			$.ajax({
				url: url,
				dataType: 'json',
				success: function(objects){
					$.each(objects, function(){
						if (this.id) {
							var options = {};
							if (this.icon) {
								var icon = new GIcon();
								if (this.isInfra) {
									icon.iconSize = new GSize(15, 15);
								} else {
									icon.iconSize = new GSize(16, 16);
								}
								icon.iconAnchor = new GPoint(0, 0);
								icon.infoWindowAnchor = new GPoint(9, 2);
								icon.image = this.icon;
								options.icon = icon;
							}
							var marker = new GMarker(new GLatLng(this.lat, this.lng), options);
							that.addMarker(marker, this.id, this.info, this.type);
						}
					});
					that.infraLegendList.removeClass('loading');
				}
			})
		}
	}, this.getLoadTimeout())
	// remember new bounds
	this.bounds = this.fullMap.getBounds();
}

ObjectMap.prototype.addMarker = function(marker, id, w, type) {
	if (marker instanceof GMarker && id) {
		// object type
		type = parseInt(type) ? parseInt(type) : 0;
		// create marker types list if not exists
		if (!(this.markers instanceof Object)) {
			this.markers = {};
			this.markersIds = {};
		}
		// create markers list if not exists
		if (!(this.markers[type] instanceof Array)) {
			this.markers[type] = new Array();
			this.markersIds[type] = new Array();
		}
		// check marker for non-existance
		if ($.inArray(id, this.markersIds[type]) < 0) {
			// info window node
			w = $(w)[0];
			// bind info window for this marker
			marker.bindInfoWindow(w, {maxWidth: 339});
			GEvent.addListener(marker, "infowindowopen", function() { 
				//$("#object_" + this.getId()).trigger("#select") 
			});
			// get-method to retrieve marker id
			marker.getId = function () { return id; }
			// add marker to list
			this.markers[type].push(marker);
			// add marker id to list
			this.markersIds[type].push(id);
			// add marker on map as overlay
			this.fullMap.addOverlay(marker);
		}
	}
}

ObjectMap.prototype.addObjectType = function(type) {
	type = parseInt(type);
	if (type > 0) {
		// add object type
		this.getObjectTypes().push(type);
		// remember in cookie
		$.cookie("infrastructure", this.getObjectTypes().join("+"), {href: "/"});
		// reload markers
		this.postLoad(type);
	}
}

ObjectMap.prototype.removeObjectType = function(type) {
	type = parseInt(type);
	if (type > 0) {
		// remove object type
		this.objectTypes = $.grep(this.getObjectTypes(), function(id) { return id != type; });
		// remember in cookie
		$.cookie("infrastructure", this.getObjectTypes().join("+"), {href: "/"});
		// remove markers
		if (this.markers && (this.markers[type] instanceof Array)) {
			var marker = null;
			while (marker = this.markers[type].pop()) {
				this.fullMap.removeOverlay(marker);
			}
			this.markersIds[type] = [];
		}
	}
}

ObjectMap.prototype.getLoadTimeout = function() {
	return 500;
}

ObjectMap.prototype.getObjectTypes = function() {
	if (!(this.objectTypes instanceof Array)) {
		this.objectTypes = new Array();
		// add zero object type, common building
		this.objectTypes.push(0);
	}
	return this.objectTypes;
}

ObjectMap.prototype.getVisibleObjects = function(type) {
	type = parseInt(type) ? parseInt(type) : 0;
	if (this.markers && this.markers[type]) {
		var bounds = this.fullMap.getBounds();
		return $.grep(this.markers[type], function(m){
			return bounds.containsLatLng(m.getPoint());
		});
	} else {
		return [];
	}
}

ObjectMap.prototype.getLimit = function() {
	var square = this.fullMap.getSize().width * this.fullMap.getSize().height;
	return (square / 10000) * this.getFrequency();
}

ObjectMap.prototype.getFrequency = function() {
	return this.frequency;
}

ObjectMap.prototype.setFrequency = function() {
	// object frequency (objects per 100*100 px square)
	var data = String(this.mainContainer.attr("class"));
	var limit = data.match(/limit_([1-9]\d*)/);
	if (limit) {
		var square = this.fullMap.getSize().width * this.fullMap.getSize().height;
		this.frequency = parseInt(limit[1]) / (square / 10000);
	}
}

ObjectMap.prototype.getFormAction = function() {
	return this.mainContainer.attr("action");
}


;

/**** script/feedback-form.js ****/
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

function FeedbackForm(options) {
	this.defaults = {
		formContainer: "#requestForm",
		form: "#feedbackForm",
		error: "#failedRequestSending",
		success: "#successfulRequestSending",
		loading: "#sendingRequestIndicator",
		switchers: ".switcher"
	}
	this.options = $.extend(this.defaults, options);
	
	this.formContainer = $(this.options.formContainer);
	if (!this.formContainer.length) return;
	this.form = $(this.options.form);
	this.submitButton = $("input.send", this.form);
	this.errorContainer = $(this.options.error);
	this.successContainer = $(this.options.success);
	this.loadingIndicator = $(this.options.loading);
	this.isIE = jQuery.browser.msie;
	
	this.initFeedbackForm(); 
}

FeedbackForm.prototype.initFeedbackForm = function() {
	this.initSubmitHandler();
	this.initSubmitButtonHandler();
	this.initSwitchers()
}

FeedbackForm.prototype.initSubmitHandler = function() {
	this.form.submit(function(){
		return false;
	})
}

FeedbackForm.prototype.initSwitchers = function() {
	commonControls.switcher(this.form.find(this.options.switchers), "selected", "");
}

FeedbackForm.prototype.initSubmitButtonHandler = function() {
	var that = this;
	
	this.submitButton.click(function(){
		var params = that.form.serialize() + "&" + $(this).attr("name") + "=" + $(this).val();
		var url = that.form.attr('action');
		that.updateLoadingIndicator();
		that.errorContainer.hide();
		$.ajax({
			url: url,
			type: 'POST',
			data: params,
			dataType: 'json',
			success: function(objects) {
				that.processResponse(objects)
			}
		});
	})
}

FeedbackForm.prototype.updateLoadingIndicator = function() {
	this.loadingIndicator.toggle("medium");
}

FeedbackForm.prototype.processResponse = function(objects) {
	var that = this;
	this.updateLoadingIndicator();
	if(objects.success) {
		this.errorContainer.hide();
		that.successContainer.show("slow");
		if (false) {
			that.formContainer.animate({"height" : 0, border: "none" }, function(){
				setTimeout(function() {
					that.successContainer.hide("slow")
				}, 2500);
			})
		} else {
			that.formContainer.hide();
			setTimeout(function() {
				that.successContainer.hide("slow")
			}, 2500);
		}
	} else {
		this.successContainer.hide();
		var errorsList = this.getErrorsList(objects.error);
		this.errorContainer.find("ul").remove();
		this.errorContainer.append(errorsList).show("slow");
	}
}

FeedbackForm.prototype.getErrorsList = function(errors) {
	if (errors.length) {
		var errorsList = $("<ul></ul>");
		$.each(errors, function(){
			var listElement = $("<li>" + this.toString().trim() + "</li>");
			errorsList.append(listElement);
		})
		return errorsList;
	}
}

;

/**** script/object.js ****/
$(document).ready(function(){
	new FeedbackForm();
})

// callback function for swf file (3D model of building)
function helloDolly()
{
	$("#rightColumn").children(".card-previews:first").children("li").removeClass('selected');
	$("#rightColumn").children(".card-previews:first").children("li.card-swf").addClass('selected').trigger('click');	
}

// init right column interaction on document loading
$(document).ready(function() {
	
/*******************************************************************
************************OBJECT DETAILS BLOCK INTERACTION
*******************************************************************/

$('#objectsDetails').children().each(function(){
	var listElement = $(this);
	var h3Element = $(this).children("h3");
	var content = $(this).children(".content");
	h3Element.click(function(){
		listElement.toggleClass("closed");
	})
})

	
/*******************************************************************
************************FAVOURITES
*******************************************************************/
var favStar = $("#address span.addToFavourite");
if (favStar.length) {
	favStar.click(function(){
		toggleFavourite(favStar, this.id)
	})
	var numberOfFavObjects = $('#newHeader ul.toolbar a.fav span span');
	
	function toggleFavourite(star, objectID) {
		if (star && objectID) {
			var isFavourite = star.hasClass("favourite");
			star.toggleClass("favourite");
			var urlPrefix = isFavourite ? "/fav/unset/" : "/fav/set/";
			
			$.ajax({
				url: urlPrefix + objectID,
				dataType: 'json',
				success: function(response){
					
					if (response.state == 1) {
						if(!star.hasClass("favourite")) {
							star.addClass("favourite")
						}
					} else if (response.state == 0) {
						if(star.hasClass("favourite")) {
							star.removeClass("favourite")
						}
					}
					
					if (response.count > 0 && numberOfFavObjects.length) {
						var updatedNumberOfFavObj;
						if (response.count > 1) {
							updatedNumberOfFavObj = response.count + L('js_number_of_fav_objects')
						} else {
							updatedNumberOfFavObj = response.count + L('js_number_of_fav_object')
						}
						numberOfFavObjects.text(updatedNumberOfFavObj);
					}
				}
			})
		}
	}
}



/*******************************************************************
************************OBJECTS NAVIGATOR INTERACTION
*******************************************************************/

var nextObjectLink = $('#objectsNavigator').children('a.next');
var prevObjectLink = $('#objectsNavigator').children('a.prev');
var prevObjectDetails = $('#objectsNavigator').children('.prevObjectDetails');
var nextObjectDetails = $('#objectsNavigator').children('.nextObjectDetails');

nextObjectLink.mouseover(function(){
	prevObjectLink.removeClass('activePrev');
	prevObjectDetails.hide();
	$(this).addClass('activeNext');
	nextObjectDetails.show();
	
})
prevObjectLink.mouseover(function(){
	nextObjectLink.removeClass('activeNext');
	nextObjectDetails.hide();
	$(this).addClass('activePrev');
	prevObjectDetails.show();
})
	
/*******************************************************************
************************RIGHT COLUMN INTERACTION
*******************************************************************/	
	// sidebar object
	var rightColumn = $("#rightColumn");
	// illustration node
	var illustration = rightColumn.children(".card-illustration:first");
	// photo container
	var photo = illustration.children("img:first");
	// init container for loading indicator
	var loadingIndicator = illustration.children(".loading-img:first");
	// map container
	var map = illustration.find('#map .mapContainer');
	//infra items legend container
	var infraLegend = map.siblings(".mapDescriptionContainer");
	// photo and map previews
	var previews = rightColumn.children(".card-previews:first").children("li");
	// swf file container
	var swfLayer = illustration.children("#swfLayer");
	//source link
	var sourceLink = $('.agencyInfo .agencyLogo');
	
	sourceLink.click(function(){ 
		// get object id
		var data = String($('#objectsDetails').attr("class"));
		var objectID  = data.match(/object_([1-9]\d*)/);
		objectID = parseInt(objectID[1]);
		if (!isNaN(objectID)) {
			$('#footer').append($('<img src="/count/object/' + objectID + '"/>'));
		}
	})
	
	//hide loading indicator as new photo is loaded
	photo.load(function() {
		illustration.removeClass('loading');
	});
	// photo preview nodes handlers
	previews.each(function() {
		var item = $(this);
		
		// highlight thumbnails on hover
		function toggle() {
			if (!item.hasClass("selected")) {
				item.toggleClass("active");
			}
		}
		
		// select item on click
		function select() {
			item.siblings("li").removeClass("selected");
			item.addClass("selected").removeClass("active");
		}
		
		if ($(this).hasClass("card-map")) {
			$(this).mouseover(toggle).mouseout(toggle).click(function() {
				// select preview (highlight)
				select();
				// hide photo
				photo.hide();
				//hide swf file
				swfLayer.hide();
			});
		} else if ($(this).hasClass("card-swf")) {
			var url = item.children("a:first").attr("href");
			swfobject.embedSWF('/img/swf/3d.swf', "swfLayerContentThumb", "124", "94", "8.0.0", false, {jsfnname:"helloDolly();"});
			
			$(this).mouseover(toggle).mouseout(toggle).click(function() {
				// select preview (highlight)
				select();
				// show SWF
				swfobject.embedSWF(url, "swfLayerContent", "392", "328", "10.0.0");
				// and hide map;
				map.parent().hide();
				photo.hide();
				swfLayer.show();
			});
			
		} else {
			// prevent link click
			$(this).children("a").click(function() { return false; });
			// change main photo
			$(this).find("img").mouseover(toggle).mouseout(toggle).click(select).click(function(e) {
				// select preview (highlight)
				select();
				// show loading indicator
				illustration.addClass('loading');
				// switch photo
				photo.attr("src", item.children("a:first").attr("href"));				
				//hide map;
				map.parent().hide();
				swfLayer.hide();
				// show photo
				photo.show();
			});
		}
		//show flash movie if there's no photos of this object
		if ($(this).hasClass("card-swf") && $(this).hasClass("selected") ) {
			helloDolly();
		}
	});

	
/*******************************************************************
 ************************GOOGLE MAP INTERACTION
 *******************************************************************/	
	// map latitude and longitude
	var data = String(map.parent().attr("class"));
	var lat = data.match(/lat_(\-?\d+(?:\.\d+)?)/);
	lat = lat ? parseFloat(lat[1]) : null;
	var lng = data.match(/lng_(\-?\d+(?:\.\d+)?)/);
	lng = lng ? parseFloat(lng[1]) : null;
	
	if (lat && lng) {
		_initGoogleMap = function(){
			new ObjectMap(map, previews, photo);
		}
		if ($.isFunction(window.GMap2)) {
			_initGoogleMap();
		} else if (googleMapsApiSrc) {
			var api = googleMapsApiSrc + "&c&async=2&callback=_initGoogleMap";
			$("head:first").append("<script type='text/javascript' src='" + api + "'> </script>");
		}
	}
	
/*******************************************************************
 ************************LEAVE COMMENT FORM
 *******************************************************************/	
	
	$('#userComments').each(function(){
		var commentsBlock = $(this);
		var h3Element = $(this).children("h3");
		h3Element.click(function(){
			commentsBlock.toggleClass("closed");
		})
	})
	
	//initializing form handlers
	var commentForm = $('#commentForm');
	var submitButton = commentForm.find("input[@type='submit']")
	commentForm.find(".userName").each(function() {
		initInputFieldHandler($(this), submitButton);
	})
	var listOfComments = $('#userComments').find(".comments").children();
	listOfComments.each(function(){
		var that = this;
		
		var deleteCommentLink = $(this).find('.delete');
		
		deleteCommentLink.click(function(){
			$.ajax({
				url: $(this).attr("href"),
				type: 'GET',
				dataType: 'json',
				success: function(objects) {
					
				}
			});
			
			$(that).remove();
			return false;
		});
		
		var hideCommentLink = $(this).find('.dirty_hide');
		hideCommentLink.click(function(){
			var messageContent = $(that).children('.message');
			messageContent.toggle();
			$.ajax({
				url: $(this).attr("href"),
				type: 'GET',
				dataType: 'json',
				success: function(objects) {
					
				}
			});
			var newTextValue = messageContent.css("display") == 'none' ? L('object_comment_complain_rollback') : L('object_comment_complain');
			$(this).text(newTextValue)
			return false;
		})
	})
	
	function initInputFieldHandler(inputElement, submitButton) {
		
		//saving the initial value of input field
		var initialValue = L('object_comments_enter_name');
		
		//binding event listener for blurring - if the value of input after blurring is blank then restore initial value
		inputElement.blur(function(e){
			if (this.value == '') {
				this.value = initialValue;
				this.style.color = "#A2A2A2";
			}
		});
		
		//binding event listener for focusing - if the value of input field is equal to initial value then set it blank
		inputElement.focus(function(e){
			if (this.value == initialValue){
				this.value = '';
				this.style.color = '#000000';
			}
		});
		
		submitButton.click(function(){
			if (inputElement.attr('value') == initialValue) {
				inputElement.val('');
			}
		});
	}

});
;

/**** script/swfobject.js ****/
/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();
;
