﻿$(function() {
    $("#reportfire").draggable({
        appendTo: "#map",
        cursor: "crosshair",
        cursorAt: { "bottom": 0, "left": 12 },
        opacity: 0.35,
        revert: true,
        revertDuration: 200,
        containment: "#map",
        start: function(event, ui) {
            gmap.closeInfoWindow();
        },
        stop: function(event, ui) {
            var x = event.pageX - this.offsetLeft + 87;
            var y = event.pageY - 226;

            var dropPos = gmap.fromContainerPixelToLatLng(new GPoint(x, y));
            PromptCreateTweet(dropPos);
        }
    });


});

function InitMyHouse() {
    if (ReadCookie("houselat")) {
        var lat = ReadCookie("houselat");
        var lng = ReadCookie("houselng");

        $(".houseusername").val(ReadCookie("twittername"));
        var dropPos = new GLatLng(lat, lng);
        $("#myhouse").css("display", "none");

        AddMyHouse(dropPos);
    }
    else {

        $("#myhouse").draggable({
            appendTo: "#map",
            cursor: "crosshair",
            cursorAt: { "bottom": 0, "left": 12 },
            opacity: 0.35,
            revert: false,
            revertDuration: 200,
            containment: "#map",
            start: function(event, ui) {
                gmap.closeInfoWindow();
            },
            stop: function(event, ui) {
                var m = $("#map");

                var x = event.pageX - m.get(0).offsetLeft;
                var y = event.pageY - 226;

                var dropPos = gmap.fromContainerPixelToLatLng(new GPoint(x, y));
                AddMyHouse(dropPos);
                $("#myhouse").css("display", "none");
            }
        });
    }
}

function AddMyHouse(pos) {
    var imageURL = "/Content/Images/house.png";
    
    var houseIcon = new GIcon(G_DEFAULT_ICON);
    houseIcon.image = imageURL;
    houseIcon.iconSize = new GSize(28, 28);
    houseIcon.infoWindowAnchor = new GPoint(9, 2);
    houseIcon.shadow = "";

    CreateCookie("houselat", pos.lat());
    CreateCookie("houselng", pos.lng());

    var markerOptions = { icon: houseIcon, draggable: true };

    var marker = new GMarker(pos, markerOptions);

    GEvent.addListener(marker, "dragstart", function() {
        gmap.closeInfoWindow();
    });

    GEvent.addListener(marker, "dragend", function() {
        PromptHouse(marker);
    });

    GEvent.addListener(marker, "click", function() {
        PromptHouse(marker);
    });

    gmap.addOverlay(marker);

}

function PromptHouse(marker) {
    var officialState = true;
    var communityState = true;
    
    if (ReadCookie("official")) officialState = ReadCookie("official");
    if (ReadCookie("community")) communityState = ReadCookie("community");

    CreateCookie("houselat", marker.getLatLng().lat());
    CreateCookie("houselng", marker.getLatLng().lng());
    
    marker.openInfoWindowHtml($("#housepromptcontainer").html());

    setTimeout(function() {
        $(".chkOfficialTweets").attr("checked", officialState);
        $(".chkCommunityTweets").attr("checked", communityState);
        var username = "";
        if (ReadCookie("twittername")) username = ReadCookie("twittername");

        $(".houseusername").val(username);

        var geocoder = new GClientGeocoder();
        geocoder.getLocations(marker.getLatLng(), showHouseAddress);
    }, 500);
}

function showHouseAddress(response) {
    if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    } else {
        $(".myhouselocation").text(response.Placemark[0].address);
    }
}

function HouseSubmit() {
    var officialNotices = $("#map .chkOfficialTweets:checked").length > 0;
    var communityNotices = $("#map .chkCommunityTweets:checked").length > 0;
    var username = $("#map .houseusername").val();
    var latitude = ReadCookie("houselat");
    var longitude = ReadCookie("houselng");

    CreateCookie("twittername", username);
    gmap.closeInfoWindow();
    
    $("#mapnotice").text("Your preferences have been saved")
            .slideDown(200);
    setTimeout(function() {
        $("#mapnotice").slideUp(200);
    }, 2000);
    
    $.post(
        "/House",
        {
            "username": username,
            "officialNotices": officialNotices,
            "communityNotices": communityNotices,
            "latitude": latitude,
            "longitude": longitude
        },
        function() {
        },
        "json");
}

function PromptCreateTweet(latlng) {
    gmap.openInfoWindow(latlng, $("#reportpromptcontainer").html());
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(latlng, showAddress);
}

function showAddress(response) {
    if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    } else {
        CreateCookie("houseaddress", response.Placemark[0].address);
        $("#map .usertweet").text(
            '"Fire spotted near ' +
            response.Placemark[0].address
            + ' #nswfires"');
    }
}

function TwitterSubmit() {
    var tweet = $("#map .reportprompt .usertweet").text();
    var username = $("#map .reportprompt .username").val();
    var password = $("#map .reportprompt .password").val();

    $.post(
        "/Tweet",
        {
            "username": username,
            "password": password,
            "tweet": tweet
        },
        function() {
            gmap.closeInfoWindow();
            LoadCommunityTweets(false);
        },
        "json");
}

function CreateCookie(name, value) {
    var date = new Date();
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = name + "=" + value + expires + "; path=/";
}

function ReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function EraseCookie(name) {
    CreateCookie(name, "", -1);
}