/* bo mootools extensions */
Element.extend({
    hasClasses: function(classList, all) {
        var oneTrue = false;
        var allTrue = true;
        var element = this;
        classList.each(function(item){
            item = item.trim();
            classTrue = element.hasClass(item);
            if (classTrue){
                oneTrue = true;
            }else{
                allTrue = false;
            }
        });
        return all ? allTrue : oneTrue;
    }
});
/* eo mootools extensions */

window.addEvent('domready',domready);

function domready() {
    windowdomready = true;
    myObjects = new Object();
    myObjects.body = $(document.body);
    if (document.body.id != 'intranet'){
        main_navigation_handler();
    }
    partnerInit();
    init_crm_client_details();
    init_crm_consultant_details();
    init_clientportal();
    init_downlineLinks();
    init_toggleActiveLinks();
    new Tips($$('.tip'));
    initConsultantOrder();
    if (window.khtml){
        var searchformCoords = $('search').getCoordinates();
        var searchbuttonCoords = $('searchbutton').getCoordinates();
        $(searchfield).style.width = (searchformCoords['width'] - searchbuttonCoords['width']) + 'px';
        $(searchfield).style.height = searchformCoords['height'] + 'px';
        khtmlFix();
        window.addEvent('resize', khtmlFix);
    }
}

function khtmlFix() {
    if ($('startpage')){
        objTeaserContent = $('teaser_content');
        objTeaserContentTable = $$('#startpage #teaser_content table');
        objTeaserContentTable[0].style.height = objTeaserContent.offsetHeight + 'px';
    }
}

function main_navigation_handler() {
    myObjects.main_navigation = new Object();
    myObjects.main_navigation.obj = $('main_navigation');
    myObjects.main_navigation.items = $$('#main_navigation li');
    myObjects.main_navigation.items.each(function(item){
        new itemHandler(item);
    });
    
    function itemHandler(item) {
        var aObj = item.getElementsByTagName('a')[0];
        aObj.onclick = followHref;
        item.addEvent('mouseover', mouseover);
        
        function mouseover() {
            if (!item.hasClass('active','hover') ){
                item.addClass('hover');
                item.addEvent('mouseout', mouseout);
            }
        }
        
        function mouseout() {
            item.removeClass('hover');
        }
        
        function followHref() {
            location.href = aObj.href;
        }
    }

}

fontsizeinit_oldondomready = window.ondomready;
window.addEvent('domready', function() {
    originalFontSize = getCurrentFontSize();
    var fontSizeFactor = Cookie.get('fontSizeFactor');
    if (fontSizeFactor){
        fontSizeFactor = parseInt(fontSizeFactor);
        changeFontSize(fontSizeFactor);
    }
    if (fontsizeinit_oldondomready) {
        fontsizeinit_oldondomready();
    }
});

function getCurrentFontSize() {
    if (document.body.currentStyle)
        var currentFontSize = document.body.currentStyle['fontSize'];
    else if (window.getComputedStyle)
        var currentFontSize = document.defaultView.getComputedStyle(document.body, null).getPropertyValue('font-size');
    return /(\d+)(.+)/.exec(currentFontSize);
}

function changeFontSize(factor) {
    var currentFontSize = getCurrentFontSize();
    var newFontSize = parseInt(currentFontSize[1]) + factor;
    document.body.style.fontSize = newFontSize + currentFontSize[2];
    
    factorToSave = newFontSize - parseInt(originalFontSize[1]);
    Cookie.set('fontSizeFactor', factorToSave);
    if (!window.ie){
        setTimeout('document.body.innerHTML = document.body.innerHTML; domready();', 100);
    }
}

function resetFontSize() {
    document.body.style.fontSize = '';
    Cookie.remove('fontSizeFactor');
    if (!window.ie){
        setTimeout('document.body.innerHTML = document.body.innerHTML; domready();', 100);
    }
}

function getAdr(prefix, postfix, text) {
        document.write('<a href="mailto:' + prefix + '@' + postfix + '">' + (text ? text.replace(/&quot;/g, '"').replace(/%EMAIL%/, prefix + '@' + postfix) : prefix + '@' + postfix) + '</a>');
}

function checkEmail(val) {
        if (val) {
                var usr = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
                var domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
                var regex = "^"+usr+"\@"+domain+"$";
                var myrxp = new RegExp(regex);
                var check = (myrxp.test(val));
                if (check!=true) {
                        return false;
                }
                else {
                        return true;
                }
        }
}

