﻿dojo.require("esri.map");
dojo.require("esri.toolbars.navigation");

//Global vars
var map;
var navToolbar;
var CurrentMapTool = "Nav";
var TweetGISUrl = "http://tweetgis.civilsolutions.biz/TweetGIS/Main.htm";//"http://localhost/TweetGIS/Main.htm"; //"http://tweetgis.civilsolutions.biz/TweetGIS/Main.htm";
var ProxyBaseURL = "http://tweetgis.civilsolutions.biz/TweetGISProxy/Proxy.mvc/";//"http://localhost/TweetGISProxy/Proxy.mvc/"; //"http://tweetgis.civilsolutions.biz/TweetGISProxy/Proxy.mvc/";
var ParcelLayer = null;
var ParcelLayerURL = "http://www3.arh-us.com/ArcGIS-Public/rest/services/TweetGIS/MapServer";
var WorksheetName = "Parcels";
var ShareUrl = "http://spreadsheets.google.com/ccc?key=pc7eowBai9SI7ASPds5WBDw";
var CurrentSelectedFeatureID = "";
var TwitterAppAccountName = "TweetGIS";
var Twitter = new TwitterClass();

function init() {
	$().ready(function() {
		
		//Set map to full expand
		var WinSize = new WindowSizeClass();
		$("#Map").css({ "height" : WinSize.height() });
		$("#Tweetbox").css({ "height" : (WinSize.height() - 20) });
		$("#TweetContent").css({ "height" : (WinSize.height() - 75) });
		
		//Setup mac dock menu
		var opt = { align: "top", labels:true, size:48 };
		$("#DockMenu").jqDock(opt);
			
		map = new esri.Map("Map");
		navToolbar = new esri.toolbars.Navigation(map);
				
		var id = querySt("id");
		
		//Wire up dojo events
		dojo.connect(map,"onLoad", function(map) {map.infoWindow.resize(400, 235);} );
		dojo.connect(map, "onClick", MapClick);
		dojo.connect(map,"onLoad", function(map) { 
			//Zoom to intial extent
			if(id == undefined){
				map.setExtent(GetIntialExtent(map.extent));
			}
		});
		
		//Zoom to parcel if id is requested
		if(id != undefined && id != ""){
			//Wait for id extent
			ParcelIDExtent(map,id);
		}
		
		//Load layers
		var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer");
		map.addLayer(tiledMapServiceLayer);
		
		ParcelLayer = new esri.layers.ArcGISDynamicMapServiceLayer(ParcelLayerURL,{ visible:true });
		ParcelLayer.setOpacity(0.5)
		map.addLayer(ParcelLayer);
		
		
		//Twitter class
		Twitter.StartStatusUpdates();
		
		//Get cookie info
		var UserInfo = $.cookie("TweetGIS");
		if(UserInfo == null ){
			//Show first time user info box
			$("#UserInfo").modal();
		}
		else{
			//Tweet returning user
			var UserInfo = new UserInfoClass(JSON.parse($.cookie("TweetGIS")));
			if(!UserInfo.IsAnonymous()){
				Twitter.Tweet("* Welcome back " + UserInfo.UserName + "! " + UserInfo.TwitterProfileURL() );
			}
		}

		//Wire resize event
		$(window).resize(function() {
			
			
			var WinSize = new WindowSizeClass();
			$("#Map").css({ "height" : WinSize.height() });
			$("#Tweetbox").css({ "height" : (WinSize.height() - 20) });
			$("#TweetContent").css({ "height" : (WinSize.height() - 75) });
			
			map.resize();
		});
		
		//---- Twitter box ------
		$(".ParcelLink").live("click", function(){
			map.infoWindow.hide();
			ParcelIDExtent(map,$(this).attr("value"),0);
		});
		
		$("#TwitterFollow").click(function() {
			window.open("http://twitter.com/" + TwitterAppAccountName);
		});
		
		//---- User info modal ------
		$("#SaveUserInfo").click(function() {
			var NewUserInfo = new UserInfoClass();
			NewUserInfo.UserName = $.trim($("#Name").val());
			NewUserInfo.TwitterProfile = $.trim($("#TwitterProfile").val());

			$.cookie("TweetGIS",JSON.stringify(NewUserInfo),{ expires: 99 });
			$.modal.close();
			
			//Tweet new user
			Twitter.Tweet("+" + NewUserInfo.UserName + " has become a new user!! " + NewUserInfo.TwitterProfileURL());
		});
		
		$("#AnonytUserInfo").click(function() {
			var NewUserInfo = new UserInfoClass();
			NewUserInfo.UserName = "Anonymous";
			NewUserInfo.TwitterProfile = "";
			
			$.cookie("TweetGIS",JSON.stringify(NewUserInfo),{ expires: 99 });
			$.modal.close();
		});

		//---- Dashboard -------
		$("#Navigation").click(function() {
			map.enableMapNavigation();
            navToolbar.deactivate();
			CurrentMapTool ="Navigation";
		});

		$("#Identify").click(function() {
			navToolbar.deactivate();
            map.disableMapNavigation();
			CurrentMapTool ="ShowEditAttrForm";
		});
		
		$("#DownloadData").click(function() {
			window.open(ShareUrl);
		});

		$("#EditProfile").click(function() {
			var UserInfo = JSON.parse($.cookie("TweetGIS"));
			$("#Name").val(UserInfo.UserName);
			$("#TwitterProfile").val(UserInfo.TwitterProfile);
			
			$("#UserInfo").modal();
		});

		//---- Spreadsheet Form -------
		$("#SaleDate").live("click",function(){
			$("#SaleDate").datepicker();
		});
		
		$("#Update").live("click",function(){
			UpdateSpreadsheet();
		});

		function MapClick(evt) {
			switch (CurrentMapTool) {
				case "ShowEditAttrForm":
					ShowEditAttrForm(evt,map);
					break;
			}
		}
	});
}
function ParcelIDExtent(Mymap,id,timeDelay){
	var extent = null;
	var WhereString = "objectid=" + id;
	
	if(timeDelay == null){
		timeDelay = 1500;
	}

    //Zoom to filtered cases
    var queryTask = new esri.tasks.QueryTask(ParcelLayerURL + "/0");
    var query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.where = WhereString;
    queryTask.execute(query, function(results) {
        
        //Give the map object time to catch up after an intial load of the site.
        window.setTimeout(function(){
	        var SelectedSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.5]));
			results.features[0].symbol = SelectedSymbol;
			map.graphics.clear();
			map.graphics.add(results.features[0]);
		},timeDelay);

        //Zoom to the extent of the points
        Mymap.setExtent(results.features[0].geometry.getExtent().expand(2));
    });
}

