﻿function mapNELon(){return SPMap.getBounds().getNorthEast().lng();}
    function mapNELat(){return SPMap.getBounds().getNorthEast().lat();}
    function mapSWLon(){return SPMap.getBounds().getSouthWest().lng();}
    function mapSWLat(){return SPMap.getBounds().getSouthWest().lat();}
    function mapCLat(){return SPMap.getCenter().lat();}
    function mapCLon(){return SPMap.getCenter().lng();}
    function mapZoom(){return SPMap.getZoom();}
    function jsReady(txt) { return jQuery.trim(txt.replace(/[']/g, "\\'")); }
    function valFields(fA)
     {var f; var v;
        for(var i=0;i<fA.length;i++)
        {
            f = $("#" + fA[i])[0];
            
            if(jQuery.trim(f.value) == "")return false;

        }
        return true;
    }
     function getLatestStories()
{
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebServices/getMoments.asmx/GetLatestMoments",
  data: "{}",
  dataType: "json",
  success:latestStoriesSuccess
});
}

  function mainLogin(u,p,b,lDiv) {

      if (!valFields([u, p])) { alert(SFRequired); return; }
    
    var uV=$("#"+u)[0].value;var pV=$("#"+p)[0].value;
    var bV=$("#"+b);bV.attr("disabled","disabled");
            $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          url: "WebServices/UserService.asmx/LoginUser",
          
          data: "{'username':'"+jsReady(uV)+"','password':'"+jsReady(pV)+"'}",
          dataType: "json",
          success:mainLoginSuccess,
          user:uV,
          lButton:bV,lDiv:lDiv,
          error:mainLoginError
        });
    
    }
       function mainLoginError(data, rText)
    
    {
        this.lButton.attr("disabled","");

    }

    function createAccount(uv, ev, pv, bv, lDiv) {
        if (!valFields([uv, ev, pv])) { alert(SFRequired); return; }
        $("#"+bv).attr("disabled", "disabled");
        var u = $("#"+uv)[0].value;
        var p = $("#"+pv)[0].value;
        var e = $("#"+ev)[0].value;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebServices/UserService.asmx/CreateUser",
            data: "{'username':'" + jsReady(u) + "','email':'" + jsReady(e) + "','password':'" + jsReady(p) + "'}",
            dataType: "json",lDiv:lDiv,
            success: createAccountSuccess
        });

    }

    function getSpotMoments(id,culture) {

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebServices/SpotsService.asmx/GetSpotMoments",

            data: "{'id':'" + id + "','culture':'" + culture + "'}",
            dataType: "json",
            success: getSpotMomentsSuccess,
            spId: id
        });

    }


    function getSWUSetting(postParams,btnText) {
        return {
            flash_url: "./justUpload/SWFUpload22/swfupload.swf",
            // upload path relative to the SWF file
            upload_url: "../../webservices/imgUpload.ashx",
            post_params: postParams,
            file_size_limit: "2750 KB",
            file_types: "*.jpg;*.gif;*.png;*.jpeg",
            file_types_description: "All Files",
            file_upload_limit: 10,
            file_queue_limit: 0,
            custom_settings: {
                progressTarget: "fsUploadProgress",
                cancelButtonId: "btnCancel"
            },
            debug: false,

            // Button Settings
           // button_image_url: "./justUpload/SWFUpload22/XPButtonUploadText_61x22.png",
            // Relative to the SWF file
            button_placeholder_id: "spanButtonPlaceholder",
            button_width: 81,
            button_height: 22,
            button_text: btnText,

            // The event handler functions are defined in handlers.js
            file_queued_handler: fileQueued,
            file_queue_error_handler: fileQueueError,
            file_dialog_complete_handler: fileDialogComplete,
            upload_start_handler: uploadStart,
            upload_progress_handler: uploadProgress,
            upload_error_handler: uploadError,
            upload_success_handler: uploadSuccess,
            upload_complete_handler: uploadComplete,
            queue_complete_handler: queueComplete, // Queue plugin event

            // SWFObject settings
            minimum_flash_version: "9.0.28",
            swfupload_pre_load_handler: swfUploadPreLoad,
            swfupload_load_failed_handler: swfUploadLoadFailed
        };
    }



    function processArea(details) {

        if (details.Country.AdministrativeArea != null) {
            if (details.Country.AdministrativeArea.Locality != null) {
                if
                        (details.Country.AdministrativeArea.Locality.Thoroughfare != null
                        &&
                        details.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName != null
                        ) {
                    $("#sStN")[0].value = details.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                    $("#sSt")[0].value = details.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                }
                if (details.Country.AdministrativeArea.Locality.PostalCode != null && details.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber != null)
                    $("#sZip")[0].value = details.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;

                if (details.Country.AdministrativeArea.Locality.LocalityName != null)
                    $("#sCity")[0].value = details.Country.AdministrativeArea.Locality.LocalityName;

            }


            if (details.Country.AdministrativeArea.AdministrativeAreaName != null)
                $("#sState")[0].value = details.Country.AdministrativeArea.AdministrativeAreaName;
            if (details.Country.CountryNameCode != null)
                $("#sCC")[0].value = details.Country.CountryNameCode;
        }
    }

    function processSubArea(details) {
        if (details.Country.AdministrativeArea.SubAdministrativeArea != null) {
            if (details.Country.AdministrativeArea.SubAdministrativeArea.Locality != null) {
                if (details.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName != null) {
                    $("#sStN")[0].value = details.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                    $("#sSt")[0].value = details.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                }
            }

            if (details.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName != null)
                $("#sCity")[0].value = details.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;

        }
        if (details.Country.AdministrativeArea.AdministrativeAreaName != null)
            $("#sState")[0].value = details.Country.AdministrativeArea.AdministrativeAreaName;
        if (details.Country.CountryNameCode != null)
            $("#sCC")[0].value = details.Country.CountryNameCode;



    }

    function addFToSelect(title) {
        var favSel = $("#favoriteSel")[0];
        try {
            favSel.add(new Option(title, mapCLat() + ":" + mapCLon() + ":" + mapZoom()), 0)

        }
        catch (e) { //in FF, try the below version instead of add()
            favSel.add(new Option(title, mapCLat() + ":" + mapCLon() + ":" + mapZoom()), favSel.options[0])
        }
        favSel.selectedIndex = 0;
        $("#favoriteSel").show(); $("#favoriteSelSpan").show();

    }
    function getSpotCount() {
        $("#totalSpots").html(0);

    }


    function makeDefaultMap() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebServices/mapsService.asmx/MakeMapDefault",
            data: "{'cLat':'" + mapCLat() + "','cLon':'" + mapCLon() + "','cZoom':'" + mapZoom() + "'}",
            dataType: "json",
            success: makeDefaultMapSuccess
        });
        return false;
    }

    function justTheseMoments(mT, cc, lat, lon, zoom) {
        MM.clearMarkers();
        SPMap.setCenter(new GLatLng(lat, lon), zoom);
        getSpotByStoryType(mT, cc);
    }


    function justTheseSpots(spT) {
        MM.clearMarkers();
        SpType = spT;
        getSpots();

    }
    function justThisCulture(culture) {
        MM.clearMarkers();
        Culture = culture;
        getSpots();

    }
    function showAddress(address, addPoint) {
        if (geocoder) {
            geocoder.getLatLng(
          address,
          function(point) {
              if (!point) {
                  alert(address + " not found");
              } else {
                  SPMap.setCenter(point, 17);
                  var marker = new GMarker(point);
                  SPMap.addOverlay(marker);
                  marker.openInfoWindowHtml(address);
              }
          }
        );
        }
    }
    (function($) {
        $.fn.aqFloater = function(options) {
            var opts = $.extend({
                offsetX: 0, offsetY: 0, attach: '', duration: 50, opacity: '.9'
            }, options);

            var $obj = this;
            $obj.css({ position: 'absolute', opacity: opts.opacity });

            $(window).scroll(function() {
                var de = document.documentElement;

                var y = (opts.attach.match(/n/) ? 0
            : (opts.attach.match(/s/)
               ? (de.clientHeight - $obj.outerHeight() - 10)
               : Math.round((de.clientHeight - $obj.height()) / 2)));

                var x = (opts.attach.match(/w/) ? 0
            : (opts.attach.match(/e/)
               ? (de.clientWidth - $obj.outerWidth() - 10)
               : Math.round((de.clientWidth - $obj.width()) / 2)));

                $obj.animate({
                    top: (y + $(document).scrollTop() + opts.offsetY) + 'px',
                    left: (x + $(document).scrollLeft() + opts.offsetX) + 'px'
                }, { queue: false, duration: opts.duration });
            });

            $(window).trigger('scroll');
        };
    })(jQuery);
    
 function deleteThisStory(st)
{
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebServices/MomentsService.asmx/RemoveStory",
  data: "{'storyid':'"+st+"'}",
  dataType: "json",
  success:deleteThisStorySuccess, 
  error:deleteThisStoryError
});

}
function deleteThisStorySuccess(){window.location.href="./default.aspx";}
function deleteThisStoryError() { }
function initTB() {
    tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
    imgLoader = new Image(); // preload image
    imgLoader.src = tb_pathToImage;
}