/*
validates formfields if they have a value or not
to check for other options do the following
specialfields = new Object();
specialfields.fieldname = new Object();
specialfields.fieldname.check1 = 'function_to_call,error_message';
specialfields.fieldname.check2 = 'second_function_to_call,second_error_message';
specialfields.another_fieldname = new Object();
specialfields.another_fieldname.check1 = 'function_to_call,error_message';
*/
function validateForm(form,specialfields) {
        var errors = new Array();
        var fields = form.getElementsByTagName('label');
        for (i = 0; i < fields.length; i++) {
                var span = fields[i].getElementsByTagName('span')[0];
                if (span) {
                        var label = span.firstChild.data;
                        label = label.trim();
                        // if there is a '*' in the label - this indicates the inputfield has to be filled
                        if (label.charAt(label.length - 1) == '*') {
                                label = label.substring(0, label.length - 1).trim();
                                // get the inputfield
                                var obj_input = fields[i].getElementsByTagName('input');
                                if (!obj_input[0])
                                        obj_input = fields[i].getElementsByTagName('select');
                                if (!obj_input[0])
                                        obj_input = fields[i].getElementsByTagName('textarea');

                                // if there is an inputfield
                                if (obj_input && obj_input[0]) {
                                        input = obj_input[0];
                                        error = false;
                                        
                                        // check if the inputfield has a value
                                        if (!input.value || input.value.trim().length==0) {
                                                error = true;
                                                if (input.tagName=='SELECT'){
                                                    errors.push(label + ' ' + langstrings['form_errormessage_part_select']);
                                                }
                                                else{
                                                    errors.push(label + ' ' + langstrings['form_errormessage_part']);
                                                }
                                        }
                                        
                                        // check the inputfield for special things (email, ...)
                                        if (!error && specialfields[input.name]){
                                                specialfield = specialfields[input.name];
                                                for (check in specialfield){
                                                        check_function = specialfield[check].split(',')[0];
                                                        check_message = specialfield[check].split(',')[1];
                                                        if (!eval(check_function)(input.value)){
                                                                error = true;
                                                                errors.push(label + ' ' + check_message);
                                                        }
                                                }
                                        }

                                        // on error give the label the className 'error' otherwise delete the className 'error' (if exists)
                                        if (error) {
                                                className = fields[i].className;
                                                if (className.length>0){
                                                        className = className + ' ';
                                                }
                                                fields[i].className = className + 'error';
                                        } else {
                                        className = fields[i].className;
                                                if (className.indexOf('error')>-1){
                                                                className = className.replace(' error', '');
                                                                className = className.replace('error', '');
                                                                fields[i].className = className;
                                                }
                                        }
                                }
                        }
                }
        }

        return errors;
}

function showFormErrors (errors) {
        error_message = '';
        for (i=0;i<errors.length;i++){
                error_message += errors[i] + '\n';
        }
        alert(error_message);
}

function partnerInit() {
    myObjects.partner = $('partner');
    if (myObjects.partner){
        myObjects.partnerFilter = $('partnerFilter');
        myObjects.partnerFilter.selects = myObjects.partnerFilter.getElements('select');
        myObjects.partner.items = myObjects.partner.getElements('tr');
        partnerClassifyItems();
    }
}

function partnerClassifyItems() {
    odd = false;
    myObjects.partner.items.each(function(item){
        item.removeClass('odd');
        item.removeClass('even');
        if (item.style.display!='none'){
            if (odd){
                odd = false;
                item.addClass('even');
            }else{
                odd = true;
                item.addClass('odd');
            }
        }
    });
}

function partnerFilter(obj) {
    if (!myObjects.partner){
        myObjects.partner = $('partner');
        myObjects.partnerFilter = $('partnerFilter');
        myObjects.partnerFilter.selects = myObjects.partnerFilter.getElements('select');
    }
    var partnerClasses = new Array();
    myObjects.partnerFilter.selects.each(function(item) {
        if (item.value.trim().length > 0){
            partnerClasses.push(item.value.trim());
        }
    });
    myObjects.partner.items.each(function(item){
        if (item.hasClasses(partnerClasses, true)){
            if (window.ie){
                item.style.display = 'block';
            }else{
                item.style.display = 'table-row';
            }
        }else{
            item.style.display = 'none';
        }
    });
    partnerClassifyItems();
}

function createInfobox(initObj, theBox){
    if (initObj && theBox){
        myObjects.body.appendChild(theBox);
        theBox.effects().set({'opacity':0});
        theBox.initClose = function() {
            this.close = this.getElement('a.close');
            this.close.theBox = theBox;
            this.close.addEvent('click', function(e){
                new Event(e).stop();
                this.theBox.hide();
            });
        }
        theBox.initLinks = function() {
            this.initClose();
        }
        theBox.getNewStyles = function() {
            var avail_width = window.getWidth();
            var avail_height = window.getHeight();
        
            this.coordinates = this.getCoordinates();
            var needed_width = this.coordinates.width;
            var needed_height = this.coordinates.height;
            
            var styles = new Object();
            var use_width = needed_width;
            var use_height = needed_height;
        
            if (needed_width >= avail_width || needed_height >= avail_height){
                if (needed_width >= avail_width){
                    use_width = avail_width - 10;
                    styles['width'] = use_width;
                }
                if (needed_height >= avail_height){
                    use_height = avail_height - 10;
                    styles['height'] = use_height;
                }
            }
            styles['overflow'] = 'auto';
            
            var rest_width = avail_width - use_width;
            var rest_height = avail_height - use_height;
            styles['top'] = (rest_height/2);
            styles['left'] = (rest_width/2);
            return styles;
        }
        theBox.resize = function() {
            styles = theBox.getNewStyles();
            effectStyles = new Object();
            allowedEffectStyles = ['top','left','width','right'];
            setStyles = new Object();
            for (style in styles){
                if (allowedEffectStyles.contains(style)){
                    effectStyles[style] = styles[style];
                }else{
                    setStyles[style] = styles[style];
                }
            }
            theBox.setStyles(setStyles);
            theBox.effects().start(effectStyles);
        }
        theBox.show = function() {
            if (window.gecko){
                $$('fieldset .content').each(function(item){
                    item.setStyle('overflow', 'hidden');
                });
            }
            this.setStyle('display', 'block');
            this.setStyles(this.getNewStyles());
            this.effects().start({'opacity':1});
            window.addEvent('resize', theBox.resize);
        }
        theBox.hide = function() {
            window.removeEvent('resize', theBox.resize);
            this.effects({onComplete:function(){theBox.setStyle('display','none');}}).start({'opacity':0});
            if (window.gecko){
                $$('fieldset .content').each(function(item){
                    item.setStyle('overflow', 'auto');
                });
            }
        }
        theBox.initLinks();
        initObj.theBox = theBox;
        initObj.addEvent('click', function(e){
            var event = new Event(e);
            if (!event.shift && !event.control && !event.alt && !event.meta){
                event.stop();
                this.theBox.show();
            }
        });
    }
}
        
