﻿$(document).ready(function() {

    $("button").button();

    $(".txtNewMessage").fieldtag();
    $("#lstBlog_Loader").show();
    ShowBlog();

    $("#lstBlog_Loader").hide();

    if (IsAuthed) {
        $(".tmpBlog_Admin").show();
        $("#lblLogin").hide();
    }
    else {
        $(".tmpBlog_Admin").hide();
        $("#lblLogin").show();
    }

    if (daysRemaining > 1) {
        $(".countdown").html(daysRemaining);
        //$("#progressbar").progressbar({ value: 75 });
    }
    else {
        $(".counter").hide();
    } 
});


jQuery.extend({
    getURLParam: function(strParamName) {
        var strReturn = "";
        var strHref = window.location.href;
        var bFound = false;

        var cmpstring = strParamName + "=";
        var cmplen = cmpstring.length;

        if (strHref.indexOf("?") > -1) {
            var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
            var aQueryString = strQueryString.split("&");
            for (var iParam = 0; iParam < aQueryString.length; iParam++) {
                if (aQueryString[iParam].substr(0, cmplen) == cmpstring) {
                    var aParam = aQueryString[iParam].split("=");
                    strReturn = aParam[1];
                    bFound = true;
                    break;
                }

            }
        }
        if (bFound == false) return null;
        return strReturn;
    }
});

var geocoder;
var map;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();

var markerWedding = null;
var markerReception = null;
var markerLocation = null;
var weddingBounds = null
var receptionBounds = null;
var stepDisplay = null;
function initMap() {

    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(54.418930, -3.647461);
    directionsDisplay = new google.maps.DirectionsRenderer();
    stepDisplay = new google.maps.InfoWindow();
    var myOptions = {
        zoom: 10,
        center: latlng,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }
    };


    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    SetLocation();
    directionsDisplay.setMap(map);

    google.maps.event.addListener(map, 'click', function(event) {
        ReverseGeocode(event);
    });

}

function calcRoute(marker, title) {
    if (markerLocation == null) {
        alert('Please enter your location on the map');
    }
    else {
        var start = new google.maps.LatLng(markerLocation.getPosition().lat(), markerLocation.getPosition().lng());
        var end = new google.maps.LatLng(marker.getPosition().lat(), marker.getPosition().lng());
        if (start.lat() == end.lat() && start.lng() == end.lng()) {
            alert("Your location is the same as the destination, please ensure you enter your address and not the venue address.");
        }
        else {
            ClearDirections();
            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.DirectionsTravelMode.DRIVING,
                unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
            };
            directionsService.route(request, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    $("#warnings").innerHTML = "" + result.routes[0].warnings + "";
                    directionsDisplay.setMap(map);
                    directionsDisplay.setDirections(result);
                    showSteps(result, title);
                    $("#btnPrint").bind("click", function() { PrintDirections("lblDirections",$("#lblYourLocation").html(),$("#lbl"+title+"VenueAddress").html() ); return false; });
                }
                else {
                    alert("Directions between the specified locations is not available.");
                }
            });
        }
    }
}


function placeMarker(lat, lng, address, markerTitle) {
    var location = new google.maps.LatLng(lat, lng);

    var image = null;

    var title = "";
    var isVenue = true;
    if (markerTitle == "Wedding Venue") {
        title = "Wedding Venue"
        isVenue = true;
        weddingBounds = location;
        image = new google.maps.MarkerImage('css/images/markerwedding.gif', new google.maps.Size(28, 24), new google.maps.Point(0, 0), new google.maps.Point(14, 12));
        //   $("#lblWeddingAddress").html(address.replace(/,/g, "<br/>"));
    }
    else if (markerTitle == "Reception Venue") {
        title = "Reception Venue"
        isVenue = false;
        receptionBounds = location;
        image = new google.maps.MarkerImage('css/images/markerreception.gif', new google.maps.Size(28, 24), new google.maps.Point(0, 0), new google.maps.Point(14, 12));
        //    $("#lblReceptionAddress").html(address.replace(/,/g, "<br/>"));
    }
    else if (markerTitle == "Location") {
        if (markerLocation != null) {
            markerLocation.setMap(null);
            markerLocation = null;
            ClearDirections();
        }
        title = "Your Location"
        image = new google.maps.MarkerImage('css/images/markeruser.gif', new google.maps.Size(28, 24), new google.maps.Point(0, 0), new google.maps.Point(14, 12));
        $("#lblYourLocation").html(address.replace(/,/g, "<br/>"));
        $("#lblLocation").html("");
    }


    var marker = new google.maps.Marker({
        position: location,
        map: map,
        title: title,
        clickable: true,
        icon: image
    });

    if (markerTitle == "Wedding Venue") {
        markerWedding = marker
    }
    else if (markerTitle == "Reception Venue") {
        markerReception = marker
    }
    else if (markerTitle == "Location") {
        marker.draggable = true;
        markerLocation = marker;
        var bounds = new google.maps.LatLngBounds();
        if (weddingBounds != null)
            bounds.extend(weddingBounds);
        if (receptionBounds != null)
            bounds.extend(receptionBounds);
        bounds.extend(location);
        // map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        map.fitBounds(bounds);
    }

    var infowindow = new google.maps.InfoWindow(
                        {
                            content: "<span style='font-size:12px;'><b>" + title + "</b><br/>" + address + "</span>"
                        });

    google.maps.event.addListener(marker, 'dragend', function(event) {
        ReverseGeocode(event, marker)
    });

    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });




}

