/**
 * handle two select boxes that depend on each other
 * and load new data via ajax
 * @param {Object} object
 */
var CoupledSelection = new Class(
{
    initialize: function(object)
    {
        this.selectionTargets = object.selectionTargets;
        this.selectionContainer = object.selectionContainer;
        this.secondSelection = object.secondSelection;
        this.currentSelectionTargetPos;
        this.ajax = new Request.HTML(
        {
            url: object.ajaxUrl,
            autoCancel: true,
            onComplete: this.requestFinished.bind(this)
        });
        /* handle preselected selection-fields */
        var selectedTarget;
        this.selectionTargets.each(function(target)
        {
            var targetValue = $(target).getProperty('value');
            if (targetValue != '0' && targetValue != '')
            {
                selectedTarget = $(target);
                selectedTarget.removeProperty('disabled');
                $(target).getParent().setProperty('class', 'row');
            }
        });
        if (selectedTarget)
        {
            this.change(selectedTarget);
        };
    },
    change: function(target)
    {
        var targetId = target.getProperty('id');
        var targetName = target.getProperty('name');
        this.currentSelectionTargetPos = this.selectionTargets.indexOf(targetId);
        var targetValue = target.getProperty('value');
        /* reset Levels */
        for (var i = this.currentSelectionTargetPos + 1; i < this.selectionTargets.length; i++)
        {
            var nextElement = $(this.selectionTargets[i]);
            if (nextElement)
            {
                nextElement.empty();
                nextElement.setProperty('disabled', 'true');
                $(this.selectionContainer[i]).addClass('inactiveFormElements');
            }
        }
        /* load next level data when not empty and not last element */
        if (targetValue != '0' && targetValue != '' && this.currentSelectionTargetPos != this.selectionTargets.length - 1)
        {
            this.ajax.get(
            {
                'value': targetValue,
                'name': targetName
            });
        }
        //unfocus the formular-selection field
        window.focus();
    },
    requestFinished: function(nodeList, responseElements, responseHTML)
    {
        var nextElement = $(this.selectionTargets[this.currentSelectionTargetPos + 1]);
        var object = JSON.decode(responseHTML);

        object.each(function(element)
        {
            if (element[1] != this.secondSelection)
            {
                var option = new Element(
                    'option',
                    {
                        'value': element[1]
                    }
                ).inject(nextElement).appendText(element[0]);
            }
            else
            {
                var option = new Element(
                    'option',
                    {
                        'value': element[1],
                        'selected': 'selected'
                    }
                ).inject(nextElement).appendText(element[0]);
            }
        }
.bind(this));
        nextElement.removeProperty('disabled');
        $(this.selectionContainer[this.currentSelectionTargetPos + 1]).removeClass('inactiveFormElements');
    }
});


/**
 * opens new popup
 * @param {Object} url
 * @param {Object} name
 * @param {Object} x
 * @param {Object} y
 * @param {Object} width
 * @param {Object} height
 * @param {Object} params
 */
function openWindow(url, name, x, y, width, height, params)
{
    if (name != null)
        name = name.replace(/ /g, "");
    if (!isNaN(x) && x > 0)
        params += ",left=" + x;
    if (!isNaN(y) && y > 0)
        params += ",top=" + y;
    if (!isNaN(width) && width > 0)
        params += ",width=" + width;
    if (!isNaN(height) && height > 0)
        params += ",height=" + height;
    if (params != null && params.charAt(0) == ",")
        params = params.substring(1);
    var win = window.open(url, name, params);
    if (win)
        win.focus();
}

/**
 * handle three selection boxes depending on each other
 */
