﻿function ShowErrorMessage(message, type) {    
    var container =  $$('#FormMessageContainer').first();
    
    if (container == undefined)
        return;
        
    // Reset classes
    container.className = "FormMessageContainer";
    
    if (message == '') {        
        container.hide();
    } else {
        container.addClassName(type);
        $$('#FormMessageContainer tr td.Message').first().innerHTML = message;

        if (container.visible()) {
            container.show();
            container.setOpacity(1);
            Effect.Pulsate(container, { duration: 0.5, pulses: 1 });
        } else {
            Effect.Appear(container, { duration: 0.5 });
        }
        
        if (Position.page(container)[1] < 0) {
            window.scrollTo(0, Position.cumulativeOffset(container)[1] - 20);
        }
    }    
}

function ShowValidationErrors(errors) {    
    var validationSummary = "<ul>";

    $A(errors).each(function(error) {
        validationSummary += "<li>" + error + "</li>"
    });

    validationSummary += "</ul>";

    ShowErrorMessage(validationSummary, "Failure")
}

function SeperateWords(word) {
    return word.replace(/([a-z])([A-Z])/g, "$1 $2");
}

function LoadPromoCode() {
    var jar = new CookieJar({ expires: '' });
    var field = $("VPSDetailsDTO_PromotionalCode");

    var value = jar.get('promotion');

    if (value != null) {
        field.value = value;
        ValidateField(field, field.form);
    }
}

(function() {
    var params = window.location.search.toQueryParams();

    if (params.promotion !== undefined) {
        var jar = new CookieJar({ expires: '' });

        jar.put('promotion', params.promotion);
    }
})();

Control.AnimatedSlider = Class.create();
Object.extend(Object.extend(Control.AnimatedSlider.prototype, Control.Slider.prototype), {

    setValueAnimated: function(sliderValue, handleIdx) {

        handleIdx = handleIdx || this.activeHandleIdx || 0;

        sliderValue = this.getNearestValue(sliderValue);
        this.values[handleIdx] = sliderValue;
        this.value = this.values[0]; // assure backwards compat

        if ((typeof (this.moveAnim) != 'undefined') && (this.moveAnim.cancel)) {
            this.moveAnim.cancel();
        }

        var closeme = this;

        this.moveAnim = new Effect.Morph(this.handles[handleIdx], {
            style: this.isVertical() ? 'top' : 'left' + ": " + this.translateToPx(sliderValue),
            duration: 1.2,
            transition: Effect.Transitions.sinoidal,
            afterUpdate: function(effect) {
                var curr = effect.element.style.left;
                curr = curr.slice(0, curr.length - 2);
                var pos = closeme.translateToValue(curr);
                if (closeme.initialized && closeme.options.onAnimate) {
                    closeme.options.onAnimate(pos);
                }
            }
        });

        this.drawSpans();
        if (!this.dragging || !this.event) this.updateFinished();
    },

    startDrag: function(event) {
        if (Event.isLeftClick(event)) {
            if (!this.disabled) {
                this.active = true;

                var handle = Event.element(event);
                var pointer = [Event.pointerX(event), Event.pointerY(event)];
                var track = handle;
                if (track == this.track) {
                    var offsets = Position.cumulativeOffset(this.track);
                    this.event = event;
                    this.setValueAnimated(this.translateToValue((this.isVertical() ? pointer[1] - offsets[1] : pointer[0] - offsets[0]) - (this.handleLength / 2)));
                    var offsets = Position.cumulativeOffset(this.activeHandle);
                    this.offsetX = (pointer[0] - offsets[0]);
                    this.offsetY = (pointer[1] - offsets[1]);
                } else {
                    // find the handle (prevents issues with Safari)
                    while ((this.handles.indexOf(handle) == -1) && handle.parentNode)
                        handle = handle.parentNode;

                    if (this.handles.indexOf(handle) != -1) {
                        this.activeHandle = handle;
                        this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
                        this.updateStyles();

                        var offsets = Position.cumulativeOffset(this.activeHandle);
                        this.offsetX = (pointer[0] - offsets[0]);
                        this.offsetY = (pointer[1] - offsets[1]);
                    }
                }
            }
            Event.stop(event);
        }
    },

    draw: function(event) {
        var pointer = [Event.pointerX(event), Event.pointerY(event)];
        var offsets = Position.cumulativeOffset(this.track);

        if ((typeof (this.moveAnim) != 'undefined') && (this.moveAnim.cancel) && this.moveAnim.state != "finished") {
            this.moveAnim.cancel();

            var handle = Event.element(event);
            var pointer = [Event.pointerX(event), Event.pointerY(event)];
            var track = handle;
            var offsets = Position.cumulativeOffset(this.track);
            this.event = event;
            this.setValue(this.translateToValue((this.isVertical() ? pointer[1] - offsets[1] : pointer[0] - offsets[0]) - (this.handleLength / 2)));
            var offsets = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
        } else {
            pointer[0] -= this.offsetX + offsets[0];
            pointer[1] -= this.offsetY + offsets[1];
            this.event = event;
            this.setValue(this.translateToValue(this.isVertical() ? pointer[1] : pointer[0]));
        }
        if (this.initialized && this.options.onSlide)
            this.options.onSlide(this.values.length > 1 ? this.values : this.value, this);
    }


});

