﻿var map;
var map2;
var gmarkers = [];
var center;
var cset = false;
var bounds;
var moveListener;
var polygon;
var currStoryIndex=-1;
var searchTerm="filterData";
var minday=0;
var maxday = 0;
var month=0;
var year =0;
var world = true;
var geocoder;
var storyDetails;
var markersCache = new Object();
var moveListener = null;
var movestarted = false;
var skipmovestarted = false;
var currmarker;
var currviewmarkers=[];
var markerCluster;
var timer;
var arrowAllowed= true;
var jsonData="";
var userid=0;
var locBounds;
var loadData=false;
var dayRange;
var selectedDateDay;
var startRange=-7;
var endRange=0;
var data = [];
var firstload = true;
var reloadSearchData=null;
var gotResponse = false;
data.push("Location:");
data.push("Story:");
data.push("User:");
var myIcon;

//G_NORMAL_MAP.getMinimumResolution = function () { return 3 };


myIcon = new GIcon();
myIcon.image = '/images/storymarker.png';
myIcon.shadow = '/images/storyshadow.png';
myIcon.iconSize = new GSize(32,32);
myIcon.shadowSize = new GSize(48,32);
myIcon.iconAnchor = new GPoint(0,32);
myIcon.infoWindowAnchor = new GPoint(16,0);
myIcon.printImage = '/images/printImage.gif';
myIcon.mozPrintImage = '/images/mozPrintImage.gif';
myIcon.printShadow = '/images/printShadow.gif';
myIcon.transparent = '/images/transparent.png';
myIcon.imageMap = [27,0,28,1,28,2,29,3,30,4,30,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,30,24,30,25,29,26,27,27,16,28,15,29,14,30,13,31,6,31,5,30,5,29,5,28,4,27,2,26,1,25,1,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,1,5,1,4,2,3,3,2,3,1,4,0];


function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	
	return randomstring;
}


function getGmarkerCount(marker){
    var i=1;
    for (idx in gmarkers){
        if (gmarkers[idx] == marker) {
            return i;
        }
        i++;
    } 
    return 0;
}



 
 LabeledMarker.prototype = new GMarker(new GLatLng(0, 0),{icon:myIcon},false);

 function LabeledMarker(latlng,icon,inert,storyID){
    this.latlng = latlng;
    this.storyID = storyID;
    this.title="";
    this.summary = "";
    this.date = "";
    this.author="";
    this.city="";
    this.country = "";
    this.storyType = "";
    this.externalUrl = "";
    this.TitleURL = "";
    this.comments="";
    this.labelText ="";
    this.labelClass ="";
    this.labelOffset =new GSize(0, 0);

   this.icon = myIcon;
//    this.setImage("/images/Location-Pointer.png");
    GMarker.apply(this, arguments);
}

 
 
 

// Toggle My horizon
$(document).ready(function() {
    $("#filter").click(function () {
        $("#limit").toggleClass("displayOn");
        $("#expand").toggleClass("displayOn");
    });
});


//function reloadFilterBox(){

//	if (minday==0){
//	minday = day-7;
//	if(minday<0) minday =1;
//	}
//	if (maxday==0){
//	max = day;
//	}
//	$('#slider-range').slider('destroy');
//	var currentTime = new Date();
//	//var month= document.getElementById('month').selectedIndex+1;
//	//var lastDay = new Date((new Date(year, month,1))-1).getDate();
//	var lastDay = currentTime.getDate();
//	var firstDay = currentTime.getDate() - 45;
//	    //alert("new slider");
//		$(function() {
//			
//			$("#slider-range").slider({
//				range: true,
//				min: -45,
//				max: 0, 
//				values: [startRange,endRange],
//				width: 300,
//				stop: function(event, ui){
//					
////					dayRange = Math.abs(ui.values[1]-ui.values[0]);
////					selectedDate = new Date() - Math.abs(ui.values[0]);
////					alert("dayRange" + dayRange);
////					alert("selectedDate " +new Date(selectedDate).getFullYear());
//					//alert( $('#slider-range').slider('option', 'values'));
//					//$("#slider-range").data("max.slider", 28);
//					startRange = ui.values[0];
//					endRange = ui.values[1];
//					refreshMapViewData(true);
//				
//				}
//			});
//		});										

//	//var month= document.getElementById('month').selectedIndex+1;
//	//var lastDay = new Date((new Date(year, month,1))-1).getDate();
//	var endMonth = new Date()-45;
////	alert(endMonth);
////	alert(endMonth.getDate().toString() + "." + endMonth.getMonth().toString() );
////	alert(new Date().getDate().toString() + "." +  new Date().getMonth().toString() );
////	
////	var dateTostring=new Date().getDate().toString();
////	dateTostring = dateTostring + ".";
////	dateTostring = dateTostring + (new Date().getMonth()+1).toString();
//    var currDate = new Date();
//	
//    var daysago = new Date();
//	daysago.setDate(daysago.getDate() -45);

//    formatDate(daysago);
//	//document.getElementById('startMonthDate').innerHTML = daysago.toLocaleDateString().substring(0,daysago.toLocaleDateString().length-5);
//    //document.getElementById('endMonthDate').innerHTML =currDate.toLocaleDateString().substring(0,currDate.toLocaleDateString().length-5);
//    document.getElementById('startMonthDate').innerHTML = formatDate(daysago);
//    document.getElementById('endMonthDate').innerHTML = formatDate(currDate);
//}

function formatDate(dte) {
    
    var d = dte.toLocaleDateString().split(" ");
    var day = "";
    var month = "";
    var MontFirst = false;
    if (d.length == 3) {
        if (Number(d[0])) {
            day = d[0];
            month = d[1];
        }
        else {
            MontFirst = true;
            day = d[1];
            month = d[0];
        }
    }

    if (d.length > 3) {
        if (Number(d[1])) {
            day = d[1];
            month = d[2];
        }
        else {
            MontFirst = true;
            day = d[2];
            month = d[1];
        }
        
        
    }
    if (month.length > 3) {
        if (monthArray != null) {
            month = monthArray[dte.getMonth()].substring(0, 3);
        } else {
            month = month.substring(0, 3);
        }
    }

    if (day.length > 1) {

        if (day.substring(day.length-1, day.length) == ",") {
            day = day.substring(0, day.length - 1);
        }
    }

    //if (MontFirst) {
      //  return month + " " + day;
    //}
    return day + " " + month;    
}


