/*
 * truly global variables
 */
var map = null;
var defaultMapLayer = null;
var defaults = {
	Bucharest : new VELatLong(44.441796480715766, 26.091385961716583),
	aerialZoom : 14,
	birdseyeZoom : 15,
	color : new VEColor(0, 150, 100, 1.0),
	fillColor : new VEColor(0, 150, 100, 0.5)
};
/*
 * layout hacks
 */
var layout = {
	hasMap : function() {
		$('body').addClass('has-map');
	},
	noMapPages : {
		error404 : 1,
		signin : 1,
		login : 1,
		apply : 1,
		resetRequest : 1
	},
	page : {
		width : 900
	},	
	//remember that 'class' is a reserved word in internet explorer
	toggleHTMLClass : function(elm, classs) {
		$(elm).hasClass(classs) ? $(elm).removeClass(classs) : $(elm).addClass(classs);
	},
	toggleText : function(elm, text1, text2) {
		$(elm).text() == text1 ? $(elm).html(text2) : $(elm).html(text1);
	},
	win : {
		width : 0,
		height : 0,
		getDim : function() {
			this.width = $(window).width();
			this.height = $(window).height();
		}
	}	
};
/*
 * project zones
 */
var zones = {
	labirint : [ "Labirint", [ new VELatLong(44.4312363276731, 26.12386822700502), new VELatLong(44.43027098749665, 26.12436175346375), new VELatLong(44.42996452696347, 26.12052083015441), new VELatLong(44.43011775743092, 26.118696928024292), new VELatLong(44.42970403424685, 26.11698031425478), new VELatLong(44.42829428881452, 26.116572618484494), new VELatLong(44.42745148997948, 26.115370988845832), new VELatLong(44.42743616625182, 26.113740205764767), new VELatLong(44.42823299476353, 26.1122167110443), new VELatLong(44.43005646529214, 26.11148715019225), new VELatLong(44.43168068525251, 26.111723184585575), new VELatLong(44.432584712657686, 26.11217379570006), new VELatLong(44.43269196921845, 26.112903356552113), new VELatLong(44.43191052405408, 26.11386895179749), new VELatLong(44.43246213349004, 26.11451268196106), new VELatLong(44.43256939027578, 26.11547827720643), new VELatLong(44.432814547904, 26.117516756057746), new VELatLong(44.43287583715038, 26.119769811630267), new VELatLong(44.43215568444616, 26.11964106559755), new VELatLong(44.43217100693652, 26.12092852592469) ], defaults.color, defaults.fillColor ],
	calarasilor : [ "Calea Calarasilor", [ new VELatLong(44.43233955406532, 26.13787472248078), new VELatLong(44.43194883043313, 26.137939095497142), new VELatLong(44.43150447489249, 26.13502085208893), new VELatLong(44.43138955480626, 26.13146960735323), new VELatLong(44.43199479805485, 26.12868010997774), new VELatLong(44.43251576190752, 26.123991608619697), new VELatLong(44.433090349006484, 26.119839549064633), new VELatLong(44.43323591017469, 26.115869879722602), new VELatLong(44.432829870221624, 26.112619042396545), new VELatLong(44.43270729156819, 26.11209332942962), new VELatLong(44.43229358671476, 26.11166417598725), new VELatLong(44.43261535740942, 26.111395955085765), new VELatLong(44.43310567125178, 26.112501025199904), new VELatLong(44.43340445423233, 26.114410758018494), new VELatLong(44.433572997803864, 26.11638486385345), new VELatLong(44.43337380989437, 26.120504736900326), new VELatLong(44.43271495274158, 26.125043034553524), new VELatLong(44.43225528056167, 26.128808856010426), new VELatLong(44.43223995809341, 26.1294847726822), new VELatLong(44.43240850502337, 26.130149960517887), new VELatLong(44.431872217649925, 26.132263541221608), new VELatLong(44.43202544311591, 26.134462952613845), new VELatLong(44.43209439444455, 26.136276125907912) ], defaults.color, defaults.fillColor ],
	magheru : [ "Bulevardul Magheru", [ new VELatLong(44.435557178758856, 26.100275516510017), new VELatLong(44.43635389655561, 26.104567050933845), new VELatLong(44.43868270167809, 26.102335453033447), new VELatLong(44.441562937517084, 26.1005759239197), new VELatLong(44.44732298323658, 26.097486019134525), new VELatLong(44.446526415010474, 26.09503984451293), new VELatLong(44.44009219653099, 26.098558902740464) ], new VEColor(255, 215, 100, 1.0), new VEColor(255, 215, 100, 0.5) ],
	bastiliei : [ "Caderea Bastiliei", [ new VELatLong(44.451680938254874, 26.094149351119988), new VELatLong(44.45188006375619, 26.09587669372558), new VELatLong(44.45050914751374, 26.09675645828247), new VELatLong(44.449153517129076, 26.097013950347915), new VELatLong(44.44796635733524, 26.097056865692153), new VELatLong(44.44703193072107, 26.096917390823354), new VELatLong(44.447024271424766, 26.096380949020386), new VELatLong(44.44773658168492, 26.095908880233775), new VELatLong(44.44867099702662, 26.09558701515197), new VELatLong(44.44967432800452, 26.095222234725963), new VELatLong(44.45060871234686, 26.094825267791755) ], defaults.color, defaults.fillColor ],
	catargiu : [ "Lascar Catargiu", [ new VELatLong(44.45180347710526, 26.085893511772163), new VELatLong(44.45203323675674, 26.08631193637849), new VELatLong(44.4520715299441, 26.087030768394467), new VELatLong(44.45175752506649, 26.087685227394115), new VELatLong(44.45130566142621, 26.088650822639455), new VELatLong(44.450432559065085, 26.090421080589284), new VELatLong(44.44940626416333, 26.092373728752154), new VELatLong(44.4483186782435, 26.094658970832835), new VELatLong(44.44723873134175, 26.096708178520192), new VELatLong(44.44690938185961, 26.096815466880795), new VELatLong(44.44675619542125, 26.09641849994659), new VELatLong(44.44746084971142, 26.09513103961945), new VELatLong(44.44865567886284, 26.092845797538764), new VELatLong(44.44981984786024, 26.090624928474444), new VELatLong(44.451045263842275, 26.088114380836483), new VELatLong(44.45155074044463, 26.086633801460255) ], defaults.color, defaults.fillColor ],
	filipescu : [ "Filipescu", [ new VELatLong(44.459423356715924, 26.092175245285034), new VELatLong(44.45907110279604, 26.09232544898988), new VELatLong(44.45757017097096, 26.090651750564568), new VELatLong(44.45599261940642, 26.089042425155654), new VELatLong(44.45565566112126, 26.088141202926643), new VELatLong(44.45545654849339, 26.087347269058228), new VELatLong(44.45548718124956, 26.086424589157094), new VELatLong(44.459193626139644, 26.086446046829213), new VELatLong(44.45949993337381, 26.086510419845578), new VELatLong(44.459362095317296, 26.0868537425995), new VELatLong(44.45931614922615, 26.087862253189083), new VELatLong(44.45931614922615, 26.089664697647112) ], defaults.color, defaults.fillColor ]
	//departFirstDay : new VELatLong(44.42924433838537, 26.109714210033417), 
	//arriveFirstDay : new VELatLong(44.4545069250817, 26.084128618240374), 
	//departSecondDay : new VELatLong(44.4450251607497, 26.106042265892032), 
	//arriveSecondDay : new VELatLong(44.4545069250817, 26.084128618240374)
};