Control.Slider.prototype.scrollVerticalElement = function(value, element) {
    element.scrollTop = Math.round(value / this.maximum * (element.scrollHeight - element.offsetHeight));
}

Autocompleter.Combo = Class.create();
Object.extend(Object.extend(Autocompleter.Combo.prototype, Autocompleter.Local.prototype), {
    baseInitialize: function(element, update, options) {
        element = $(element)
        this.element = element;
        this.update = $(update);
        this.hasFocus = false;
        this.changed = false;
        this.active = false;
        this.index = 0;
        this.entryCount = 0;

        if (this.setOptions)
            this.setOptions(options);
        else
            this.options = options || {};

        this.options.paramName = this.options.paramName || this.element.name;
        this.options.tokens = this.options.tokens || [];
        this.options.frequency = this.options.frequency || 0.4;
        this.options.minChars = this.options.minChars || 1;
        this.options.onShow = this.options.onShow ||
      function(element, update) {
          if (!update.style.position || update.style.position == 'absolute') {
              update.style.position = 'absolute';
          }
          Effect.Appear(update, { duration: 0.15 });
      };
        this.options.onHide = this.options.onHide ||
      function(element, update) { new Effect.Fade(update, { duration: 0.15 }) };

        if (typeof (this.options.tokens) == 'string')
            this.options.tokens = new Array(this.options.tokens);

        this.observer = null;

        this.element.setAttribute('autocomplete', 'off');

        Element.hide(this.update);

        Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
        Event.observe(this.element, 'keypress', this.onKeyPress.bindAsEventListener(this));

        // Turn autocomplete back on when the user leaves the page, so that the
        // field's value will be remembered on Mozilla-based browsers.
        Event.observe(window, 'beforeunload', function() {
            element.setAttribute('autocomplete', 'on');
        });
    },
    markPrevious: function() {
        if (this.index > 0) this.index--
        else this.index = this.entryCount - 1;
        this.safeScrollIntoView(this.getEntry(this.index));
    },

    markNext: function() {
        if (this.index < this.entryCount - 1) this.index++
        else this.index = 0;
        this.safeScrollIntoView(this.getEntry(this.index));
    },
    onObserverEvent: function() {
        this.changed = false;
    },
    safeScrollIntoView: function(elem) {
        var ul = this.update.getElementsByTagName("UL")[0];

        var bottom = this.getEntry(this.index).offsetTop + this.getEntry(this.index).offsetHeight;
        var visbase = ul.scrollTop + ul.offsetHeight;

        if (visbase < bottom) {
            ul.scrollTop += bottom - visbase;
        }
        if (ul.scrollTop > this.getEntry(this.index).offsetTop) {
            ul.scrollTop = this.getEntry(this.index).offsetTop;
        }
        if (this.options.Slider && this.options.onScroll) this.options.onScroll(ul.scrollTop / (ul.scrollHeight - ul.offsetHeight));
    },
    getCurrentEntry: function() {
        var entry = this.options.array[this.index];
        if (typeof (entry) == "object") {
            return entry.value;
        } else {
            return entry;
        }
    },
    updateElement: function(selectedElement) {
        this.element.value = selectedElement;
        if (this.element.onblur) {
            this.element.onblur();
        }
        this.element.focus();

    }
});