function toggleClientsTableDateVisibility(obj) {
    table = $(obj);
    while (table.getTag()!='table'){
        table = table.getParent();
    }
    if (table.hasClass('show_date')){
        table.removeClass('show_date');
        obj.innerHTML = 'Datum anzeigen';
    }else{
        table.addClass('show_date');
        obj.innerHTML = 'Datum verstecken';
    }
}

function toggleClientsSearch(obj) {
    table = $(obj);
    while (table.getTag()!='table'){
        table = table.getParent();
    }
    if (table.hasClass('advanced')){
        table.removeClass('advanced');
        obj.innerHTML = 'erweiterte Suche';
    }else{
        table.addClass('advanced');
        obj.innerHTML = 'einfache Suche';
    }
}

function init_crm_client_details() {
    myObjects.crm_client_details = $('crm_client_details');
    if (myObjects.crm_client_details){
        myObjects.crm_client_details.showLastDelivery = $('showLastDelivery');
        myObjects.crm_delivery_details = $('crm_delivery_details');
        createInfobox(myObjects.crm_client_details.showLastDelivery, myObjects.crm_delivery_details);
        
        myObjects.crm_client_details.showSubscriptions = $('showSubscriptions');
        myObjects.crm_client_subscriptions = $('crm_client_subscriptions');
        createInfobox(myObjects.crm_client_details.showSubscriptions, myObjects.crm_client_subscriptions);
        if (myObjects.crm_client_details.showSubscriptions && myObjects.crm_client_subscriptions){
            myObjects.crm_client_subscriptions.oldinitLinks = myObjects.crm_client_subscriptions.initLinks;
            myObjects.crm_client_subscriptions.initLinks = function() {
                myObjects.crm_client_subscriptions.oldinitLinks();
                myObjects.crm_client_subscriptions.items = myObjects.crm_client_subscriptions.getElements('fieldset');
                myObjects.crm_client_subscriptions.items.each(function(item){
                    item.toggleDetails = item.getElement('a.toggleDetails');
                    item.details = item.getElement('tr.details');
                    item.toggleDetails.addEvent('click', function(e){
                        new Event(e).stop();
                        item.details.toggleClass('show');
                        item.details.toggleClass('hide');
                        if (window.gecko){
                            myObjects.crm_client_subscriptions.innerHTML = myObjects.crm_client_subscriptions.innerHTML;
                            myObjects.crm_client_subscriptions.initLinks();
                        }
                        myObjects.crm_client_subscriptions.resize();
                    });
                });
            }
            myObjects.crm_client_subscriptions.initLinks();
        }
        
        myObjects.crm_client_details.showPetAdd = $('showPetAdd');
        myObjects.crm_pet_add = $('crm_pet_add');
        createInfobox(myObjects.crm_client_details.showPetAdd, myObjects.crm_pet_add);
        
        myObjects.crm_client_details.pet_edit_items = $$('a.pet_edit');
        myObjects.crm_client_details.pet_edit_items.each(function(item){
            createInfobox(item, $('crm_pet_edit_' + item.rel));
        });
        
        myObjects.crm_client_details.showComments = $('showComments');
        myObjects.crm_client_comments = $('crm_client_comments');
        createInfobox(myObjects.crm_client_details.showComments, myObjects.crm_client_comments);
        if (myObjects.crm_client_comments){
            myObjects.crm_client_comments.textarea = myObjects.crm_client_comments.getElement('textarea');
            if (window.ie || window.khtml){
                myObjects.crm_client_comments.h2 = myObjects.crm_client_comments.getElement('h2');
                myObjects.crm_client_comments.container_send = myObjects.crm_client_comments.getElement('.container_send');
                myObjects.crm_client_comments.resize = function() {
                    myObjects.crm_client_comments.coordinates = myObjects.crm_client_comments.getCoordinates();
                    myObjects.crm_client_comments.h2.coordinates = myObjects.crm_client_comments.h2.getCoordinates();
                    myObjects.crm_client_comments.container_send.coordinates = myObjects.crm_client_comments.container_send.getCoordinates();
                    var newHeight = myObjects.crm_client_comments.coordinates.height - myObjects.crm_client_comments.h2.coordinates.height - myObjects.crm_client_comments.container_send.coordinates.height - 20;
                    myObjects.crm_client_comments.textarea.setStyles({'height':newHeight});
                    if (window.khtml){
                        var newWidth = myObjects.crm_client_comments.coordinates.width - 20;
                        myObjects.crm_client_comments.textarea.setStyles({'width':newWidth});
                    }
                }
            }
            myObjects.crm_client_comments.oldshow = myObjects.crm_client_comments.show;
            myObjects.crm_client_comments.show = function(){
                myObjects.crm_client_comments.oldshow();
                if (window.ie || window.khtml){myObjects.crm_client_comments.resize();}
                (function(){myObjects.crm_client_comments.textarea.focus()}).delay(1000);
            }
        }
        
        myObjects.crm_client_details.showAppointmentNew = $('showAppointmentNew');
        myObjects.crm_appointment_new = $('crm_appointment_new');
        createInfobox(myObjects.crm_client_details.showAppointmentNew, myObjects.crm_appointment_new);
        
        myObjects.crm_client_details.showAppointmentDoneNew = $('showAppointmentDoneNew');
        myObjects.crm_appointment_done_new = $('crm_appointment_done_new');
        createInfobox(myObjects.crm_client_details.showAppointmentDoneNew, myObjects.crm_appointment_done_new);
        
        myObjects.crm_client_details.appointment_edit_items = $$('a.appointment_edit');
        myObjects.crm_client_details.appointment_edit_items.each(function(item){
            createInfobox(item, $('crm_appointment_edit_' + item.rel));
        });
    }
}