function refreshMapViewData(hideRefinements){
	//var day = $('#slider-range').slider('option', 'values')[1];
	//var month= new Date().getMonth()+1;
	//var year = new Date().getFullYear();
	//var period= $('#slider-range').slider('option', 'values')[1] - $('#slider-range').slider('option', 'values')[0];

	//userid = $('#hiddenSearchUserId').val();
	
		var minLat =map.getBounds().getSouthWest().lat();
	    var minLong =map.getBounds().getSouthWest().lng();
		var maxLat =map.getBounds().getNorthEast().lat();
		var maxLong =map.getBounds().getNorthEast().lng();
				
	
	//alert(startRange);
	//alert(endRange);
	//alert(year);
	//alert(period);

//VLA
	//$("#ThirdActionBox").remove();
	//var containerRefresh = '#ajax2';
	//var par = '?re=1';
	//if (location.href.indexOf("Search") > -1) {
	//    containerRefresh = '#mainContentContainer';
	//    par = '';
	//}

		var containerRefresh = '#mainContentContainer';
		var par = '';

		var showtype = "Stories";
    if(document.getElementById("HiddenCurrentStoriesViewType") != null)
    {
       showtype = document.getElementById("HiddenCurrentStoriesViewType").value
            }
		//alert(containerRefresh);
    //alert("refreshMapViewData " + showtype);

    $(containerRefresh).load('/SearchAjax/' + showtype + '/' + searchTerm + '/' + startRange + '/' + endRange + "/" + minLat + "/" + minLong + "/" + maxLat + "/" + maxLong + par, null, function() {
//        if (hideRefinements) {
//            if (document.getElementById('HappenexLogOnAjax') == null) {
//                $("#refinements_box").remove();
//                $("#refineBox").remove();
//            }
//        }

    });
		
		
	 GDownloadUrl("/UCMap/MarkerData/" + randomString(), function(data, responseCode) {
	     gmarkers = [];
	     markersCache = [];
	     jsonData = eval('(' + data + ')');
	     loadMarkers(jsonData);
	     if (gmarkers.length > 0) {
	         setTimeout("if (document.getElementById('mapStoryControl') != null){document.getElementById('mapStoryControl').style.visibility = 'visible';}", 100);
	     }


	     getVisibleMarkersData(map.getBounds());

	 });
					  
	
	searchTerm = "filterData";
	//reloadFilterBox();
}

function startHappenexSlideShow(){
    if (timer != null) {
        clearTimeout(timer) 
    }
    if (document.getElementById('mapStoryControl') != null) {
        showNextStory(false);
        timer = setTimeout("startHappenexSlideShow();", 10000);
    }
}

function showNextStory(up){


    if (up && currStoryIndex > 0) currStoryIndex -= 1;
    else
        if (currStoryIndex < gmarkers.length - 1 && !up) currStoryIndex += 1;
    else {
        currStoryIndex = 0;
    }

    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    if (is_chrome) gmarkers.reverse();
    if (gmarkers.length > currStoryIndex) {
        //GEvent.trigger(gmarkers[currStoryIndex], 'click');
        refreshStoryBox(gmarkers[currStoryIndex]);
    }

}


//for debugging only, should be removed later      
function getParameters() {
//	var params = polyDragControl.getParams();
//	var url = 'http://' + window.location.host + '/myServerSideScript.php?' + params;
//	GLog.write(url);
//SelectLocation();
}

 // ====== Create a Client Geocoder ======
      var geo = new GClientGeocoder(); 

      // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      



 // ====== Geocoding ======
      function showAddress(search) {
        //alert(search);
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
             // alert(result.Placemark.length +" results");
              // Loop through the results, placing markers
//              for (var i=0; i<result.Placemark.length; i++) {
//                var p = result.Placemark[i].Point.coordinates;
//                var marker = new GMarker(new GLatLng(p[1],p[0]));
//                document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
//                map.addOverlay(marker);
//              }
              // centre the map on the first result, we assume the first result is the most relevant
              var p = result.Placemark[0].Point.coordinates;
              var positionMarkerLatLng=new GLatLng(p[1],p[0]); 
              map2.setCenter(positionMarkerLatLng,14);
              //add marker
              GEvent.trigger(map2, "click",null,positionMarkerLatLng); 
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Could not find "'+search+ '" ' + reason);
            }
          }
        );
      }

 function removeArrow(){
    if (polygon != null) {
        map.removeOverlay(polygon);
    }
 }

 function drawArrow(marker){


        //remove old arrow
        if (!arrowAllowed) return;

        if (marker == null) return;

     if (polygon == null) {
      }
     else {
       map.removeOverlay(polygon);
       }
            //get the position of the story div
     var divPoint = new GPoint(document.getElementById("mapStoryControl").offsetLeft + 20, document.getElementById("mapStoryControl").offsetTop + 120);
     var divPoint2 = new GPoint(document.getElementById("mapStoryControl").offsetLeft + 20, document.getElementById("mapStoryControl").offsetTop + 170);

     var polyOptions = { geodesic: true };
    //set endpoints of the arrow
     var pts = [marker.getLatLng(), map.fromContainerPixelToLatLng(divPoint), map.fromContainerPixelToLatLng(divPoint2)];
    //create polygon arrow
     polygon = new GPolygon(pts, "#ffffff", 2, 0.5, "#ffffff", 0.9, { clickable: false });
    //add arrow to the map
     if (firstload) {
         //alert(1);
         setTimeout("map.addOverlay(polygon);", 2000);
     } else {
        //alert(2);
        map.addOverlay(polygon);
     }     
 }
 
  // #todo: This function is obsolete and can be removed?
  function markerClicked(marker,title,author,story,city,drawArrowFlag){
  //clear all markers, set icon to default  
  for (key in gmarkers)
        gmarkers[key].setImage(marker.getIcon().image);
        //set the clicked marker image to the selected icon

        marker.setImage("/images/Location-Pointer-Current-and-Location-Picker.png");
       
          //draw the arrow
         
         if (drawArrowFlag) drawArrow(marker);
        //fill news ticker

         var rss = (marker.externalUrl != "" && marker.storyType == 'RSS');
         var url = "#";
         var target = "";
         var comment = "";
        url = "/Story/Read/" + marker.storyID + "/" + marker.TitleURL;

         document.getElementById("newsTickerContent").innerHTML = "<div class=\"center displayOff\"><a href=\"javascript:showNextStory(true);\" class=\"btn-220-up\"></a></div><h4><a href=\"" + url + "\" " + target + ">" + marker.title + "</a></h4>" +
       "<p class=\"small\">" + marker.EditedBy + "<a onclick=\"javascript:GoToUserProfile('" + marker.author + "');return false;\">" + marker.author + "</a> on " + marker.date + "</p><div class=\"newsTickerStory\"><p>" + marker.summary + "</p></div><div class=\"newsTickerStoryComments small\">" + comment + "</div><p class=\"newsTickerStoryLocation small\"><a onclick=\"javascript:SearchLocation('" + marker.city + "');return false;\">" + marker.city + ", " + marker.country + "</a></p><div class=\"center displayOff\"><a class=\"btn-220-down\" href=\"javascript:showNextStory(false);\"/></div>";

    //fill news ticker header
      var numstories = getGmarkerCount(marker);

      document.getElementById("newsTickerHeader").innerHTML = "<h2>" + marker.labelText + " <a onclick=\"javascript:SearchLocation('" + marker.city + "');return false;\">" + marker.city + "?</a><span class=\"smallHeader\"> (" + numstories + "/" + gmarkers.length + ")</span></h2>"; 
      //  document.getElementById("locCityCountry").innerHTML =marker.city + "," + marker.country;
        
       // document.getElementById("commentsNr").innerHTML =marker.comments;
       $('#hpxCity').text(marker.city+'?') ;
 }
 

function HPXZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
HPXZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
HPXZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
       container.style.background = 'url(/images/MapControlBackground.png) no-repeat';
       container.style.width = "73px";
       container.style.height = "136px";
       container.style.position = "relative";
       container.style.top = "0px";
       container.style.left = "0px";
    
       
  var zoomInDiv = document.createElement("div");
  zoomInDiv.style.background = 'url(/images/MapControlZoomIn.png) no-repeat';
  zoomInDiv.style.width = "30px";
  zoomInDiv.style.height = "30px";
  zoomInDiv.style.position = "absolute";
  zoomInDiv.style.top = "75px";
  zoomInDiv.style.left = "0px";
  zoomInDiv.style.cursor = "pointer";
       
  
  container.appendChild(zoomInDiv);
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
  });

  var zoomOutDiv = document.createElement("div");
  
  zoomOutDiv.style.background = 'url(/images/MapControlZoomOut.png) no-repeat';
  zoomOutDiv.style.width = "30px";
  zoomOutDiv.style.height = "30px";
  zoomOutDiv.style.position = "absolute";
  zoomOutDiv.style.top = "105px";
  zoomOutDiv.style.left = "0px";
  zoomOutDiv.style.cursor = "pointer";
  
  container.appendChild(zoomOutDiv);
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut();
  });
  
  var panUp = document.createElement("div");
  
  panUp.style.background = 'url(/images/MapControlUp.png) no-repeat';
  panUp.style.width = "14px";
  panUp.style.height = "14px";
  panUp.style.position = "absolute";
  panUp.style.top = "17px";
  panUp.style.left = "32px";
  panUp.style.cursor = "pointer";
  
  container.appendChild(panUp);
  
  GEvent.addDomListener(panUp, "click", function() {
   map.panDirection(0,1);

  });
  
    var panDown = document.createElement("div");
  
  panDown.style.background = 'url(/images/MapControlDown.png) no-repeat';
  panDown.style.width = "14px";
  panDown.style.height = "14px";
  panDown.style.position = "absolute";
  panDown.style.top = "45px";
  panDown.style.left = "32px";
  panDown.style.cursor = "pointer";
  
  container.appendChild(panDown);
  GEvent.addDomListener(panDown, "click", function() {
  map.panDirection(0,-1);

  });
  
    var panLeft = document.createElement("div");
  
  panLeft.style.background = 'url(/images/MapControlLeft.png) no-repeat';
  panLeft.style.width = "14px";
  panLeft.style.height = "14px";
  panLeft.style.position = "absolute";
  panLeft.style.top = "31px";
  panLeft.style.left = "18px";
  panLeft.style.cursor = "pointer";
  
  container.appendChild(panLeft);

  GEvent.addDomListener(panLeft, "click", function() {
   map.panDirection(1,0);

  });
  
    var panRight = document.createElement("div");
  
  panRight.style.background = 'url(/images/MapControlRight.png) no-repeat';
  panRight.style.width = "14px";
  panRight.style.height = "14px";
  panRight.style.position = "absolute";
  panRight.style.top = "31px";
  panRight.style.left = "46px";
  panRight.style.cursor = "pointer";
  
  container.appendChild(panRight);
 
  GEvent.addDomListener(panRight, "click", function() {
   map.panDirection(-1,0);

  });
  
  
  
  

  map.getContainer().appendChild(container);
  return container;
}


HPXZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
}



MPolyDragControl = function(MOptions) {
	MOptions = MOptions ? MOptions : {};
	this.type = MOptions.type ? MOptions.type : 'circle';
	this.map = MOptions.map ? MOptions.map : null;

	this.unitDivisor = 2589988.11;
	this.initialize()
};


MPolyDragControl.prototype.initialize = function() {
	this.self = this;
	this.polyInitialized = false;
	this.bounds = null;
	this.addListener();

	this.radius;
	this.circleCenter;

	this.dragMarker0;
	this.dragMarker1;

	var baseIcon = new GIcon();
//	baseIcon.iconSize = new GSize(11,11);
	baseIcon.iconAnchor = new GPoint(6,6);
	baseIcon.infoWindowAnchor = new GPoint(1,1);
	baseIcon.dragCrossSize = new GSize(0,0);
//	baseIcon.maxHeight = 0.1;
	this.polyEditIcon = (new GIcon(baseIcon,"/images/Location-Pointer-Current-and-Location-Picker.png"));


//	this.floatingLabel = new ELabel(this.map.getCenter(), 'Label text', 'MDR_labelStyle',new GSize(10,20));
//	this.floatingLabel.hide();
	
//	this.map.addOverlay(this.floatingLabel); 
	
	}
;



MPolyDragControl.prototype.addListener = function(latlon) {
	var self = this.self;
	GEvent.addListener(this.map,'click',function(a,b,c){self.mapClick(b)});
}