var contest = {
	firstDay : {
		from : zones.departFirstDay,
		fromTitle : 'Punctul de plecare',
		fromDescription : 'Barfly, pe strada Olteni, nr. 3. Mai multe detalii despre <a href="/detalii-concurs#menu">desf&#259;&#537;urarea concursului</a>.',
		fromPhotoURL : 'http://bucuresti.24fun.ro/out/big/locations/barfly/d6297bfBarfly5.jpg',
		to : zones.arriveFirstDay,
		toTitle : 'Punctul de sosire',
		toDescription : 'Muzeul &#538;&#259;ranului Rom&#226;n, &#537;oseaua Kiseleff nr. 3 (intrarea Monet&#259;riei). S&#226;mb&#259;t&#259;, 29 mai 2010 &#537;i duminic&#259;, 30 mai 2010 c&#259;ut&#259;torii Bucurestiului pierdut sunt a&#537;teptati s&#259; ne aduc&#259; cele g&#259;site. Se ofer&#259; recompens&#259; la fa&#539;a locului echipei c&#226;stig&#259;toare!',
		zones : [ zones.labirint, zones.calarasilor, zones.magheru ],
		zoomLevel : 13
	},
	secondDay : {
		from : zones.departSecondDay,
		fromTitle : 'Punctul de plecare',
		fromDescription : 'Ceain&#259;ria Serendipity, pe strada Dumbrava Ro&#537;ie, nr. 12. Mai multe detalii despre <a href="/detalii-concurs#menu">desf&#259;&#537;urarea concursului</a>.',
		fromPhotoURL : 'http://storage0.dms.mpinteractiv.ro/media/401/401/6348/2600521/1/ceaiserend2.jpg',
		to : zones.arriveSecondDay,
		toTitle : 'Punctul de sosire',
		toDescription : 'Muzeul &#538;&#259;ranului Rom&#226;n, &#537;oseaua Kiseleff nr. 3 (intrarea Monet&#259;riei). S&#226;mb&#259;t&#259;, 29 mai 2010 &#537;i duminic&#259;, 30 mai 2010 c&#259;ut&#259;torii Bucurestiului pierdut sunt a&#537;teptati s&#259; ne aduc&#259; cele g&#259;site. Se ofer&#259; recompens&#259; la fa&#539;a locului echipei c&#226;stig&#259;toare!',
		zones : [ zones.bastiliei, zones.catargiu, zones.filipescu ],
		zoomLevel : 14
	}
};