function init_clientportal() {
    myObjects.clientportal = $('clientportal');
    if (myObjects.clientportal){
        myObjects.clientportal.showMasterdata = $('showMasterdata');
        myObjects.clientportal_masterdata = $('clientportal_masterdata');
        createInfobox(myObjects.clientportal.showMasterdata, myObjects.clientportal_masterdata);
        
        myObjects.clientportal_masterdata.initLinks = function() {
            this.initClose();
            myObjects.clientportal_masterdata.theForm = myObjects.clientportal_masterdata.getElement('form');
            myObjects.clientportal_masterdata.change = $$('#clientportal_masterdata a.change');
            myObjects.clientportal_masterdata.change.addEvent('click', function(e){
                new Event(e).stop();
                myObjects.clientportal_masterdata.theForm.addClass('show');
                if (window.ie){
                    $$('#clientportal_masterdata td.form').each(function(item){item.style.display='block';});
                } else if (window.gecko || window.khtml){
                    myObjects.clientportal_masterdata.innerHTML = myObjects.clientportal_masterdata.innerHTML;
                    myObjects.clientportal_masterdata.initLinks();
                }
                myObjects.clientportal_masterdata.resize();
            });
            myObjects.clientportal_masterdata.abort_link = $$('#clientportal_masterdata a.abort');
            myObjects.clientportal_masterdata.abort_link.addEvent('click', function(e){
                new Event(e).stop();
                myObjects.clientportal_masterdata.theForm.removeClass('show');
                if (window.ie){
                    $$('#clientportal_masterdata td.form').each(function(item){item.style.display='none';});
                } else if (window.gecko || window.khtml){
                    myObjects.clientportal_masterdata.innerHTML = myObjects.clientportal_masterdata.innerHTML;
                    myObjects.clientportal_masterdata.initLinks();
                }
                myObjects.clientportal_masterdata.resize();
            });
        }
        myObjects.clientportal_masterdata.initLinks();
        
        myObjects.clientportal.showChangePassword = $('showChangePassword');
        myObjects.clientportal_change_password = $('clientportal_change_password');
        createInfobox(myObjects.clientportal.showChangePassword, myObjects.clientportal_change_password);
        
        myObjects.clientportal.shortMessage = $('shortMessage');
        myObjects.clientportal.showSendmessage = $('showSendmessage');
        myObjects.clientportal_send_message = $('clientportal_send_message');
        myObjects.clientportal_send_message.longMessage = $('longMessage');
        createInfobox(myObjects.clientportal.showSendmessage, myObjects.clientportal_send_message);
        myObjects.clientportal_send_message.oldshow = myObjects.clientportal_send_message.show;
        myObjects.clientportal_send_message.show = function(){
            myObjects.clientportal_send_message.longMessage.value = myObjects.clientportal.shortMessage.value;
            myObjects.clientportal_send_message.oldshow();
            (function(){myObjects.clientportal_send_message.longMessage.focus()}).delay(1000);
        }
        myObjects.clientportal_send_message.oldhide = myObjects.clientportal_send_message.hide;
        myObjects.clientportal_send_message.hide = function(){
            myObjects.clientportal.shortMessage.value = myObjects.clientportal_send_message.longMessage.value;
            myObjects.clientportal_send_message.oldhide();
        }
        
        myObjects.clientportal.showSubscriptionDetails = $$('a.showSubscriptionDetails');
        myObjects.clientportal.showSubscriptionDetails.each(function(item){
            createInfobox(item, $(item.rel));
        });
        $$('a.showSubscriptionDetails2').each(function(item){
            item.theBox = $(item.rel);
            item.addEvent('click', function(e){
                var event = new Event(e);
                if (!event.shift && !event.control && !event.alt && !event.meta){
                    event.stop();
                    this.theBox.show();
                }
            });
        });
    }
}

function init_toggleActiveLinks(){
    $$('a.toggleActive').each(function(toggleActiveLink){
        init_toggleActiveLink(toggleActiveLink);
    });
}