var DoubleSelection = new Class(
{
    initialize: function(object)
    {
        this.table = $(object.tableId);
        this.firstSelection = $(object.firstSelection);
        this.secondSelection = $(object.secondSelection);
        this.initialValues = object.initialValues;
        this.inputName = object.inputName;
        this.savedIds = 1;
        this.imgDelete = object.imgDelete;
        this.secondSelectionContainer = $(object.secondSelectionContainer);
        this.ajax = new Request.HTML(
        {
            url: object.ajaxUrl,
            onComplete: this.onAjaxComplete.bind(this),
            autoCancel: true
        });
        if (this.firstSelection.value != '0' && targetValue != '')
        {
            this.firstSelectionChanged();

        }
        for (var i=0; i<this.initialValues.length; i++)
        {
            this.initialSelectionChanged(this.initialValues[i]);
        }
    },
    firstSelectionChanged: function(event)
    {
        var value = this.firstSelection.getProperty('value');
        if (value == '')
        {
            this.cleanup();
        }
        else
        {
            this.ajax.get(
            {
                'value': value
            });
        }
    },
    secondSelectionChanged: function(event)
    {
        var tableBody = this.table.getChildren('tbody')[0];
        this.table.setStyle('display', 'block');
        var row = new Element('tr').inject(tableBody, 'top');
        var firstSelectionText = this.firstSelection.options[this.firstSelection.selectedIndex].text;
        var firstSelectionValue = this.firstSelection.getProperty('value');
        var td1 = new Element('td').inject(row).appendText(firstSelectionText);
        var secondSelectionText = this.secondSelection.options[this.secondSelection.selectedIndex].text;
        var secondSelectionValue = this.secondSelection.getProperty('value');
        var td2 = new Element('td').inject(row).appendText(secondSelectionText);
        var td3 = new Element('td').inject(row);

        var link = new Element('a',
        {
            'href': '#',
            'class': 'deleteLink',
            'events':
            {
                'mouseover': function()
                {
                    link.getFirst().setProperty('src', this.imgDelete[1])
                }.bind(this),
                'mouseout': function()
                {
                    link.getFirst().setProperty('src', this.imgDelete[0])
                }.bind(this),
                'click': function()
                {
                    row.destroy();
                    if (tableBody.getChildren().length <= 0)
                    {
                        this.table.setStyle('display', 'none');
                    }
                }.bind(this)
            }
        }).inject(td3);
        var imageLink = new Element('img',
        {
            'src': this.imgDelete[0]
        }).inject(link);

        var storeFirstSelection = new Element('input',
        {
            'type': 'hidden',
            'name': this.inputName + '[' + this.savedIds + '][firstSelection]',
            'value': firstSelectionValue
        }).inject(td3);

        var storeSecondSelection = new Element('input',
        {
            'type': 'hidden',
            'name': this.inputName + '[' + this.savedIds + '][secondSelection]',
            'value': secondSelectionValue
        }).inject(td3);
        //unfocus the formular-selection field
        window.focus();
        this.cleanup();
        this.savedIds++;

    },
    initialSelectionChanged: function(initSelection)
    {
        var tableBody = this.table.getChildren('tbody')[0];
        this.table.setStyle('display', 'block');
        var row = new Element('tr').inject(tableBody, 'top');
        var firstSelectionText = initSelection[1];
        var firstSelectionValue = initSelection[0];
        var td1 = new Element('td').inject(row).appendText(firstSelectionText);
        var secondSelectionText = initSelection[3];
        var secondSelectionValue = initSelection[2];
        var td2 = new Element('td').inject(row).appendText(secondSelectionText);
        var td3 = new Element('td').inject(row);

        var link = new Element('a',
        {
            'href': '#',
            'class': 'deleteLink',
            'events':
            {
                'mouseover': function()
                {
                    link.getFirst().setProperty('src', this.imgDelete[1])
                }.bind(this),
                'mouseout': function()
                {
                    link.getFirst().setProperty('src', this.imgDelete[0])
                }.bind(this),
                'click': function()
                {
                    row.destroy();
                    if (tableBody.getChildren().length <= 0)
                    {
                        this.table.setStyle('display', 'none');
                    }
                }.bind(this)
            }
        }).inject(td3);
        var imageLink = new Element('img',
        {
            'src': this.imgDelete[0]
        }).inject(link);

        var storeFirstSelection = new Element('input',
        {
            'type': 'hidden',
            'name': this.inputName + '[' + this.savedIds + '][firstSelection]',
            'value': firstSelectionValue
        }).inject(td3);

        var storeSecondSelection = new Element('input',
        {
            'type': 'hidden',
            'name': this.inputName + '[' + this.savedIds + '][secondSelection]',
            'value': secondSelectionValue
        }).inject(td3);
        //unfocus the formular-selection field
        window.focus();
        this.cleanup();
        this.savedIds++;
    },
    cleanup: function()
    {
        this.firstSelection.options[0].selected = true;
        this.secondSelection.empty();
        this.secondSelection.setProperty('disabled', 'true');
        this.secondSelectionContainer.addClass('inactiveFormElements');
    },
    onAjaxComplete: function(nodeList, responseElements, responseHTML)
    {
        var object = JSON.decode(responseHTML);
        this.secondSelection.empty();
        object.each(function(element)
        {
            var option = new Element('option',
            {
                'value': element[1]
            }).inject(this.secondSelection).appendText(element[0]);
        }
.bind(this));
        this.secondSelection.removeProperty('disabled');
        this.secondSelectionContainer.removeClass('inactiveFormElements');
    }
});