MPolyDragControl.prototype.mapClick = function(latlon) {

//if(cset) return;
    
    if (latlon == null) return;
    // 0,0046 is 500m 
    var offsetMarkerPoint = new GLatLng(latlon.lat()+0.0046, latlon.lng());
	var self = this.self;
	
	self.clear();
	
	var dotIcon = new GIcon();
	dotIcon.iconSize = new GSize(5,5);
	dotIcon.iconAnchor = new GPoint(0,0);
	dotIcon.infoWindowAnchor = new GPoint(1,1);
	dotIcon.dragCrossSize = new GSize(0,0);
	dotIcon.dragCrossAnchor = GPoint(0,0);

	self.dragMarker0 = new GMarker(latlon,{icon:self.polyEditIcon,draggable:false,bouncy:false,dragCrossMove:false});
	self.map.addOverlay(self.dragMarker0);

	self.dragMarker1 = new GMarker(offsetMarkerPoint,{icon:new GIcon(dotIcon,"/images/dot.png"),draggable:false,bouncy:false,dragCrossMove:false});
	//self.map.addOverlay(self.dragMarker1);

	GEvent.addListener(self.dragMarker0,'dragstart',function(){self.dragStart(this)});
	GEvent.addListener(self.dragMarker0,'drag',function(){self.drag(this)});
	GEvent.addListener(self.dragMarker0,'dragend',function(){self.dragEnd(this)});

	GEvent.addListener(self.dragMarker1,'dragstart',function(){self.dragStart(this)});
	GEvent.addListener(self.dragMarker1,'drag',function(){self.drag(this)});
	GEvent.addListener(self.dragMarker1,'dragend',function(){self.dragEnd(this)});

	this.poly = new GPolygon([latlon,latlon,latlon,latlon,latlon],'#A0A0A0',1,1,'#A0A0A0',0.3);
	//this.map.addOverlay(this.poly);
	cset = true;
	//draw the radius line
	this.radiusLine = new GPolygon([latlon,offsetMarkerPoint],'#A0A0A0',1,1,'#A0A0A0',0.5);
	//this.map.addOverlay(this.radiusLine);
	//GEvent.trigger(self.dragMarker1, 'dragstart');
	GEvent.trigger(self.dragMarker1, 'drag');
	GEvent.trigger(self.dragMarker1, 'dragend');
	

};




MPolyDragControl.prototype.dragStart = function() {
};

MPolyDragControl.prototype.drag = function() {
	var self = this.self;

	if (self.type == 'circle') {
		self.updateCircle();
	}
	else if (self.type == 'rectangle') {
		self.updateRectangle();
	}
};	

MPolyDragControl.prototype.dragEnd = function() {
	var self = this.self;
	if (self.ondragend) {
		self.ondragend();
	}
//	GLog.write('Search parameters: ' + self.getParams());
};

	

MPolyDragControl.prototype.updateRectangle = function() {
	var self = this.self;
	var latlon0 = self.dragMarker0.getLatLng();
	var latlon1 = self.dragMarker1.getLatLng();

	self.bounds = null;
	self.bounds = new GLatLngBounds();

	if (latlon0.lat() <= latlon1.lat() && latlon0.lng() <= latlon1.lng()) {
		var p1 = latlon0; // SW
		var p2 = latlon1; // NE
	}
	else if (latlon0.lat() <= latlon1.lat() && latlon0.lng() >= latlon1.lng()) {
		var p1 = latlon0; // SE
		var p2 = latlon1; // NW
	}
	else if (latlon0.lat() >= latlon1.lat() && latlon0.lng() >= latlon1.lng()) {
		var p1 = latlon0; // NE
		var p2 = latlon1; // SW
	}
	else if (latlon0.lat() >= latlon1.lat() && latlon0.lng() <= latlon1.lng()) {
		var p1 = latlon0; // NW
		var p2 = latlon1; // SE
	}

	self.bounds.extend(p1);
	self.bounds.extend(p2);

	var p1 = this.bounds.getSouthWest();
	var p2 = new GLatLng(this.bounds.getNorthEast().lat(),this.bounds.getSouthWest().lng());
	var p3 = this.bounds.getNorthEast();
	var p4 = new GLatLng(this.bounds.getSouthWest().lat(),this.bounds.getNorthEast().lng());
	var points = Array(p1,p2,p3,p4,p1);

	self.drawPoly(points);

};


MPolyDragControl.prototype.updateCircle = function() {

	this.circleCenter = this.dragMarker0.getLatLng();
	var points = Array();
	this.radius = this.dragMarker0.getLatLng().distanceFrom(this.dragMarker1.getLatLng()); // meters

	with (Math) {
		var d = this.radius/6378800;	// circle radius / meters of Earth radius = radians
		var lat1 = (PI/180)* this.circleCenter.lat(); // radians
		var lng1 = (PI/180)* this.circleCenter.lng(); // radians

		for (var a = 0 ; a < 361 ; a+=10 ) {
			var tc = (PI/180)*a;
			var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
			var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
			var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
			var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
			points.push(point);
		}
	}

	this.drawPoly(points);
};




MPolyDragControl.prototype.drawPoly = function(points) {
	if (this.poly) {
		this.map.removeOverlay(this.poly);
		this.poly = null;
		this.map.removeOverlay(this.radiusLine);
		this.radiusLine = null;
	}
	this.poly = new GPolygon(points,'#A0A0A0',1,1,'#A0A0A0',0.2);
	//this.map.addOverlay(this.poly);
	this.radiusLine = new GPolygon([this.dragMarker0.getLatLng(),this.dragMarker1.getLatLng()],'#A0A0A0',1,1,'#A0A0A0',0.5);
    //this.map.addOverlay(this.radiusLine);
    
	var html = '';
	if (this.type == 'circle') {
		html += 'Center:&nbsp;' + this.circleCenter.lat().toFixed(5) + ',' + this.circleCenter.lng().toFixed(5) + '<br>';
		html += 'Radius:&nbsp;' + (this.radius).toFixed(2) + '&nbsp;m.<br>';
	}
	else {
		html += 'Lat:&nbsp;' + this.bounds.getSouthWest().lat().toFixed(5) + '&nbsp;to&nbsp;' + this.bounds.getNorthEast().lat().toFixed(5) + '<br>';
		html += 'Lon:&nbsp;' + this.bounds.getSouthWest().lng().toFixed(5) + '&nbsp;to&nbsp;' + this.bounds.getNorthEast().lng().toFixed(5) + '<br>';
	}
	html += 'Area:&nbsp;' + (this.poly.getArea()/ this.unitDivisor).toFixed(2) + '&nbsp;sq.mi.';

	
	//this.floatingLabel.setContents(html);
	//this.floatingLabel.setPoint(this.dragMarker1.getLatLng());
	//this.floatingLabel.show();
}




