// JavaScript Document

function setUpFocusHilighting(tagid) {
    Event.observe(tagid, 'focus', function(event) {
        event.element().addClassName('focused')
    });
    Event.observe(tagid, 'blur', function(event) {
        event.element().removeClassName('focused')
    });
}

function setUpFoldableSection(question, fieldset) {
    if($(question).value != '1')
        $(fieldset).style.display = 'none';
    Event.observe(question, 'change', function() {
        if(this.value == '1')
            $(fieldset).style.display = 'block';
        else
            $(fieldset).style.display = 'none';
    });
}

/**
 * petw: this doesn't seem to do what the name suggests...?
 */
function isInViewPort(element) {
    x1 = document.viewport.getScrollOffsets().left;
    x2 = document.viewport.getWidth() + document.viewport.getScrollOffsets().left;
    y1 = document.viewport.getScrollOffsets().top;
    y2 = document.viewport.getHeight() + document.viewport.getScrollOffsets().top;
    px = element.cumulativeOffset().left;
    py = element.cumulativeOffset().top;
    if(px >= x1 && px <= x2 && py >= y1 && py <= y2)
        return true;
    else
        return false;
}

function initialize() {

    // Setup cleanup section.
    setUpFoldableSection('from_cleanup', 'reinigung');

    // Setup cleaner section.
    setUpFoldableSection('cleaner', 'raumpflegerin');

    // Setup storage section.
    setUpFoldableSection('storage', 'lagerung');

    // Setup survey section.
    setUpFoldableSection('survey', 'umfrage');

    // Copy dismantle value to assemble value if asseble value is not already set.
    Event.observe($('items_to_dismantle'), 'change', function() {
        if($('items_to_assemble').value == "")
            $('items_to_assemble').value = $('items_to_dismantle').value;
    });

    // Set focus on first form element when form scrolled in sight.
    Event.observe(window, 'scroll', function() {
        if(isInViewPort($('customer_first_name')) && !$('request').initialized) {
            $('request').focusFirstElement();
            $('request').initialized = true;
        }
    });

    // Setup Focus Hilighting for every form field.
    formfields = $('request').getElements();
    for(i = 0; i < formfields.length; i++)
        setUpFocusHilighting(formfields[i]);

    // Set focus on first form element.
    //$('request').focusFirstElement();

    makeDateField("up_relocation_date", {
        notBefore: Date.today(),
        notBeforeMsg: "<b>Dieses Datum liegt in der Vergangenheit.</b><br>Wir können Ihre Umsiedlung leider frühestens heute vornehmen."
    });
    makeDateField("up_decision_date");
    makeDateField("up_storage_from");
    makeDateField("up_cleaner_from");
    makeDateField("up_from_last_cleanup");

    makeRequired("customer_first_name", "Ihren Vornamen", true);
    autoCapitalize("customer_first_name");
    makeRequired("customer_last_name", "Ihren Nachnamen", true);
    autoCapitalize("customer_last_name");
	
    var telMsg = "<b>Bitte geben Sie eine Telefonnummer ein, unter der wir Sie bei Rückfragen erreichen können.</b>";
    makeRequired("customer_phone", telMsg)
    /*.add(Validate.Exclusion, {
        failureMessage: telMsg,
        within: [ "0041(0)" ]
    })*/;
    makeRequired("customer_ac", telMsg)
    makeRequired("customer_mail", "Ihre E-Mail Adresse", true).add(Validate.Email, {
        failureMessage: "<b>Bitte überprüfen Sie die E-Mail Adresse.</b><br/>Die eingegebene Adresse scheint nicht gültig zu sein."
    });
    setPrompt("up_personal_meeting", "TT.MM.JJJJ HH:MM");

    enableAutocompletion("from_street", "from_postal_code", "from_city", "from_number_of_rooms");
    enableAutocompletion("to_street", "to_postal_code", "to_city", "to_walking_distance");

    showOnlyWhen("from_floor", "from_elevator", isElevetorRelevant);
    showOnlyWhen("to_floor", "to_elevator", isElevetorRelevant);
	
	$('customer_phone').onfocus = function() { Form.Element.select(this); };
}

function isElevetorRelevant(src){
    return !src.value.empty() && src.value != "0";
}

function autoCapitalize(fieldId){
    Event.observe(fieldId, "blur", function(){
        var field = $(fieldId);
        field.value = capitalizeParts(capitalizeParts(field.value, " "), "-");
    });
}

function capitalizeParts(value, seperator){
    var parts = value.split(seperator);
    var result = "";
    
    parts.each(function(part){
        result += part.substring(0,1).toUpperCase() + part.substring(1) +seperator;
    });
    return result.substring(0, result.length-1);
}