function UpdateSpreadsheet(){
	var RowItem = new RowItemClass();
	RowItem.Acreage = $("#Acreage").val();
    RowItem.PropertyClass = $("#PropClass option:selected").val();
    RowItem.Zoning = $("#Zoning option:selected").val();
    RowItem.SaleDate = $("#SaleDate").val();
    RowItem.SalePrice = $("#SalePrice").val();
    RowItem.Address = $("#Address").val();
    
	$("#StatusMsg").text("Saving to Google Spreadsheets...");
    $("#StatusMsgContainer").fadeIn(500);

    $.post(ProxyBaseURL + "UpdateSpreadSheet", { Worksheet:WorksheetName, RowId:CurrentSelectedFeatureID, UpdatedRow:JSON.stringify(RowItem) },function(data){
    	ShowProgress = false;
    	
    	//Tweet update
    	var UserInfo = JSON.parse($.cookie("TweetGIS"));
    	Twitter.Tweet("~" + UserInfo.UserName + " has updated parcel ID:" + CurrentSelectedFeatureID + " " + TweetGISUrl + "?id=" + CurrentSelectedFeatureID);
    	
    	if(data){
    		$("#StatusMsg").text("Save successful!");
    	}
    	else{
    		$("#StatusMsg").text("Error saving!");
    	}
    	
    	$("#StatusMsgContainer").fadeOut(5000,function(){
			$("#StatusMsg").text("");
		});
    });
}