var ComboBox = Class.create();

ComboBox.Autocompleter = Autocompleter.Combo;

ComboBox.Autocompleter.prototype.onBlur = function(event) {
    if (Element.getStyle(this.update, 'display') == 'none') { return; }
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;
}

ComboBox.prototype = {
    initialize: function(textBox, arrowElement, resultsElement, array, options) {

        this.textBox = $(textBox);
        this.arrow = $(arrowElement);
        this.results = $(resultsElement);
        this.array = array;

        this.resultsWidth = this.textBox.getWidth();

        this.results.style.display = 'none';

        this.events = {
            showChoices: this.showChoices.bindAsEventListener(this),
            hideChoices: this.hideChoices.bindAsEventListener(this),
            click: this.click.bindAsEventListener(this),
            keyDown: this.keyDown.bindAsEventListener(this)
        }

        this.autocompleter = new ComboBox.Autocompleter(this.textBox, this.results, this.array, Object.extend(options, {
            onShow: function(element, update) { if (!update.style.position || update.style.position == 'absolute') { update.style.position = 'absolute'; } update.show(); update.style.display = "block"; },
            onHide: function(element, update) { update.update(); update.hide(); },
            onScroll: this.onSliderScroll
        }));

        Event.observe(this.arrow, 'click', this.events.click);
        Event.observe(this.textBox, 'keydown', this.events.keyDown);
    },

    onSliderScroll: function(v) {
        if (this.Slider) { this.Slider.setValue(v); }
    },

    getAllChoices: function(width) {
        var choices = this.array.collect(function(choice) {
            var choicestring = ""
            if (typeof (choice) == "object") {
                choicestring = choice.name;
            } else {
                choicestring = choice;
            }
            return '<li>' + choicestring + '</li>';
        });
        var html = '<ul id="CBPanel" style="float:left;width:' + (width /* -15 */) + 'px;overflow:hidden;height:180px;">' + choices.join('') + '</ul>';
        if (this.array.length > 10) {
            html = html + '<div id="CBTrack"><div id="CBHandle"></div></div>';
        }
        this.autocompleter.updateChoices(html);

        if (this.array.length > 10) {
            var track = $("CBTrack");
            var handle = $("CBHandle");
            var panel = $("CBPanel");
            track.style.height = this.autocompleter.update.getHeight() + "px";
            handle.style.height = Math.max(panel.offsetHeight * (panel.offsetHeight / panel.scrollHeight), 15) + "px";
            slider1 = new Control.Slider('CBHandle', 'CBTrack', {
                axis: 'vertical',
                onSlide: function(v) { slider1.scrollVerticalElement(v, $('CBPanel')); },
                onChange: function(v) { slider1.scrollVerticalElement(v, $('CBPanel')); }
            });
            Event.observe(this.autocompleter.update, 'DOMMouseScroll', function(e) { wheel(e, function(delta) { slider1.setValueBy(-(delta / 10)); }) });
            Event.observe(this.autocompleter.update, 'mousewheel', function(e) { wheel(e, function(delta) { slider1.setValueBy(-(delta / 10)); }) });
            this.autocompleter.options.Slider = slider1;
        }
    },

    keyDown: function(e) {
        if (e.keyCode == Event.KEY_DOWN && this.choicesVisible()) {
            this.showChoices();
        }
    },

    // returns boolean indicating whether the choices are displayed
    choicesVisible: function() { return (Element.getStyle(this.autocompleter.update, 'display') == 'none'); },

    click: function() {
        if (this.choicesVisible()) {
            this.showChoices();
        } else {
            this.hideChoices();
        }
    },

    showChoices: function() {
        this.textBox.focus();
        this.autocompleter.changed = false;
        this.autocompleter.hasFocus = true;
        this.getAllChoices(this.textBox.getWidth());
    },

    hideChoices: function() {
        this.autocompleter.hide();
    },
    updateArray: function(newarray) {
        this.array = newarray;
        this.autocompleter.options.array = newarray;
    }
}