window.addEvent('domready', function()
{
    /**
     * set hover state for navigation-buttons
     * @param {Object} element
     */
    $$('img.navigation-item').each(function(element)
    {
        element.onmouseover = imageHoverOver;
        element.onmouseout = imageHoverOut;
    });

    /**
     * set hover state for content-buttons
     * @param {Object} element
     */
    $$('a.button img').each(function(element)
    {
        element.onmouseover = imageHoverOver;
        element.onmouseout = imageHoverOut;
    });

    /**
     * set hover state for input-buttons
     * @param {Object} element
     */
    $$('input.button').each(function(element)
    {
        element.onmouseover = imageHoverOver;
        element.onmouseout = imageHoverOut;
    });

    /**
     * set hover state for linked images
     * @param {Object} element
     */
    $$('.teaser').each(function(element)
    {
        if (element.getElement('a', this) != undefined)
        {
//	        var linkUrl = element.getElement('a', this).getProperty('href');
            var linkUrl = element.getElement('a', this);
            if (linkUrl != undefined)
            {
                element.addClass('clickable');
                element.addEvent('click', function()
                {
                    document.location.href = linkUrl;
                });
            }
        }
    });

});


function imageHoverOver()
{
    var src = this.getProperty('src');
    this.setProperty('src', src.substr(0, src.length - 5) + '2' + src.substr(src.length - 4, 4));

}

function imageHoverOut()
{
    var src = this.getProperty('src');
    this.setProperty('src', src.substr(0, src.length - 5) + '1' + src.substr(src.length - 4, 4));
}

/**
 * reload new adress-form structure depending on the country
 * @param {Object} ajaxUrl
 * @param {Object} event
 */
function countrySelector(ajaxUrl, event)
{
    //Check lock for Safari
    if (Browser.Engine.webkit)
    {
        // alert('Safari');
        if (window.countrySelectorLocked == true)
        {
            return;
        }
        window.countrySelectorLocked = true;
    }

    //Check for IE
    if (Browser.Engine.trident)
    {
        window.countrySelectorUrl = ajaxUrl;
    }

    target = new Event(event).target;
    var country = (target.getProperty) ? target.getProperty('value') : target.value;
    var adressContainer = $('adressContainer');

    //save input values
    var values = new Object();
    adressContainer.getElements('input').each(function(inputElement)
    {
        var value = inputElement.getProperty('value');
        var key = inputElement.getProperty('id');
        if (typeof(key) != 'undefined')
        {
            values[key] = value;
        }
    });

    //send ajax request
    countrySelectorRequest = new Request.HTML(
    {
        url: ajaxUrl,
        update: adressContainer,
        autoCancel: true,
        onComplete: function()
        {
            //read input values and fill them in
            var newAdressContainer = $('adressContainer');
            newAdressContainer.getElement('select').setProperty('value', country);
            newAdressContainer.getElements('input').each(function(inputElement)
            {
                var key = inputElement.getProperty('id');
                if (typeof(key) != 'undefined')
                {
                    inputElement.setProperty('value', values[key]);
                }
            });

            //unlock selector for Safari
            if (Browser.Engine.webkit)
            {
                window.countrySelectorLocked = false;
            }

            //Check for IE
            if (Browser.Engine.trident)
            {
                var select = newAdressContainer.getElement('select');
                var selectHandler = function(event)
                                    {
                                        countrySelector(window.countrySelectorUrl, event);
                                    };
                select.addEvent('change', selectHandler);
            }
        }
    }).get(
    {
        'country': country
    });
}