var project = {
	showDay : function(day) {
		map.Clear();
		//do not populate the map with other pins
		map.DetachEvent('onendzoom', mapProxy.fetchMarkers);
		map.DetachEvent('onendpan', mapProxy.fetchMarkers);
		//if for whatever reason the map's native layer is hidden, then show it
		if (!mapProxy.findLayer('Unsaved Collection').IsVisible()) mapProxy.findLayer('Unsaved Collection').Show();
		map.SetMapStyle(VEMapStyle.Road);
		for ( var zone in day.zones) {
			project.drawZone(day.zones[zone]);
			/*
			 * for ( var corner in day.zones[zone][1]) {
			 * corners.push(day.zones[zone][1][corner]); // push each corner in
			 * a big array }
			 */
		}
		/*
		 * center and zoom
		 */
		project.setView( [ day.from, day.to ], day.zoomLevel);
		/*
		 * departure
		 */
		var from = new VEShape(VEShapeType.Pushpin, day.from);
		from.SetTitle(day.fromTitle);
		from.SetDescription(day.fromDescription);
		from.SetCustomIcon('<img src="' + MapConfig.greenMarker + '">');
		from.SetPhotoURL(day.fromPhotoURL);
		map.AddShape(from);
		/*
		 * arrival
		 */
		var to = new VEShape(VEShapeType.Pushpin, day.to)
		to.SetTitle(day.toTitle);
		to.SetDescription(day.toDescription);
		to.SetCustomIcon('<img src="' + MapConfig.redMarker + '">');
		to.SetPhotoURL('http://www.casadincasa.ro/images/articole/cache/casa_foto_500_333.jpg');
		map.AddShape(to);
	},
	showDays : function() {
		// Nu e necesar
		//map.Clear();
		if (!mapProxy.findLayer('Unsaved Collection').IsVisible()) mapProxy.findLayer('Unsaved Collection').Hide();		
		for ( var dayName in contest) {
			var day = contest[dayName];
			for ( var zone in day.zones) {
				project.drawZone(day.zones[zone]);
			}
		}
		// project.setView( [ contest.firstDay.from, contest.secondDay.to ],
		// defaults.aerialZoom);
		map.SetCenterAndZoom(new VELatLong(44.438927833660216, 26.107549667358416), defaults.aerialZoom);
	},
	drawZone : function(zone) {
		// Numai daca e si array, da?
		if (zone instanceof Array && zone[1].length > 0) {
			var shape = new VEShape(VEShapeType.Polygon, zone[1]);
			shape.SetLineWidth(3);
			shape.SetLineColor(new VEColor(0, 150, 100, 0.2));
			shape.SetFillColor(new VEColor(0, 150, 100, 0.5));
			shape.SetTitle(zone[0]);
			shape.SetCustomIcon('<img src="' + MapConfig.blackMarker + '">');
			map.AddShape(shape);
		};
	},
	setView : function(zones, zoomLevel) {
		if (zones.length > 0) {
			map.SetMapView(zones);
			map.SetZoomLevel(zoomLevel);
		}
	}
};
/*
 * our little map API
 */
