var TCApplication = {actionURL:"/cgi-bin/WebObjects/Mudderstadt.woa/go",newsServiceBaseURL:"http://mudderstadt.net/cgi-bin/WebObjects/NewsService.woa"};
/** Start:TRMComments **/
var TRMComments = {
	clicked: function(link,gInfo,type,picid) {
		var e = $(link);
		$("commentContainer").update("<div class='wait'><img src='"+TCApplication.actionURL+"/pic?i=$waitanimation2.gif' /> "+TCu.loc.TRMLoadingComments+"</div>");		
		$("commentContainer").show();
		var params = { type: type, gid: gInfo.id, gname: gInfo.name };
		if (picid) {
			params.pid = picid;
			params.pname = gInfo.pics[picid];
		}
		new Ajax.Updater('commentContainer', TRMComments.contentURL, { method:"GET", evalScripts: true, parameters: params });
		return false;
	},
	submit: function(form) {
		new Ajax.Updater('commentContainer', TRMComments.dataURL, {
				 parameters: $(form).serialize(true),
				 method: "POST"
			});
		return false;
	}
};

/** End:TRMComments **/
if (!TRMComments) TRMComments={};
TRMComments.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMComments";
TRMComments.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMComments/data";

/** Start:TRMMapView **/
var TRMMapView = function(mapElementId, channelId) {
	this.map = null;
	this.markerManager = null;
	this.markers = new Hash();
	this.mapElementId = mapElementId;
	this.channelId = channelId;
	Event.observe(window, "load", this.initializeMap.bindAsEventListener(this));
};

TRMMapView.instances = new Array();
TRMMapView.gInfo = {};

TRMMapView.openGallery = function(id, picid) {
	$("galleryContent").update("<div class='wait'><img src='"+TCApplication.actionURL+"/pic?i=$waitanimation2.gif' /> "+TCu.loc.TRMLoadingGallery+"</div>");
	$("gallery").show();
	new Ajax.Updater("galleryContent", TRMMapView.contentURL+"?g="+id, { 
		evalScripts: true,
		onComplete: function() {
			if (picid) {
				window.__lb.displayImageWithName("pic"+picid);
			}
			else {
				window.__lb.handleDirectLink();
			}
		} 
	});
	TRMMapView.showGallery(id, true);
};

TRMMapView.showGallery = function(id, leaveGallery) {
	if (!leaveGallery) {
		$("gallery").hide(); 
	}
	TRMMapView.instances.each( function(map) { 
		var marker = map.markers.get(id);
		if (marker) {
			marker.openInfoWindowHtml(marker.__tc_content);
		}
	});
	var mapbox = $("mainBox"); 
	if (mapbox) {
		if (document.viewport.getScrollOffsets().top>mapbox.cumulativeOffset().top) {
			mapbox.scrollTo();
		}
	}
};

TRMMapView.setGalleryInfo = function(dict) {
	TRMMapView.gInfo = dict;
};

