// TODO:
//======
// - 301 van hetlelijkstegebouw.be naar de www.
// - backslashes in de teksten

// POLISH:
//========
// - auto inloggen (adhv sessie) + jquery
// - vote form hiden en tonen na klik op knop (zie design: nomineren)
// - deze file minifyen
// - use markermanager for different layers and amounts
// - geef een melding als de latlon al bestaat
// - img replacement


// DONE:
//======
// - localisation!
// - IE6 upgrade pagina
// - perma urls
// - footer updaten naar nieuw design
// - localisatie form validation messages
// - form submit handlers
// - loader when sending / retrieving data
// - hoe pagina
// - waarom pagina
// - display marker on search result
// - facebook integratie
// - handle errors
// - zoekresultaten layout
// - paging top
// - paging recent


var center = new GLatLng(51.205588,4.424142);
var geocoder = null;
var map = null;
var mgr = {};
var IMAGES = ["marker"];
var ICONS = [];
var buildings = new Array();
var FB = [];
var marker = [];
var recentindex = 0;
var topindex = 0;
var initbuilding = "";

$(document).ready(function(){
  if (GBrowserIsCompatible()) {
  
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(center, 9);
    //map.setMapType(G_HYBRID_MAP);
    //map.setMapType(G_SATELLITE_MAP);
    map.setMapType(G_SATELLITE_MAP);
    // G_NORMAL_MAP
    // G_PHYSICAL_MAP
  
  	var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
    map.addControl(new GLargeMapControl3D(), topRight);
    map.enableScrollWheelZoom();
    geocoder = new GClientGeocoder();
    

  	mgr = new MarkerManager(map);
    loadMarkers();
  }
  
  
  
  $(function()
    {
       var  testTextBox = $('input.searchbuilding');
        var code =null;
        testTextBox.keypress(function(e)
        {
            code= (e.keyCode ? e.keyCode : e.which);
            if (code == 13) {
            	lookup();
            	e.preventDefault();
            }
        });
        
        testTextBox.focus(function(e){
        	$("div.results").fadeOut();
        });
    });
    
    // addBuildingForm
	
	var v = jQuery("#addBuildingForm").validate({
		submitHandler: function(form) {
			
			//validate het adres
			validateAddress ($("#buildingaddress").attr("value"), submitBuilding,form)
			
		},
		rules:{agree: "required",buildingphoto: {required:true,accept:'jpg?|gif|png|jpeg'}},
		messages:{agree: acceptPolicyError}
	});
	
	function submitBuilding(form) {
			jQuery(form).ajaxSubmit(handleBuildingAdd);
			$("#addBuildingPopup").addClass("loading");
	}
	
	
	// voteBuildingForm
	
	var v = jQuery("#voteBuildingForm").validate({
		submitHandler: function(form) {
			jQuery(form).ajaxSubmit(handleBuildingVote);
			$("#voteBuildingPopup").addClass("loading");
			
		},
		rules:{agree: "required"},
		messages:{agree: acceptPolicyError}
	});

	
	// reactBuildingForm
	
	var loader = jQuery('<div id="loader"><img src="images/loading.gif" alt="loading..." /></div>')
		.css({position: "relative", top: "1em", left: "25em"})
		.appendTo("body")
		.hide();
	jQuery().ajaxStart(function() {
		//loader.show();
	}).ajaxStop(function() {
		loader.hide();
	}).ajaxError(function(a, b, e) {
		throw e;
	});
	
	var v = jQuery("#reactBuildingForm").validate({
		submitHandler: function(form) {
			
			jQuery(form).ajaxSubmit(handleBuildingReaction);
			$("#voteBuildingPopup").addClass("loading");
		},
		rules:{agree: "required"},
		messages:{agree: acceptPolicyError}
	});
	
	jQuery("#reset").click(function() {
		v.resetForm();
	});
	
    $.address.change(function(event) {
        initbuilding = event.value.replace("/","");
        showbuilding();
    });    
});

function update_user_box() {
	$(".fblogin").hide();
	$(".postToFacebook").show();
}

function callPublish(msg, attachment) {
  FB.ensureInit(function () {
    FB.Connect.streamPublish(msg, attachment);
  });
}

function show_box(){
	//$(".fblogin").hide();
}