MPolyDragControl.prototype.clear = function() {
	if (this.poly) {
		//this.map.removeOverlay(this.poly);
		this.poly = null;
	}
	if (this.dragMarker0) {
		this.map.removeOverlay(this.dragMarker0);
		this.dragMarker0 = null;
	}
	if (this.dragMarker1) {
		this.map.removeOverlay(this.dragMarker1);
		this.dragMarker1 = null;
	}
//	if (this.floatingLabel) {
//		this.floatingLabel.hide();
//	}
};



MPolyDragControl.prototype.getParams = function() {
	var str = '';
	if (this.type == 'circle') {
		str += 'centerLat=' + this.circleCenter.lat().toFixed(5) + '&centerLon=' + this.circleCenter.lng().toFixed(5);
		str += '&radius=' + (this.radius).toFixed(2); // radius in meters
	}
	else {
		str += 'lat1=' + this.bounds.getSouthWest().lat().toFixed(5) + '&lat2=' + this.bounds.getNorthEast().lat().toFixed(5);
		str += '&lon1=' + this.bounds.getSouthWest().lng().toFixed(5) + '&lon2=' + this.bounds.getNorthEast().lng().toFixed(5);
	}
	return str;
}

MPolyDragControl.prototype.getLat = function() {
	var str = '';
	
	if(this.circleCenter == null)
	    return 0;
	
	str=this.circleCenter.lat().toFixed(5);
	
	return str;
}

MPolyDragControl.prototype.getLng = function() {
	var str = '';
	
	if(this.circleCenter == null)
	    return 0;
	
	str=this.circleCenter.lng().toFixed(5);
	
	return str;
}

MPolyDragControl.prototype.getRadius = function() {
	var str = '';
	
	if (this.radius == null)
	    return 0;
	
	str=(this.radius).toFixed(2);
	
	return str;
}


MPolyDragControl.prototype.setType = function(type) {
	this.type = type;
	if (this.poly) {
		this.drag();
		this.dragEnd();
	}
};




MPolyDragControl.prototype.show = function() {
	this.poly.show();
};

MPolyDragControl.prototype.hide = function() {
	this.poly.hide();
};

MPolyDragControl.prototype.isVisible = function() {
	return !this.poly.isHidden();
};

//--


function dhtmlLoadScript(url)
{
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e); 
 //  alert(e.src.toString());
}



function getMap(markerFeed,loadnewMap, startlat, startlng,fitDataToZoom) {

    
    if (startlat == null || startlat == null) {
        fitDataToZoom = true;
    }
    //alert(fitDataToZoom);
    if (GBrowserIsCompatible()) {
        bounds = new GLatLngBounds();

        if (loadnewMap){
            map = new GMap2(document.getElementById("happenexMap"));
            if (document.getElementById('mapStoryControl') != null) {
                document.getElementById('mapStoryControl').style.visibility = 'visible';
            }
                     
            map.addControl(new GLargeMapControl());
            map.disableScrollWheelZoom();

            if (startlat != null && startlng != null){
                map.setCenter(new GLatLng(startlat, startlng), 10);
            }else{
                map.setCenter(new GLatLng(48.66, 8.43), 5);
            }
            
            if (locBounds != null){ 
                fitDataToZoom = false;
                map.setCenter(locBounds.getCenter());
                map.setZoom(map.getBoundsZoomLevel(locBounds));
            }
            bounds = new GLatLngBounds();                        
        }

            bounds = new GLatLngBounds();

            loadMarkers(jsonData);

            if (fitDataToZoom) {
                map.setCenter(bounds.getCenter());
                var zoomLevel = map.getBoundsZoomLevel(bounds);

                if (zoomLevel < 1) zoomLevel = 1;
                if (zoomLevel > 12) zoomLevel = 12;

                map.setZoom(zoomLevel);
            }

            getVisibleMarkersData(map.getBounds());

            if (gmarkers.length > 0) {
                setTimeout("if (document.getElementById('mapStoryControl') != null){document.getElementById('mapStoryControl').style.visibility = 'visible';}", 100);
            } else {
                setTimeout("if (document.getElementById('mapStoryControl') != null){document.getElementById('mapStoryControl').style.visibility = 'hidden';}", 100);
            } 
    }

            
    if (gmarkers.length<1){
        map.setCenter(new GLatLng(startlat, startlng), 10);
    }
          
    if (moveListener !=null) GEvent.removeListener(moveListener);
    //add event listener for move map, as soon as map is moved it should reload the markers
    moveListener = GEvent.addListener(map, "moveend", function() {
        // drawArrow(currmarker);

        if (document.getElementById("HiddenCurrentStoriesViewType") != null) {
            var type = document.getElementById("HiddenCurrentStoriesViewType").value;
            //alert("getMap " + type);
            if (type == "UserStories" || type == "SearchUsers") {
                //alert(document.getElementById("HiddenCurrentStoriesViewType").value);
                return;
            }
        }
        //                      
        //                          var center = map.getCenter();
        //                          
        //XXXXXXXXXXXX
        bounds = map.getBounds();

        var sw = bounds.getSouthWest();
        var ne = bounds.getNorthEast();

        var storyMarkers = getVisibleMarkersData(bounds);
        if (reloadSearchData != null) clearTimeout(reloadSearchData);
        //alert($("input#SearchTerm").val().substring(9,0));

        //        if ($("input#SearchTerm").val().substring(9, 0) == 'Location:' || $("input#SearchTerm").val().substring(9, 0) == 'location:') {
        //            if (movestarted) {
        //                reloadSearchData = setTimeout("SearchTrend('Story');", 1500);
        //                movestarted = false;
        //            }
        //        }
        //        else {
            if (movestarted) {
            if (!skipmovestarted) {
                //alert("Going to Refreshmap")
                searchTerm = "NULL";
                reloadSearchData = setTimeout("refreshMapViewData(true);", 1500);
                //  searchTerm = "filterData";
            }
                movestarted = false;
            }
        //}
        //                        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  
        //                          markers = null;
        //                          


        //                          month = document.getElementById('month').selectedIndex+1;
        //                          year = document.getElementById('year')[document.getElementById('year').selectedIndex].value;
        //                          //alert("move triggered");
        //                          minday = new Date().getDate()-7;
        //                          maxday = new Date().getDate();
        //                          
        //                         getMap("UCMap/CurrentLocationMap/"+ sw.lat() + "/" + sw.lng()+ "/" + ne.lat() + "/" + ne.lng()+ "/" + world + "/" + month + "/" + year + "/" + minday + "/" + maxday,false,null,null);
    });

    //Listener move
    var movestartListener = GEvent.addListener(map, "movestart", function() {
        if (polygon != null) {
            map.removeOverlay(polygon);
        }
        if (!skipmovestarted) {
            //alert("movestarted Move");
             movestarted = true;
        } 
         });

    //Listener zoom
    var zoomendListener = GEvent.addListener(map, "zoomend", function(a, b) {
        if (!skipmovestarted) {
            //alert("movestarted Zoom");
            movestarted = true;
        } 
        });
     
        //     markerClicked(marker,title,author,story,city,false);
        //            var polyOptions = {geodesic:true};
        //            var polyline = new GPolyline([new GLatLng(43.91892, -78.89231), new GLatLng(43.82589, -79.10040)], "#ff0000", 10, 0.5, polyOptions);
        //            map.addOverlay(polyline);       
}

