﻿var AtmsOnline = {};

AtmsOnline.addToCalendar = function(calendar, url) {
    if (calendar == 'outlook' || calendar == 'ical')
        document.location.href = url;
    else
        window.open(url, 'calendar', 'toolbar=yes, menubar=yes, location=yes, status=yes, scrollbars=yes,resizable=yes, width=800, height=600, left=0, top=0');
};

// Function that will automatically select the first non hidden input field
// on the page.  If there is an error on the page, that control will be selected first
AtmsOnline.focusFirstField = function() {
    var errorFound;

    $('.ErrorInput:first').each(function(i) {
        $(this)[this.tagName == 'SELECT' ? 'focus' : 'select']();
        try { $(window).scrollTo(this, 0, {offset:-75} ); } catch (error) { /*gulp*/ }
        errorFound = true;
    });

    if (!errorFound) {
        $('input:not(:hidden):first, select:first').filter(function() { return !($(this).hasClass('NoFocus')); }).each(function(i) {
            if (!i) $(this).focus();
        })
    }
};

AtmsOnline.AddOnSelector = function(checkbox, btn, container, undo) {
    $(checkbox).click(function() {
        $(container).slideToggle(100, function() { $(undo).show(); });
    }).each(function() { if (this.checked) { $(container).hide(); $(undo).show(); } });

    $(btn).click(function() {
        $(checkbox).click(); return false;});

    $(undo).click(function(e) {
        $(e.target).hide();
        $(checkbox).attr('checked', false);
        $(container).slideToggle(100);
        return false;
    });
};


AtmsOnline.DateFilter = function(from, until) {
    $(from).datepicker(AtmsOnline.DateFilter.defaultOptions).datepicker('option', 'onSelect',
        function() { AtmsOnline.DateFilter.ensureFromIsBeforUntil(from, until, true);
                     AtmsOnline.DateFilter.search(from, until);});
    $(until).datepicker(AtmsOnline.DateFilter.defaultOptions).datepicker('option', 'onSelect',
        function() {
            AtmsOnline.DateFilter.ensureFromIsBeforUntil(from, until, false);
            AtmsOnline.DateFilter.search(from, until);
        });
};

AtmsOnline.DateFilter.defaultOptions = {
    dateFormat: 'mm/dd/yy',
    changeMonth: true,
    changeYear: true,
    maxDate: '+2y',
    minDate: 0,
    showButtonPanel: true,
    showOtherMonths: true
};

AtmsOnline.DateFilter.ensureFromIsBeforUntil = function(from, until, fChange) {
    var f = $(from).datepicker('getDate');
    var u = $(until).datepicker('getDate');

    if(f > u && fChange)
        $(until).datepicker('setDate', f);
    else if (f > u && !fChange)
        $(from).datepicker('setDate', u);
};

AtmsOnline.DateFilter.search = function(from, until) {
    window.location = window.location.pathname + $.query.set('from', $(from).val()).set('until', $(until).val()).toString();
};

AtmsOnline.Forms = {
    loadProv: function(dest, country, optional, labelClass, inputClass) {
        var url = 'atms/uc/services/ProvinceSelectionGenerator.aspx?country=' + escape(country);
        url += optional ? '&optional=1' : '';
        url += labelClass ? '&labelclass=' + labelClass : '';
        url += inputClass ? '&inputclass=' + inputClass : '';

        var prov = $('input:text,select', dest).val();

        $(dest).load(url, null, function() {
            AtmsOnline.Forms.highlite($('input:text,select', this).val(prov));
        });
    },

    highlite: function(el) {
        // remove all fields that have a parent marked with no highlite class
        $(el).filter(function() { return !($(this).parents('fieldset:first').hasClass('NoHightlite')); })
             .focus(function() { $(this).parents('fieldset:first').addClass('Selected'); })
             .select(function() { $(this).parents('fieldset:first').addClass('Selected'); })
             .blur(function() { $(this).parents('fieldset:first').removeClass('Selected'); });
    },

    // Sets Hint Text In A Field When It Is Blank
    hint: function(el, txt) {
        $(el).each(function() {

            $(this).focus(function() {
                // Add do the select so the cursor appears in IE7/8   
                if ($(this).val() == txt) $(this).val('').removeClass('FillerValue').select();
            }).blur(function() {
                if (!($(this).val())) $(this).val(txt).addClass('FillerValue');
            });
            
            $(this.form).submit(function() {
                if ($(el).val() == txt) $(el).val('');
            });

            if (!($(this).val())) $(this).val(txt).addClass('FillerValue');
        });
    }
};

AtmsOnline.PriceSelector = function(itemMax, pMax, seMax, ffMax, ffSeMax) {
    this.itemMax = itemMax || 10;
    this.pMax = pMax || this.itemMax;
    this.seMax = seMax || this.itemMax;
    this.ffMax = ffMax || this.itemMax;
    this.ffSeMax = ffSeMax || this.itemMax;
    this.prices = new Array();
};