function showOnlyWhen(src, dest, shouldShowDest){
    Event.observe(src, "change", showOrHide);
    
    showOrHide();

    function showOrHide(){
        if(shouldShowDest($(src))){
            $("label_"+dest).show();
            $(dest).show();
        }else{
            $("label_"+dest).hide();
            $(dest).hide();
        }
    }
}

function makeDateField(fieldId, options){
    /*var field = $(fieldId);

    field.addClassName("w8em");
    field.addClassName("format-d-m-y");
    field.addClassName("divider-dot");
    field.addClassName("no-transparency");*/
    
    setPrompt(fieldId, "TT.MM.JJ");

    var dateValidation =  new MyValidation(fieldId, {})
    dateValidation.add(Validate.Date.bind(dateValidation), options);

    if(!Object.isUndefined(options) && !Object.isUndefined(options.notBefore)){
        var picker = datePickerController.datePickers[fieldId];
        if(Object.isUndefined(picker)){
            //fix IE. create picker
            datePickerController.create();
            picker = datePickerController.datePickers[fieldId];
        }
        picker.setRangeLow(options.notBefore.toString("yyyyMMdd"));
    }
}

function setPrompt(fieldId, prompt){
    var field = $(fieldId);
    field.prompt = prompt;
    field.value = prompt;

    field.addClassName("prompt");
    Event.observe(field, "focus", function(){
        if(field.value == field.prompt){
            this.value = "";
            this.removeClassName("prompt");
        }
    });
    Event.observe(field, "blur", function(){
        if(this.value.toString().empty()){
            this.value = this.prompt;
            this.addClassName("prompt");
        }else{
            this.removeClassName("prompt");
        }
    });
}

function scrollIntoViewIfNecessary(element, alignWithTop){
    if(!isInVerticalView(element, alignWithTop)){
        element.scrollIntoView(alignWithTop);
    }
}

function isInVerticalView(element, checkTop) {
    var top = document.viewport.getScrollOffsets().top;
    var bottom = top + (Prototype.Browser.IE ? document.documentElement.clientHeight : window.innerHeight);
    var elementY = element.cumulativeOffset().top;
    if(!checkTop){ //check bottom
        elementY += element.offsetHeight;
    }

    //status = "top: "+top+" bottom: "+bottom+" Y: "+elementY+" top: "+checkTop;
    if(checkTop)
        return elementY > top;
    else
        return elementY < bottom;
}

BetterAutocompleter = Class.create(Ajax.Autocompleter, {
    initialize: function($super, element, update, url, options) {
        $super(element, update, url, options);
    },

    //petw: fixed stupid scrolling behavior: scroll only if necessary
    markPrevious: function() {
        if(this.index > 0) this.index--;
        else this.index = this.entryCount-1;

        scrollIntoViewIfNecessary(this.getEntry(this.index), true);
    },

    markNext: function() {
        if(this.index < this.entryCount-1) this.index++;
        else this.index = 0;

        scrollIntoViewIfNecessary(this.getEntry(this.index), false);
    }
});
   

function enableAutocompletion(street, postalCode, city, nextFocus){
    var autocompletePopupName = "autocomplete_choices";
    var servicePrefix = "fileadmin/ajax/";

    new BetterAutocompleter(postalCode, autocompletePopupName, servicePrefix+"postalcodes_cities.php",
    {
        updateElement: function (selectedElement){
            selectedPLZ = selectedElement.innerHTML.toString().slice(0, 4);
            selectedOrt = selectedElement.innerHTML.toString().slice(5);

            $(postalCode).value = selectedPLZ;
            $(city).value = selectedOrt;

            if(nextFocus != null){
                $(nextFocus).focus();
            }
        },
        
        onShow: function (element, update){
            var cityElement = $(city);

            /*
             * petw:
             * Copied and modified from scriptaculous controls.js for setting custom popup size.
             */
            if(!update.style.position || update.style.position=='absolute') {
                update.style.position = 'absolute';
                Element.clonePosition(update, element, {
                    setHeight: false,
                    setWidth: false,
                    offsetTop: element.offsetHeight
                });
                update.style.width = ((cityElement.offsetLeft + Element.getWidth(cityElement)) - element.offsetLeft)+"px";
            }
            Effect.Appear(update,{
                duration:0.15
            });
        },
        
        paramName: "postalCode"
    });

    new BetterAutocompleter(street, autocompletePopupName, servicePrefix+"streets.php", {
        updateElement: function (selectedElement){
            selectedStreet = selectedElement.innerHTML.toString();

            $(street).value = selectedStreet + " ";
        },
        
        paramName: "street"
    });

    new BetterAutocompleter(city, autocompletePopupName, servicePrefix+"cities.php", {
        paramName: "city"
    });
}

Event.observe(window, 'load', function() {
    initialize();
});