function handleBuildingAdd(data){
	data = eval('(' + data + ')');

	$("#addBuildingPopup").removeClass("loading");
	
	
	if(data.message == "ok") {
	
		$(".postToFacebook").bind("click",data.building[0],publish);
		
		$("#addBuildingForm").slideUp();
		$("#addBuildingPopup .thanks").slideDown();
		
		// facebook integratie
		b = new UglyBuilding(data.building[0]);
			
		// nieuw toegevoegde locatie toevoegen op de map
		// navigeer naar de toegevoegde als de popup gesloten wordt
		mgr.addMarkers([b.getMarker()], 1);
		mgr.refresh();
		b.infoWindowListener();
	} else if(data.message == "needUserCredentialsError") {
	
		//$("#userCredentials").children().appendTo("#addBuildingForm .identification").slideDown();
		$("#addBuildingForm .identification").append($("#userCredentials").children()).slideDown();
		// .appendTo("#chat_box").show();
	} else {
		msg = eval('(' + data.message + ')');
		
		$("#addBuildingForm").prepend("<p class=\"error\">"+msg+"</p>");
		
	}
}

function handleBuildingVote(data){
	data = eval('(' + data + ')');	
	$("#voteBuildingPopup").removeClass("loading");
	
	if(data.message == "ok"){
		$("#voteBuildingForm").slideUp();
		$("#voteBuildingPopup .thanks").slideDown();
		$(".postToFacebook").bind("click",data.building[0],publish)
		buildings["building"+data.building[0].id].updateVoteCount();
	} else if(data.message == "needUserCredentialsError") {
	
		//.children().appendTo.slideDown();
		$("#voteBuildingForm .identification").append($("#userCredentials").children()).slideDown();
		
		// .appendTo("#chat_box").show();
	} else {
		
		$("#voteBuildingForm .errorMessage").text( eval('(' + data.message + ')'));
		
    	$("#voteBuildingForm .identification").empty();
    	$("#voteBuildingForm .identification").hide();
	}
}

function handleBuildingReaction(data){
	data = eval('(' + data + ')');
	$("#voteBuildingPopup").removeClass("loading");
	if(data.message == "ok"){
	    $("#reactionsform .reactions").append("<p><span class='who'><strong>"+data.reaction.naam+" "+data.reaction.voornaam+"</strong>"+reactionsays+":</span>"+data.reaction.reaction+"</p>");
		$("#reactBuildingForm").resetForm();
	
	} else if(data.message == "needUserCredentialsError") {
		$("#reactBuildingForm .identification").append($("#userCredentials").children()).slideDown();
	} else {
		
		$("#reactBuildingForm .errorMessage").text( eval('(' + data.message + ')'));
	}
}

function publish(e) {  
	callPublish('',
		{	'media':[{	'type':'image','src':siteurl+'/images/thumbs/thumb'+e.data.id+'.jpg',
					'href':siteurl+'/#/building'+e.data.id}],
			'caption':'{*actor*} '+fbgestemd01+' '+e.data.naam+' '+fbgestemd02,
			'properties':[{'text':claim2,
			'href':siteurl+'/#/building'+e.data.id}]});
			
	return false;
}

function loadTop(nbr) {
	if (nbr ==null) nbr = 0;
	if (nbr < 0) nbr = 0;
	$.getJSON("/building/top/",{"index":nbr},
        function(data){
		  if(data.length ==0) return;
		  topindex = nbr;
		  $(".column.lelijkste .thumbs").empty();
          $.each(data, function(i,item){
          		myitem = $("<div class=\"item\"><div class=\"img\"><img src=\"/images/thumbs/thumb"+item.id+".jpg\" /></div><div class=\"details\"><p class=\"address\">"+item.naam+"<br />"+item.address.replace(",","<br/>")+"</p><p><em>"+item.nbr+"</em> "+ugly+"</p></div></div>");

         		$(".column.lelijkste .thumbs").append(myitem);
         		
         		myitem.bind("click",item.id,clickedon);
         		
         		$(".column.lelijkste .nav span").text((topindex+1)+" - "+(topindex+3));
         		
         		if (i == 2) return false;
          });
        });
}

