﻿function mp_onload() {
    if (window.body_onload != null)
        window.body_onload();
}

// 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 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;
    }
}

// Google Maps variables
var map;
var geocoder;
var bounds;
var countPointOnMap = 0;
var svc;
var marker;

// Initialize Google Maps
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();
}

// Create marker on Google Maps
function createMarker(gCoordsLat, gCoordsLng, Adresse, DepartmentPicture, DepartmentPictureThumbnailWidth, DepartmentPictureThumbnailHeight, pageId, afd, Beliggenhed, PostBy) {
   if (gCoordsLat != '' && gCoordsLng != '') {
        var point = new google.maps.LatLng(gCoordsLat, gCoordsLng);
        bounds.extend(point);
        countPointOnMap++;
    }

    if (point) {
        var marker = new google.maps.Marker({ position: point, map: map });
        marker.y = 0;
        marker.p = 5;
        marker.z = 0;
        var infowindow;
        var html = "<div id='GoogleMapsDepartmentInfo'>";
        
        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=220></IFRAME>';
                    html += "<div><b>" + data.location.description + "</b></div><div>" + gSIframe + "</div><div id='streetViewDisclaimer'>NB: Det viste er ikke nødvendigvis den præcise adresse</div>";
                } else {
                   if (DepartmentPicture != "") {
                        html += "<img src=\'" + DepartmentPicture + "\' width=\'" + DepartmentPictureThumbnailWidth + "\' height=\'" + DepartmentPictureThumbnailHeight + "\' align=\'left\'>";
                    }
                }
                
                html += "<a href=\'/Default.aspx?ID=" + pageId + "&amp;departmentID=" + afd + "&amp;action=DisplayDepartment\'>Klik her for at se detaljer for hele afdelingen</a>";
                // html += "<a href=\'javascript:void(0);\' onclick=\'javascript:$(\"\#tabs\").tabs(\"select\", 1);\'>Klik her for at se lejligheder fra din søgning</a>";
                html += "</div>"; 
                
                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 = '';
    }
}

// Insert point on map
function insertPointOnMap(gCoordsLat, gCoordsLng, Adresse, DepartmentPicture, DepartmentPictureThumbnailWidth, DepartmentPictureThumbnailHeight, pageId, afd, Beliggenhed, PostBy) {
    if (gCoordsLat != '' && gCoordsLng != '') {
        var point = new google.maps.LatLng(gCoordsLat, gCoordsLng);
        bounds.extend(point);
        countPointOnMap++;
    }
    if (point) {
        var htmlBefore = "<div id='GoogleMapsDepartmentInfo'>";
        if (DepartmentPicture != "") {
            htmlBefore += "<img src=\'" + DepartmentPicture + "\' width=\'" + DepartmentPictureThumbnailWidth + "\' height=\'" + DepartmentPictureThumbnailHeight + "\' align=\'left\'>";
        }
        markerString += "<a href=\'/Default.aspx?ID=" + pageId + "&amp;departmentID=" + afd + "&amp;action=DisplayDepartment\'>Klik her for at se detaljer for hele afdelingen</a>";
        //markerString += "<a href=\'javascript:void(0);\' onclick=\'javascript:$(\"\#tabs\").tabs(\"select\", 1);\'>Klik her for at se lejligheder fra din søgning</a>";
        markerString += "</div>"; 
        var marker = createMarker(point, markerString);
    }
}

// Validate search form
function validateForm(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;
}

$(document).ready(function() {
    // Initialize the right menu
    $("#accordion").accordion({ autoHeight: false, animated: false });

    $('.accordion .head').click(function() {
        $(this).next().toggle();
        return false;
    }).next().hide();

    // 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();
}
);

$(window).ready(function() {
    // bind click-event to submitToList-button
    $('#submitToList').bind('click', function() {
        $('#frmSearchApartment').submit();
        return false;
    });

    // Activate lightbox
    $('#Pictures a').lightBox({
        txtImage: 'Billede',
        txtOf: 'af',
        imageLoading: '/Files/System/lightbox/lightbox-ico-loading.gif',
        imageBtnClose: '/Files/System/lightbox/closelabel.gif',
        imageBtnPrev: '/Files/System/lightbox/prev.gif',
        imageBtnNext: '/Files/System/lightbox/next.gif',
        fixedNavigation: true
    });

    // 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');
            }
        }
    });

    // Activate wish list changed dialog
    $("#wishlistChangedDialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 300,
        height: 100,
        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');
            }
        }
    });

    // 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 });


    // validate login form on keyup and submit
    $("#ExtUserForm").validate({
        rules: {
            Username: {
                required: true
            },
            Password: {
                required: true
            }
        },
        messages: {
            Username: {
                required: "Indtast venligst din e-mail"
            },
            Password: {
                required: "Indtast venligst dit password"
            }
        }
    });

    $("#loginButton").bind("click", function(e) {
        if ($("#Username").val() == '' || $("#Password").val() == '') {
            alert('Du bedes venligst indtaste både din e-mail og dit password');
            return false;
        }
    });

    // Set default values for search form
    //    apartmentTypes = new Array;
    //    apartmentTypes = $("#Server_Request_apartmenttypes").val().split(",");
    //    $.each(apartmentTypes, function() {
    //        alert(this);
    //    });

    //$.each($("#ApartmentTypes"), function() { alert(this); });
    //alert($("#Server_Request_apartmenttypes").val());
    //$("#frmSearchApartment :input[@ApartmentTypes]").val([$("#Server_Request_apartmenttypes").val()]);

    //$("#ApartmentTypes").each(function() { alert(this); });

    $("#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);
    }
});