function ClearDirections() {

    for (var i = 0; i < dirMarker.length; i++) {
        dirMarker[i].setMap(null);
        dirMarker[i] = null;
    }
    dirMarker = [];
    directionsDisplay.setMap(null);
}


function ReverseGeocode(event, marker) {

    var latlng = new google.maps.LatLng(event.latLng.va, event.latLng.wa);

    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {

                var title = "";
                if (marker != null) {
                    title = marker.title;
                }
                placeMarker(event.latLng.va, event.latLng.wa, results[0].formatted_address, "Location");
            }
        } else {
            alert("Could not determine address from marker location");
        }

    });
}

function SetLocation() {
    Proxy.invoke("Location_SelectByReference",
            {
                reference: reference
            }
            ,
             function(result) {
                 if (result) {
                     if (result.WeddingVenue != "null") {
                         $("#lblWeddingVenue").html(result.WeddingVenue);
                     }
                     if (result.ReceptionVenue != "null") {
                         $("#lblReceptionVenue").html(result.ReceptionVenue);
                     }
                     if (result.ReceptionVenueAddress) {
                         $("#lblReceptionVenueAddress").html(result.ReceptionVenueAddress.replace(/,/g, "<br/>"));

                         placeMarker(result.ReceptionVenueLat, result.ReceptionVenueLng, result.ReceptionVenueAddress, "Reception Venue");
                     }
                     else {
                         $("#divReception").hide();
                     }

                     if (result.WeddingVenueAddress) {
                         $("#lblWeddingVenueAddress").html(result.WeddingVenueAddress.replace(/,/g, "<br/>"));

                         placeMarker(result.WeddingVenueLat, result.WeddingVenueLng, result.WeddingVenueAddress, "Wedding Venue")
                     }
                     else {
                         $("#divWedding").hide();

                     }
                     if (result.SameLocation) {
                         $("#divReception").hide();
                     }
                     var bounds = new google.maps.LatLngBounds();
                     if (weddingBounds != null)
                         bounds.extend(weddingBounds);
                     if (receptionBounds != null)
                         bounds.extend(receptionBounds);
                     //  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
                     map.fitBounds(bounds);
                 }


             }
             ,
             function(error) {
                 alert(error);
             });

}

var dirMarker = [];
function showSteps(directionResult, title) {

    $("#divPrintDirections").show();
    $("#lblDirections").html("");

    var myRoute = directionResult.routes[0].legs[0];
    $("#lblDirections").append("<div style='clear:both;'><div style='float:left;font-size:12px;padding:10px;width:220px; margin-top:10px; background-color: #EAEAE1; text-align:left;'>Your location to the " + title + " </div><div style='float:left;font-size:12px;padding:10px;width:140px; margin-top:10px;margin-left:7px; background-color: #EAEAE1; text-align:right;'>" + myRoute.distance.text + "</div><div style='float:left;font-size:12px;padding:10px;width:140px; margin-top:10px;margin-left:7px; background-color:#EAEAE1; text-align:right;'>" + myRoute.duration.text + "</div><div>");
    
    for (var i = 0; i < myRoute.steps.length; i++) {
        var marker = new google.maps.Marker({
            position: myRoute.steps[i].start_point,
            map: map
        });
        dirMarker[i] = marker;

        var text = "<span style='font-size:12px;'>" + myRoute.steps[i].instructions + "</span>"
        dirMarker[i].info = text;
        attachInstructionText(marker, text);

        //    markerArray[i] = marker;
        $("#lblDirections").append("<div><div style='float:left;clear:both;font-size:12px;padding:10px;width:380px; margin-top:10px; background-color: #f7f7f4; text-align:left;'><a href='#map' onclick='showMarker(" + i + ")'>" + (i + 1) + ": " + myRoute.steps[i].instructions + "</a></div><div style='float:left;font-size:12px;padding:10px;width:60px; margin-top:10px;margin-left:7px; background-color: #f7f7f4; text-align:right;'>" + myRoute.steps[i].distance.text + "</div><div style='float:left;font-size:12px;padding:10px;width:60px; margin-top:10px;margin-left:7px; background-color: #f7f7f4; text-align:right;'>" + myRoute.steps[i].duration.text + "</div><div>");

    }

}