function showSetRadiusMap(lat, lng) {
  map2 = new GMap2(document.getElementById("happenexMap1"));
                        map2.addControl(new GSmallMapControl());
        map2.addControl(new GMapTypeControl());
                        map2.disableScrollWheelZoom();
                         
                     //   var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0, -85));
                        
                          GEvent.addListener(map2, "click", getLocations);
                            geocoder = new GClientGeocoder();
                        
	//	map.addControl(new MStatusControl({position:pos}));

		polyDragControl = new MPolyDragControl({map:map2,type:'circle'});
		//getParameters should actually call some callback
		//polyDragControl.ondragend = getParameters;

		if (lat != null && lng !=  null){
		GEvent.trigger(map2, "click",null,new GLatLng(lat,lng)); 
		map2.setCenter(new GLatLng(lat, lng), 12);
		// TODO SelectLocation();
		}
}

   function createPositionMarker(point) {
        var marker = new GMarker(point,{draggable: true});
        var radiusMarker = new GMarker(new GPoint(point.x+100,point.y),{draggable: true});
        
        map.addOverlay(marker);
        map.addOverlay(radiusMarker);
        polyDragControl = new MPolyDragControl({map:map,type:'rectangle'});
		polyDragControl.ondragend = getParameters;


      }
   function removePositionMarker(marker) {
        map.removeOverlay(marker);
        map.removeOverlay(radiusMarker);
        polyDragControl.clear();
		


      }

function loadLocationSelector() {
  counter = 0;
  var marker;
  map = new GMap2(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  var myEventListener = GEvent.bind(this.map, "click", this, function(overlay, latlng) {
     if (this.counter == 0) {
       if (latlng) {
        marker = new GMarker(latlng,{draggable: true});
         map.addOverlay(marker);
         marker.enableDragging();
         GEvent.addListener(marker, "drag", function(){
         //   alert(marker.getPoint().toUrlValue());
            });


         this.counter++;
       } else if (overlay instanceof GMarker) {
         // This code is never executed as the event listener is
         // removed the second time this event is triggered
         this.removeOverlay(marker);
       }
     } else {
       GEvent.removeListener(myEventListener);
     }
  });
}

function getLocations(overlay, latlng) {

  if (latlng != null) {
    address = latlng;
    geocoder.getLocations(latlng, getLocInfo);
  }
}

function getLocInfo(response) {

    if (!response || response.Status.code != 200) {
         // alert("Status Code:" + response.Status.code);
        //resetWritePosition();
    } else {
        // place is xAL formated structure
        var locationCity = document.getElementById("LocationCityTemp");

        for (var i = 0; i < response.Placemark.length; i++) {
            place = response.Placemark[i];
            if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null &&
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null &&
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality != null &&
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality.DependentLocalityName != null) {
                locationCity.value = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality.DependentLocalityName;
                break;
            }
            else if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null &&
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null &&
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null &&
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName != null) {
                locationCity.value = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                break;
            } else if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.Locality != null &&
            place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName != null) {
                locationCity.value = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
                break;
            } else if (place.AddressDetails.Country != null && place.AddressDetails.Country.SubAdministrativeArea != null && place.AddressDetails.Country.SubAdministrativeArea.Locality != null &&
            place.AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName != null) {
                locationCity.value = place.AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
                break;
            } else if (place.AddressDetails.Country != null && place.AddressDetails.Country.Locality != null && place.AddressDetails.Country.Locality.LocalityName != null) {
                locationCity.value = place.AddressDetails.Country.Locality.LocalityName;
                break;
            }
        }
        if (locationCity.value == "") {
            for (var i = 0; i < response.Placemark.length; i++) {
                place = response.Placemark[i];
                locationCity.value = getCityFromAddress(place.address);
                if (locationCity.value != "") {
                    break;
                }
            }
        }
        
        //alert(locationCity.value);
        var locationTextBox = document.getElementById("location");

        if (locationCity != null) {
            if (locationCity.value != "") $('#hpxCity').text(locationCity.value + '?');
        else {
            //resetWritePosition();
            //return;
        }
    }

    var locationCountry = document.getElementById("LocationCountryTemp");
    for (var i = 0; i < response.Placemark.length; i++) {
        place = response.Placemark[i];
        if (locationCountry != null) {
            if (place.AddressDetails.Country.CountryName != null) {
                locationCountry.value = place.AddressDetails.Country.CountryName;
                break;
            } else {
                locationCountry.value = getCountryFromAddress(place.address);
            }
        }
    }
   
    var locationCode = document.getElementById("LocationPostalcodeTemp");
    for (var i = 0; i < response.Placemark.length; i++) {
        place = response.Placemark[i];
        if (locationCode != null) {
            if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality != null && place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.PostalCode != null && place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber != null) {
                locationCode.value = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
                break;
            }else if(place.AddressDetails.PostalCode != null && place.AddressDetails.PostalCode.PostalCodeNumber != null){
                locationCode.value = place.AddressDetails.PostalCode.PostalCodeNumber;
                break;
            }
        }
    }

    
    var locationStreet = document.getElementById("LocationStreetTemp");
    for (var i = 0; i < response.Placemark.length; i++) {
        place = response.Placemark[i];
        if (locationStreet != null) {
            if (place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality != null && place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare != null && place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName != null) {
                locationStreet.value = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
                break;
            }
        }
    }

    var locationRegion = document.getElementById("LocationRegionTemp");
    for (var i = 0; i < response.Placemark.length; i++) {
        place = response.Placemark[i];
        if (locationRegion != null) {
            if (place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName) {
                locationRegion.value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                break;
            }
        }
    }
  }
    
  gotResponse = true;

}