/** Event handler for mouse wheel event. */
function wheel(event, handle) {
    var delta = 0;
    if (!event) /* For IE. */
        event = window.event;
    if (event.wheelDelta) { /* IE/Opera. */
        delta = event.wheelDelta / 120;
        /** In Opera 9, delta differs in sign as compared to IE. */
        if (window.opera)
            delta = -delta;
    } else if (event.detail) { /** Mozilla case. */
        /** In Mozilla, sign of delta is different than in IE.
        * Also, delta is multiple of 3.
        */
        delta = -event.detail / 3;
    }

    /** If delta is nonzero, handle it.
    * Basically, delta is now positive if wheel was scrolled up,
    * and negative, if wheel was scrolled down.
    */
    if (delta)
        handle(delta);

    /** Prevent default actions caused by mouse wheel.
    * That might be ugly, but we handle scrolls somehow
    * anyway, so don't bother here..
    */
    if (event.preventDefault)
        event.preventDefault();

    event.returnValue = false;
}

var ComboBoxMap = {};
var ComboBoxDataSource = {};

function InitComboBox(textelement, arrow, results, values, options) {
    $(textelement).onfocus = null;
    $(arrow).onmouseover = null;
    if (ComboBoxDataSource[$(textelement).name]) {
        values = ComboBoxDataSource[$(textelement).name];
    }
    ComboBoxMap[$(textelement).name] = new ComboBox(textelement, arrow, results, values, options);
}

var FormTemplateMap = {};

function CreateFormTemplateInstance(template, fieldId, presetValue) {
    setTimeout(function() {
        var focusid = document.activeElement.id;

        var master = $(template);
        var counter = master.getAttribute("counter");
        var data = { 'Form]Index': "[" + counter + "]", 'Form_Index': "_" + counter };
        master.setAttribute("counter", new Number(counter) + 1);
        var src = FormTemplateMap[master.id];
        var view = new Template(src);
        var newrow = master.cloneNode(false);
        master.id = "";
        master.removeClassName("FormTemplate");
        master.parentNode.appendChild(newrow);
        newrow.update(src);
        master.update(view.evaluate(data));
        var newId;
        if (fieldId) {
            newId = (new Template(fieldId)).evaluate(data);
            focusid = (new Template(focusid)).evaluate(data);
            $(newId).value = presetValue;
            setTimeout("$('" + focusid + "').focus()", 1);

            ValidateField(newId, $(newId).up("form"));
        }

        FixTableRows(master.parentNode);
        return newId;
    }, 1);
}

function DeleteFormSegment(button) {
    var row = $(button).up(".FormRow");
    if (row) {
        var table = row.up("table");
        row.remove();  
              
        FixTableRows(table);
    }

}

function FixTableRows(table) {    
    var i = 0;

    table.getElementsBySelector("tr").each(function(row) {
        if (row.hasClassName("Header")) { return; }

        row.removeClassName("Row");
        row.removeClassName("AlternateRow");
        
        row.addClassName((i++ % 2 == 0) ? "Row" : "AlternateRow");
    });
}