function init_toggleActiveLink(toggleActiveLink){
    toggleActiveLink.addEvent('click', function(e){
        new Event(e).stop();
        toggleActive(this);
    });
}

function toggleActive(toggleActiveLink){
    var requestUrl =  toggleActiveLink.href + '&rpc=1';
    var downlineRequest = new Ajax(
        requestUrl,
        {
            method: 'get',
            onComplete: function(){
                if (this.response.text = '1'){
                    toggleActiveLink.innerHTML = toggleActiveLink.innerHTML == 'JA' ? 'NEIN' : 'JA';
                }
            }
        }
    );
    downlineRequest.setHeader('Authorization', 'Basic ' + authHash);
    downlineRequest.request();
}

function init_downlineLinks(){
    downlineLinks = {};
    $$('a.downlineLink').each(function(downlineLink){
        downlineLinks[downlineLink.rel] = downlineLink;
        init_downlineLink(downlineLink);
    });
    $$('a.downlineInactiveLength').each(function(downlineLink){
        init_downlineInactiveLink(downlineLink);
    });
    $$('a.completeDownlineLink').each(function(completeDownlineLink){
        completeDownlineLink.addEvent('click', function(e){
            new Event(e).stop();
            downlineTable = this.getParent();
            while (downlineTable.tagName.toLowerCase() != 'table'){
                downlineTable = downlineTable.getParent();
            }
            downlineTable.getElements('a.downlineLink').each(function(downlineLink){
                toggleDownline(downlineLink, false, true);
            });
        });
    });
}

function init_downlineLink(downlineLink){
    var rel = downlineLink.rel.split('_');
    downlineLink['_prefix'] = rel[0];
    downlineLink['consultantId'] = rel[1];
    downlineLink['consultantRow'] = downlineLink.getParent().getParent();
    downlineLink['downlineActiveRow'] = $(downlineLink['_prefix'] + '_' + downlineLink['consultantId'] + '_downlineActive');
    downlineLink['downlineInactiveRow'] = $(downlineLink['_prefix'] + '_' + downlineLink['consultantId'] + '_downlineInactive');
    downlineLink['loadingRow'] = null;
    downlineLink.addEvent('click', function(e){
        new Event(e).stop();
        toggleDownline(this);
    })
}

function init_downlineInactiveLink(downlineLink){
    downlineLink['downlineLink'] = downlineLinks[downlineLink.rel];
    downlineLink.addEvent('click', function(e){
        new Event(e).stop();
        toggleDownline(this['downlineLink'], true);
    });
}

function toggleDownline(downlineLink, showInactive, showCompleteDownline){
    if (downlineLink['downlineActiveRow'] || downlineLink['downlineInactiveRow']){
        var show = (downlineLink.innerHTML == '+') || showInactive || showCompleteDownline;
        downlineLink.innerHTML = show || showCompleteDownline ? '-' : '+';
        if (downlineLink['downlineActiveRow']){
            if (show || showInactive){
                downlineLink['downlineActiveRow'].setStyle('display',(window.ie ? 'block' : 'table-row'));
            }else{
                downlineLink['downlineActiveRow'].setStyle('display','none');
            }
            if (showCompleteDownline){
                downlineLink['downlineActiveRow'].getElements('a.downlineLink').each(function(downlineLink){
                    toggleDownline(downlineLink, false, true);
                });
            }
        }
        if (downlineLink['downlineInactiveRow']){
            if (showInactive){
                downlineLink['downlineInactiveRow'].setStyle('display',(window.ie ? 'block' : 'table-row'));
            }else{
                downlineLink['downlineInactiveRow'].setStyle('display','none');
            }
        }
    }else{
        if (!downlineLink['loadingRow']){
            downlineLink.innerHTML = '-';
            downlineLink['loadingRow'] = new Element('tr', {'class':'loadingRow'}).injectAfter(downlineLink['consultantRow']);
            new Element('td', {'colspan':9}).injectInside(downlineLink['loadingRow']).innerHTML = '... lade Downline';
            
            var requestUrl = location.protocol + '//' + location.host + '/AnifitCRM/getDownline?consultantId=' + downlineLink['consultantId'] + '&prefix=' + downlineLink['_prefix'] + '&rpc=1';
            var downlineRequest = new Ajax(
                requestUrl,
                {
                    method: 'get',
                    onComplete: function(){
                        var downline = Json.evaluate(this.response.text, false);
                        var downlineActive = downline['downlineActive'];
                        var downlineInactive = downline['downlineInactive'];
                        if (downlineActive.length > 0){
                            downlineLink['downlineActiveRow'] = newDownlineRow(downlineLink, 'Active', downlineActive, downlineLink['loadingRow'], true);
                        }
                        if (downlineInactive.length > 0){
                            downlineLink['downlineInactiveRow'] = newDownlineRow(downlineLink, 'Inactive', downlineInactive, downlineLink['downlineActiveRow'] ? downlineLink['downlineActiveRow'] : downlineLink['loadingRow'], showInactive);
                        }
                        downlineLink['loadingRow'].setStyle('display','none');
                        if (showCompleteDownline){
                            downlineLink['downlineActiveRow'].getElements('a.downlineLink').each(function(downlineLink){
                                toggleDownline(downlineLink, false, true);
                            });
                        }
                    }
                }
            );
            downlineRequest.setHeader('Authorization', 'Basic ' + authHash);
            downlineRequest.request();
        }
    }
}

