﻿//Googlemaps start

//VARIABLES GOOGLEMAPS
var markerArray = [];
var markerBase = "Files/System/NemLejeSystem/images/";
var map;
var geocoder;
var bounds;
var countPointOnMap = 0;
var svc;
var marker;

//Provide markers to points on map
function getMarkerIcon(key) {

    if (typeof markerArray[key] == 'undefined') {
        var new_icon = "";

        switch (key) {

            case "12":
                new_icon = markerBase + "marker_1.gif";
                break;
            case "16":
                new_icon = markerBase + "marker_12.gif";
                break;
            case "15":
                new_icon = markerBase + "marker_15.gif";
                break;
            case "16":
                new_icon = markerBase + "marker_16.gif";
                break;
            case "20":
                new_icon = markerBase + "marker_20.gif";
                break;

            default:
                new_icon = markerBase + "marker_default.gif";
                break;
        }

        var icon = new google.maps.MarkerImage(new_icon, null, null, new google.maps.Point(0, 64), new google.maps.Size(15, 23));

        markerArray[key] = icon;

    }

    return markerArray[key];

}

function initialize() {
    svc = new google.maps.StreetViewService();

    var latlng = new google.maps.LatLng(0, 0);
    var myOptions = {        
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: false
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    bounds = new google.maps.LatLngBounds();
   
}

function createMarker(point, html, imageID) {//gCoordsLat, gCoordsLng, Adresse, DepartmentPicture, DepartmentPictureThumbnailWidth, DepartmentPictureThumbnailHeight, pageId, afd, Beliggenhed, PostBy) {
    bounds.extend(point);
    countPointOnMap++;

    if (point) {
        var marker;

        //Frontend-developer should set imageID to empty to use standard google markers
        if (imageID == "") {
            marker = new google.maps.Marker({ position: point, map: map});
         }
        else {
            marker = new google.maps.Marker({ position: point, map: map, icon: getMarkerIcon(imageID) });
         }
        
        marker.y = 0;
        marker.p = 5;
        marker.z = 0;
        var infowindow;

        google.maps.event.addListener(marker, "click", function (event) {
            svc.getPanoramaByLocation(point, 50, function (data, status) {
                if (status == google.maps.StreetViewStatus.OK) {
                    var gSIframe = '<iframe marginWidth=0 marginHeight=0 src="http://maps.google.com/maps?t=h&amp;ie=UTF8&amp;ll=' + data.location.latLng + ' &amp;spn=0,0.004292&amp;z=19&amp;layer=c&amp;cbll=' + data.location.latLng + '&amp;panoid=' + data.location.pano + '&amp;cbp=13,136.72,,0,-9.44&amp;source=embed&amp;output=svembed" frameBorder=0 width=400 scrolling=no height=180></iframe>';
                    html = "<div><strong>" + data.location.description + "</strong></div><div>" + gSIframe + "</div><div id='streetViewDisclaimer'>NB: Det viste er ikke nødvendigvis den præcise adresse</div>" + html;
                } else {}
                infowindow = new google.maps.InfoWindow(
					{ content: html
					});
                infowindow.open(map, marker);
            }
        );
        });
    }
}

// Calculate the boundaries and center of Google Map
function showMap() {
    // Reset center and zoom level
    if (countPointOnMap > 0) {
        map.setCenter(bounds.getCenter());
        map.fitBounds(bounds);
    } else {
        document.getElementById("map").style.display = 'none';
        document.getElementById("mapError").style.display = '';
    }
}


function insertPointOnMapSimpleInfo(gCoordsLat, gCoordsLng, Adresse, sel, html) {
    if (gCoordsLat != '' && gCoordsLng != '') {
        var point = new google.maps.LatLng(gCoordsLat, gCoordsLng);
        bounds.extend(point);
        countPointOnMap++;
    } else {
    }
    if (point) {
        //var markerString = "<h2 class=h2>" + Adresse + " " + Beliggenhed + "<br />" + PostBy + "</h2><br />";
        var markerString = "<div id='GoogleMapsDepartmentInfo'>";
        markerString += html + "</div>";

        var marker = createMarker(point, markerString, sel);

        //   map.addOverlay(marker);
    }
}
//Googlemaps end

function mp_onload() {
    if (window.body_onload != null)
        window.body_onload();
}
function signUpMessagePassiv(url, companyName) {
    var con = confirm("Du er medlem af "+companyName+", men ikke som aktiv. \n\n Du kan blive det ved at redigere dine medlemsskaber. Tryk ok for at gøre dette nu");
    if (con) {
        location.href = url;
    }
}

function signUpMessage(logInUrl, companyName) {

    var con = confirm("Du er ikke logget ind. Log ind via boksen til venstre. \n\n Hvis du ikke er medlem af " + companyName + " kan du oprette dig ved at klikke ok");
    if (con) {
        location.href = logInUrl;
     }
 }

function signUpMessageOtherCompany(url, companyName){

    var con = confirm("Du er ikke medlem af dette " + companyName + ". \n\n Du kan blive det ved at redigere dine medlemsskaber. Tryk ok for at gøre dette nu");
    if (con) {
        location.href = url;
     }
}

//LOADING INFO
function showLoadingInfo() {
    setTimeout('showLoadingInfoDelayed()', 2000);
}

function showLoadingInfoDelayed() {
    $('#waitingForResultBox').dialog('open');
 }

function getAdditionalApartmentData(companyID, departmentID, apartmentID, xsltName, divID) {
    var url2 = "/Public/AdditionalApartmentInfo.aspx?companyID=" + companyID + "&departmentID=" + departmentID + "&apartmentID=" + apartmentID + "&departmentXSLT=" + xsltName;
        var result ="no";
        $.ajax({
            type: "GET",
            url: url2,
            dataType: "text",
            success: function(data, msg) {
                $('#' + divID).html(data);
                $('#' + divID).dialog('open');
            },
            error: function() {
                $('#' + divID).html("");
            }
        });
    }

/*Images on front page uses this function*/
function getDepartmentData(companyID, departmentID, apartmentID, xsltName, divID) {
    var url2 = "/Public/AdditionalApartmentInfo.aspx?companyID=" + companyID + "&departmentID=" + departmentID + "&apartmentID=" + apartmentID + "&departmentXSLT=" + xsltName;
        var result ="no";
        $.ajax({
            type: "GET",
            url: url2,
            dataType: "text",
            success: function(data, msg) {
                $('#' + divID).html(data);
                //$('#' + divID).dialog('open');
                $('#'+ divID).load(data);
            },
            error: function() {
                $('#' + divID).html("");
            }
        });
    }


// Load blueprint file into JQuery dialog
function loadBlueprint(completePath) {
    $('#blueprint').attr("src", completePath);
    $("#dialog").dialog("open");
}

// Load values into dialog form
function respond(Afd, Sel, Lejemaal, Datotilb, Lejer) {
    $('#Afd').val(Afd);
    $('#Sel').val(Sel);
    $('#Lejemaal').val(Lejemaal);
    $('#Datotilb').val(Datotilb);
    $('#Lejer').val(Lejer);

    $("#responddialog").dialog("open");
}
function respondAccept(Afd, Sel, Lejemaal, Datotilb, Lejer) {
    $('#Afd').val(Afd);
    $('#Sel').val(Sel);
    $('#Lejemaal').val(Lejemaal);
    $('#Datotilb').val(Datotilb);
    $('#Lejer').val(Lejer);

    $("#responddialogAccept").dialog("open");
}
function respondDecline(Afd, Sel, Lejemaal, Datotilb, Lejer) {
    $('#Afd').val(Afd);
    $('#Sel').val(Sel);
    $('#Lejemaal').val(Lejemaal);
    $('#Datotilb').val(Datotilb);
    $('#Lejer').val(Lejer);

    $("#responddialogDecline").dialog("open");
}

function confirmOffer(Afd, Sel, Lejemaal, Internetnr, Datotilb, Lejer, ID) {
    if (confirm("Ved denne handling accepterer du tilbuddet! Er du helt sikker?")) {
        location.href = "/Default.aspx?ID=" + ID + "&action=AcceptMemberOffer&Afd=" + Afd + "&Sel=" + Sel + "&Lejemaal=" + Lejemaal + "&Internetnr=" + Internetnr + "&Datotilb=" + Datotilb + "&Lejer=" + Lejer;
    } else {
        return false;
    }
}

function rejectOffer(Afd, Sel, Lejemaal, Internetnr, Datotilb, Lejer, ID) {
    if (confirm("Ved denne handling afviser du tilbuddet! Er du helt sikker?")) {
        location.href = "/Default.aspx?ID=" + ID + "&action=RejectMemberOffer&Afd=" + Afd + "&Sel=" + Sel + "&Lejemaal=" + Lejemaal + "&Internetnr=" + Internetnr + "&Datotilb=" + Datotilb + "&Lejer=" + Lejer;
    } else {
        return false;
    }
}


// Validate search form
function validateForm(frm) {
    if (parseInt($('#MinimumHusleje').val()) > parseInt($('MaximumHusleje').val())) {
        alert('Du bedes vælge en maksimum husleje, der er større end minimum');
        return false;
    }

    if (parseInt($('Minimumbareal').val()) > parseInt($('Maximumbareal').val())) {
        alert('Du bedes vælge et maksimum areal, der er større end minimum');
        return false;
    }

    if (parseInt($('Minimumrum').val()) > parseInt($('Maximumrum').val())) {
        alert('Du bedes vælge et maksimum areal, der er større end minimum');
        return false;
    }

    return true;
}


function validateForm_SNEBACKUP(frm) {
    if (parseInt(document.getElementById('MinimumHusleje').options[document.getElementById('MinimumHusleje').selectedIndex].value) > parseInt(document.getElementById('MaximumHusleje').options[document.getElementById('MaximumHusleje').selectedIndex].value)) {
        alert('Du bedes vælge en maksimum husleje, der er større end minimum');
        return false;
    }

    if (parseInt(document.getElementById('Minimumbareal').options[document.getElementById('Minimumbareal').selectedIndex].value) > parseInt(document.getElementById('Maximumbareal').options[document.getElementById('Maximumbareal').selectedIndex].value)) {
        alert('Du bedes vælge et maksimum areal, der er større end minimum');
        return false;
    }

    if (parseInt(document.getElementById('Minimumrum').options[document.getElementById('Minimumrum').selectedIndex].value) > parseInt(document.getElementById('Maximumrum').options[document.getElementById('Maximumrum').selectedIndex].value)) {
        alert('Du bedes vælge et maksimum areal, der er større end minimum');
        return false;
    }

    return true;
}



$().ready(function() {
    // Initialize the right menu
    /*$("#accordion").accordion({ autoHeight: false, animated: false });*/

    $('.accordion .head').click(function() {
        $(this).next().toggle();
        return false;
    }).next().hide();
    // if 'map' div is present - insert loading-text
    //$('<div id="loading">Henter kort...</div>')
    //          .insertBefore('#map')
    //          .ajaxStart(function() {
    //              $(this).show();
    //          }).ajaxStop(function() {
    //              $(this).hide();
    //          });

    // bind click-event to submitToList-button
    $('#submitToList').bind('click', function() {
        $('#frmSearchApartment').submit();
        return false;
    });

    // bind click-event to submitToMap-button
    //$('#submitToMap').bind('click', function() {
    //    $.get('/Public/GoogleMapSearch.aspx?search=true', $('#frmSearchApartment').serialize(), function(data) {
    //        $('#googleMapScript').empty();
    //        $('#googleMapScript').html(data);
    //    });
    //    return false;
    //});

    // Take care of Dynamicweb replacing hyperlinks
    $("a.tabLink").each(function() {
        var tabId = $(this).attr('href').split('#')[1];
        $(this).attr('href', '#' + tabId);
    });

    // Activate tabs
    //$('#tabs').tabs();


 
 // LOADING INFO
   /*
    $("#waitingForResultBox").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 300,
        height: 100,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
//            Ok: function() {
//                $(this).dialog('close');

//            }
        }
    });
    */

    // Activate lightbox
    /*$('#Pictures a').lightBox({
        txtImage: 'Billede',
        txtOf: 'af',
        imageLoading: '/Files/System/NemLejeSystem/lightbox/lightbox-ico-loading.gif',
        imageBtnClose: '/Files/System/NemLejeSystem/lightbox/closelabel.gif',
        imageBtnPrev: '/Files/System/NemLejeSystem/lightbox/prev.gif',
        imageBtnNext: '/Files/System/NemLejeSystem/lightbox/next.gif',
        fixedNavigation: false
    });
    */
    // Activate dialog 
    /*
    $("#dialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 600,
        height: 700,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
           Ok: function() {
                $(this).dialog('close');
           
           }
        }
    });
    */
/*
	    $("#additionalInfoWindow").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 900,
       // height: 700,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
 //           Ok: function() {
 //             $(this).dialog('close');

//            }
        }
    });
    */
	/*
	
    // Activate wish list changed dialog
    $("#wishlistChangedDialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 300,
        height: 150,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });

    */

    /*
    // Activate wish list changed dialog
    $("#YouNeedToUpgradeDialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 400,
        height: 300,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });
    */
    // Activate wish list changed dialog
    
    /*
    $("#AnErrorOccurred").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 300,
        height: 100,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });
    */

    // Activate wishlist actions
    $('a.addToWishList').bind('click', function() {
        var div = $(this).find('div');
        var link = $(this);
        $.get(this.href, function(data) {
            //alert(data);
            if (data == "1") {
                $("#wishlistChangedDialog").dialog("open");
                div.removeClass('addToWishList');
                link.removeClass('addToWishList');
                div.addClass('removeFromWishList');
                link.addClass('removeFromWishList');
            } else if (data != "Fejl") {
                $("#YouNeedToUpgradeDialog").dialog("open");
            } else {
                $("#AnErrorOccurred").dialog("open");
            }
        }
            );
        return false;
    });

    // Activate wishlist actions
    $('a.removeFromWishList').bind('click', function() {
        var div = $(this).find('div');
        var link = $(this);
        $.get(this.href, function(data) {
            $("#wishlistChangedDialog").dialog("open");
            div.removeClass('removeFromWishList');
            link.removeClass('removeFromWishList');
            div.addClass('addToWishList');
            link.addClass('addToWishList');
        }
            );
        return false;
    });

    // Activate respond dialog
    /*
    $("#responddialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 400,
        height: 200,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Accepter: function() {
                if (confirm("Ved denne handling accepterer du tilbuddet! Er du helt sikker?")) {
                    $('#Svar').val("J");
                    $("#responddialogform").submit();
                }
                $(this).dialog('close');
            },
            Afvis: function() {
                    if (confirm("Ved denne handling afviser du tilbuddet! Er du helt sikker?")) {
                        $('#Svar').val("N");
                        $("#responddialogform").submit();
                    }
                    $(this).dialog('close');
                }
            
        }
    });
    */

    /*
    $("#responddialogAccept").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 400,
        height: 200,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Accepter: function() {
                if (confirm("Ved denne handling accepterer du tilbuddet! Er du helt sikker?")) {
                    $('#Svar').val("J");
                    $("#responddialogform").submit();
                }
                $(this).dialog('close');
            }
            
        }
    });

    */
    /*
    $("#responddialogDecline").dialog({
            autoOpen: false,
            bgiframe: true,
            modal: true,
            width: 400,
            height: 200,
            overlay: { opacity: 0.5, background: "black" },
            buttons: {                
                Afvis: function() {
                    if (confirm("Ved denne handling afviser du tilbuddet! Er du helt sikker?")) {
                        $('#Svar').val("N");
                        $("#responddialogform").submit();
                    }
                    $(this).dialog('close');
                }
            }
        });
        */
    // Activate response reciept dialog
    /*
    $("#recieptdialog").dialog({
        autoOpen: true,
        bgiframe: true,
        modal: true,
        width: 300,
        height: 200,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });
    */
    // Activate Terminate Lease dialog
    /*
    $("#TerminateLeaseDialog").dialog({
        autoOpen: false,
        autoResize: true,
        resizable: true,
        bgiframe: true,
        modal: true,
        width: 820,
        height: 800,
        overlay: { opacity: 0.5, background: "black" },
        buttons: {
            Luk: function() {
                $(this).dialog('close');
            }
        }
    });
    */
    // Load terminate lease file into JQuery dialog
    $("a.TerminateLeaseLink").click(
        function(e) {
            e.preventDefault();
            $('#TerminateLeaseIframe').attr("src", "/Public/TerminateLease.aspx?apartmentId=1032");
            $("#TerminateLeaseDialog").dialog("open");
            return false;
        }
    );

    // Activate respond actions

    // Activate table sorter
    /*
    $("#apartmentsTable")
          .tablesorter({ widgets: ['zebra'], sortList: [[0, 0]] })
          .tablesorterPager({ container: $("#pager"), size: 20, positionFixed: false });
    // Min side - Tilbud
    $("#Apartments")
          .tablesorter({ widgets: ['zebra'], sortList: [[0, 0]] })
    // Min side - Tilbudshistorik
    $("#Apartments_history")
          .tablesorter({ widgets: ['zebra'], sortList: [[0, 0]] })
          //.tablesorterPager({ container: $("#pager"), size: 20, positionFixed: false });

          */
    // validate signup form on keyup and submit
    $("#CreateUserForm").validate({
        rules: {
            Navn: {
                required: true,
                minlength: 5
            },
            Adresse: {
                required: true,
                minlength: 5
            },
            Postby: {
                required: true,
                minlength: 5
            },
            Email: {
                required: true,
                email: true
            },
            Cpr6: {
                required: true,
                minlength: 6,
                maxlength: 6
            },
            Tlf: {
                required: true
            },
            Password: {
                required: true,
                minlength: 5
            },
            RepeatPassword: {
                equalTo: "#Password"
            }

        },
        messages: {
            Navn: {
                required: "<br /><span>Indtast venligst dit navn</span>",
                minlength: "<br /><span>Indtast venligst dit navn</span>"
            },
            Adresse: {
                required: "<br />Indtast venligst din adresse",
                minlength: "<br />Indtast venligst din adresse"
            },
            Postby: {
                required: "<br />Indtast venligst dit postnummer og by",
                minlength: "<br />Indtast venligst dit postnummer og by"
            },
            Email: {
                required: "<br />Indtast venligst en gyldig e-mail adresse",
                email: "<br />Indtast venligst en gyldig e-mail adresse"
            },
            Cpr6: {
                required: "<br />Indtast venligst de første seks cifre i dit personnummer",
                minlength: "<br />Indtast venligst de første seks cifre i dit personnummer",
                maxlength: "<br />Indtast venligst de første seks cifre i dit personnummer"
            },
            Tlf: {
                required: "<br />Indtast venligst dit telefonnummer"
            },
            Password: {
                required: "<br />Indtast venligst dit nye password.",
                minlength: "<br />Dit password skal bestå af mindst fem tegn."
            },
            RepeatPassword: {
                equalTo: "<br />Gentag venligst dit nye password."
            }
        }
    });

    // validate login form on keyup and submit
    $("#ExtUserForm").validate({
        rules: {
            Username: {
                required: true
            },
            Password: {
                required: true
            }
        },
        messages: {
            Username: {
                required: "<br />Indtast venligst dit brugernavn"
            },
            Password: {
                required: "<br />Indtast venligst dit kodeord"
            }
        }
    });

    $("#loginButton").bind("click", function(e) {
        if ($("#Username").val() == '' || $("#Password").val() == '') {
            alert('Du bedes venligst indtaste både dit brugernavn og dit password');
            return false;
        }
    });


    $("#MinimumHusleje").val($("#Server_Request_minimumhusleje").val());
    if ($("#Server_Request_maximumhusleje").val() != '') {
        $("#MaximumHusleje").val($("#Server_Request_maximumhusleje").val());
    }

    $("#Minimumbareal").val($("#Server_Request_minimumbareal").val());

    if ($("#Server_Request_maximumbareal").val() != '') {
        $("#Maximumbareal").val($("#Server_Request_maximumbareal").val());
    }

    $("#Minimumrum").val($("#Server_Request_minimumrum").val());

    if ($("#Server_Request_maximumrum").val() != '') {
        $("#Maximumrum").val($("#Server_Request_maximumrum").val());
    }

    if ($("#Server_Request_petallowed").val() != '') {
        $("#petAllowed").attr("checked", true);
    }

    if ($("#Server_Request_noorlowwaitingtime").val() != '') {
        $("#noOrLowWaitingTime").attr("checked", true);
    }

    if ($("#Server_Request_showonlyfreeapartments").val() != '') {
        $("#showOnlyFreeApartments").attr("checked", true);
    }


    var dt = new Date();
    $(function() {
        /*$("#Cpr6").datepicker({
            dateFormat: 'ddmmy',
            maxDate: dt.getDate() - (15 * 365),
            showButtonPanel: true,
            yearRange: "-100:+0",
            showOn: "both",
            changeYear: true,
            changeMonth: true
        });
        */
    });
});