function ShowEditAttrForm(evt,myMap){
	//Clear any previous selections
	myMap.graphics.clear();

	//Show progress status
    $("#StatusMsg").text("Getting Google Spreadsheet data...");
    $("#StatusMsgContainer").fadeIn(500);
            
    var queryTask = new esri.tasks.QueryTask(ParcelLayerURL + "/0");
    var query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.geometry = GetPointExtent(evt.mapPoint,myMap.extent);
    query.outFields = ["OBJECTID"];
    
    queryTask.execute(query, function(results) {   	
    	CurrentSelectedFeatureID = results.features[0].attributes.OBJECTID;
    	myMap.infoWindow.setTitle("Edit Google spreadsheet");
    	
    	$.get("SpreadsheetForm.htm","",function(html){
       		var fHtml = $(html);
    		myMap.infoWindow.setContent(fHtml.html());
    		
    		//Get spreadsheet data
    		$.ajax({
                    type: "GET",
                    cache: false, //have to set this because IE likes caching everything!
                    data: "Worksheet=" + WorksheetName + "&Query=objectid=" + CurrentSelectedFeatureID,
                    url: ProxyBaseURL + "QuerySpreadsheet?",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(spResults){	
		    			ShowProgress = false;
		    			$("#StatusMsgContainer").fadeOut(1000,function(){
		    				$("#StatusMsg").text("");
		    			});
		    			
		    			//Highlight parcel
		    			var SelectedSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,255,0]), 2), new dojo.Color([255,255,0,0.5]));
						results.features[0].symbol = SelectedSymbol;
						myMap.graphics.add(results.features[0]);
		
						//$("#DebugWindow").append(spResults);
		    			//Serialize JSON to RowItemClass object
		    			var RowItem = spResults;//JSON.parse(spResults);    			
		    			$("#Acreage").val(RowItem[0].Acreage);
					    $("#PropClass option[value='" + RowItem[0].PropertyClass + "']").attr("selected","selected");
					    $("#Zoning option[value='" + RowItem[0].Zoning + "']").attr("selected","selected");
					    $("#SaleDate").val(RowItem[0].SaleDate);
					    $("#SalePrice").val(RowItem[0].SalePrice);
					    $("#Address").val(RowItem[0].Address);
			    		
				    	myMap.infoWindow.show(evt.screenPoint,myMap.getInfoWindowAnchor(evt.screenPoint));
				    	}
    		});
    		
    	},"html");
    });
}
function GetPointExtent(pt,MapExtent){
    var factor = (MapExtent.xmax - MapExtent.xmin) / 800; //some factor for converting point to extent
    var extent = new esri.geometry.Extent(pt.x - factor, pt.y - factor, pt.x + factor, pt.y + factor, MapExtent.spatialReference);
    return extent;
}