function loadRecent(nbr) {
	if (nbr ==null) nbr = 0;
	if (nbr < 0) nbr = 0;
	$.getJSON("/building/recent/",{"index":nbr},
        function(data){
		  if(data.length ==0) return;
		  recentindex = nbr;
		  $(".column.recente .thumbs").empty();
          $.each(data, function(i,item){
          		myitem = $("<a href=\"#\"><img src=\"/images/thumbs/thumb"+item.id+".jpg\" /></a>");
          		
         		$(".column.recente .thumbs").append(myitem);
         		
         		myitem.bind("click",item.id,clickedon);
         		
         		$(".column.recente .nav span").text((recentindex+1)+" - "+(recentindex+9));
         		
         		
         		if (i == 8) return false;
          });
        });
}


function clickedon (id) {
	buildings["building"+id.data].infoWindowListener();
}

function getWeatherIcon(id) {
  if (!ICONS[id]) {
    var icon = new GIcon();
    icon.image = "/images/markers/marker" 
        + id + ".png";
    icon.iconAnchor = new GPoint(19, 39);
    icon.infoWindowAnchor = new GPoint(16, 0);
    icon.iconSize = new GSize(40, 44);
    icon.shadow = "/images/marker-shadow.png";
    icon.shadowSize = new GSize(59, 44);
    ICONS[id] = icon;
    
  }
  return ICONS[id];
}

function getMarkers(data) {
	var batch = [];
    $.each(data,function(n,item){
    
    
    	var ub = new UglyBuilding(item);
		batch.push(ub.getMarker());
		
	});
	return batch;
}

function loadMarkers() {
	/*
    var cat_icon = new GIcon(G_DEFAULT_ICON);
    cat_icon.image = "/images/pinpoint.png";
    cat_icon.shadow = "/images/shadow.png";
	cat_icon.iconSize = new GSize(30, 40);
	cat_icon.shadowSize = new GSize(40, 51);
	cat_icon.iconAnchor = new GPoint(0, 40);
	cat_icon.infoWindowAnchor = new GPoint(30, 0);
	cat_icon.imageMap = [0,0, 30,0, 30,30, 0,30]
	*/

	$.getJSON("/building/get",
		function(data){
  			
  			mgr.addMarkers(getMarkers(data), 1);
			mgr.refresh();
			
			showbuilding();
			
		    loadTop();
		    loadRecent();
		    //t = setTimeout(function() {$("#myFlashContent")[0].dropStamp()}, 1000); 
		}
	);
}

function showbuilding() {
	if (initbuilding != "") {
		b = buildings[initbuilding]
		if (b != null) b.infoWindowListener();
	}
}

function validateAddress (address, callback,params) {
	if (address == "") {
		alert(emptyaddressmessage); 
		return false;
	}
	address = address+",Belgium";
	 if (geocoder) {
	    geocoder.getLatLng(address,function(point){
	    	if (!point) {
	          alert(address + " niet gevonden");
	        } else {
	          map.setCenter(point, 13);
	          geocoder.getLocations(point,function(address){
		        //$("#addressview").empty();
		        $("#addBuildingForm .hiddens").empty();
	          	//$("#addressview").append(address.Placemark[0].address);
	          	
	          	$("#addBuildingForm .hiddens").append("<input type=\"hidden\" name=\"buildinglat\" value=\""+address.Placemark[0].Point.coordinates[1]+"\">");
	          	$("#addBuildingForm .hiddens").append("<input type=\"hidden\" name=\"buildinglon\" value=\""+address.Placemark[0].Point.coordinates[0]+"\">");
	          	$("#addBuildingForm .hiddens").append("<input type=\"text\" id=\"buildingaddress\" name=\"buildingaddress\" value=\""+address.Placemark[0].address+"\">");
	          	
	          	
	          	callback(params);
	          });
	        }
		});
	    return true;
	 } else {
	 	return false;
	 }
}