function showMarker(markerIndex) {
    stepDisplay.setContent(dirMarker[markerIndex].info);
    stepDisplay.open(map, dirMarker[markerIndex]);
    map.setCenter(dirMarker[markerIndex].getPosition());
    map.setZoom(15);
}

function attachInstructionText(marker, text) {
    google.maps.event.addListener(marker, 'click', function() {
        stepDisplay.setContent(text);
        stepDisplay.open(map, marker);
    });
}

function codeAddress() {

    var address = $("#txtLocation").val() + ', UK';
    if (geocoder) {
        geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                $("#divPrintDirections").hide();
                $("#lblDirections").html("");
                if (results.length == 1) {
                    placeMarker(results[0].geometry.location.lat(), results[0].geometry.location.lng(), results[0].formatted_address, "Location");
                }
                else if (results.length > 1) {
                    $("#lblLocation").html("Did you mean:");
                    for (var i = 0; i < results.length; i++) {
                        $("#lblLocation").append("<br>" + (i + 1) + ": <a href='javascript:placeMarker(" + results[i].geometry.location.lat() + "," + results[i].geometry.location.lng() + ",\"" + results[i].formatted_address + "\",\"Location\");'>" + results[i].formatted_address + "<\/a>");
                    }
                }
            } else {
                alert("Could not determine location from the address");
            }
        });
    }
}

function btnNewMessage_Click() {
    var txtMessage = $(".txtNewMessage");
    if (txtMessage.val() != "" && txtMessage.val() != txtMessage.attr("title")) {

        $("#btnNewMessage").hide();
        $("#NewPost_Loader").show();
        Proxy.invoke("Blog_Insert", { reference: reference, message: txtMessage.val(), blogid: "", from: "" },
                      function(result) {
                          if (result) {
                              var html = parseTemplate($("#tmpBlog").html(),
                                         { message: result, auth: IsAuthed });
                              txtMessage.val("");
                              $(html).fadeIn("slow").prependTo("#lstBlog");
                              $(".tmpBlog_ActionButton").button();
                              $(".tmpBlog_ProfileImage").attr("src", profileThumnbnailLink);


                          }
                          else {
                              alert("Sorry an error has occured, please contact us for help.");
                          }
                          $("#btnNewMessage").show();
                          $("#NewPost_Loader").hide();


                      },
                         function(error) {

                             alert(error);
                             $("#btnNewMessage").show();
                             $("#NewPost_Loader").hide();

                         }, true);
    }

}

function tmpBlog_ActionButton_Click(blogid) {
    if (!$(".tmpBlog_Create_" + blogid).length) {
        var message = new Object();
        message.ParentID = blogid;
        var html = parseTemplate($("#tmpCommentCreate").html(),
         { create: true, message: message, auth: IsAuthed });
        $(html).appendTo("#Comment_" + blogid);
        $(".tmpBlog_Create_" + blogid + " button").button();
        $(".tmpBlog_Create_" + blogid + " textarea").fieldtag();
        $(".tmpBlog_Create_" + blogid + " input").fieldtag();
        $(".tmpBlog_Create_" + blogid + " button").focus();
    }
    else {
        $(".tmpBlog_Create_" + blogid).remove();
    }

}

function tmpBlog_Delete_Click(id, isComment) {


    $("#tmpBlog_Delete_" + id).hide();
    $("#tmpBlog_Loader_" + id).show();

    Proxy.invoke("Blog_Delete", { id: id, reference: reference },
                      function(result) {
                          if (result) {
                              if (!isComment) {
                                  $(".tmpBlog_Set_" + id).remove();
                              }
                              else {
                                  $(".tmpBlog_" + id).remove();
                              }
                          }
                          else {
                              alert("Sorry an error has occured, please contact us for help.");
                          }
                          $("#tmpBlog_Delete_" + id).show();
                          $("#tmpBlog_Loader_" + id).hide();


                      },
                         function(error) {

                             alert(error);
                             $("#tmpBlog_Delete_" + id).show();
                             $("#tmpBlog_Loader_" + id).hide();

                         }, true);

}