TRMMapView.prototype = {
    initializeMap: function() {
  		this.map = new GMap2($(this.mapElementId));
  		TRMMapView.instances.push(this);
		this.map.setCenter(TCApplication.defaultCenterPoint, 12);
		this.map.enableScrollWheelZoom();
		this.map.addControl(new GLargeMapControl());
		this.map.addControl(new GScaleControl());
		// this.markerManager = new MarkerManager(this.map);
		// load galleries
		new Ajax.Request(TCApplication.newsServiceBaseURL+"/gallery/list,c="+this.channelId, { 
			method: 'get',
			requestHeaders: {Accept: 'application/json'},
			onSuccess: function(transport) {
					var json = eval(transport.responseText);
					var list = $A(json.result);
					this.locmap = new Hash();					
					list.each( this.createMarker.bind(this) ); // create Markers
					this.declutterMarkers();
					
					/* 
					// add markers to marker manager
					this.markerManager.addMarkers(this.markers.values(), 3);
					this.markerManager.refresh()
					*/
					var query = window.location.href.toQueryParams();
					var newGalId = query.newgallery;
					if (newGalId) {
						var markerToOpen = this.markers.get(newGalId);
						if (markerToOpen) {
							markerToOpen.openInfoWindowHtml("<h3>"+TCu.loc.TRMNewGalleryTitle+"<h3><p style='font-size:10px'>"+TCu.loc.TRMNewGalleryHint+"</p>");
						}
					}
					var showGalId = query.showgallery;
					if (showGalId) {
						TRMMapView.showGallery(showGalId);
					}
					var showPicGalId = query.showpicture;
					if (showPicGalId) {
						TRMMapView.openGallery(showPicGalId);
					}
					
				}.bindAsEventListener(this),
			onException: function(transp, e) { console.debug(e); }
		}); 
	},
	
	createMarker: function(item) {
		if (item.media_count<1) return;
		var point = new GLatLng(item.location_lat, item.location_lng);
		var icon = new GIcon();
		var sz = Math.min(14 + item.media_count,40);
		icon.iconSize = new GSize(sz,sz); 
		icon.image = TCApplication.actionURL+"/pic?i="+item.latestMedium_src;
		icon.shadow = TCApplication.actionURL+"/pic?i=$shadow.png";
		if (1==item.status) {
			icon.transparent = TCApplication.actionURL+"/pic?i=$transparent_featured.png";
		}
		else {
			icon.transparent = TCApplication.actionURL+"/pic?i=$transparent.png";
		}
		icon.shadowSize = new GSize(sz*1.5,sz);
		icon.iconAnchor = new GPoint(sz/2, sz/2);
		icon.infoWindowAnchor = new GPoint(sz/2, sz/2);
		// create marker
		var openGalleryLink = "<a href=\"javascript:TRMMapView.openGallery('"+item.id+"');\">";
		var mediaCountString = item.media_count+" "+(item.media_count==1?"Bild":"Bilder");
		var content = "<div style='width:250px;height:200px;overflow:auto;font-size:10px;'>"+openGalleryLink; 
		content += "<img src='"+TCApplication.actionURL+"/pic?i="+item.latestMedium_src+"&t=qi' style='float:right;margin-left:4px' title='"+item.latestMedium_caption+"'/>";
		content += "</a><h3>"+item.name+"</h3><p>"+item.text+"</p><p>"+mediaCountString+"</p>";
		content += "<p>"+openGalleryLink+TCu.loc.TRMViewGallery+"</a></p>";
		content += "<span class=\"msuser\""+item.userRef+"</span>, "+TC.displayDate(item.modDate)+",<br />"+item.viewCount+"x angeschaut, Kommentare: "+item.comments_count;
		content += "</div>";
		var title = item.name + " "+ mediaCountString;
		var marker = new GMarker(point, { icon:icon, title:title });
		marker.bindInfoWindowHtml(content);
		marker.__tc_content = content;
		this.map.addOverlay(marker);
		this.markers.set(item.id, marker);
		var lockey = item.location_lat+"|"+item.location_lng;
		if (this.locmap.get(lockey)) {
			var ms = $A(this.locmap.get(lockey));
			ms.push(marker);
			this.locmap.set(lockey, ms);
		}
		else {
			this.locmap.set(lockey, [marker]);
		}
	},
	
	declutterMarkers: function() {
		var multipleIcon = new GIcon();
		multipleIcon.image = TCApplication.actionURL+"/pic?i=$multiple.png";
		multipleIcon.iconAnchor = new GPoint(7,7);
		this.locmap.values().each( function(markerArray) {
			if (markerArray.length<2) return;
			var vertices = [];
			var origin = markerArray[0].getLatLng();
			for (var ix=0;ix<markerArray.length;++ix) {
				var marker = markerArray[ix];
				var rad = ix/markerArray.length*(2*Math.PI);
				var r = Math.min(0.0003,0.00005*markerArray.length);
				var repos = new GLatLng(origin.lat() + r*Math.cos(rad), origin.lng() + r*Math.sin(rad)*1.67);
				marker.setLatLng(repos);
				vertices.push(repos);
			}
			vertices.push(vertices[0]);
			this.map.addOverlay(new GPolygon(vertices , "#8BD708", 2, 1, "#8BD708", 0.5));
			//this.markerManager.addMarker(new GMarker(origin, {icon:multipleIcon,title:markerArray.length+" Galerien"}), 16);
			this.map.addOverlay(new GMarker(origin, {icon:multipleIcon,title:markerArray.length+" Galerien"}), 16);
		}.bind(this));
	},
	
	info: function() { 
		alert(this.map.getCenter());
	}
	
};
/** End:TRMMapView **/
if (!TRMMapView) TRMMapView={};
TRMMapView.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMMapView";
TRMMapView.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMMapView/data";