function showAddress(address) {
	if (address == "") {
		alert(emptyaddressmessage); 
		return false;
	}
	address = address+",Belgium";
	 $('input.searchbuilding').blur();
  if (geocoder) {
    geocoder.getLatLng(address,
      function(point) {
        if (!point) {
          alert(address + " niet gevonden");
        } else {
          map.setCenter(point, 13);
          
          
          map.removeOverlay(marker);
          marker = new GMarker(point);
          map.addOverlay(marker);
          //map.refresh();
          //map.removeOverlay(marker)
          //marker.openInfoWindowHtml(address);
          
          geocoder.getLocations(point,function(address){
	        //$("#addressview").empty();
	        $("#addBuildingForm .hiddens").empty();
          	//$("#addressview").append(address.Placemark[0].address);
          	
          	$("#addBuildingForm .hiddens").append("<input type=\"hidden\" name=\"buildinglat\" value=\""+address.Placemark[0].Point.coordinates[1]+"\">");
          	$("#addBuildingForm .hiddens").append("<input type=\"hidden\" name=\"buildinglon\" value=\""+address.Placemark[0].Point.coordinates[0]+"\">");
          	$("#addBuildingForm .hiddens").append("<input type=\"text\" id=\"buildingaddress\" name=\"buildingaddress\" value=\""+address.Placemark[0].address+"\">");
          	/*
          	$("#address").attr('value',address.Placemark[0].address);
          	$("#lat").attr('value', address.Placemark[0].Point.coordinates[1]);
          	$("#lon").attr('value', address.Placemark[0].Point.coordinates[0]);
          	$("#brbrbr").attr('value',"enfin");
          	*/
          	
          	$.getJSON("/building/nearby/",{lat:address.Placemark[0].Point.coordinates[1],lon:address.Placemark[0].Point.coordinates[0]},
          		function(data){
          			$("div.results").empty();
          			$("div.results").fadeIn();
          			$("div.results").append("<a class='close' href='#' onclick='$(\"div.results\").fadeOut();return false'>X</a>");
          			$.each(data,function(i,item) {
          				myitem = $("<a href=\"#\">&raquo; "+item.naam+"</a><br>")
          				myitem.bind("click",{"id":item.id},function(e){buildings["building"+e.data.id].infoWindowListener();return false;});
          				$("div.results").append(myitem);
          			});
          			$("div.results").append("<a class='gebouwtoevoegen' href='#' onclick='newBuilding();return false'>"+gebouwtoevoegen+"</a>");
          		}
          	);
          });
        }
      }
    );
  }
}

//map.panTo(new GLatLng("+item.lat+","+item.lon+"));map.setZoom(14);

 
// Infowin class for displaying a miniature info window. Does not
// respond to any events - so you should show and remove the
// overlay yourself as necessary.
 
function Infowin(latlng, html) {
        this.latlng_ = latlng;
        this.html_ = html;
        this.prototype = new GOverlay();
 
        // Creates the DIV representing the infowindow
        this.initialize = function(map) {
                var div = $('<div />');
                div.css({
                        position : 'absolute',
                        width : 234
                }).appendTo(map.getPane(G_MAP_FLOAT_PANE))
 
                this.map_ = map;
                this.div_ = div;
 
                this.update(html);
        }
 
        this.update = function(html){
                this.html_ = html;
 
                this.div_.empty();
 
                $('<div />').css({
                        'background-image' : 'url(/images/infow-top.png)',
                        height : 14,
                        padding: '0 0 0 0'
                }).appendTo(this.div_);
 
                var content = $('<div />').addClass('infowin-content').css({
                        'position' : 'relative',
                        'overflow' : 'hidden',
                        'max-height' : 100,
                        'top' : -5
                }).html(html);
 
                $('<div />').css({
                        'background-image' : 'url(/images/infow-bottom.png)',
                        'background-position' : 'bottom left',
                        'padding' : '0 10px 30px 10px'
                }).append(content).appendTo(this.div_);
 
                this.redraw(true);
        }
 
        // Remove the main DIV from the map pane
        this.remove = function() {
          this.div_.remove();
        }
 
        // Copy our data to a new instance
        this.copy = function() {
          return new Infowin(this.latlng_, this.html_);
        }
 
        // Redraw based on the current projection and zoom level
        this.redraw = function(force) {
                if (!force) return;
 
                var point = this.map_.fromLatLngToDivPixel(this.latlng_);
 
                // Now position our DIV based on the DIV coordinates of our bounds
                this.div_.css({
                        left : point.x - 108,
                        top : point.y - this.div_.height() - 22
                });
        }
}

function lookup(){
	showAddress($("input.searchbuilding").val());
	return false;
}