/**
 * updates the download urls
 */
function updateDownloadUrls(downloadgroup, event)
{
    target = new Event(event).target;
    var url = target.getSelected().getProperty('value');
    //read input values and fill them in
    var downloadContainer = $('download-container');
    downloadContainer.getElements('a.'+downloadgroup).each(function(aElement)
    {
        aElement.setProperty('href', url);
    });
}

/**
 *
 */
function checkConfirmDialoge(element)
{
    if(element != undefined)
    {
        switch(element.id)
        {
            case 'editConsentdeklaration':
                if(element.checked == true)
                {
                    $('editRefuseconsentdeklaration').checked = false;
                    $('editContactphone').disabled = false;
                    $('editContactphoneLabel').setProperty('class', 'inlineLabel');
                    $('editContactemail').disabled = false;
                    $('editContactemailLabel').setProperty('class', 'inlineLabel');
                    $('editContactmail').disabled = false;
                    $('editContactmailLabel').setProperty('class', 'inlineLabel');
                }
                else
                {
                    $('editContactemail').checked = false;
                    $('editContactemail').disabled = true;
                    $('editContactemailLabel').setProperty('class', 'inlineLabel readonlyLabel');
                    $('editContactphone').checked = false;
                    $('editContactphone').disabled = true;
                    $('editContactphoneLabel').setProperty('class', 'inlineLabel readonlyLabel');
                    $('editContactmail').checked = false;
                    $('editContactmail').disabled = true;
                    $('editContactmailLabel').setProperty('class', 'inlineLabel readonlyLabel');
                }
                break;
            case 'editRefuseconsentdeklaration':
                if(element.checked == true)
                {
                    $('editConsentdeklaration').checked = false;
                    $('editContactphone').checked = false;
                    $('editContactphone').disabled = true;
                    $('editContactemailLabel').setProperty('class', 'inlineLabel readonlyLabel');
                    $('editContactemail').checked = false;
                    $('editContactemail').disabled = true;
                    $('editContactphoneLabel').setProperty('class', 'inlineLabel readonlyLabel');
                    $('editContactmail').checked = false;
                    $('editContactmail').disabled = true;
                    $('editContactmailLabel').setProperty('class', 'inlineLabel readonlyLabel');
                }
                break;
        }
    }
}


/**
 *
 */
function checkQuestionElement(element, htmlElement)
{
    if(element != undefined && htmlElement != undefined)
    {
        switch(element)
        {
            case 'Question3':
                if(htmlElement.value == 'Yes')
                {
                    $('edit'+element+'1').disabled = false;
                    $('edit'+element+'2').disabled = false;
                    $('label'+element).setProperty('class', 'radioSpecialServiceportfolioLabel');
                } else
                {
                    $('edit'+element+'1').disabled = true;
                    $('edit'+element+'1').checked = false;
                    $('edit'+element+'2').disabled = true;
                    $('edit'+element+'2').checked = false;
                    $('label'+element).setProperty('class', 'radioSpecialServiceportfolioLabel readonlyLabel');
                }
                break;

            case 'Question7':
                if(htmlElement.value == 'Yes')
                {
                    $('edit'+element).disabled = false;
                    $('label'+element).setProperty('class', 'questionLabel padding-top_no');
                } else
                {
                    $('edit'+element).disabled = true;
                    $('edit'+element).value = '';
                    $('label'+element).setProperty('class', 'questionLabel readonlyLabel padding-top_no');
                }
                break;
        }

    }

}


/**
 *
 */
function checkInitCustomerserviceServicePortfolio()
{
    if($('editQuestion21').checked)
    {
        checkQuestionElement('Question3', $('editQuestion21'));
    }
    if($('editQuestion61').checked)
    {
        checkQuestionElement('Question7', $('editQuestion61'));
    }
}
