﻿/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" />
/// <reference path="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" />
/// <reference path="jsonhelper.min.js" />
/// <reference path="../persistencehelper.js" />
/// <reference path="datahelper.js" />
var temp = "";
UIHelper.Dialogs = {

    Init: function() {
        this.PrepareDialogs();
        this.InitGenericEvents();
        this.SendDialog.InitEvents();
        this.PrintDialog.InitEvents();
        this.ConfirmLeaveDialog.InitEvents();
        this.SearchDialog.InitEvents();
        this.ShoppinglistDialog.Init();
        //this.SelectDayDialog.Init();
    },

    // Prepares the dialog boxes
    PrepareDialogs: function() {
        $('#confirm-leave-dialog').dialog('option', 'width', 475);
        $('#send-dialog').dialog();
        $('#print-dialog').dialog('option', 'width', 323);

        $('#shoppinglist-dialog').dialog('option', 'width', 822);
        $('#shoppinglist-dialog').dialog('option', 'open', function() { UIHelper.Dialogs.ShoppinglistDialog.InitData(); });
        $('#shoppinglist-dialog').dialog('option', 'close', function() { UIHelper.Dialogs.ShoppinglistDialog.PersistShoppinglist(); });

        $('#wizard-dialog').dialog('option', 'width', 720);
        $('#wizard-dialog').dialog('option', 'open', function() { UIHelper.Dialogs.WizardDialog.Init(); });

        $('#archive-dialog').dialog('option', 'width', 620);
        $('#archive-dialog').dialog('option', 'open', function() { UIHelper.Dialogs.ArchiveDialog.Init(); });
    },

    InitGenericEvents: function() {
    },

    // ----------------------------------------------------

    ArchiveDialog: {
        Weekplans: [],

        Init: function() {
            this.PopulateDialog(1, true);
            // "Use empty weekplan" button
            $("#archive-dialog .button.use-empty").click(function() {
                var weekplan = { Recipes: [null, null, null, null, null, null, null] };
                UIHelper.Dialogs.ArchiveDialog.UseWeekplan(weekplan);
            });
            // "Use this weekplan" button
            $("#archive-dialog .button.use-this").click(function() {
                var clickedIndex = $("#archive-dialog li.week").index($(this).closest("li"));
                var weekplanIndex = clickedIndex - 1;
                var weekplan = UIHelper.Dialogs.ArchiveDialog.Weekplans[weekplanIndex];
                UIHelper.Dialogs.ArchiveDialog.UseWeekplan(weekplan);
            });
            // Paging links
            $("#archive-dialog ul.paging a").click(function() {
                var clickedIndex = $("#archive-dialog ul.paging li").index($(this).closest("li"));
                var newPage = clickedIndex + 1;
                UIHelper.Dialogs.ArchiveDialog.PopulateDialog(newPage, false);
                // Update paging
                $("#archive-dialog ul.paging li").removeClass("active-page");
                $(this).closest("li").addClass("active-page");
            });
        },

        PopulateDialog: function(page, isFirstRun) {
            //console.log(isFirstRun);
            var weeksUl = $("ul.weeks");
            weeksUl.hide();
            $("#archive-dialog img.loading-image").show();
            var requestData = { PageNo: page };
            JSONHelper.MakeRequest("GetPreviousPlans", requestData, function(responseData) {
                $("#archive-dialog img.loading-image").hide();
                weeksUl.show();
                var pagingObj = responseData.d;
                var list = pagingObj.List;
                if (list == null || list == undefined) {
                    $('#archive-dialog div .inner-body').html('<p style="color:red;margin:15px">Der er ingen tidligere madplaner</p>');
                    return;
                }
                UIHelper.Dialogs.ArchiveDialog.Weekplans = list;
                $("li.week:not(li.proto)", weeksUl).remove();
                var protoLI = $("li.proto.week");
                $.each(list, function(i, weekplan) {
                    var newLI = protoLI.clone(true);
                    // IE6 clone() fix
                    if ($.browser.msie && parseInt($.browser.version) < 7)
                        newLI.innerHTML = protoLI.innerHTML;
                    $("h5 span", newLI).text("Madplan for " + weekplan.WeekNo);
                    var daysUL = $("ul", newLI);
                    $.each(weekplan.Recipes, function(i, recipe) {
                        $("li:eq(" + i + ") .recipe", daysUL).text(recipe.Name);
                    });
                    $("img", newLI).attr("src", weekplan.Recipes[0].SmallImageUrl);
                    $("img", newLI).attr("alt", weekplan.Recipes[0].Name);
                    newLI.removeClass("proto");
                    weeksUl.append(newLI);
                });
                if (isFirstRun)
                    UIHelper.Dialogs.ArchiveDialog.SetupPaging(pagingObj.PageCount);
            });
        },

        SetupPaging: function(pageCount) {
            //console.log(pageCount);
            var pagingUL = $("#archive-dialog ul.paging");
            var protoLI = $("li:first", pagingUL);
            $("li:not(li:first)", pagingUL).remove();
            for (var i = 1; i <= pageCount; i++) {
                var newLI = (i == 1) ? protoLI : protoLI.clone(true);
                // IE6 clone() fix
                if ($.browser.msie && parseInt($.browser.version) < 7)
                    newLI.innerHTML = protoLI.innerHTML;

                // Set title attribute
                $("a", newLI).text(i);
                var title = $("a", newLI).attr("title");
                title = title.replace("x", i);
                $("a", newLI).attr("title", title);
                pagingUL.append(newLI);

                if (i == 1) {
                    newLI.addClass("active-page");
                }
                else {
                    newLI.removeClass("active-page");
                }
            }
        },

        UseWeekplan: function(weekplan) {


            $('div .inner-body').html('<p>Din nuværende madplan vil forsvinde, når du går til en ny madplan.</p><p>Er du sikker på, at du vil fortsætte?</p>');
            UIHelper.Dialogs.ConfirmLeaveDialog.Confirm(function(confirm) {
                // TODO: Check if weekplan has been changed from default (?)
                if (confirm) {
                    UIHelper.MainView.UI.PopulateWeek(weekplan.Recipes);
                    $("#archive-dialog").dialog("close");
                }
                else {
                    return false;
                }
            });
        }
    },

    // --------------------------------------------------------

    ConfirmLeaveDialog: {
        Callback: null,
        InitEvents: function() {
            $("#confirm-leave-dialog .button.no").click(function() {
                $("#confirm-leave-dialog").dialog("close");
                UIHelper.Dialogs.ConfirmLeaveDialog.Callback(false);
            });
            $("#confirm-leave-dialog .button.continue").click(function() {
                $("#confirm-leave-dialog").dialog("close");
                UIHelper.Dialogs.ConfirmLeaveDialog.Callback(true);
            });
        },
        Confirm: function(callback) {
            $("#confirm-leave-dialog").dialog("open");
            UIHelper.Dialogs.ConfirmLeaveDialog.Callback = callback;
        }
    },

    // ----------------------------------------------------

    WizardDialog: {
        Vars: {
            SelectedDay: 0,
            RecipesInWeekplan: [],
            CurrentSuggestions: null
        },

        Init: function() {
            //UIHelper.Dialogs.WizardDialog.Vars.RecipesInWeekplan = PersistenceHelper.WeekPlan.GetPlan().Recipes;
            UIHelper.Dialogs.WizardDialog.Clear();
            UIHelper.Dialogs.WizardDialog.ShowRecipes();
            // "5 nye forslag"
            $(".button.new-suggestions").bind("click", UIHelper.Dialogs.WizardDialog.NewSuggestions_Click);
            //            $(".button.new-suggestions").click(function(event) {
            //                UIHelper.Dialogs.WizardDialog.NewSuggestions_Click();
            //            });
            // "Benyt denne"
            $(".button.insert-recipe").click(function(event) {
                event.preventDefault();
                var recipeId = $(this).closest("li").children("input[name='recipeid']").val();
                var clickedIndex = $("#suggestions li:not(.proto)").index($(this).closest("li"));
                var recipe = UIHelper.Dialogs.WizardDialog.Vars.CurrentSuggestions[clickedIndex];
                UIHelper.MainView.UI.PopulateDay(recipe, UIHelper.Dialogs.WizardDialog.Vars.SelectedDay);
                //UIHelper.MainView.UI.GetRecipeAndInsertOnDay(recipeId, UIHelper.Dialogs.WizardDialog.Vars.SelectedDay);
                $(".button.new-suggestions").unbind("click");
                $("#wizard-dialog").dialog("close");
            });
        },

        NewSuggestions_Click: function(event) {
            event.preventDefault();
            //            $(".button.new-suggestions").unbind("click");
            UIHelper.Dialogs.WizardDialog.Clear();
            UIHelper.Dialogs.WizardDialog.ShowRecipes();
        },

        Clear: function() {
            var protoLI = $("#suggestions li:not(.proto)").remove();
            UIHelper.Dialogs.WizardDialog.Vars.CurrentSuggestions = null;
        },

        ShowRecipes: function() {
            var suggestionUl = $("#suggestions");
            suggestionUl.hide();
            $("#wizard-dialog img.loading-image").show();
            var recipeCount = 5;
            requestData = { Count: JSON.stringify(recipeCount), MainIngredient: null, Exclude: JSON.stringify(PersistenceHelper.WeekPlan.GetPlan().Recipes) };
            JSONHelper.MakeRequest("GetRandomRecipes", requestData, function(responseData) {
                suggestionUl.show();
                $("#wizard-dialog img.loading-image").hide();
                var recipes = responseData.d;
                if (UIHelper.Dialogs.WizardDialog.Vars.CurrentSuggestions == null)
                    UIHelper.Dialogs.WizardDialog.Vars.CurrentSuggestions = recipes;
                else {
                    UIHelper.Dialogs.WizardDialog.Vars.CurrentSuggestions = {};
                    UIHelper.Dialogs.WizardDialog.Vars.CurrentSuggestions = recipes;
                }
                var protoLI = $("#suggestions li.proto");
                $.each(recipes, function(i, recipe) {
                    var newLI = protoLI.clone(true);
                    // IE6 clone() fix
                    if ($.browser.msie && parseInt($.browser.version) < 7)
                        newLI.innerHTML = protoLI.innerHTML;
                    $("input[name='recipeid']", newLI).val(recipe.Id);
                    $("img.recipe-image", newLI).attr("src", recipe.SmallImageUrl);
                    $("p.description", newLI).text(recipe.Name);
                    newLI.removeClass("proto");
                    suggestionUl.append(newLI);
                });
                //                $(".button.new-suggestions").bind("click", UIHelper.Dialogs.WizardDialog.NewSuggestions_Click);
            });
        }
    },

    // ----------------------------------------------------

    ShoppinglistDialog: {
        Init: function() {
            UIHelper.Dialogs.ShoppinglistDialog.InitEvents();
            UIHelper.Dialogs.ShoppinglistDialog.FixPngIcons();
        },

        InitData: function() {
            UIHelper.Dialogs.ShoppinglistDialog.ClearDialog();
            UIHelper.Dialogs.ShoppinglistDialog.PopulateDays();
            UIHelper.Dialogs.ShoppinglistDialog.GetPersistedShoppinglist();
        },

        InitEvents: function() {
            // Items back-and-forth events
            $(".week .add-item").click(function(event) {
                event.preventDefault();
                var ingredient = $(this).next("span").text();
                UIHelper.Dialogs.ShoppinglistDialog.AddItem(ingredient);
            });
            $(".shoppinglist .new-item a").click(function(event) {
                event.preventDefault();
                var item = $(this).next("input").val();
                $(this).next("input").val($(this).next("input").attr("title"));
                UIHelper.Dialogs.ShoppinglistDialog.AddItem(item);
            });
            $(".shoppinglist .new-item input").keyup(function(event) {
                event.preventDefault();
                if (event.keyCode == 13) {
                    var item = $(this).val();
                    $(this).blur();
                    $(this).val($(this).attr("title"));
                    UIHelper.Dialogs.ShoppinglistDialog.AddItem(item);
                }
            });
            $(".shoppinglist a.remove-item").live("click", function(event) {
                event.preventDefault();
                $(this).parent("li").remove();
            });
            $(".shoppinglist .new-item input, .shoppinglist textarea").click(function(event) {
                event.preventDefault();
                if ($(this).val() == $(this).attr("title"))
                    $(this).val("");
            });
            $(".shoppinglist .new-item input, .shoppinglist textarea").blur(function() {
                if ($(this).val() == "")
                    $(this).val($(this).attr("title"));
            });

            // "Send"
            $("#send-shoppinglist").click(function(event) {
                event.preventDefault();
                // Close shopping list dialog?
                //$("#shoppinglist-dialog .cancel").click();
                // Persist shopping list and open Send dialog
                UIHelper.Dialogs.ShoppinglistDialog.PersistShoppinglist();
                $("#send-dialog").dialog("open");
            });
            // "Udskriv"
            $("#print-shoppinglist").click(function(event) {
                event.preventDefault();
                // Close shopping list dialog?
                //$("#shoppinglist-dialog .cancel").click();
                // Persist shopping list and open Print dialog
                UIHelper.Dialogs.ShoppinglistDialog.PersistShoppinglist();
                $("#print-dialog").dialog("open");
            });
        },

        ClearDialog: function() {
            // Clear days
            var weekContainer = $(".list .week"); /// <reference path="../SuperBrugsen.Web.csproj.vspscc" />

            $("li:not(.proto)", weekContainer).remove();
            // Clear shopping list
            var itemUL = $(".shopping-items");
            $("li:not(.proto):not(.new-item):not(.comments)", itemUL).remove();
        },

        // Adds an item to the shopping list
        AddItem: function(item) {
            var test = "";
            var itemUL = $(".shopping-items");
            var protoLI = $(".proto", itemUL);
            var target = $(".new-item", itemUL);
            var newLI = protoLI.clone();
            newLI.removeClass("proto");
            $("input", newLI).val(item);
            // Argh! clone() bug in IE6
            if ($.browser.msie && parseInt($.browser.version) < 7)
                newLI.innerHTML = protoLI.innerHTML;
            //            if (newLI == target)
            //                alert(newLI + " og "+target);

            newLI.insertAfter(target);
            newLI.show();
        },

        // Persist the changes made to the shopping list
        PersistShoppinglist: function() {
            var message = $(".shopping-items textarea").val() != $(".shopping-items textarea").attr("title") ? $(".shopping-items textarea").val() : "";
            var items = new Array();
            var itemLIs = $(".shopping-items li:not(.new-item):not(.proto) input");
            itemLIs.each(function(i) {
                var itemLine = $(this).val();
                items.push(itemLine);
            });
            var shoppingList = {
                ShoppingListLines: items,
                Message: message
            };
            PersistenceHelper.ShoppingList.Set(shoppingList);
        },

        // Populates the left side of the dialog with the current weekplan
        PopulateDays: function() {
            var weekContainer = $(".list .week");
            var protoLI = $("li:first", weekContainer);
            $("#shoppinglist-dialog img.loading").show();
            DataHelper.GetCurrentWeekPlan(function(weekplan) {
                $("#shoppinglist-dialog img.loading-image").hide();
                $.each(weekplan, function(i, recipe) {
                    var newLI = protoLI.clone(true);
                    $("h5", newLI).text(DataHelper.DaysOfWeek[i + 1]);
                    newLI.removeClass("proto");
                    newLI.show();
                    if (recipe != null && recipe.Id != 0) {
                        // IE6 clone() fix
                        if ($.browser.msie && parseInt($.browser.version) < 7)
                            newLI.innerHTML = protoLI.innerHTML;
                        $(".description .recipe-title", newLI).text(recipe.Name);
                        $("img.recipe-image", newLI).show();
                        $("img.recipe-image", newLI).attr("src", recipe.SmallImageUrl);
                        $("img.recipe-image", newLI).attr("alt", recipe.Name);

                        UIHelper.Dialogs.ShoppinglistDialog.PopulateIngredients(newLI, recipe);
                    }
                    else {
                        $("img.recipe-image", newLI).hide();
                        $(".description", newLI).text("Du har ikke valgt en ret til denne dag.");
                    }
                    weekContainer.append(newLI);
                });
            });
        },

        // Populates the specified day with the ingredients of the recipe
        PopulateIngredients: function(dayLI, recipe) {
            if (recipe != null) {
                var ingredientContainer = $("ul.ingredients", dayLI);
                var protoLI = $("li.proto", ingredientContainer);

                $.each(recipe.SubRecipes, function(i, subRecipe) {
                    if (subRecipe.Ingredients != null) {
                        $.each(subRecipe.Ingredients, function(i, ingredient) {
                            if (ingredient.substring(0, 2) == "0 ")
                                ingredient = ingredient.replace(ingredient.charAt(0), "");
                            var newLI = protoLI.clone(true);
                            // IE6 clone() fix
                            if ($.browser.msie && parseInt($.browser.version) < 7)
                                newLI.innerHTML = protoLI.innerHTML;
                            $("span", newLI).text(ingredient);
                            ingredientContainer.append(newLI);
                            newLI.removeClass("proto");
                        });
                    }
                });
            }
        },

        // Populates the dialog with the persisted shopping list
        GetPersistedShoppinglist: function() {
            var shoppingList = PersistenceHelper.ShoppingList.Get();
            if (shoppingList.Message != "")
                $(".shoppinglist textarea").val(shoppingList.Message);
            var shoppingListLines = shoppingList.ShoppingListLines.reverse();
            $.each(shoppingListLines, function(i, item) {
                UIHelper.Dialogs.ShoppinglistDialog.AddItem(item);
            });
        },

        // Replaces icon-add.png and icon-remove.png with gif images for IE6
        FixPngIcons: function() {
            if ($.browser.msie && parseInt($.browser.version) < 7) {
                $("#shoppinglist-dialog img[src$='icon-add.png'], #shoppinglist-dialog img[src$='icon-remove.png']").each(function() {
                    var src = $(this).attr("src");
                    var newSrc = src.replace("png", "gif");
                    $(this).attr("src", newSrc);
                });
            }
        }

    },

    // --------------------------------------------------------

    PrintDialog: {
        InitEvents: function() {
            $("#print-dialog .button.submit").click(function() {
                if ($("#print-dialog input[name='print-what']:checked").val() != undefined) {
                    var url;
                    //console.log($("#print-dialog input[name='print-what']:checked").val());
                    var host = window.location.toString().split("/")[2];
                    if ($("#print-dialog input[name='print-what']:checked").val() == "plan") {
                        url = DataHelper.MakeLink("PrintShoppinglist", {});
                        host += "/mad+og+opskrifter/indkoebsseddel/udskrift"; // + url;
                    }
                    else {
                        url = DataHelper.MakeLink("PrintRecipe", {});
                        host += "/mad+og+opskrifter/opskrifter/udskrift"; // + url;
                    }
                    url = "http://" + host;
                    var options = "height=500, width=650, scrollbars=yes, menubar=yes";
                    window.open(url, "print", options);
                    $("#print-dialog").dialog("close");
                }
            });
        }
    },

    // --------------------------------------------------------

    SendDialog: {
        InitEvents: function() {
            // Dialog close button
            $("#send-dialog .close").click(function() {
                UIHelper.Dialogs.SendDialog.Close_Click();
            });
            // Send dialog toggle type
            $("#send-dialog .message-type input[name='type']").change(function() {
                $("#send-email").show();
                //                $("#send-email").toggle();
                //                $("#send-sms").toggle();

            });
            // Fix change event for IE
            $("#send-dialog .message-type input[name='type']").click(function() {
                if ($.browser.msie)
                    this.blur();
            });
            // Send dialog textarea
            $("#send-dialog textarea").focus(function() {
                $(this).text("");
            });
            $("#send-dialog textarea").blur(function() {
                if ($(this).text() == "") {
                    $(this).text($(this).attr("title"));
                }
            });
            // Send dialog "Send" button
            $("#send-button").click(function() {
                if (UIHelper.Dialogs.SendDialog.ValidateForm())
                    UIHelper.Dialogs.SendDialog.DoSend();
            });
            // Check fields on blur
            $("#send-dialog .input-text").blur(function() {
                UIHelper.Dialogs.SendDialog.ValidateSingleField($(this));
            });
            $("#send-dialog #email-recipients, #send-dialog #email-fromaddress").blur(function() {
                UIHelper.Dialogs.SendDialog.ValidateEmailField($(this));
            });
            $("#send-dialog #sms-recipients").blur(function() {
                UIHelper.Dialogs.SendDialog.ValidatePhoneField($(this));
            });
        },

        ValidateForm: function() {
            var isValid = false;
            var validateField = UIHelper.Dialogs.SendDialog.ValidateSingleField;
            switch ($("#send-dialog .message-type input[name='type']:checked").val()) {
                case "SMS":
                    isValid = UIHelper.Dialogs.SendDialog.ValidatePhoneField($("#send-dialog #sms-recipients"));
                    isValid = validateField($("#send-dialog #sms-fromname")) && isValid;
                    break;
                default:
                    isValid = UIHelper.Dialogs.SendDialog.ValidateEmailField($("#send-dialog #email-recipients"));
                    isValid = UIHelper.Dialogs.SendDialog.ValidateEmailField($("#send-dialog #email-fromaddress")) && isValid;
                    isValid = validateField($("#send-dialog #email-fromname")) && isValid;
                    break;
            }
            if ($("#content-shoppinglist").attr('checked')) {
                var start = document.cookie.indexOf("Shoppinglist=");
                var end = document.cookie.indexOf(";", start); // First ; after start
                if (end == -1) {
                    end = document.cookie.length; // failed indexOf = -1
                }
                tempcookie = document.cookie.substring(start, end);
                var cookie = unescape(tempcookie).replace("Shoppinglist=", "");
                if (cookie.indexOf('ShoppingListLines":[]') !== -1) {
                    $('#info-text').html('<p>Din indkøbsseddel er tom. Tilføj ingredienser til indkøbssedlen </p>');
                    isValid = false && isValid;
                }
            }
            return isValid;
        },

        ValidateSingleField: function(theField) {
            if ($.trim(theField.val()) == "") {
                theField.addClass("invalid-field");
                return false;
            }
            else {
                theField.removeClass("invalid-field");
                return true;
            }
        },

        ValidatePhoneField: function(theField) {
            var isValid = true;
            var val = theField.val();
            var phoneNos = val.split(",");
            for (var i = 0; i < phoneNos.length; i++) {
                var phoneNo = $.trim(phoneNos[i]);
                isValid = UIHelper.Dialogs.SendDialog.ValidatePhoneNo(phoneNo) && isValid;
            }
            if (isValid) {
                theField.removeClass("invalid-field");
                return true;
            }
            else {
                theField.addClass("invalid-field");
                return false;
            }
            return true;
        },

        ValidateEmailField: function(theField) {
            var isValid = true;
            var val = theField.val();
            var emails = val.split(",");
            for (var i = 0; i < emails.length; i++) {
                var email = $.trim(emails[i]);
                isValid = UIHelper.Dialogs.SendDialog.ValidateEmail(email) && isValid;
            }
            if (isValid) {
                theField.removeClass("invalid-field");
                return true;
            }
            else {
                theField.addClass("invalid-field");
                return false;
            }
            return true;
        },

        ValidatePhoneNo: function(phoneNo) {
            var regEx = /\b[0-9]{8}\b/;
            return regEx.test(phoneNo);
        },

        ValidateEmail: function(email) {
            var regEx = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
            return regEx.test(email);
        },

        DoSend: function() {
            $('#info-text').html("");
            // Set variables for request
            var requestData;
            var webMethod;
            var recipients;
            var senderName;
            var shoppingList;

            switch ($("#send-dialog .message-type input[name='type']:checked").val()) {
                case "SMS":
                    webMethod = "SendSMS";
                    var recipientString = $("#send-dialog #sms-recipients").val();
                    recipients = recipientString.split(",");
                    senderName = $("#send-dialog #sms-fromname").val();
                    shoppingList = JSON.stringify(PersistenceHelper.ShoppingList.Get());

                    requestData = {
                        Recipients: JSON.stringify(recipients),
                        SenderName: JSON.stringify(senderName),
                        ShoppingList: shoppingList
                    };
                    break;
                default:
                    webMethod = "SendEmail";
                    recipientString = $("#send-dialog #email-recipients").val();
                    senderName = $("#send-dialog #email-fromname").val();
                    var senderEmail = $("#send-dialog #email-fromaddress").val();
                    var message;
                    if ($("#send-dialog #content-shoppinglist").attr("checked")) {
                        shoppingList = PersistenceHelper.ShoppingList.Get();
                        if ($("#email-message").val() != $("#email-message").attr("title"))
                            message = $("#email-message").val();
                    }

                    var weekplan;
                    if ($("#send-dialog #content-weekplan").attr("checked"))
                        weekplan = PersistenceHelper.WeekPlan.GetPlan();

                    var recipients = recipientString.split(",");

                    requestData = {
                        Recipients: (recipients != undefined) ? JSON.stringify(recipients) : null,
                        SenderName: (senderName != undefined) ? JSON.stringify(senderName) : null,
                        SenderEmail: (senderEmail != undefined) ? JSON.stringify(senderEmail) : null,
                        ShoppingList: (shoppingList != undefined) ? JSON.stringify(shoppingList) : null,
                        Subject: null,
                        WeekPlan: (weekplan != undefined) ? JSON.stringify(weekplan) : null,
                        Message: (message != undefined) ? JSON.stringify(message) : null
                    };
                    break;
            }

            //console.log(requestData);

            // Make request
            JSONHelper.MakeRequest(webMethod, requestData, function(responseData) {
                // Hide form, show reply
                $("#confirm").show();
                $(".message-type").hide();
                $("#send-sms").hide();
                $("#send-email").hide();
                $("#send-button span").text("Luk");
                $("#send-button").attr("title", "Luk");
                $("#send-button").unbind("click");
                $("#send-button").bind("click", function() {
                    UIHelper.Dialogs.SendDialog.Close_Click(this);
                });
            });
        },

        Send_Click: function() {
            $(".message-type").hide();
            $("#send-sms").hide();
            $("#send-email").hide();
            $("#confirm").show();
            $("#send-button span").text("Luk");
            $("#send-button").attr("title", "Luk");
            $("#send-button").unbind("click");
            $("#send-button").bind("click", function() {
                EventHelper.Dialogs.SendDialog.Close_Click();
            });
        },

        Close_Click: function() {
            $(".message-type").show();
            $("#send-dialog .message-type input#type-sms").attr("checked", true);
            //            $("#send-sms").show();
            //            $("#send-email").hide();
            $("#send-email").show();
            $("#confirm").hide();
            $("#send-button").attr("title", "Send");
            $("#send-button span").text("Send");
            $("#send-button").unbind("click");
            $("#send-button").bind("click", function() {
                UIHelper.Dialogs.SendDialog.Send_Click();
            });
            $("#send-dialog").dialog("close");
            UIHelper.Dialogs.Init();
        }
    },

    // --------------------------------------------------------

    SearchDialog: {
        InitEvents: function() {
            // "Search" input field
            $("#search-dialog input.search-field").focus(function() {
                $(this).val("");
            });
            $("#search-dialog input.search-field").blur(function() {
                if ($(this).val() == "") {
                    $(this).val($(this).attr("title"));
                }
            });
            // "Search" button
            $("#do-search").click(function(event) {
                event.preventDefault();
                UIHelper.Dialogs.SearchDialog.Search_Click(this);
            });
            // Form action
            var theForm = $("#search-dialog form");
            theForm.attr("action", DataHelper.MakeLink("SearchView", {}));
        },

        Search_Click: function(theButton) {
            var theForm = $(theButton).closest("form");
            theForm.submit();
        }
    }
};

jQuery(function($) {
    UIHelper.Dialogs.Init();
});