/** Start:TRMNewGallery **/
var TRMEP = null;

// ---------- EditPage class

var TRMNewGallery = function(addToId) {
	TRMEP = this;
	Event.observe(window, "load", this.initializeMap.bindAsEventListener(this));
	this.addToId = addToId;
};

TRMNewGallery.prototype = {

	// functions for TRMFindPlace

	initializeMap: function() {
		if ($("findPlaceMap")) {
	  		this.map = new GMap2($("findPlaceMap"));
			this.map.setCenter(TCApplication.defaultCenterPoint, 12);
			this.map.addControl(new GSmallMapControl());
			this.geocoder = new GClientGeocoder();
			this.geocoder.setBaseCountryCode("de");
			this.reversegeocoder = new GReverseGeocoder(this.map);
			this.address = null;
			this.coordinates = null;
			GEvent.addListener(this.reversegeocoder, "load", function(placemark) { this.updateAddress(true, placemark); }.bind(this));
			GEvent.addListener(this.reversegeocoder, "error", function() { this.updateAddress(false); }.bind(this));
		}
	},

	addAddressToMap: function(response) {
      this.map.clearOverlays();
      if (!response || response.Status.code!=200) {
      	this.updateAddress(false);
      } 
      else {
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        this.map.setCenter(point, 13);
        var marker = new GMarker(point, {draggable: true});
        GEvent.addListener(marker, "dragend", function(marker) { this.reversegeocoder.reverseGeocode(marker.getLatLng()); }.bind(this, marker));
        this.map.addOverlay(marker);
        this.updateAddress(true, place);
      }
    },
    
    showLocation: function(address) {
      this.geocoder.getLocations(address, this.addAddressToMap.bindAsEventListener(this));
    },
    
    updateAddress: function(success, place) {
    	var style = success?"success":"error";
    	var message;
    	if (success) {
    		message = place.address;
    		this.address = place.address;
    		this.coordinates = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    	}
    	else {
    		message = TCu.loc.TRMNewGalleryAddressNotFound;
    		this.address = null;
    		this.coordinates = null;
    	}
    	$("findPlaceMessage").update("<span class=\""+style+"\">" + message + "</span>");
    },
    
    // image upload
    
    uploadConfiguration: function(settings) {
    	this.uploadActionURL = settings.url;
    	this.ticket = settings.ticket;
    },
    
    uploadStart: function() {
    	$('uploadResults').show();
		$('wait').show();
		this.updateProgress(true);
		$('uploadDialog').hide();
    },
    
    updateProgress: function(instantaneous) {
		if (!instantaneous) {
			window.setTimeout(this.updateProgress.bind(this, true), 2000);
		}
		else {
			new Ajax.Updater('uploadResults', this.uploadActionURL, {
				parameters: { t: this.ticket },
				evalScripts: true
			});
		}
	},
	
	uploadEnd: function(list) {
		$('wait').hide();
		this.images = list;
	},
    
    previewImage: function(ref) {
    	var win = window.open(this.uploadActionURL+"?i="+ref+"&ty=fi"+"&t="+this.ticket,"preview", "width=520,height=520");
    	win.focus();
    	return false;
    },
    
    // submission
    
    submit: function() {
    	var errors = 0;
    	var errormsg = "";
		
		if (!this.addToId) {
			
			if (!this.address || !this.coordinates) {
				errors++;
				errormsg += "- "+TCu.loc.TRMErrorNoAddr+"\n";
				this.markField("addressField");
			}
		}
		
		if (!this.checkField("title")) {
				errors++;
				errormsg += "- "+TCu.loc.TRMErrorNoTitle+"\n";
		}
		if (!this.checkField("description")) {
			errors++;
			errormsg += "- "+TCu.loc.TRMErrorNoDesc+"\n";
		}
	
		if (!this.images && !this.addToId) {
			// generating a new gallery only works with images uploaded
			errors++;
			errormsg += "- "+TCu.loc.TRMErrorNoPics+"\n";
		}
		else {
			// collect captions
			var missing = false;
			var i;
			if (this.images) {
				// check captions of newly uploaded images
				for (i=0;i<this.images.length;++i) {
					var fieldId = "caption"+this.images[i].r;
					if (!this.checkField(fieldId)) {
						missing = true;
					}
					else {
						this.images[i].c = $(fieldId).value;
					}
				}
			}
			// collect images to delete
			var deletes = $$("input.del");
    		this.deleteImg = new Array();
			for (i=0;i<deletes.length;++i) {
				var del = deletes[i];
				if (del.checked) {
					this.deleteImg.push(del.id);
				}
			}
			// check captions of existing images
			var captions = $$("input.caption");
			this.captions = new Hash();
			for (i=0;i<captions.length;++i) {
				var cap = captions[i];
				if (!this.checkField(cap.id)) {
					missing = true;
				}
				else {
					this.captions.set(cap.id,cap.value);
				}
			}
			if (this.deleteImg.length==captions.length && (this.images===null || this.images.length===0)) {
				errors++;
				errormsg += "- "+TCu.loc.TRMErrorNoPicsLeft+"\n";
			}
			if (missing) {
				errors++;
				errormsg += "- "+TCu.loc.TRMErrorMissingCaptions+"\n";
			}
		}
		
		if (errors>0) {
			alert(errors+TCu.loc.TRMErrorHead+"\n"+errormsg);
		}
		else {
			// submit the results
			var json = this.assembleJSON();
			new Ajax.Updater('newResult', TRMNewGallery.dataURL, {
				parameters: { g: json, t: this.ticket },
				method: "post",
				evalScripts: true,
				asynchronous: false
			});
		}
    },
    
    checkField: function(id) {
    	var val = $(id).value;
    	var check = !(!val || val.strip()==="");
    	if (!check) {
    		this.markField(id);	
    	}
    	return check;
    },
    
    markField: function(id) {
    	$(id).style.background = "#dd7f3a";
    	$(id).observe("focus", function() {this.style.background='';});
    },
    
    assembleJSON: function() {
    	var gallery = new Hash();
    	if (this.addToId) {
    		gallery.set("addToId", this.addToId);
    		gallery.set("captions", this.captions);
			gallery.set("delete", this.deleteImg);
    	}
    	else {
    	   	gallery.set("locAddress", this.address);
    		gallery.set("locLat", this.coordinates.lat());
    		gallery.set("locLng", this.coordinates.lng());
    	}
    	if ($("isFeatured") && $("isFeatured").checked) {
    		gallery.set("status", 1);
    	}
    	else {
    		gallery.set("status", 0);
    	}
    	gallery.set("text", $("description").value);
    	gallery.set("name",$("title").value);
    	gallery.set("images", this.images);
    	
		return gallery.toJSON();    	
    },
    
    submitSuccess: function (gid) {
    	window.location.href = TCApplication.actionURL+"/start?newgallery="+gid;
    }

};
/** End:TRMNewGallery **/
if (!TRMNewGallery) TRMNewGallery={};
TRMNewGallery.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMNewGallery";
TRMNewGallery.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMNewGallery/data";