function tmpBlog_AddComment_Click(blogid) {

    var txtComment = $("#txtComment_" + blogid);
    var txtFrom = $("#txtFrom_" + blogid);
    if (txtComment.val() != "" && txtComment.val() != txtComment.attr("title") &&
    txtFrom.val() != "" && txtFrom.val() != txtFrom.attr("title")) {
        $("#tmpBlog_AddComment_" + blogid).hide();
        $("#tmpBlog_CreateLoader_" + blogid).show();
        Proxy.invoke("Blog_Insert", { reference: reference, message: txtComment.val(), blogid: blogid, from: txtFrom.val() },
                      function(result) {
                          if (result) {
                              var html = parseTemplate($("#tmpComment").html(),
                                         { message: result, auth: IsAuthed });
                              $(html).fadeIn("slow").appendTo("#Comment_" + result.ParentID);
                              $(".tmpBlog_Create_" + result.ParentID).remove();
                              $(".tmpBlog_Action button").button();

                          }
                          else {
                              alert("Sorry an error has occured, please contact us for help.");
                          }
                          $("#tmpBlog_AddComment_" + blogid).show();
                          $("#tmpBlog_CreateLoader_" + blogid).hide();


                      },
                         function(error) {

                             alert(error);
                             $("#tmpBlog_AddComment_" + blogid).show();
                             $("#tmpBlog_CreateLoader_" + blogid).hide();

                         }, true);
    }
}


function ShowBlog() {
    Proxy.invoke("Blog_SelectByReference", { reference: reference },
                      function(result) {
                          if (result) {
                              $("#lstBlog").empty();
                              if (result.length > 0) {

                                  for (var i = 0; i < result.length; i++) {
                                      var message = result[i];

                                      if (message.ParentID == null) {
                                          var html = parseTemplate($("#tmpBlog").html(),
                                         { message: message, auth: IsAuthed });
                                          $(html).fadeIn("slow").appendTo("#lstBlog");
                                          $(".tmpBlog_ActionButton").button();
                                          $(".tmpBlog_ProfileImage").attr("src", profileThumnbnailLink);

                                      }
                                      else {
                                          var html = parseTemplate($("#tmpComment").html(),
                                         { create: false, message: message, auth: IsAuthed });
                                          $(html).fadeIn("slow").appendTo("#Comment_" + message.ParentID);
                                          $(".tmpBlog_ActionButton").button();
                                      }
                                  }
                              }
                          }
                          else {
                              alert("Sorry an error has occured, please contact us for help.");
                          }
                      },
                         function(error) {

                             alert(error);
                         }, true);




}

function PrintDirections(id,locaddress,venaddress) {
    str = $("#" + id).html();

    newwin = window.open('', 'printwin', 'left=100,top=100,width=400,height=400')
    newwin.document.write('<HTML>\n<HEAD>\n')
    newwin.document.write('<TITLE>Print Directions</TITLE>\n')
        newwin.document.write('<script>\n')
        newwin.document.write('function chkstate(){\n')
        newwin.document.write('if(document.readyState=="complete"){\n')
        newwin.document.write('window.close()\n')
        newwin.document.write('}\n')
        newwin.document.write('else{\n')
        newwin.document.write('setTimeout("chkstate()",2000)\n')
        newwin.document.write('}\n')
        newwin.document.write('}\n')
        newwin.document.write('function print_win(){\n')
        newwin.document.write('window.print();\n')
        newwin.document.write('chkstate();\n')
        newwin.document.write('}\n')
        newwin.document.write('<\/script>\n')
    newwin.document.write('</HEAD>\n')
    // newwin.document.write('<BODY onload="print_win()">\n')
    newwin.document.write('<BODY onload="print_win()">\n')
    newwin.document.write('<div style="padding-left:50px; padding-top:50px;">')
    newwin.document.write('<div style="float: left; background-color: #f7f7f4;">');
    newwin.document.write('<img src="css/images/logo.gif" /></div>');
    newwin.document.write('<div style="margin-left:10px;float: left; background-color: #f7f7f4; width: 200px; height:80px;">');
    newwin.document.write('<b>Your Location:</b><br />'+locaddress  );
    newwin.document.write('</div>');
    newwin.document.write('<div style="margin-left:10px;float: left; background-color: #f7f7f4; width: 200px; height:80px;">');
    newwin.document.write('<b>Venue Location:</b><br />'+venaddress);
    newwin.document.write('</div>');
    newwin.document.write('<div style="margin-left:0px;margin-top:0px;">')
    newwin.document.write(str)
    newwin.document.write('</div>');
    newwin.document.write('</div>');
    
    newwin.document.write('</BODY>\n')
    newwin.document.write('</HTML>\n')
    newwin.document.close()
}