function newDownlineRow(downlineLink, downlineType, downline, where, display){
    downlineRowAttrs = {'id': downlineLink['rel'] + '_downline' + downlineType, 'class':'downlineRow', 'styles': (display ? {} : {'display':'none'})};
    var downlineRow = new Element('tr', downlineRowAttrs).injectAfter(where);
    var downlineContent = new Element('td', {'colspan':9, 'class':'downlineContent'}).injectInside(downlineRow);
    var table = new Element('table', {'class': 'consultants'}).injectInside(downlineContent);
    var odd = true;
    var tbody = new Element('tbody').injectInside(table);
    downline.each(function(consultant){
        odd = odd ? false : true;
        newConsultantRow(consultant, tbody, odd);
    });
    return downlineRow;
}

function newConsultantRow(consultant, tbody, odd){
    var consultantRow = new Element('tr', {'id': consultant['rowId'], 'class': (odd ? 'odd' : 'even')}).injectInside(tbody);
    new Element('td', {'class': 'level'}).injectInside(consultantRow).innerHTML = consultant['level'];
    new Element('td', {'class': 'qualification'}).injectInside(consultantRow).innerHTML = consultant['qualificationlevel'];
    
    consultant['downlineAllowed'] = consultant['downlineAllowed'] == 1 ? true : false;
    if (consultant['downlineAllowed']){
        var td = new Element('td', {'class': 'downline'}).injectInside(consultantRow);
        if (consultant['uri_showDownline'].length > 0){
            var sub_downlineLink = new Element('a', {'class': 'downlineLink', 'href': consultant['uri_showDownline'], 'rel': consultant['showDownline_link_rel']}).injectInside(td);
            sub_downlineLink.innerHTML = consultant['showDownline_link_content'];
            downlineLinks[consultant['showDownline_link_rel']] = sub_downlineLink;
            init_downlineLink(sub_downlineLink);
        }else{
            var span = new Element('span', {'class': 'downlineLinkDummy'}).injectInside(td);
            span.innerHTML = '&nbsp;';
        }
        new Element('span', {'class': 'downlineActiveLength'}).injectInside(td).innerHTML = consultant['downlineActiveLength'];
        td.appendText(' ');
        if (consultant['uri_showDownlineInactive'].length > 0){
            var sub_dowlineInactiveLink = new Element('a', {'class': 'downlineInactiveLength', 'href': consultant['uri_showDownlineInactive'], 'rel':consultant['showDownline_link_rel']}).injectInside(td);
            sub_dowlineInactiveLink.innerHTML = consultant['downlineInactiveLength'];
            init_downlineInactiveLink(sub_dowlineInactiveLink);
        }else{
            new Element('span', {'class': 'downlineInactiveLength'}).injectInside(td).innerHTML = consultant['downlineInactiveLength'];
        }
    }else{
        new Element('td', {'class': 'downline'}).injectInside(consultantRow).innerHTML = '&nbsp;';
    }
    
    var td = new Element('td', {'class': 'consultant'}).injectInside(consultantRow);
    new Element('a', {'href': consultant['uri_consultantDetails']}).injectInside(td).innerHTML = consultant['name'];
    td.appendText(', ');
    new Element('span').injectInside(td).innerHTML = consultant['city'];
    
    consultant['appointmentok'] = consultant['appointmentok'].toLowerCase() == 'true' ? true : false;
    var td = new Element('td', {'class': 'appointment'}).injectInside(consultantRow);
    new Element('span', {'class': consultant['appointmentok'] ? 'ok' : 'notok'}).injectInside(td);
    new Element('span', {'class': 'date' + (consultant['appointmentok'] ? '' : ' error')}).injectInside(td).innerHTML = consultant['appointment'];
    
    consultant['contactok'] = consultant['contactok'].toLowerCase() == 'true' ? true : false;
    var td = new Element('td', {'class': 'contact'}).injectInside(consultantRow);
    new Element('span', {'class': consultant['contactok'] ? 'ok' : 'notok'}).injectInside(td);
    new Element('span', {'class': 'date' + (consultant['contactok'] ? '' : ' error')}).injectInside(td).innerHTML = consultant['contact'];
    
    consultant['newclientsok'] = consultant['newclientsok'].toLowerCase() == 'true' ? true : false;
    consultant['newclients_lastmonthok'] = consultant['newclients_lastmonthok'].toLowerCase() == 'true' ? true : false;
    var td = new Element('td', {'class': 'new'}).injectInside(consultantRow);
    new Element('span', {'class': consultant['newclientsok'] ? 'ok' : 'notok'}).injectInside(td);
    new Element('span', {'class': 'new' + (consultant['newclientsok'] ? '' : ' error')}).injectInside(td).innerHTML = consultant['newclients_thismonth'];
    td.appendText(' ');
    new Element('span', {'class': 'new' + (consultant['newclients_lastmonthok'] ? '' : ' error')}).injectInside(td).innerHTML = consultant['newclients_lastmonth'];
    
    consultant['newconsultantsok'] = consultant['newconsultantsok'].toLowerCase() == 'true' ? true : false;
    consultant['newconsultants_lastmonthok'] = consultant['newconsultants_lastmonthok'].toLowerCase() == 'true' ? true : false;
    var td = new Element('td', {'class': 'new'}).injectInside(consultantRow);
    new Element('span', {'class': consultant['newconsultantsok'] ? 'ok' : 'notok'}).injectInside(td);
    new Element('span', {'class': 'new' + (consultant['newconsultantsok'] ? '' : ' error')}).injectInside(td).innerHTML = consultant['newconsultants_thismonth'];
    td.appendText(' ');
    new Element('span', {'class': 'new' + (consultant['newconsultants_lastmonthok'] ? '' : ' error')}).injectInside(td).innerHTML = consultant['newconsultants_lastmonth'];
    
    consultant['active'] = consultant['active'] == 1 ? true : false;
    var td = new Element('td', {'class': 'active'}).injectInside(consultantRow);
    var toggleActiveLink = new Element('a', {'href': consultant['uri_toggleActive'], 'class': 'toggleActive', 'title': consultant['active'] ? 'inaktiv setzen' : 'aktiv setzen'}).injectInside(td);
    toggleActiveLink.innerHTML = consultant['active'] ? 'JA' : 'NEIN'
    init_toggleActiveLink(toggleActiveLink);
}