function getSpotsSuccess(data, textStatus, outSideData) {
    var sA = data.d; var point; var marker; var markerName; var desc; var addedBy; var id;
    $("#totalSpots").html(sA.length); for (var i = 0; i < sA.length; i++) {
        point = new GLatLng(sA[i].Lat, sA[i].Lon);
        marker = new GMarker(point, {});
        markerName = sA[i].Name;
        desc = sA[i].Desc;
        id = sA[i].ID;
        addedBy = sA[i].AddedBy;
        marker.SpotId = id;

        MM.addMarker(marker, 3, 17);
        GEvent.addListener(marker, "click", function() { ActiveSpot = this; getSpotMoments(this.SpotId, Culture); });

    }

    MM.refresh();

    $("#totalViewSpots").html(MM.getMarkerCount(mapZoom()));
    if (!outSideData) {
        timeoutId = window.setTimeout(getOutSpots, 500);
        dIn = data;
    }
    {
        dOut = data;
    }

} //end of getSpotsSuccess


function zoomToSpot(id, innerOut,innerIn) {
    SPMap.ZoomOutCenter = SPMap.getCenter();
    SPMap.ZoomOutZoom = SPMap.getZoom();
    SPMap.setCenter(ActiveSpot.getPoint(), 16);
    var l = $("#zoom" + id);
    l.html(innerOut);
    l.removeAttr("href");
    var newHref="javascript:zoomOut("+id+",\""+ innerOut+"\",\""+innerIn+"\")";
    l.attr("href", newHref);


}
function zoomOut(id, innerOut, innerIn) {

    SPMap.setCenter(SPMap.ZoomOutCenter, SPMap.ZoomOutZoom);
    var l = $("#zoom" + id);
    l.html(innerIn);
    l.removeAttr("href");
    var newHref = "javascript:zoomToSpot(" + id + ",\"" + innerOut + "\",\"" + innerIn + "\")";
    l.attr("href", newHref);


}