(function ($) {

    var Config = {
        ClientURL: '/Plugins/comHome/Home.htm',
        ServerUtilityURL: "/Controller/Utility.ashx",
        ServerURL: '',
        StyleURL: '/Plugins/comHome/Home.css',
        Container: '',
        Plugins_Count: 4,
        Plugins_LoadedCount: 0,
        Plugins_LoadedError: false
    };

    $.fn.Home = function (options) {
        //Extending the configuration
        if (options) {
            Config = $.extend(Config, options);
        }
        Config.Container = $(this);
        Init();
    };

    $.fn.Home.GetConfig = function () {
        return Config;
    }


    $.fn.Home.Destroy = function () {
        // distruzione degli oggetti interni al plugin
        Config = {
            ClientURL: '/Plugins/comHome/Home.htm',
            ServerURL: '',
            StyleURL: '/Plugins/comHome/Home.css',
            Container: '',
            Plugins_Count: 4,
            Plugins_LoadedCount: 0,
            Plugins_LoadedError: false
        };
        //rimuovo la classe "hompage" per rendere visibile il background sulla sidebar
        $('#page').removeAttr('class');
    }

    //Add event listners
    //Initialize other plugins needed for the Home plugin
    function Init() {

        //Try to load the html code
        Config.Container.load(Config.ClientURL, function () {

            Config.Container = $(this);

            //Loggo su google Analytics
            $.fn.Utility.Analytics("PAGEVIEW", "/Default.htm#Home");

            //After loading the code I add the listner for the event 'ModuleLoaded' for each plugin from the home page. 

            //Quando sono in HP tramite css tolgo il background per la colonna di sinistra
            var found = $(this).find('#home');
            if (found.length != 0) {
                $('#page').attr('class', 'homepage')
            }

            Config.Container.find('#box_offerte_lista:first').bind('ModuleLoaded', function (event) {
                PluginLoaded(event);
            });

            Config.Container.find('#box_offerte_banners').bind('ModuleLoaded', function (event) {
                PluginLoaded(event);
            });

            Config.Container.find('#box_offerte_box').bind('ModuleLoaded', function (event) {
                PluginLoaded(event);
            });

            Config.Container.find('#box_ricerca').bind('ModuleLoaded', function (event) {
                PluginLoaded(event);
            });

            Config.Plugins_LoadedCount = 0;
            Config.Plugins_LoadedError = false;

            //Initialize each of the 3 plugins for the Home plugin.
            $(this).find('#box_offerte_lista').OfferteLista({ RoundCorners: true, idArea: 10, numMaxOfferte: 999, listaTitle: "Offerte Viaggi" });
            $(this).find('#box_offerte_banners').OfferteBanners({ RoundCorners: false, idArea: 8, numMaxOfferte: 4 });
            $(this).find('#box_offerte_box').OfferteBox({ RoundCorners: false, idArea: 9, numMaxOfferte: 999 });
            $(this).find('#box_ricerca').Ricerca({ RoundCorners: true });
            $(this).find('#contact_left').AreaClub();

            // email newsletter
            $("#contact_right #email").bind("click", function () {
                if ($(this).val() == "email") $(this).val("");
            });

            // email newsletter
            $("#contact_right #iscriviti img").bind("click", function () {
                InviaRichiestaRegistrazioneNL();
            });

            ShowMotoreED();

            //            var AgenziaB2B2C = $.request("AgenziaB2B2C");
            //            if (AgenziaB2B2C != "" && $.fn.Utility.IsAgenziaLoggata) {
            //                LogOut();
            //            }
        });
    }


    function InviaRichiestaRegistrazioneNL() {
        var parameters = {};
        parameters.action = "UpdNewsLetterUtenteB2C";
        parameters.emailUtente = $("#contact_right #email").val();
        $.ajax({
            async: false,
            cache: false,
            url: Config.ServerUtilityURL,
            data: parameters,
            success: function (returnData) {
//                if (returnData != "-1") {
//                    ShowMessage("Grazie per esserti iscritto", "Iscrizione avvenuta con successo, riceverai le nostre Newsletter con tutte le migliori proposte di viaggio.<br><br>Lo staff di Mia Vacanza srl <br>Via Boscovich, 14 <br>20124 Milano <br>E mail: miavacanza@miavacanza.it <br>www:miavacanza.it");
//                } else {
//                    ShowMessage("Errore Registrazione", "Si &egrave; verificato un errore nella registrazione. <br>Ti ricordiamo che per registrarsi alla NewsLetter e' necessario aver gia' effettuato almeno un acquisto e che non e' possibile registrarsi piu' di una volta con la stessa mail.");
//                }

                switch (returnData) {
                    case '0': //utente inserito
                    case '1': //utente già inserito, ma non iscritto
                    case '2': //utente già inserito, iscritto e poi cancellatosi dalla newsletter
                        ShowMessage("Grazie per esserti iscritto", "Iscrizione avvenuta con successo, riceverai le nostre Newsletter con tutte le migliori proposte di viaggio.<br><br>Lo staff di Mia Vacanza srl <br>Via Boscovich, 14 <br>20124 Milano <br>E mail: miavacanza@miavacanza.it <br>www:miavacanza.it");
                        break;
                    case '3': //utente già inserito e già iscritto
                        ShowMessage("Iscrizione gi&agrave; effettuata", "Utente gi&agrave; registrato alla Newsletter. Riceverai le nostre Newsletter con tutte le migliori proposte di viaggio.<br><br>Lo staff di Mia Vacanza srl <br>Via Boscovich, 14 <br>20124 Milano <br>E mail: miavacanza@miavacanza.it <br>www:miavacanza.it");
                        break;
                    default: //errore
                        ShowMessage("Errore Registrazione", "Si &egrave; verificato un errore nella registrazione.");
                        break;
                }
            }
        });
    }


    //Function is called whenever a plugin is loaded
    //I don't pass any parameters because the end user doesn't need to know any information on a certain plugin
    function PluginLoaded(event) {

        event.cancelBubble = true;
        if (event.stopPropagation) event.stopPropagation();

        //Increment the number of loaded plugins
        ++Config.Plugins_LoadedCount;

        //Test to see if all plugins were loaded  
        if (Config.Plugins_LoadedCount == Config.Plugins_Count) {
            //Trigger the event 'ComponentLoaded' for the Home plugin            
            $(Config.Container).trigger("ComponentLoaded");
            $.fn.Travelmind.SaveState("Home", Config);
        }
    }

    function ShowMessage(title, msg) {
        var msgBox = $("<div/>");
        $(Config.Container).append(msgBox);
        $(msgBox).html(msg).dialog({
            width: 500,
            title: title,
            modal: true,
            draggable: true,
            buttons: {
                "Chiudi": function () { $(this).dialog("close"); }
            },
            close: function () {
                $(this).dialog("destroy");
            }
        });
        $(msgBox).dialog('open');
    }



    function ShowMotoreED() {
        engineHTML = $("#EDengineHTML").html();
        $("#motoreED").html(engineHTML);
    }


    //    function LogOut() {
    //        var parameters = {};
    //        parameters.action = "LogOut";
    //        $.ajax({
    //            async: false,
    //            cache: false,
    //            url: Config.ServerURL,
    //            data: parameters,
    //            success: function (returnData) {
    //                if (returnData != "-1") {
    //                    $("#logged").fadeOut("fast", function () {
    //                        Config.Agenzia = {};
    //                        $("#txtUsername").val("");
    //                        $("#txtPassword").val("");
    //                        $("#not_logged").fadeIn("slow");
    //                        $(document).trigger("logout");
    //                    });
    //                } else {
    //                    ShowMessage("Errore", "Si è verificato un errore durante il logout, se il problema persiste contattare un amministratore");
    //                }
    //            }
    //        });
    //    }
})(jQuery);



