﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

var loginReturnUrl;
var source = "widget";
function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
}

jQuery.extend({
    put: function (url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function (url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

var appointmentDetailsID;

var globalLoaded;

var appointmentTypeSelected;
jQuery(document).ready(function () {

    if (globalLoaded != true) {

        loadInsuranceCarrierSelection();

        initLoginButton("E-Mail");

        initRegisterButton();

        init_Login_Register_Tabs();

        initDialog();

        initMessageBox();

        initConfirmAppointmentDialog();

        initFreeAppointmentDialog();

        initAppointmentDetailsDialog();

        initUploadPracticePictureDialog();

        initForgotPasswordDialog();

       // initChooseAppointmentTypeDialog();

        

        globalLoaded = true;
    }
});


function initChooseAppointmentTypeDialog() {

    jQuery("#chooseAppointmentTypeDialog").dialog({

        bgiframe: true, autoOpen: false, buttons: {

            'Termine anzeigen': function () {
                jQuery("#chooseAppointmentTypeDialog").dialog("close");
              
                window.location = "?minTime=" + jQuery("#chooseAppointmentTypeDialog option:selected").attr("value")
            }
        }
    });

}

function loadInsuranceCarrierSelection() {

    $.get("/Docplaner/GetInsuranceCarriers", function (res) {

    
        if (JSON != null) {
            
            var array = JSON.parse(res);
        } else {
            
            var array = jQuery.parseJSON(res);
        }

        for (var i = 0; i < array.length; i++) {

            var insurance = array[i];

            var html = "<option value='" + insurance.id + "'>" + insurance.name + "</option>";

            jQuery("#insuranceCarrierSelect").append(html)

        }

    });



}

function initForgotPasswordDialog() {
    jQuery("#forgotPasswordDialog").dialog({
        bgiframe: true, autoOpen: false, buttons: {

            'Passwort zurücksetzen': function () {
                jQuery("#forgotPasswordDialog").dialog("close");
                $.blockUI({ message: "<img src=\"/Content/symbols/ajax-loader-circle.gif\" /><br />Bitte warten..." });
                $.post("/Account/ForgotPassword", jQuery("#forgotPasswordForm").serialize(), function (obj) {
                    $.unblockUI();

                    if (obj == "Success") {

                        messagebox("Passwort zurückgesetzt", "Ihr Passwort wurde erfolgreich zurückgesetzt und Ihnen per E-Mail zugeschickt.");
                    }
                });
            }

        }
    });

    return true;
}

function openForgotPasswordDialog() {
    jQuery("#forgotPasswordDialog").dialog("open");
}

function openUploadPracticePictureDialog() {
    jQuery("#uploadPracticeImageDialog").dialog("open");
}

function initUploadPracticePictureDialog() {
    $("#uploadPracticeImageForm").submit(function () {
        jQuery("#uploadPracticeImageDialog").dialog("close");
    });
    jQuery("#uploadPracticeImageDialog").dialog({
        bgiframe: true, autoOpen: false, width:375
    });


}


function init_Login_Register_Tabs() {
    jQuery("#loginRegisterTabs").tabs();
    return true;
}



function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


function initLoginButton(usernameCaption, command) {
    
    jQuery("#loginEmailLabel").attr("value", usernameCaption);

 


    jQuery("#loginButton").button();
    jQuery("#loginButton").click(function (evt) {

        var username = $("#usernameField").val();
        var password = $("#passwordField").val();

        jQuery("#loginDialog").dialog("close");

        jQuery("#loginErrorLabel").text("");

        $.blockUI({ message: "<img src=\"/Content/symbols/ajax-loader-circle.gif\" /><br />Bitte warten..." });

        $.get("/Account/LogOnAjax?usernameField=" + username + "&passwordField=" + password, function (obj) {

            $.unblockUI();
            if (obj == "Doctor" || obj == "Practice") {

                var returnUrl = getUrlVars()["ReturnUrl"];

                if (returnUrl == null) {

                    window.location = "/Home/Backend#backendTabs";

                } else {
                    window.location = returnUrl;
                }
                return true;
            }
            if (obj == "Success" || obj == "Patient") {
                if (command != null) {
                    command();
                } else {
                    if (loginReturnUrl != null) {
                        window.location = loginReturnUrl;
                    } else {
                        location.reload();
                    }
                }
                return true;
            } else {


                jQuery("#loginErrorLabel").text("Die Logindaten konnten nicht zugeordnet werden. Bitte versuchen Sie es erneut.");

                jQuery("#loginDialog").dialog("open");

                jQuery("#usernameField").removeAttr("value");

                jQuery("#passwordField").removeAttr("value");

                return false;
            }

        });

    });

    return true;
}

function initRegisterButton() {

    jQuery("#registerButton").button();
    jQuery("#registerButton").click(function (evt) {

        jQuery("#registerErrorLabel").empty();
        var firstName = $("#firstNameField").val();
        var lastName = $("#lastNameField").val();
        var birthday = $("#birthdayField").val();
        var email = $("#emailField").val();

        if (firstName == "") {

            jQuery("#registerErrorLabel").text("Bitte geben Sie Ihren Vornamen an.");


            return false;
        }

        if (lastName == "") {
            jQuery("#registerErrorLabel").text("Bitte geben Sie Ihren Nachnamen an.");


            return false;
        }

        if (!(/(0[1-9]|[12][0-9]|3[01])[\- \/.](0[1-9]|1[012])[\- \/.](19|20)[0-9]{2}/.test(birthday))) {
            //invalid birthday
            jQuery("#registerErrorLabel").text("Bitte geben Sie ein gültiges Geburtsdatum der Form tt.mm.jjjj an.");


            return false;
        }

        if (!(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test(email))) {
            // invalid email

            jQuery("#registerErrorLabel").text("Bitte geben Sie eine gültige E-Mail Adresse an.");


            return false;
        }


        if ($('#agb_check').attr("checked") == true) {
            var data = "firstName=" + firstName + "&lastname=" + lastName + "&birthday=" + birthday + "&email=" + email;

            jQuery("#registerErrorLabel").text("");

            jQuery("#loginDialog").dialog("close");

            $.blockUI({ message: "<img src=\"/Content/symbols/ajax-loader-circle.gif\" /><br />Bitte warten..." });



            $.post("/Account/RegisterPatient", jQuery("#registerForm").serialize(), function (obj) {


                if (obj == "Success") {




                    messagebox("Willkommen", "Ihre Anmeldung bei docPlaner war erfolgreich. Sie erhalten in Kürze eine E-Mail mit Ihrem Passwort und den sonstigen Anmeldedaten.");

                    $.unblockUI();





                    return true;


                } else {
                    //TODO Error Handling
                    jQuery("#loginDialog").dialog("open");

                    jQuery("#firstNameField").attr("value", "");
                    jQuery("#lastNameField").attr("value", "");
                    jQuery("#birthdayField").attr("value", "");
                    jQuery("#emailField").attr("value", "");

                    if (obj == "DuplicateUserName") {
                        jQuery("#loginErrorLabel").text("Die angegebene E-Mail Adresse existiert bereits. Bitte geben Sie ihr Passwort ein.");

                        jQuery("#usernameField").attr("value", email);
                        jQuery("#loginRegisterTabs").tabs({ selected: 1 });
                    } else {
                        jQuery("#registerErrorLabel").text(obj);
                    }


                    $.unblockUI();

                    return false;
                }


            });

        } else {
            jQuery("#registerErrorLabel").text("Sie müssen die Datenschutzerklärung akzeptieren um sich zu registrieren.");
        }




    });

}

function messagebox(newtitle, text) {

    
    $("#messageBox").dialog("option", "title", newtitle);
    $("#messageBox").text(text);
    $("#messageBox").dialog("open");

}

function initMessageBox() {

    jQuery("#messageBox").dialog({
        bgiframe: true, autoOpen: false, modal: true, width: 350, buttons: {

            'OK': function () {
                $("#messageBox").dialog("close");
                if (loginReturnUrl != null) {
                    location = loginReturnUrl;
                    loginReturnUrl = null;
                    location.reload();
                } else {
                    location.reload();
                }
            }

        }

    });

    return true;
}

function initDialog() {
    jQuery("#loginDialog").dialog({
        bgiframe: true, autoOpen: false, modal: true, width:350

    });
 
    return true;
}


function initAppointmentDetailsDialog() {

    jQuery("#terminDetailsDialog").dialog({
        bgiframe: true, autoOpen: false, width: 450 , modal: true, buttons: {

            'Schließen': function () {

             



                    var dat = jQuery("#docCommentText").serialize();

                    if (jQuery("#practiceDoctorSelection").length) {
                        dat = dat + "&" + jQuery("#practiceDoctorSelection").serialize();
                    }

                    $.post("/Appointment/Comment/" + appointmentDetailsID, dat, function (res) {
                        
                    });
                

                $("#terminDetailsDialog").dialog("close");

            },

            'Termin absagen': function () {
                //TODO absagetext aus messagebox holen
                $("#terminDetailsDialog").dialog("close");

                openCancelAppointmentDialog();



            }



        }

    });
    return true;
}

function initFreeAppointmentDialog() {

    jQuery("#freeAppointmentDetailsDialog").dialog({
        bgiframe: true, autoOpen: false, modal: true,width: 350, buttons: {

            'Schließen': function () {

                $("#freeAppointmentDetailsDialog").dialog("close");

            },

            'Entfernen': function () {

                $.post("/Appointment/Delete/" + appointmentDetailsID, function (obj) {

                    $("#freeAppointmentDetailsDialog").dialog("close");

                    if (obj == "Success") {
                        messagebox("Termin entfernt", "Der Termin wurde erfolgreich entfernt.");
                        appointmentDetailsID = null;
                    } else {
                        messagebox("Fehlgeschlagen", "Der Termin konnte nicht abgesagt werden.");
                    }

                });

            }



        }

    });


    
    return true;

}

function terminDetails(id) {

    $.blockUI({ message: "<img src=\"/Content/symbols/ajax-loader-circle.gif\" /><br />Bitte warten..." });
    $.post("/Appointment/Details/" + id, function (res) {
        //TODO parse JSON and fill the dialog box with data

        var obj = JSON.parse(res);

        jQuery("#patientText").text(obj.patient);
        jQuery("#startTimeText").text(obj.start);
        jQuery("#endTimeText").text(obj.ende);
        jQuery("#dateText").text(obj.date);
        if (obj.comment == "") {
            jQuery("#commentLabel").empty();
            jQuery("#commentText").empty();
        } else {
            jQuery("#commentText").text(obj.comment);
            jQuery("#commentLabel").text("Patienten-Kommentar:");
        }
        jQuery("#docCommentText").text(obj.docComment);
        jQuery("#appointmentTypeField").text(obj.appointmentType);
        jQuery("#stammpatientStatus").text(obj.stammpatient);
        jQuery("#insuranceType").text(obj.insurance);
        appointmentDetailsID = id;
        jQuery("#terminDetailsDialog").dialog("open");
        $.unblockUI();


    }, function () {
        alert("error");
    });
    jQuery("#createFreeSlotDialog").dialog("close");

}

function freeAppointmentDetails(id) {

    $.blockUI({ message: "Bitte warten..." });
    $.post("/Appointment/Details/" + id, function (obj) {
       


        jQuery("#freeAppStartTimeText").text(obj.start);
        jQuery("#freeAppEndTimeText").text(obj.ende);
        jQuery("#freeAppDateText").text(obj.date);
        jQuery("#freeAppointmentDetailsDialog").dialog("open");

        appointmentDetailsID = id;

        $.unblockUI();


    });
    jQuery("#createFreeSlotDialog").dialog("close");

}

function confirmAppointment(id, doc, time, place) {

    

    jQuery("#confirmAppDoctorField").text(doc);

    jQuery("#confirmAppTimeField").text(time + " Uhr");

    jQuery("#confirmAppPlaceField").text(place);

    jQuery("#confirmAppId").attr("value", id);

    jQuery("#confirmAppointmentForm").attr("action", "/Appointment/Reserve/" + id);


    jQuery("#confirmAppComment").empty();
    jQuery("#confirmAppointmentDialog").dialog("open");



    return true;
}

function initConfirmAppointmentDialog() {

    jQuery("#confirmAppointmentDialog").dialog({
        bgiframe: true, autoOpen: false, modal: true, buttons: {
            "Bestätigen": function () {

                jQuery("#confirmAppointmentDialog").dialog("close");

                $.blockUI({ message: "<img src=\"/Content/symbols/ajax-loader-circle.gif\" /><br />Bitte warten..." });



                var data = { comment: jQuery("#confirmAppComment").attr("value"), appointmentType: jQuery("#confirmAppTypeId").attr("value"), stammpatient: jQuery("#confirmAppointmentForm input:checked").attr("value") };

                $.post(jQuery("#confirmAppointmentForm").attr("action"), data, function (obj) {
                    $.unblockUI();
                    if (obj == "Success") {
                        jQuery(".widget").empty();
                        jQuery(".widget").append("<h2>Ihre Terminbuchung war erfolgreich!</h2><p>Wir haben Ihren Wunschtermin verbindlich für Sie gebucht. In Kürze erhalten Sie eine Terminbestätigung per Email. </p><p>Die volle Übersicht über Ihre Termine erhalten Sie unter „Mein Konto“. Dort können Sie sich die Anfahrt zur Praxis anzeigen lassen oder auch den Termin absagen, falls Sie verhindert sein sollten. </p><p>Wir freuen uns auf Sie!<br />Ihr Praxisteam </p>");
                        /*
                        if (source == "homepage") {
                            window.location.href = "TerminErfolgreich";
                        } else {
                            window.location.href = "/Appointment/TerminErfolgreich";
                        }
                        */

                        return true;
                    } else {
                        messagebox("Terminreservierung", "Leider ist Ihre Terminreservierung fehlgeschlagen. Bitte versuchen Sie es später erneut.");
                    }
                });
            },

            "Abbrechen": function () {
                jQuery("#confirmAppointmentDialog").dialog("close");
            }
        }
    });
    

    return true;
}


function loginDialog() {

    $("#loginDialog").dialog("open");
    return true;

}




function reserve(id, doc, time, place) {

    $.get('/Appointment/CheckRights/', function (obj) {

        if (obj == "Auth") {

            return confirmAppointment(id, doc, time, place);
        } else {
            loginDialog();
            return false;
        }
    });


}

function logout() {

    $.get('/Account/LogOff/', function (obj) {
        if (obj == "Success") {
            location.reload();
            return true;
        } else {
            return false;
        }
    });

}