var mapProxy = {
	// add marker on map
	addCase : function(latLong, pixel) {
		$.get(MapConfig.addMarkerUrl, {
			lat : latLong.Latitude,
			lng : latLong.Longitude
		}, function(data) {
			mapProxy.addPin(latLong, MapConfig.pictMarker, 'defaultMapLayer', '', '', '');
			mapProxy.addCaseForm(data, latLong, pixel);
		});
	},
	// the form with which you add a marker on the map
	addCaseForm : function(data, latLong, pixel) {
		mapProxy.focusMap();		
		$('#add-marker, #add-marker-box').remove();
		$('#page').append(data);
		var MFLeft;
		var MFTop;
		var MFWidth = $('#add-marker').width();
		var MFHeight = $('#add-marker').height();
		if (pixel.x > layout.page.width + (layout.win.width-layout.page.width)/2 - MFWidth - 40) {
			//MFLeft = (layout.page.width + (layout.win.width-layout.page.width)/2) - MFWidth - 30;
			MFLeft = pixel.x - MFWidth - 35;
		} else {
			MFLeft = pixel.x + 15;
		};
		if (pixel.y + 200 < MFHeight) {
			MFTop = pixel.y + 200 - MFHeight + (MFHeight - (pixel.y+190)); 
		} else {
			MFTop = pixel.y + 165 - MFHeight;
			};
		$('#add-marker').css({left : MFLeft, top : MFTop});
		$('#add-marker .reset').live('click', function() {
			mapProxy.removeCaseForm();
		});
	},
	// in case someone wonders how to use the map
	addHelper : function(){
		if (getCookie('helperShown') != 'true') {
			$('#page').append('<div id="map-helper"></div>');
			map.AttachEvent('onclick', mapProxy.removeHelper);			
		};
		setCookie( 'helperShown', 'true', 1, '/', '', '' );
	},
	// adds a new layer to the map, based on the layer's title
	addLayer : function(layerTitle) {
		var layer = new VEShapeLayer();
		layer.SetTitle(layerTitle);
		map.AddShapeLayer(layer);
	},
	// this is called for every pin we add
	addPin : function(latLong, type, layerTitle, title, description, image) {
		var pinShape = new VEShape(VEShapeType.Pushpin, latLong);
		pinShape.SetCustomIcon('<img src="' + type + '">'); 
		if (title != '') pinShape.SetTitle(title);
		if (description != '') pinShape.SetDescription(description);
		if (image != '') pinShape.SetPhotoURL(image);
		if(layerTitle == 'defaultMapLayer') {
			if (defaultMapLayer == null) {
				defaultMapLayer = new VEShapeLayer;
				defaultMapLayer.SetTitle('defaultMapLayer');
				map.AddShapeLayer(defaultMapLayer);
			} else {
				defaultMapLayer.DeleteAllShapes();			
			};		
		};
		var targetLayer = mapProxy.findLayer(layerTitle);
		targetLayer.AddShape(pinShape);
		var markerID = pinShape.GetID();
	},
	addZone : function(zone, layerTitle) {
		// Numai daca e si array, da?
		if (zone instanceof Array && zone[1].length > 0) {
			var shape = new VEShape(VEShapeType.Polygon, zone[1]);
			shape.SetLineWidth(3);
			shape.SetLineColor(new VEColor(0, 150, 100, 0.2));
			shape.SetFillColor(new VEColor(0, 150, 100, 0.5));
			shape.SetTitle(zone[0]);
			shape.SetCustomIcon('<img src="' + MapConfig.blackMarker + '">');
			if(!mapProxy.findLayer(layerTitle)) mapProxy.addLayer(layerTitle);
			var targetLayer = mapProxy.findLayer(layerTitle);
			targetLayer.AddShape(shape);
		};
	},	
	addAllZones : function() {
		for (x in zones) {
			mapProxy.addZone(zones[x], 'protectedZones');
		};
	},
	centerAndZoom : function(latLong, zoom, mapStyle) {
		map.SetCenterAndZoom(latLong, zoom);	
		//nicht: merge oribil -> if (map.IsBirdseyeAvailable()) 
		if (mapStyle != '')
			map.SetMapStyle(mapStyle);		
	},
	// to be noted that clustering is available only for shapes that share the same parent layer 
	// when working with concomitent multiple layers, this is a drawback
	setClustering : function(layer) {
		var clusteringOptions =  new VEClusteringOptions();
		var clusteringIcon = new VECustomIconSpecification();
		clusteringIcon.Image = MapConfig.pictClusterMarker;
		// ie6 and webkit don't like the "for in" loop here
		function clusteringCallback(clusters) {
			for (var z=0; z<clusters.length; z++) {
			  var cluster = clusters[z];
			  var clusterShape = cluster.GetClusterShape();
			  // as opposed to people, arrays count from 0
			  clusterShape.SetTitle("Grup de semnale"); //+ (parseInt(z)+1));
			  clusterShape.SetDescription("&#206;n aceast&#259; zon&#259; sunt " + cluster.Shapes.length + " semnale de alarm&#259;!");
			}
		};
		clusteringOptions.Icon = clusteringIcon;
		clusteringOptions.Callback = clusteringCallback;
		layer.SetClusteringConfiguration(VEClusteringType.Grid, clusteringOptions);
	},
	// alert Opera users about Bing Maps/Opera bugs
	alertNonCompliantBrowser : function(){
		if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) $('#page').append('<div id="browser-alert">Bing Maps nu func&#539;ioneaz&#259; bine pe Opera. Din p&#259;cate, nu po&#539;i ad&#259;uga marker-e pe hart&#259;. Recomand&#259;m s&#259; instalezi <a href="http://getfirefox.com">Firefox</a>, <a href="http://www.google.com/chrome">Chrome</a>, <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">IE8</a> sau <a href="http://www.apple.com/safari/download">Safari</a>.</div>');
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
			var ieversion = new Number(RegExp.$1);
			if (ieversion == 6) {
				$('#page').append('<div id="browser-alert">Din p&#259;cate, o parte dintre func&#539;iile h&#259;r&#539;ii nu func&#539;ioneaz&#259; pe IE6. Recomand&#259;m s&#259; instalezi un browser superior: <a href="http://getfirefox.com">Firefox</a>, <a href="http://www.google.com/chrome">Chrome</a>, <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">IE8</a> sau <a href="http://www.apple.com/safari/download">Safari</a>.</div>');
			};
		};
	},
	// a collection of VELatLong objects, representing all the pins we've added to the map
	currentPinCollection : new Array,
	// add back previously removed functionality of the map
	defocusMap : function() {
	    map.DetachEvent('onmousemove', noMouse); map.DetachEvent('onmousewheel', noMouse); map.DetachEvent('ondoubleclick', noMouse); map.ShowControl(document.getElementById('MSVE_navAction_container')); $('#filters').removeClass('hidden');		
	},
	// fetch markers, create layers and populate the layers
	fetchMarkers : function() {
		var nW = map.PixelToLatLong(new VEPixel(0, 0));
		var sE = map.PixelToLatLong(new VEPixel(900, 414));
		$.get(MapConfig.markersUrl, {
			'boundingBox[nwLat]' : nW.Latitude,
			'boundingBox[nwLong]' : nW.Longitude,
			'boundingBox[seLat]' : sE.Latitude,
			'boundingBox[seLong]' : sE.Longitude
		}, function(data) {	
			for (var x in data) {
				// we don't know yet whether a certain pin is or not on the map
				var isPinInCollection = false;
				var pinComments = data[x].comment_count == '0' ? '0 comentarii. Ai putea fi primul!' : data[x].comment_count + ' comentarii. Bag&#259; &#537;i tu unul!';
				var pinLatLong = new VELatLong(data[x].lat, data[x].lng);
				var pinTitle = '<a class="ugly-hack" href="' + MapConfig.markerShowUrl + '/slug/' + data[x].slug + '"></a>' + data[x].title;
				var pinDescription = data[x].content + '<span>' + pinComments + '</span>';
				var pinImage = data[x].thumb == '' ? '' : MapConfig.markerThumbUrl + data[x].thumb;
				var pinLayerTitle = data[x].in_contest_zone == '1' ? "contestYes" : "contestNo";
				function addThisPin() {
					if(!mapProxy.findLayer(pinLayerTitle)) mapProxy.addLayer(pinLayerTitle);					
					mapProxy.addPin(pinLatLong, MapConfig.pictMarker, pinLayerTitle, pinTitle, pinDescription, pinImage);				
				}
				// we automatically put the first pin on the map
				if (mapProxy.currentPinCollection.length == 0) {
					mapProxy.currentPinCollection.push(pinLatLong);
					addThisPin();
				};
				// we check the pin collection array
				for (var y in mapProxy.currentPinCollection) {
					// is this pin on the map?
					if (mapProxy.currentPinCollection[y].Latitude == pinLatLong.Latitude && mapProxy.currentPinCollection[y].Longitude == pinLatLong.Longitude) {
						isPinInCollection = true;
					};
					// if we parsed the entire array and pin is not on map, then we should add it
					if (y == mapProxy.currentPinCollection.length-1 && isPinInCollection == false) {
						mapProxy.currentPinCollection.push(pinLatLong);
						addThisPin();
					};
				};
				// clustering is good. we shouldn't call this within addPin()
				mapProxy.setClustering(mapProxy.findLayer(pinLayerTitle));
//				console.log(mapProxy.findLayer(pinLayerTitle).GetShapeCount());
//				console.log(mapProxy.currentPinCollection.length);
			}
		}, 'json');	
	},
	// find a layer by title
	findLayer : function (layerTitle){
		for (var i = 0; i < map.GetShapeLayerCount(); i++) {
			if(layerTitle == map.GetShapeLayerByIndex(i).GetTitle()) return map.GetShapeLayerByIndex(i);
//			console.log(map.GetShapeLayerByIndex(i).GetTitle());
		}
	},
	// remove all of the map's functionality
	focusMap : function() {
	    map.AttachEvent('onmousemove', noMouse); map.AttachEvent('onmousewheel', noMouse); map.AttachEvent('ondoubleclick', noMouse); map.HideControl(document.getElementById('MSVE_navAction_container')); $('#filters:not(.outside)').addClass('hidden');		
	},
	// get an array with all the map's layers, either custom or native
	getAllLayers : function(){
		var myLayers = [];
		for (var i = 0; i < map.GetShapeLayerCount(); i++) {
			myLayers.push(map.GetShapeLayerByIndex(i));
		}
		return myLayers;
	},
	// due to copyright issues, we cannot retrieve lat long coordinates in birdseye view. actually, we can
	getBirdseyeViewLatLong : function(pixel) {
		var be = map.GetBirdseyeScene();
		var centrePixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());
		var currentPixelWidth = be.GetWidth();
		var currentPixelHeight = be.GetHeight();
		var mapDiv = document.getElementById("map");
		var mapDivPixelWidth = mapDiv.offsetWidth;
		var mapDivPixelHeight = mapDiv.offsetHeight;
		var xScreenPixel = centrePixel.x - (mapDivPixelWidth / 2) + pixel.x;
		var yScreenPixel = centrePixel.y - (mapDivPixelHeight / 2) + pixel.y;
		var position = be.PixelToLatLong(new VEPixel(xScreenPixel, yScreenPixel), map.GetZoomLevel())
		return (new _xy1).Decode(position);
	},
	// hide absolutely all the layers
	hideAllLayers : function() {
		for (var i = 0; i < map.GetShapeLayerCount(); i++) {
			map.GetShapeLayerByIndex(i).Hide();
		}		
	},
	// start the map
	init : function() {
		$('#header').after('<div id="map"></div>');
		/*
		 * we have map
		 */
		map = new VEMap('map');
		map.onLoadMap = layout.hasMap();
		map.EnableShapeDisplayThreshold(false);
		map.SetCredentials('AsD1EVdgLXubgn_sLId92ZJTvysSFLD0JXm_PgrZLc4wSfajsMeJsFOF1JEvcVMW');
		map.LoadMap();
		map.AttachEvent('onmousedown', mapProxy.rightClick);
		map.Resize(900, 414);
		/*
		 * default view
		 */
		map.SetMapStyle(VEMapStyle.Hybrid);
		map.SetCenterAndZoom(defaults.Bucharest, defaults.aerialZoom);
		/*
		 * fetch markers for the first time, add helper tooltip if cookie doesn't say otherwise
		 * and show contest days
		 */
		mapProxy.fetchMarkers();
		mapProxy.addHelper();
		//project.showDays();
		mapProxy.addAllZones();
		/*
		 * opera and ie6 don't work that well. the first with bing, the second with the script.
		 */		
		mapProxy.alertNonCompliantBrowser();
		/*
		 * when will we fetch markers again?
		 */		
		map.AttachEvent('onendzoom', mapProxy.fetchMarkers)
		map.AttachEvent('onendpan', mapProxy.fetchMarkers)		
		/*
		 * ugly hack to make beautiful link on marker info box at mouseover;
		 * map.SetMoreInfoURL is simply unusable
		 */				
		$('.ero-body').live('mouseover', function(){
			var eroBodyHeight = $(this).height();
			var eroBodyWidth = $(this).width();			
			$(this).find('.ugly-hack').css({
				height : eroBodyHeight + 'px',
				width : eroBodyWidth + 'px'				
			});
		});
	},
	// toggle a layer's visibility using its title
	showHideLayer : function(layerTitle) {
		var targetLayer = mapProxy.findLayer(layerTitle);
		targetLayer.IsVisible() ? targetLayer.Hide() : targetLayer.Show();
		mapProxy.toggleHTMLFilter(layerTitle);
	},
	// we make sure the user sees what layers are visible or not
	toggleHTMLFilter : function(layerTitle){
		var _filter = $('#'+ layerTitle);
		$(_filter).hasClass('active') ? $(_filter).removeClass('active') : $(_filter).addClass('active');
	},
	// cancel the add new marker form
	removeCaseForm : function() {
		$('#add-marker').remove();
		defaultMapLayer.DeleteAllShapes();
		mapProxy.defocusMap();
	},
	// what happens at right click?
	rightClick : function(e) {
		if (e.rightMouseButton == true) {
			var x = e.mapX;
			var y = e.mapY;
			var pixel = new VEPixel(x, y);
			switch (map.GetMapStyle()) {
			case VEMapStyle.Birdseye:
				var pixelLatLong = mapProxy.getBirdseyeViewLatLong(pixel);
				break;
			case VEMapStyle.BirdseyeHybrid:
				var pixelLatLong = mapProxy.getBirdseyeViewLatLong(pixel);
				break;
			default:
				var pixelLatLong = map.PixelToLatLong(pixel);
				break;
			}
			mapProxy.addCase(pixelLatLong, pixel);
		};
	},
	// removes the 'how to use the map' label
	removeHelper : function(){
		$('#map-helper').remove();
	}
};