function getCountryFromAddress(address){
    return address.toString().substring(address.toString().lastIndexOf(", ") + 2);
}

function getCityFromAddress(address) {
    var ar = address.toString().split(",");
    if (ar.length < 2 && ar.length == 1)
        return address.toString();

    return ar[ar.length - 2];
}

function parseJson (doc,marker) {
//alert(doc);
//doc = escape(doc);
//try{
//alert("start eval");
 var json = eval('(' + doc + ')');
//alert("end eval");
marker.title = json.title;
//alert("set title to" + json.title);
marker.summary = json.summary;
marker.EditedBy = json.EditedBy;
marker.author = json.author;
marker.date = json.date;
marker.storyType = json.storyType;
marker.externalUrl = json.externalUrl; 
marker.city = json.city;
marker.comments = json.comments;
marker.country = json.country;
marker.labelText = json.labelText;
marker.titleURL = json.TitleURL; 

markersCache[marker.storyID] = marker;
//}
//catch (err) {
//alert(err);
//}


}


function loadMarkers(doc){

    //alert(doc);
    try {
            var data = jsonData;
            //alert(data.markers.length);

            for (var i = 0; i < data.markers.length; i++) {
                // obtain the attribues of each marker
                var lat = data.markers[i].lat;
                var lng =data.markers[i].lng;
                var point = new GLatLng(lat,lng);
                var storyID= data.markers[i].storyID;

                // create the marker
                // alert("create marker" + storyID);
                var marker = createMarker(point,storyID,data.markers[i]);         
                markersCache[storyID] = marker;
                              
                // marker.image="/images/Location-Pointer.png";
                bounds.extend(point);       
            }
                 
            if (markerCluster != null) markerCluster.clearMarkers();
            markerCluster= null;
            markerCluster = new MarkerClusterer(map, getGmarkersFromCache(),"/images/Location-Pointer.png");    
      }
      catch (err){
            alert("Parse error:" + err);
      }

}


   // A function to create the marker and set up the event window
      function createMarker(point,storyID,data) {
          
        var marker = new LabeledMarker(point,myIcon,false,storyID);
        
        if (typeof(data.title) != "undefined"){
      
            marker.title = data.title;
            marker.summary = data.summary;
            marker.EditedBy = data.EditedBy;
            marker.author = data.author;
            marker.date = data.date;
            marker.city = data.city;
            marker.comments = data.comments;
            marker.country = data.country;
            marker.labelText = data.labelText;
            marker.storyType = data.storyType;
            marker.externalUrl = data.externalUrl;
            marker.TitleURL = data.TitleURL;

            gmarkers.push(marker); 
        }
        GEvent.addListener(marker, "click", function(stopSlideshow) {
            refreshStoryBox(marker);
        });


        return marker;
    }

    function refreshStoryBox(marker) {
        if (typeof (stopSlideshow) != "undefined") {
            clearTimeout(timer);
        }
        currmarker = marker;
        drawArrow(marker);
        //for (var key1 in gmarkers) {
        // x       alert("key:" + key1 + " is hidden:" + gmarkers[key1].isHidden() );        
        //x    if (!gmarkers[key1].isHidden()) gmarkers[key1].setImage(marker.getIcon().image);
        //}


        //x     if (!marker.isHidden()) 
        //x  marker.setImage("/images/Location-Pointer-Current-and-Location-Picker.png");

        //        for (var key1 in gmarkers)
        //        gmarkers[key1].setImage(marker.getIcon().image);
        //  marker.setImage("/images/Location-Pointer.png");

        if (marker.title == "" || marker.title == "undefined") {
            GDownloadUrl("/UCMap/StoryDetails/" + marker.storyID, function(data, responseCode) {
                parseJson(data, marker);
                showStoryBox(marker);
            });
        } else {
            showStoryBox(marker);
        }
    }
      
 
 //loads markers from cache to object loadable by map clusterer
 function getGmarkersFromCache(){
 var markers=[];
 var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

// alert(is_chrome);
 
 for(var storyID in markersCache){
 markers.push(markersCache[storyID]);
         }
         //alert(markers.length);
         if (is_chrome)
          markers.reverse();
 return markers;
 }
 
 function showStoryBox(marker){
//  for (key in gmarkers)
//        gmarkers[key].setImage(marker.getIcon().image);
//        marker.setImage("http://maps.google.com/mapfiles/ms/micons/green-dot.png");
       
  //alert("write html");
     // drawArrow(marker);
     var rss = (marker.externalUrl != "" && marker.storyType == 'RSS');
     var url = "#";
     var target = "";
     var comment = "";
        url = "/Story/Read/" + marker.storyID + "/" + marker.TitleURL;
        
     document.getElementById("newsTickerContent").innerHTML="" + 
       "<div class=\"newsTickerStoryPaging\"><div id=\"pagingLeft\"><a href=\"javascript:showNextStory(true);\">«</a></div><div id=\"pagingRight\"><a href=\"javascript:showNextStory(false);\"/>»</a></div></div>" +
       "<h2><a href=\"" + url + "\" " + target + " >" + marker.title + "</a></h2>" +
       "<p class=\"small\">" + marker.EditedBy + "<a onclick=\"javascript:GoToUserProfile('" + marker.author + "');return false;\">" + marker.author + "</a> on " + marker.date + "</p>" +
       "<div class=\"newsTickerStory\"><p>" + marker.summary + "</p></div>" +
       "<div class=\"newsTickerBottom small\"><div class=\"newsTickerStoryComments\">" + comment + "</div>" +
       "<div class=\"newsTickerStoryLocation \"><a onclick=\"javascript:SearchLocation('" + marker.city + "');return false;\">" + marker.city + ", " + marker.country + "</a></div></div>";
       //
  
  
      var numstories=getGmarkerCount(marker);

      document.getElementById("newsTickerHeader").innerHTML = "<div class=\"v-middle\"><h2>" + marker.labelText + " <a onclick=\"javascript:SearchLocation('" + marker.city + "');return false;\">" + marker.city + "?</a><span class=\"smallHeader\"> (" + numstories + "/" + gmarkers.length + ")</span></h2></div>"; 
         //document.getElementById("locCityCountry").innerHTML =marker.city + "," + marker.country;
        
       // document.getElementById("commentsNr").innerHTML =marker.comments;
       
        $('#hpxCity').text(marker.city + '?') ;
 }
 
 
 function getVisibleMarkersData(bounds){
// alert("getVsible");
// bounds = map.getBounds();
     gmarkers = [];

     var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

    

 for (var sid in markersCache){
  if (bounds.containsLatLng(markersCache[sid].getLatLng()) && gmarkers.length<20 )
      gmarkers.push(markersCache[sid]);



}

if (is_chrome) 
gmarkers.reverse();
 
 //alert("load clusterer");
map.clearOverlays();
//document.getElementById('mapStoryControl').style.visibility = 'hidden';
 if (markerCluster != null) markerCluster.clearMarkers();
markerCluster = new MarkerClusterer(map, getGmarkersFromCache(),"/images/Location-Pointer.png");
 
 
 if (gmarkers.length>0){
     //TODO GEvent.trigger(gmarkers[0], 'click');
     if (document.getElementById('mapStoryControl') != null) {
         document.getElementById('mapStoryControl').style.visibility = 'visible';
     }
    //setTimeout("startHappenexSlideShow();", 5000);
    if (firstload) {
        startHappenexSlideShow();
        firstload = false;
    }
} else {
    if (document.getElementById('mapStoryControl') != null) {
        document.getElementById('mapStoryControl').style.visibility = 'hidden';
    }
 }
 
 return gmarkers;
 
 }
 
 
 
 
 
 
 function loadSessionMarkers(addMoveListener){
 
 }
 