function init_crm_consultant_details() {
    myObjects.crm_consultant_details = $('crm_consultant_details');
    if (myObjects.crm_consultant_details){
        myObjects.crm_consultant_details.showStatistics = $('showStatistics');
        myObjects.crm_statistics = $('crm_statistics');
        createInfobox(myObjects.crm_consultant_details.showStatistics, myObjects.crm_statistics);
        
        myObjects.crm_consultant_details.showComments = $('showComments');
        myObjects.crm_consultant_comments = $('crm_consultant_comments');
        createInfobox(myObjects.crm_consultant_details.showComments, myObjects.crm_consultant_comments);
        if (myObjects.crm_consultant_comments){
            myObjects.crm_consultant_comments.textarea = myObjects.crm_consultant_comments.getElement('textarea');
            if (window.ie || window.khtml){
                myObjects.crm_consultant_comments.h2 = myObjects.crm_consultant_comments.getElement('h2');
                myObjects.crm_consultant_comments.container_send = myObjects.crm_consultant_comments.getElement('.container_send');
                myObjects.crm_consultant_comments.resize = function() {
                    myObjects.crm_consultant_comments.coordinates = myObjects.crm_consultant_comments.getCoordinates();
                    myObjects.crm_consultant_comments.h2.coordinates = myObjects.crm_consultant_comments.h2.getCoordinates();
                    myObjects.crm_consultant_comments.container_send.coordinates = myObjects.crm_consultant_comments.container_send.getCoordinates();
                    var newHeight = myObjects.crm_consultant_comments.coordinates.height - myObjects.crm_consultant_comments.h2.coordinates.height - myObjects.crm_consultant_comments.container_send.coordinates.height - 20;
                    myObjects.crm_consultant_comments.textarea.setStyles({'height':newHeight});
                    if (window.khtml){
                        var newWidth = myObjects.crm_consultant_comments.coordinates.width - 20;
                        myObjects.crm_consultant_comments.textarea.setStyles({'width':newWidth});
                    }
                }
            }
            myObjects.crm_consultant_comments.oldshow = myObjects.crm_consultant_comments.show;
            myObjects.crm_consultant_comments.show = function(){
                myObjects.crm_consultant_comments.oldshow();
                if (window.ie || window.khtml){myObjects.crm_consultant_comments.resize();}
                (function(){myObjects.crm_consultant_comments.textarea.focus()}).delay(1000);
            }
        }
        
        myObjects.crm_consultant_details.showAppointmentNew = $('showAppointmentNew');
        myObjects.crm_appointment_new = $('crm_appointment_new');
        createInfobox(myObjects.crm_consultant_details.showAppointmentNew, myObjects.crm_appointment_new);
        
        myObjects.crm_consultant_details.showAppointmentDoneNew = $('showAppointmentDoneNew');
        myObjects.crm_appointment_done_new = $('crm_appointment_done_new');
        createInfobox(myObjects.crm_consultant_details.showAppointmentDoneNew, myObjects.crm_appointment_done_new);
        
        myObjects.crm_consultant_details.appointment_edit_items = $$('a.appointment_edit');
        myObjects.crm_consultant_details.appointment_edit_items.each(function(item){
            createInfobox(item, $('crm_appointment_edit_' + item.rel));
        });
    }
}

