﻿var VakantieWizard = function($) {
    var priv = {
        emailRegExp: /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,

        callBackUrl: Resource.GetText("path_prefix") + "/js/ajax/lastminutetop10.ashx", //the location where the AJAX handler is located;

        //the variables below are used to animate the resulting top 10 table
        animate: true,  //animate the resultlist or show immediately
        listBuildTime: 500, //the total time it takes to animate the result list
        currentListItem: 0,    //currently showing this item
        itemsToShow: new Array(),  //list of acco id's to show
        timeouts: new Array(), //an array of listBuildInterval objects
        listBuildInterval: null, //variable to store an interval object
        nrOfAdults: -1, //nr of selected adults

        emailSuccess: function(nrEmailsSend) {
            $('#divEmailSuccess').text(nrEmailsSend == 1 ? Resource.GetText("lastminute_top10_email_send") : Resource.GetText("lastminute_top10_emails_send"));

            $('#imgSendingMail').hide();
            $('#divEmailSuccess').show();
            $('.btn-versturen').show();
        }
    };

    return {
        refreshPage: function() {
            if (location.href.indexOf('lastminutetop10-splashpage.aspx') != -1) {
                location.href = resources.path_prefix + "/lastminutetop10.aspx";
            }
            else {
                location.href = location.href;
            }
        },

        checkOccupancy: function(_nrOfAdults) {
            priv.nrOfAdults = _nrOfAdults;

            if (priv.nrOfAdults == 0) {
                $('#occupancyError').show();
                return false;
            }
            else {
                $('#occupancyError').hide();
                return true;
            }
        },

        setAnswer: function(answerIndex, mode) {
            $('#question').hide();
            $('.resultsInnerTable').hide();
            $('#question-loader').show();
            $('#homeSplash').addClass('emptySplash');

            if (answerIndex == 'multiselect') {
                answerIndex = '';
                $("input[name=multiselect]").each(function(i) {
                    if ($(this).attr("checked") == true) {
                        answerIndex += answerIndex == '' ? $(this).val() : ';' + $(this).val();
                    }
                });

                if (answerIndex == '') {
                    //all options where selected -> ignore this question
                    answerIndex = -1;
                }
            }

            var timer = new Timer();
            timer.Start();
            $.ajax({
                type: "POST",
                url: priv.callBackUrl,
                data: "r=setanswer&answerIndex=" + answerIndex,
                cache: false,
                success: function(msg) { VakantieWizard.refreshPage(); }
            });
        },

        changeQuestion: function(direction) {
            $.ajax({
                type: "POST",
                url: priv.callBackUrl,
                data: "r=setquestion&direction=" + direction,
                cache: false,
                success: function(msg) {
                    VakantieWizard.refreshPage();
                }
            });
        },

        toggleMailForm: function(doShow) {
            if (doShow == false) {
                $('.mail-form').hide();
                $('#txtOtherAddresses').val('');
                $('#txtAddress').val('');
                $('#txtEmailContent').val('');
                $('.answer-form').show();
                $('#lnkToMailForm').removeClass('inactive');

            } else {
                $('#lastminute-mail-form').show();
                $('.answer-form').hide();
                $('.mail-form').show();
                $('#lnkToMailForm').addClass('inactive');

                $('#lastminute-mail-form').attr("src", Resource.GetText("path_prefix") + "/_search/lastminutetop10mailform.aspx?accos=" + $('#accos').val());

                // set focus to first textbox
                $('#txtAddress').focus();
            }
        },

        sendMail: function() {
            $('#divEmailSuccess').hide();

            var emails = new Array();
            var from = "";
            var valid = true;

            //get the emailadresses from the input fields, txtOtherAddresses can hold multiple addresses delimited by a ','
            emails = $('#txtOtherAddresses').val().split(',');

            //remove empty entries
            for (var i = 0; i < emails.length; i += 1) {
                if (emails[i] == "") {
                    emails.splice(i, 1);
                }
            }
            from = $('#txtAddress').val();
            emails[emails.length] = from;

            //trim whitespaces and validate email
            for (var j = 0; j < emails.length; j += 1) {
                emails[j] = emails[j].toString().replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");

                if (priv.emailRegExp.test(emails[j]) == false) {
                    valid = false;
                }
            }



            //check if emailaddresses are valid
            if (emails.length > 0 && valid) {
                //get the top 10 table HTML
                var $table = $('.resultsInnerTable');
                var txt = $table.html().replace(/\t|\n|\r\n/g, '');

                // Find and replace short texts with long texts
                $table.find('.accospan').each(function() {
                    var shortLink = $(this).text();
                    var longLink = $(this).attr('title');
                    txt = txt.replace(shortLink, longLink);
                });

                var text = encodeURIComponent($('#txtEmailContent').val());
                var toptenTable = encodeURIComponent(txt.replace(/&nbsp;/g, ""));

                $('.btn-versturen').hide();
                $('#imgSendingMail').show();

                //send request to server to send mail
                $.ajax({
                    type: "POST",
                    url: priv.callBackUrl,
                    /*data: "r=sendmail&from=" + from + "&emails=" + emails + "&table=" + toptenTable + "&emailText=" + text,*/
                    data: "r=sendmail&from=" + from + "&emails=" + emails + "&table=" + toptenTable + "&emailText=" + text,
                    cache: false,
                    success: function(nrEmailsSend) { priv.emailSuccess(nrEmailsSend); }
                });
            }
            else {
                alert(Resource.GetText('validation_missing_mail'));
            }
        },

        gotoAcco: function(url, index) {
            $.ajax({
                type: "POST",
                url: priv.callBackUrl,
                data: "r=gotoacco&url=" + url + "&index=" + (index),
                cache: false,
                success: function() { window.location = url; }
            });
        },

        showTopTen: function() {
            if (priv.animate == false) { priv.listBuildTime = 0; }

            var timePerItem = priv.listBuildTime / 10;
            $('.resultsInner .resultsInnerTable table tr').each(function() {
                // vary interval time for 50% per item
                var timeThisItem = Math.floor((Math.random() - 0.5) * timePerItem + timePerItem);
                var id = $(this).attr('id');

                priv.itemsToShow[priv.itemsToShow.length] = id;
                priv.timeouts[priv.timeouts.length] = timeThisItem;
            });

            priv.listBuildInterval = setInterval('VakantieWizard.showItems()', priv.timeouts[priv.currentListItem]);
        },

        showItems: function() {
            $('#' + priv.itemsToShow[priv.currentListItem]).show();
            $('#' + priv.itemsToShow[priv.currentListItem]).animate({ opacity: "1" }, priv.timeouts[priv.currentListItem]);

            if (priv.currentListItem == 9) {
                setTimeout(function() {
                    $('#question-loader').hide();
                }, priv.timeouts[priv.currentListItem]);

                setTimeout(function() {
                    $('#question').show();
                }, priv.timeouts[priv.currentListItem]);

                clearTimeout(priv.listBuildInterval);
            }
            else {
                priv.currentListItem = priv.currentListItem + 1;

                clearTimeout(priv.listBuildInterval);
                priv.listBuildInterval = setInterval('VakantieWizard.showItems()', priv.timeouts[priv.currentListItem]);
            }

        },

        OnReady: function() {

            //bind the elements of the occupancy selector to the related elements           
            if (typeof Occupancy != "undefined") {
                Occupancy.bindTravelerSelectors();
                $('#btnSaveTravelers').bind('click', function() {
                    Occupancy.lmtop10_saveTravelers();
                });

                //if no occupancy is set, use a default of 2 adults
                if ($.cookie(Resource.GetTextForCookie('cookie-prefix') + "occupancy") == null || $.cookie(Resource.GetTextForCookie('cookie-prefix') + "occupancy") == '') {
                    $('.adults #nr-adults #nr-adults-default').attr('selected', 'selected');
                    Occupancy.changeNrAdults();
                }
            }

            // Hide the travelers popup during the wizard.
            if (location.href.indexOf('lastminutetop10') != -1) {
                $('#travelersDiv').hide();
            }

            if (location.href.indexOf('lastminutetop10-splashpage.aspx') != -1) {
                $.ajax({
                    url: priv.callBackUrl,
                    cache: false,
                    data: "r=back",
                    success: function(msg) {
                        if (msg == "1") {
                            VakantieWizard.changeQuestion('prev');
                        }
                        else {
                            $('#whiteOverlay').hide();
                        }
                    }
                });
            }
            else {
                //css hover psuedo class doesn't work in IE6, use jquery to mimick it
                $('.resultsInnerTable tr').bind('mouseover', function() {
                    $(this).addClass('hover');
                });
                $('.resultsInnerTable tr').bind('mouseout', function() {
                    $(this).removeClass('hover');
                });
            }

            $('.top-accos ul li').bind('click', function() {
                location.href = $(this).find('a').attr('href');
            }).hover(function() {
                $(this).addClass('hover');
            },
                function() {
                    $(this).removeClass('hover');
                }
            );

            VakantieWizard.showTopTen();
        }
    };
} (jQuery);

$(function() {
   VakantieWizard.OnReady();

});