function GetIntialExtent(MapExtent){
	var extent = new esri.geometry.Extent(-74.81906175613403, 39.6076226234436, -74.79159593582153, 39.62214946746826, MapExtent.spatialReference);
	return extent;
}
function querySt(ji,url) {
	if($.trim(url) == ""){
		hu = window.location.search.substring(1);
	}else{
		hu = url;
	}
	
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

//---Custom Objects -----
function RowItemClass()
{
    this.ID = "";
    this.Acreage = "";
    this.PropertyClass = "";
    this.Zoning = "";
    this.SaleDate = "";
    this.SalePrice = "";
    this.Address = "";
    this.Desc = "";
}

function UserInfoClass(ExistingObject){
	this.UserName = "";
	this.TwitterProfile = "";
	this.TwitterProfileURL = function(){
		if($.trim(this.TwitterProfile) != ""){
			return "http://www.Twitter.com/" + this.TwitterProfile;
		}
		else{
			return "";
		}
	};
	
	//Construct new object with existing
	if(ExistingObject != null){
		this.UserName = ExistingObject.UserName;
		this.TwitterProfile = ExistingObject.TwitterProfile;
	}
	
	this.IsAnonymous = function(){
		if($.trim(this.UserName) == "Anonymous"){
			return true;
		}else{
			return false;
		}
	}
}

function TwitterClass(){
	var LastStatuID = "";
	var Interval = null;
	
	this.StartStatusUpdates = function(){
		GetTwitterUpdate(LastStatuID)
		Interval = self.setInterval(function(){GetTwitterUpdate(LastStatuID)},18000);
	}
	
	this.StopStatusUpdates = function(){
		Interval = window.clearInterval(Interval);
	}

	var GetTwitterUpdate = function(id){
	
		var Tweets = "";
		var url = "http://search.twitter.com/search.json?q=from:" + TwitterAppAccountName + "&rpp=80&callback=?";
		if(id != ""){
			url = url + "&since_id=" + id;
		}
		
		$.getJSON(url, function(data){
			var last;
			$.each(data.results, function(i,item){
				Tweets += CreateTweetHTML(item.text);
				
				//Grab first item which is the last status update
				if(i == 0){
					//We save last status id so that next time it only grabs new tweets.
					LastStatuID = item.id;
					//alert(item.id);
				}		
			});
			
			if(Tweets != ""){
				AddTweet(Tweets);
			}
			
		});	
	}
	
	this.Tweet = function(Msg){
		$.post(ProxyBaseURL + "AddTweet", { TweetMsg:Msg }, function(data){
			//var TweetItem = JSON.parse(data);
			//alert(TweetItem.text);
		});
	}

	var CreateTweetHTML = function(Msg){
		var Tweet = "<div class='Tweet'>";
		var Link = "";
		var EventType = Msg.charAt(0);
		switch(EventType){
			case "*":
				Tweet += "<img src='Images/User_Logged_In_Event.png' alt='UserLoggedIn' />";
				var l = GetURL(Msg);
				if(l != ""){
					Link = "<a href='" + l + "' target='_blank'>Follow</a>"
				}
				break;
			case "+":
				Tweet += "<img src='Images/User_Created_Event.png' alt='UserCreated' />";
				var l = GetURL(Msg);
				if(l != ""){
					Link = "<a href='" + l + "' target='_blank'>Follow</a>"
				}
				break;
			case "~":
				Tweet += "<img src='Images/Edit_Event.png' alt='Edit' />";
				Link = "<div class='ParcelLink' value='" + GetParcelID(Msg) + "'>Parcel Link</div>"				
				break;
		}
		
		Tweet += "<p>" + StripURL(Msg) + "</p>";
		Tweet += Link;
		Tweet += "</div>";
		return Tweet;
	}
	
	function GetURL(s){
		var aryURL = s.split(" ");
		if(aryURL.length > 0){
			var LastItem = aryURL[aryURL.length - 1];
			if(LastItem.indexOf("http://") != -1){
				return LastItem;
			}else{
				return "";
			}
		}
	}
	
	function StripURL(s){
		var aryURL = s.split(" ");
		if(aryURL.length > 0){
			var urlindex = s.indexOf("http://");
			if(urlindex != -1){
				return s.substring(0,urlindex);
			}else{
				return s;
			}
		}
	}

	function GetParcelID(s){
		var aryURLItems = s.split(" ");
		for(var i in aryURLItems){
			if(aryURLItems[i].indexOf("ID:") != -1){
				return aryURLItems[i].split(":")[1];
			}
		}
	}

	
	var AddTweet = function(Tweet){
		var defaultColor = $("#TweetContent").css("backgroundColor");
		$("#TweetContent").prepend(Tweet).animate({ backgroundColor: "#FF9900" }, 500,"",function(){
			$(this).animate({ backgroundColor: defaultColor }, 500);
		});
	}
}

function WindowSizeClass() {
	var myWidth = 0;
	var myHeight = 0;
	getSize();

	this.height = function(){
		return myHeight;
	}

	this.Width = function(){
		return myWidth;
	}
	
	function getSize(){
	  //var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  //window.alert( 'Width = ' + myWidth );
	  //window.alert( 'Height = ' + myHeight );
	}
}

dojo.addOnLoad(init);