/** Start:TRMRecommendation **/
var TRMRecommendation = {

	showForm: function(mode, gallid, gallN, imgid, imgN) {
		new Ajax.Updater('recommendationFormContainer', TRMRecommendation.contentURL, 
			{ 
				method:"POST",
				parameters: {mode:mode,gallid:gallid,galln:gallN,imgid:imgid,imgn:imgN}
			}
		);
		return false;
	},
	
	submitForm: function() {
		new Ajax.Updater('recommendationFormContainer', TRMRecommendation.dataURL, 
			{
				parameters: $('recommendationForm').serialize(true)
			}
		);
		return false;
	}

};
/** End:TRMRecommendation **/
if (!TRMRecommendation) TRMRecommendation={};
TRMRecommendation.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMRecommendation";
TRMRecommendation.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMRecommendation/data";

/** Start:TRMSearch **/
var TRMSearch = {
	searchForTerm: function() {
		var term = $('search').value;
		term = term.strip();
		var element = $("searchResult");
		if (term!=="" && term.length>2) {
			element.update("<div class='wait'><img src='"+TCApplication.actionURL+"/pic?i=$waitanimation.gif' /></div>");
			new Ajax.Updater(element, TRMSearch.contentURL, {method:"POST", parameters: {q:term}});
		}
		else {
			element.update("<em>"+TCu.loc.TRMErrorTermLength+"</em>");
		}	
	}
};
/** End:TRMSearch **/
if (!TRMSearch) TRMSearch={};
TRMSearch.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMSearch";
TRMSearch.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMSearch/data";