function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
}


function SelectLocation()
{
    //alert("select location");
    var locationLatitude = document.getElementById('LocationLatitude');
    var locationLongitude = document.getElementById('LocationLongitude');
    var locationRadius = document.getElementById('LocationRadius');
    var location = document.getElementById('location');

    if (locationLatitude == null || locationLongitude == null || locationRadius == null || location == null || typeof (polyDragControl) == "undefined") {
       
        return;
    }
    // alert("polyl1");
    
    locationLatitude.value = polyDragControl.getLat();    
    locationLongitude.value = polyDragControl.getLng(); 
    locationRadius.value = polyDragControl.getRadius();
            
    var locationCity = document.getElementById('LocationCityTemp');
    // alert("coty" + locationCity);
    if (locationCity != null && locationCity != ""){
        location.value = locationCity.value;
        if (document.getElementById('locationTemp') != null) {
            document.getElementById('locationTemp').value = locationCity.value;
        }
        document.getElementById('LocationCity').value = locationCity.value;
    }
 
    var locationTextBox = document.getElementById("location");

    // alert(locationCity.value);
  
    if (location != null && locationCity.value != "")
    {
       //  alert("setting location to ->" + locationCity.value);
        location.value = locationCity.value;
        if (document.getElementById('locationTemp') != null) {
            document.getElementById('locationTemp').value = locationCity.value;
        }
        $('#location').valid();
    }
    
    if (document.getElementById("hpxCity") != null && locationCity.value !="") {
        if (locationCity.value == null) {
            setTimeout('SelectLocation()', 500);
            return;
        }
        // alert("hpxCity->"  + locationCity.value);
        $('#hpxCity').text(locationCity.value + '?') ;
    }else{
        // resetWritePosition();
        // return;
    }
    
    var locationCountry = document.getElementById("LocationCountryTemp");
    if (locationCountry != null){
        document.getElementById('LocationCountry').value = locationCountry.value;
    }
    
    var locationCode = document.getElementById("LocationPostalcodeTemp");
    if (locationCode != null){ 
        document.getElementById('LocationPostalcode').value = locationCode.value;
    }
    
    var locationStreet = document.getElementById("LocationStreetTemp");
    if (locationStreet != null){
        document.getElementById('LocationStreet').value = locationStreet.value;
    }
    
    var locationRegion = document.getElementById("LocationRegionTemp");
    if (locationRegion != null){
        document.getElementById('LocationRegionTemp').value = locationRegion.value;
    }
}
            
 //    Hide('LocationPicker');
       
        
function showStory(lat, lng){
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("happenexMap1"));
        map.disableDragging();
        // map.disableDoubleClickZoom();
        //  map.disableContinuousZoom();
        map.addControl(new GSmallZoomControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,30)));
        map.addControl(new GMapTypeControl());
        
        map.disableScrollWheelZoom();

        map.setCenter(new GLatLng(lat, lng), 17);
        var latlng = new GLatLng(lat, lng);
        map.addOverlay(new GMarker(latlng,myIcon,true));
        map.setMapType(G_SATELLITE_MAP);
    }
}

function openUserProfile(userName){

    //window.location = "/" + userName + "/" + map.getBounds().getSouthWest().lat() + "/" + map.getBounds().getSouthWest().lng() + "/" + map.getBounds().getNorthEast().lat() + "/" + map.getBounds().getNorthEast().lng();
    window.location = "/" + userName;

}

//function loadUserProfile(userName){

// $.ajax({
//   type: "GET",
//   url: "/Home/UserStoriesAjax/" + userName + "/"  + map.getBounds().getSouthWest().lat() + "/" + map.getBounds().getSouthWest().lng() + "/" + map.getBounds().getNorthEast().lat() + "/" + map.getBounds().getNorthEast().lng(),
//   //data: "&id=" + userName +"&minLat=" + map.getBounds().getSouthWest().lat() + "&minLong=" + map.getBounds().getSouthWest().lng() + "&maxLat=" + map.getBounds().getNorthEast().lat() + "&maxLong=" + map.getBounds().getNorthEast().lng(),
//   success: function(msg){
//
//     $("#leftContentContainer").html(msg);
// 
//     
//   }
// });
//return false;


//}

function writeSubmit(){

if ($("input#LocationLatitude").val()==""){
$("input#LocationLatitude").val(map.getCenter().lat());
}
if ($("input#LocationLongitude").val()==""){
$("input#LocationLongitude").val(map.getCenter().lng());
}

$("input#LocationRadius").val(500);
//$("input#LocationCity").val($('#hpxCity').text());
//$("input#location").val($('#hpxCity').text());





}



    
    
    



 