function initConsultantOrder(){
    myObjects.consultant_order = $('consultant_order');
    if (myObjects.consultant_order){
        $('fld_client_id').addEvent('change', function(){
            var val = this.value.trim();
            var requestUrl = location.protocol + '//' + location.host + '/AnifitCRM/getClient?clientId=' + val + '&rpc=1';
            var clientRequest = new Ajax(
                requestUrl,
                {
                    method: 'get',
                    onComplete: function(){
                        try {
                            client = Json.evaluate(this.response.text)
                            $('fld_client_salutation').value = client['salutation_addr'];
                            $('fld_client_firstname').value = client['firstname'];
                            $('fld_client_lastname').value = client['lastname'];
                            $('fld_client_address').value = client['address'];
                            $('fld_client_zipcode').value = client['zip'];
                            $('fld_client_city').value = client['city'];
                            $('fld_client_email').value = client['email'];
                            $('fld_client_phone').value = client['phone'];
                            $('fld_client_country').value = client['country'] == '' ? 'DE' : client['country'];
                            if (client['bank_account_number'].length>0){
                                $('fld_payment_accountowner').value = client['bank_account_holder'];
                                $('fld_payment_bank').value = client['bank_name'];
                                $('fld_payment_bcn').value = client['bank_code_number'];
                                $('fld_payment_accountnumber').value = client['bank_account_number'];
                                $('fld_payment_method').value = 'debit';
                            }else{
                                $('fld_payment_accountowner').value = '';
                                $('fld_payment_bank').value = '';
                                $('fld_payment_bcn').value = '';
                                $('fld_payment_accountnumber').value = '';
                                $('fld_payment_method').value = 'cod';
                            }
                            $('fld_payment_method').changehandler();
                            document.location.href = document.location.href + '?clientId=' + $('fld_client_id').value;
                        } catch (e){
                            $('fld_client_salutation').value = '';
                            $('fld_client_firstname').value = '';
                            $('fld_client_lastname').value = '';
                            $('fld_client_address').value = '';
                            $('fld_client_zipcode').value = '';
                            $('fld_client_city').value = '';
                            $('fld_client_email').value = '';
                            $('fld_client_phone').value = '';
                            $('fld_client_country').value = '';
                            $('fld_payment_accountowner').value = '';
                            $('fld_payment_bank').value = '';
                            $('fld_payment_bcn').value = '';
                            $('fld_payment_accountnumber').value = '';
                            $('fld_payment_method').value = 'cod';
                            $('fld_payment_method').changehandler();
                        }
                    }
                }
            );
            clientRequest.setHeader('Authorization', 'Basic ' + authHash);
            clientRequest.request()
        });
        
        var fld_payment_method = $('fld_payment_method');
        fld_payment_method.changehandler = function(){
            if (this.value=='debit'){
                $('payment_debit').style.display = 'block';
            }else{
                $('payment_debit').style.display = 'none';
            }
        }
        fld_payment_method.changehandler();
        fld_payment_method.addEvent('change', function(){
            this.changehandler();
            domready();
        });
        
        var fld_delivery_type = $('fld_delivery_type');
        fld_delivery_type.changehandler = function(){
            if (this.value=='subscription'){
                $('delivery_rhythm').style.display = 'block';
            }else{
                $('delivery_rhythm').style.display = 'none';
            }
        }
        fld_delivery_type.changehandler();
        fld_delivery_type.addEvent('change', function(){
            this.changehandler();
            domready();
        });
        
        var fld_deliveryaddress = $('fld_deliveryaddress');
        fld_deliveryaddress.changehandler = function(){
            if (this.value=='other'){
                $('deliveryaddress_other').style.display = 'block';
            }else{
                $('deliveryaddress_other').style.display = 'none';
            }
        }
        fld_deliveryaddress.changehandler();
        fld_deliveryaddress.addEvent('change', function(){
            this.changehandler();
            domready();
        });
        
        $$('.addProduct').each(function(item){
            item.addEvent('click', function(){
                var id = this.getParent().id;
                myObjects.consultant_order.action = '#' + id;
            });
        });
        
        $$('.deleteProduct').each(function(item){
            if (window.ie){
                item.name += 'Button';
            }
            item.addEvent('click', function(){
                deleteProductValue = window.ie ? getButtonTagValue(this) : this.value;
                if (window.ie){
                    new Element('input', {'type':'hidden', 'name':'deleteProduct', 'value':''}).injectInside(myObjects.consultant_order).value = deleteProductValue;
                }
                myObjects.consultant_order.action = '#' + 'productsection_' + deleteProductValue.split('_')[0];
            });
        });
        
        if (window.ie){
            $$('.submitOrder').each(function(item){
                item.name += 'Button';
                item.addEvent('click', function(){
                    new Element('input', {'type':'hidden', 'name':'submitOrder', 'value':'1'}).injectInside(myObjects.consultant_order);
                });
            });
        }
    }
}

function getButtonTagValue(buttonObj) {
    var regexObj = /<[^<]*value="([^"'<>]*)"[^>]*>/;
    var match = regexObj.exec(buttonObj.outerHTML);
    if (match != null && match.length > 1) {
        return match[1];
    } else {
        return '';
    }
}

// Anifit Cockpit
window.addEvent('domready', function() {
    if($('crm_consultant_cockpit')) {
        // replace content of h1 with content of h2
        $$('h1')[0].innerHTML = $$('h2')[0].innerHTML;
        $$('h2')[0].remove();
    }

    if($('clientportal_subscriptions')) {
        var showSubscriptionDetails = $$('a.showSubscriptionDetails');
        showSubscriptionDetails.each(function(item){
            createInfobox(item, $(item.rel));
        });
        $$('a.showSubscriptionDetails2').each(function(item){
            item.theBox = $(item.rel);
            item.addEvent('click', function(e){
                var event = new Event(e);
                if (!event.shift && !event.control && !event.alt && !event.meta){
                    event.stop();
                    this.theBox.show();
                }
            });
        });
   }
});