/** Start:TRMTopGalleries **/
var TRMTopGalleries = {
	selectTab: function(type, link, contentid) {
    		if (link) {
    			var selected = $("tab"+contentid).getElementsByClassName('selected');
    			for (var i=0;i<selected.length;++i) {
    				selected[i].removeClassName("selected");
    			}
    			$(link).addClassName("selected");
    		}
    		var element = $("tabcontainer"+contentid);
    		element.update("<div class='wait'><img src='"+TCApplication.actionURL+"/pic?i=$waitanimation.gif' /></div>");
    		new Ajax.Updater(element, TRMTopGalleries.contentURL, {method:"GET", parameters: {type:type}});
    		return false; 
    	}
};
/** End:TRMTopGalleries **/
if (!TRMTopGalleries) TRMTopGalleries={};
TRMTopGalleries.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMTopGalleries";
TRMTopGalleries.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMTopGalleries/data";

/** Start:TRMVoting **/
var TRMVoting = {

	showForm: function(element, type, id, name) {
		$('votingFormContainer').clonePosition($(element), {setWidth:false,setHeight:false, offsetTop:-5});
		$('votingFormContainer').show();
		new Ajax.Updater('votingFormContainer', TRMVoting.contentURL, {
				method:"GET", 
				evalScripts: true, 
				parameters: {id:id,type:type,name:name}
			});
		element.onclick = function() { alert(TCu.loc.TRMErrorVoteOnce); };
		return false;
	},
	
	clicked: function(event) {
		var e = event.element();
		var pos = e.cumulativeOffset();
		var clickedx = Math.round((event.pointerX()-pos[0])/11);
		var points = Math.max(1,clickedx);
		e.style.backgroundPosition = (11*points-55)+"px 0";
		$('votingValue').update(points);
		event.stop();
	},
	
	submit: function(type, id, name) {
		var points = $('votingValue').innerHTML;
		new Ajax.Updater('votingFormContainer', TRMVoting.dataURL, {
				 parameters: {p:points,id:id,type:type,name:name}
			});
		$('votingFormContainer').hide();
		return false;
	}

};
/** End:TRMVoting **/
if (!TRMVoting) TRMVoting={};
TRMVoting.contentURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMVoting";
TRMVoting.dataURL="/cgi-bin/WebObjects/Mudderstadt.woa/ajax/TRMVoting/data";

/** Start:app **/
TCApplication.defaultCenterPoint = new GLatLng(52.51851897366125, 13.391990661621094);

// ---------- Utilities

var TC = {
	displayDate: function(date) {
		return TC.formatNumber(date.getDate(),2)+"."+TC.formatNumber(date.getMonth()+1,2)+"."+date.getFullYear()+" "+TC.formatNumber(date.getHours(),2)+":"+TC.formatNumber(date.getMinutes(),2);
	},
	formatNumber: function(v, len) {
		var result = new String(v);
		while (result.length<len) result = "0"+result;
		return result;
	},
	trackerRefresh: function() {
		var tracker = $("MSTrackPixel");
		if (tracker) {
	        var src = tracker.src;
	        src = src.replace(/(&d=.+)$/,"&d="+(Math.random()*100000));
	        tracker.src = src;
      	}
	},
	analyticsRefresh: function(pagename) {
		if (pageTracker) {
			pageTracker._trackPageview(pagename);
		}
	}
};
/** End:app **/