AtmsOnline.PriceSelector.prototype.adjustSelects = function() {
    var items = this.getNumberOfItems();
    var pItems = this.getNumberOfItems(function(p) { return p.isP; });
    var seItems = this.getNumberOfItems(function(p) { return p.isSE && !p.isFF; });
    var ffItems = this.getNumberOfItems(function(p) { return !p.isSE && p.isFF; });
    var ffSeItems = this.getNumberOfItems(function(p) { return p.isSE && p.isFF; });

    for (var i = 0; i < this.prices.length; ++i) {
        var p = this.prices[i];

        var el = $(p.el).get(0);
        var val = parseInt(el.value) * p.qtyToReceive;

        // calculate the newQty
        var qty = this.itemMax - items + 1 + val;

        if (p.qtyToReceive && p.qtyToReceive > 1)
            qty = Math.min(qty > p.qtyToReceive ? Math.floor(qty / p.qtyToReceive) + 1 : 1, qty);

        // adjust for passes
        qty = p.isP ? Math.min(this.pMax - pItems + 1 + val, qty) : qty;

        // adjust if non-family and friend special event
        qty = p.isSE && !p.isFF ? Math.min(this.seMax - seItems + 1 + val, qty) : qty;

        // adjust if family-friend price
        qty = !p.isSE && p.isFF ? Math.min(this.ffMax - ffItems + 1 + val, qty) : qty;

        // adjust if family-friend special event price
        qty = p.isSE && p.isFF ? Math.min(this.ffSeMax - ffSeItems + 1 + val, qty) : qty;

        // ensure we don't go over the max for the price
        qty = p.maxQty ? Math.min(p.maxQty + 1, qty) : qty;

        // ensure we don't go under the min
        qty = p.minQty ? (p.minQty > qty ? 0 : qty) : qty;

        for (var j = el.options.length; j < qty - (p.minQty || 0); ++j) {
            el.options.add(this.createOption(j), j);
        }

        while (qty < el.options.length)
            el.remove(el.options.length - 1);
    }
};

AtmsOnline.PriceSelector.prototype.createOption = function(qty) {
    var o = document.createElement('OPTION');
    o.text = o.value = qty;
    return o;
};

AtmsOnline.PriceSelector.prototype.getNumberOfItems = function(compare) {
    var count = 0;

    for (var i = 0; i < this.prices.length; ++i) {
        if (!compare || compare(this.prices[i])) {
            count += this.prices[i].qtyToReceive * parseInt($(this.prices[i].el).val() || '0');
        }
    }

    return count;
};

AtmsOnline.PriceSelector.prototype.register = function(elId, isGroup, isP, isSE, isFF, minQty, maxQty, qtyToReceive) {
    elId = '#' + elId;
    if ($(elId).length != 0) {
        this.prices.push({ el: elId, isGroup: isGroup, isP: isP, isSE: isSE, isFF: isFF, minQty:minQty, maxQty: maxQty, qtyToReceive: qtyToReceive || 1 });
        $(elId).change(AtmsOnline.PriceSelector.onQtyChange).get(0).priceSelector = this;
        this.adjustSelects();
    }
};

AtmsOnline.PriceSelector.onQtyChange = function(event) {
    if (event.target && event.target.priceSelector)
        event.target.priceSelector.adjustSelects();
};

AtmsOnline.ShoppingCartTimer = function(el) {
    this.seconds = this.parseSeconds(el);
    this.el = el;
    var t = this;
    setInterval(function() { t.tick(); }, 1000);
};

AtmsOnline.ShoppingCartTimer.prototype.parseSeconds = function(el) {
    var val = $(el).text();
    if (!val) return 0;

    try {
        var arr = val.split(':');
        return (parseInt(arr[0]) * 60) + parseInt(arr[1]);
    } catch (Error) {
        return 0;
    }
};

AtmsOnline.ShoppingCartTimer.prototype.tick = function() {
    if (this.seconds == 0) return;

    --this.seconds;
    var str = Math.floor(this.seconds / 60) + ":";
    str += (this.seconds % 60 < 10 ? "0" : "");
    str += this.seconds % 60;

    $(this.el).html(str);
};

AtmsOnline.Observers = {
    init: function() {
        //AtmsOnline.Observers.roundCorners();

        new AtmsOnline.DateFilter('#dateFilterFrom', '#dateFilterUntil');
        $('#OrderCountDownTimer').each(function() { new AtmsOnline.ShoppingCartTimer(this); });
        $('.Box input, .Box select').each(function(i, el) { AtmsOnline.Forms.highlite(el); });
        $('.AddToOrderCheckBox').each(function() { AtmsOnline.Observers.initAddOnSelector(this); });

        AtmsOnline.focusFirstField();
    },

    initAddOnSelector: function(cbox) {
        var btn = $(cbox.parentNode).hide().siblings('.ButtonArea').show().children('input').get(0);
        new AtmsOnline.AddOnSelector(cbox, btn, cbox.parentNode.parentNode, $(cbox.parentNode.parentNode).siblings('.Remove'));
    },

    roundCorners: function() {
        $(".Box").corner("5px");
        $("fieldset span label").corner("5px");
        $("h2").corner("3px top");
        $("#BreadCrumbs").corner("3px top");
        $(".EventListing .Two .MapIt").corner("5px");
        $("ul.SwitchDate").corner("3px top");
        $("#WeekView p").corner("5px");
        $("fieldset").corner("5px");
        $("fieldset legend").corner("5px");
        $("fieldset span label").corner("5px");
        $("fieldset div.CheckBox label").corner("5px");
        $("fieldset div.RadioButton label").corner("5px");
        $(".ButtonArea input.PrimaryAction").corner("5px");
        $(".ButtonArea input.BackButton").corner("5px");
        $(".ButtonArea input.BackButton.nobg").corner("5px");
        $(".FullBorder").corner("5px");
        $(".LoginBox").corner("5px");
        $(".ButtonArea a").corner("5px left");
        $(".nobg").corner("5px");
        $("#RightSide ul li a").corner("5px right");
        $("#RightSide ul li.selected").corner("5px right");
        $("#RightSide ul li div#DateSelect input").corner("5px");
        $("#RightSide #Account").corner("5px");
        $("#RightSide #Account #LogInBox").corner("5px bottom");
        $("#RightSearchBar").corner("5px");
    }
};

$(document).ready(AtmsOnline.Observers.init);