$(function() {
	/*
	 * "console"
	 */
	if (!window.console) {
		window.console = {
			log : function(args) {
				return false;
			}
		}
	}
	/*
	 * move them boxes around like depending on resolution
	 */
	layout.win.getDim();
	if (layout.win.width >= 1132) 
		$('#filters, #log-pie, #pukka').addClass('outside');
	$(window).resize(function() {
		layout.win.getDim();
		if (layout.win.width >= 1132) {
			$('#filters, #log-pie, #pukka').addClass('outside');
		} else {
			$('#filters, #log-pie, #pukka').removeClass('outside');
		}
	});
	/*
	 * some pages don't do maps
	 */
	var bodyClass = $('body').attr('class');
	if (!(bodyClass in layout.noMapPages)) 
		mapProxy.init();
	/*
	 * hide markers' filters and show 'back' link when choosing to see the competition's zones
	 */		
	$('.filter#days ul li a').bind('click', function(){
		$('.filter#markers').addClass('hidden');
		$('.filter#get-out-of-here').removeClass('hidden');
	});		
	/*
	 * 'shorten' the blogs' box
	 */
	$('.box.blogs').addClass('collapsed');
	$('.box.blogs ul li:gt(4)').addClass('toggle');
	$('.box.blogs span.expand').bind('click', function(){
		layout.toggleHTMLClass('.box.blogs', 'collapsed');
		layout.toggleText('.box.blogs span.expand', 'Mai mult >', 'Mai pu&#355;in >')
	});
	/*
	 * auto-select code textareas
	 */
	$('.code textarea').bind('click', function() {
		$(this).select();
	});
	/*
	 * space age mail obfuscation
	 */
	$('span#dgh21R').replaceWith('<a href="mailto:pos' + 'ta@' + 'bucurestiulpie' + 'rdut.r' + 'o">post' + 'a@bucu' + 'restiulpierd' + 'ut.ro</a>');
	/*
	 * hack to show the marker photo's file input value
	 */	
	$('input#marker_photo').live('change', function(){
		$('div.file div').html($('input#marker_photo').val());
	});
	/*
	 * Facebook Friends .|. cache hack
	 */
	var cache = jQuery.ajaxSettings.cache;
	jQuery.ajaxSettings.cache = true;
	FB.init("97e49991d8c93a278807c102bb5faff3", 
		"http://bucurestiulpierdut.ro/web/xd_receiver.htm", {
			"reloadIfSessionStateChanged" : false, 
			"doNotUseCachedConnectState" : false
		}
	); 
	/*
	 * back to normal cache
	 */
	jQuery.ajaxSettings.cache = cache;
	/*
	 * stupid ie6
	 */
	$('.story .photo').hover(
		function(){$(this).addClass('hover')},
		function(){$(this).removeClass('hover')}
	);
	/*
	 * ugly
	 */
	$('div.toggle:not(:first)').addClass('hidden');
	$('.box ul.menu li:first').addClass('current');	
	// futu-te, ie6
	$('div.toggle:first').removeClass('hidden');
	$('.box ul.menu li a').bind('click', function(){
		var cine = $(this).attr('href');
		$('div.toggle').addClass('hidden');
		$(cine).removeClass('hidden');
		$('.box ul.menu li.current').removeClass('current');
		$(this).parent('li').addClass('current');
		return false;
	});
	if ($('input#similar-events_no:checked').length > 0) {
		$('input#what-events').parent('div').addClass('hidden');
	}
	$('input#similar-events_yes').click(function() {
		$('input#what-events').parent('div').removeClass('hidden');
	});
	$('input#similar-events_no').click(function() {
		$('input#what-events').parent('div').addClass('hidden');
	});
	if ($('input#another-person_no:checked').length > 0) {
		$('input#name-second-person').parent('div').addClass('hidden');
	}
	$('input#another-person_yes').click(function() {
		$('input#name-second-person').parent('div').removeClass('hidden');
	});
	$('input#another-person_no').click(function() {
		$('input#name-second-person').parent('div').addClass('hidden');
	});
	if ($('input#signin_chooseType_1:checked').length > 0) {
		$('input#signin_password').parent('div').addClass('hidden');
	}
	$('input#signin_chooseType_2').click(function() {
		$('input#signin_password').parent('div').removeClass('hidden');
	});
	$('input#signin_chooseType_1').click(function() {
		$('input#signin_password').parent('div').addClass('hidden');
	});
});
/*
 * Several functions we sometimes need
 */
function noMouse() {
	return true;
};
function setCookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime( today.getTime() );
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	};
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
};
function getCookie(check_name) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	for (i = 0; i < a_all_cookies.length; i++) {
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if (cookie_name == check_name) {
			b_cookie_found = true;
			if (a_temp_cookie.length > 1) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			};
			return cookie_value;
			break;
		};
		a_temp_cookie = null;
		cookie_name = '';
	};
	if (!b_cookie_found) {
		return null;
	};
};