function newBuilding() {

	$("#addBuildingPopup .thanks").hide();
	$("#addBuildingForm").show();
	// reset form 
	
	$("#addBuildingForm").resetForm();

	// add info to 
	$("div.results").fadeOut();
	
	$(".popup").removeClass("active");

	$("#addBuildingPopup").addClass("active");
	$('#overlay').fadeIn();
}

function zoomr() {
	GEvent.removeListener(map, "moveend", zoomr);			
	map.setZoom(14);
}

function UglyBuilding(item) {
	this.itemdata = item;
	this.reactionPostUrl = "/reaction/add/";
	
	var pos = new GLatLng(Number(item.lat),Number(item.lon));
	this._marker = new GMarker(pos, { icon: getWeatherIcon(item.id) });
	
	this.getInfoHtml = function(){
		return $("<div class='infohtml'><img height='85px' width='85px' src='images/thumbs/thumb"+this.itemdata.id+".jpg' /><div class='infoWindowDesc'><div class='address'><p>"+this.itemdata.naam+"</p><p>"+this.itemdata.address.replace(",","<br/>")+"</p></div><p><em>"+item.nbr+"</em> "+ugly+"</p><!--<a href='#'>STEM HIER</a>--></div></div>");
	}
	
	thisObj = this;
	
	buildings["building"+item.id] = this;
		
	this.infoWindowListener = function() {
		$.address.value("building"+item.id);
		html = this.getInfoHtml()[0];
		
		map.panTo(new GLatLng(item.lat,item.lon));
		this._marker.openInfoWindow(html);
		
		//$(html).bind("click", this.vote);
	}
	
	GEvent.bind(this._marker, 'click',this,this.infoWindowListener);
		
	this.openAlternativeWindow = function() {
		var iw = new Infowin(this._marker.getLatLng(),html);
		iw.initialize(map);
	}
	
    this.vote = function() {
    
    	// set info of popup:
    	$("#voteBuildingForm .errorMessage").empty();
    	$("#reactBuildingForm .identification").empty();
    	$("#reactBuildingForm .identification").hide();
    	
		$("#voteBuildingPopup .thanks").hide();
		$("#voteBuildingForm").show();
		
		$(".postToFacebook").hide()
		$(".fblogin").show();
		
		
		$("#voteBuildingForm").resetForm();
		$($("#voteBuildingPopup .building img")[0]).attr("src",'images/buildings/building'+item.id+'.jpg');
		
		closebttn = $("#voteBuildingPopup h3 a")[0];
		$($("#voteBuildingPopup h3")[0]).text(item.naam).prepend(closebttn);
		$($("#voteBuildingPopup .building .details")[0]).html("<div class='address'><p>"+item.address.replace(",","<br/>") +"</p></div><p><em>"+item.nbr+"</em> "+ugly+"</p></div>");
		$("#bid").attr("value",item.id);
    
    	// set info of reactions:
    	$("#reactBuildingForm .buildingid").attr("value",item.id);
    	$.post("/reaction/get/", { "buildingid": item.id}, thisObj.renderReactions,"json");
		
		// show popup
		$(".popup").removeClass("active");
	
		$("#voteBuildingPopup").addClass("active");
		$('#overlay').fadeIn();
		
		$(".scrollingContent").css("height", $(window).height()/100*80);
		
		$(window).bind('resize', function() {
			$(".scrollingContent").css("height", $(window).height()/100*80);
		});
				
		return false;
    }
    
    this.updateVoteCount = function(){
    	item.nbr++;
    	$($("#voteBuildingPopup .building .details")[0]).html("<div class='address'><p>"+item.address.replace(",","<br/>") +"</p></div><p><em>"+item.nbr+"</em> "+ugly+"</p></div>");
    	this.infoWindowListener()
    }
    
    this.renderReactions = function(data) {
    	
    	$("#reactionsform .reactions").empty();
    	
    	if (data.length == 0 ) $("#reactionsform .reactions").append("<p>"+popup3noreactions+"</p>");
    	
    	$.each(data, function(i,item){
    		$("#reactionsform .reactions").append("<p><span class='who'><strong>"+item.naam+" "+item.voornaam+"</strong>"+reactionsays+":</span>"+item.reaction+"</p>");
    	});
    }
   
    this.getMarker = function() {
    	return this._marker;
    }
}