﻿//define URLs
$.efapers.baseUrl = "/Personalization";
$.efapers.serviceUrl = "/efaservice";

var tempUserID = $.efapers.guid,
    service_domain = 'http://62.50.117.10:8888',
    proxied_domain = 'http://www2.vvs.de',
    //service_domain = 'tfl-mobile:8888',
    //proxied_domain = 'schriefel',
    mdvProfile, 
    mdvAccountSettings, 
    mdvRegistration, 
    mdvNotification, 
    empty_func = function () {},
    markupFindStop = '<option value="${stateless}">${name}</option>',
    markupFindLine = '<option value="${mode.diva.network}:${mode.diva.line}|${mode.diva.dir}">${mode.name} - ${mode.desc}</option>',
    markupDisplayMonitoredStop = '<tr id="Point(${ID}M)"><td>${Position}</td><td>${Name}</td><td class="center"><img src="./images/icon.loeschen.png" title="Löschen" alt="" class="trashImg"/></td></tr>',
    // we cannot use $.template with this one
    markupMonitoredLine = '<tr id="Service(#ID#M)"><td>#Description# </td><td class="center"><img src="./images/icon.loeschen.png" title="Löschen" alt="" class="trashImg"/></td></tr>';

// prepare templates
$.template("findLineTemplate", markupFindLine);
$.template("findStopTemplate", markupFindStop);
$.template("displayMonitoredStopTemplate", markupDisplayMonitoredStop);

function getPersonFromForm() {
    return {
        'Name': $("#surname").val(),
        'FirstName': $("#name").val(),
        'Email': $("#email").val()
    };
}

function getNotificationFromForm() {
    // 0=keine Benachrichtigung, 1=email, 2=sms, 4=email+sms
    var sms = $('#messagesms').attr('checked'),
        email = $('#messageemail').attr('checked');
    if (sms && email) {
        return '4';
    }
    if (sms) {
        return '2';
    }
    if (email) {
        return '1';
    }
    return '0';
}

function getPersonRegisterFromForm() {
    return {
        'Username': $("#username").val(),
        'Password': $("#password").val(),
        'Language': 'de',
        'Notification': getNotificationFromForm(),
        'SelectedDays': '255',
        'Data': getPersonFromForm()
    };
}

function getMobileNumber(s) {
    // remove all blanks, dots, dashes, brackets
    var clean_mobile = s.replace(/[ \.\-\(\)]/g, '');
    // anything left and a number with at least 8 digits and nothing else?
    if (clean_mobile.length > 0 && /^[1-9]{1}\d{7,14}$/.test(clean_mobile)) {
        return clean_mobile;
    } else {
        return null;
    }
}

function getCountryCode(s) {
    // accept +49, 0049, 001, +1, 00333, +333
    if (/^(\+|00)[1-9]{1,3}$/.test(s)) {
        // return only the country code as str
        return s.replace(/^(?:\+|00)/, '');
    } else {
        return null;
    }
}
$(document).ready(function () {
    var addOnEnter;
    
    // create objects
    mdvProfile = new MDVProfile();
    mdvAccountSettings = new MDVAccountSettings();
    mdvRegistration = new MDVRegistration();
    mdvNotification = new MDVNotification();
    
    if (/.*viewPage=monitored(Lines|Stops)$/.test(window.location.href)===true) {
        // prevent submitting of form on ENTER key
        $(document).keydown(function (event) {
            if (event.keyCode !== 13) {
                return;
            }
            event.preventDefault();
            return false;
        });
        // update monitoring ?
        $(window).unload(function() {
            if (mdvNotification.isModified) {
                 // notify monitoring service
                $.efapers.updateMonitoring({
                    url: $.efapers.serviceUrl + '/CHANGE_PROFILEMONITORING?type=MONITORING',
                    success: empty_func,
                    error: empty_func
                });
            }
        });
    }
    // trigger func on enter
    addOnEnter = function (func) {
        $(document).keyup(function (event) {
            if (event.keyCode !== 13) {
                return;
            }
            event.preventDefault();
            func();
            return false;
        });
    };
    
    
    // initialize pages
    if ($('#displayAccountSettings').length == 1) {
        mdvAccountSettings.getAccountSettings();
    }
    if ($('#monitoredStops').length == 1) {
        mdvNotification.getMonitoredStops();
        addOnEnter(mdvNotification.findStop);
    }
    if ($('#monitoredLines').length == 1) {
        mdvNotification.getMonitoredLines();
        addOnEnter(mdvNotification.findLine);
    }
});


function MDVProfile() {}


MDVProfile.prototype.logoff = function () {
    $.cookie("Authorization", null);
    $.cookie("EFA_User", null);
    location.href = 'XSLT_TRIP_REQUEST2?language=de';
};


MDVProfile.prototype.getPersonalDataForCookie = function (obj) {
    $.efapers.selectObject({
        uri: obj.PersonalData.__deferred.uri.replace(service_domain, proxied_domain),
        success: function (msg) {
            var username = msg.d[0].FirstName + ' ' + msg.d[0].Name + '#' + $('#usernameLogin').val();
            $.cookie("EFA_User", username);
            location.href = 'XSLT_REQUEST?language=de&itdLPxx_viewPage=loginSuccess';
        },
        error: empty_func
    });
};


MDVProfile.prototype.delObjWithUri = function (uriPart) {
    $.efapers.deleteObject({
        uri: $.efapers.baseUrl + '/Data/' + uriPart,
        success: empty_func,
        error: empty_func
    });
}


function MDVRegistration() {

}


MDVRegistration.prototype.login = function () {
    $.cookie("Authorization", null);
    $('#errorLogin').css('display', 'none')
    $.efapers.authenticate({
        username: $('#usernameLogin').val(),
        password: $('#passwordLogin').val(),
        success: function (msg) {
            if ($.cookie('Authorization')) {
                mdvProfile.getPersonalDataForCookie(msg.d[0]);
            }
        },
        error: function (msg) {
            $('#errorLogin').css('display', 'block');
        }
    });
};


// validate fields
MDVRegistration.prototype.beforeRegister = function () {
    
    var info = $('#alreadyExists'),
        email = $('#email').val(),
        email_pattern = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/,
        mobile_number = $('#mobilenumber').val(),
        country_code = $('#countrycode').val(),
        clean_mobile = getMobileNumber(mobile_number),
        clean_code = '49';
    // we need this in register()   
    this.mobilePhone = '';
    
    if ($('#username').val().length < 6) {
        info.html('Benutzername zu kurz.').toggle();
        return false;
    }
    if ($('#password').val().length < 6) {
        info.html('Passwort zu kurz.').toggle();
        return false;
    }
    if ($('#password').val() !== $('#password2').val()) {
        info.html('Passwort fehlerhaft. Bitte prüfen Sie Ihre Eingaben.').toggle();
        return false;
    }
    if ($('#name').val().length < 1) {
        info.html('Bitte geben Sie einen Vornamen an.').toggle();
        return false;
    }
    if ($('#surname').val().length < 1) {
        info.html('Bitte geben Sie einen Nachnamen an.').toggle();
        return false;
    }
    if (email.length < 1 || email_pattern.test(email) === false) {
        info.html('Bitte geben Sie eine gültige E-Mail-Adresse an.').toggle();
        return false;
    }
    if (clean_mobile) {
        this.mobilePhone = clean_code + '|' + clean_mobile;
    }
    info.hide();
    mdvRegistration.register();
};


MDVRegistration.prototype.register = function () {
    $.cookie("Authorization", null);
    // mobile phone isn't part of personal data -
    // save as cookie to store upon profile activation.
    if (this.mobilePhone) {
        $.cookie('mobilePhone', this.mobilePhone, {
            expires: 30
        });
    }
    $.efapers.register({
        registerData: JSON.stringify(getPersonRegisterFromForm()),
        success: function (msg) {
            if (msg.RegisterCredentialsResult == 'UsernameAlreadyExists') {
                $('#alreadyExists').css('display', 'block');
            } else {
                location.href = 'XSLT_REQUEST?language=de&itdLPxx_viewPage=registerSuccess';
            }
        },
        error: empty_func
    });
};


MDVRegistration.prototype.activate = function () {
    var identID = $('#IdentificationID').val();

    $.cookie("Authorization", null);
    $.efapers.activate({
        data: JSON.stringify({
            IdentificationID: identID
        }),
        success: function (msg) {
            var mobile_data;
            if (msg.ActivateCredentialsResult == 'AccessDenied') {
                $('#error').css('display', 'block')
            } else {
                mobilePhone = $.cookie('mobilePhone');
                if (mobilePhone) {
                    mobile_data = mobilePhone.split('|');
                    $.efapers.createMobilePhone({
                        data: JSON.stringify({
                            Number: mobile_data[1],
                            CountryCode: mobile_data[0]
                        }),
                        sucess: function() {
                            $.cookie('mobilePhone', null);
                            document.location.href = "XSLT_REQUEST?language=de&itdLPxx_viewPage=loginSuccess";
                        },
                        // failure isn't critical here
                        error: function() {
                            this.success()
                        }
                    });
                }
                document.location.href = "XSLT_REQUEST?language=de&itdLPxx_viewPage=loginSuccess";
            }
        },
        error: function (msg) {
            $('#error').show();
        }
    });
};


MDVRegistration.prototype.resendPassword = function () {
    $.cookie("Authorization", null);
    $.efapers.sendPassword({
        data: JSON.stringify({
            Username: $('#email').val()
        }),
        success: function (msg) {
            if (msg.SendPasswordResult === 'Success') {
                $('#errorPW').hide();
                $('#contentPW').hide();
                $('#successPW').show();
            } else {
                $('#errorPW').show();
            }
        },
        error: empty_func
    });
};


function MDVAccountSettings() {
    this.user = null;
    this.uri = null;
}


MDVAccountSettings.prototype.getAccountSettings = function () {
    $.efapers.getProfile({
        success: function (msg) {
            if (msg.d[0] !== undefined) {
                $.efapers.selectObject({
                    uri: msg.d[0].PersonalData.__deferred.uri.replace(service_domain, proxied_domain),
                    success: function (msg) {
                        mdvAccountSettings.uri = msg.d[0].__metadata.uri.replace(service_domain, proxied_domain);
                        mdvAccountSettings.displayAccountSettings(msg.d[0]);
                    },
                    error: empty_func
                });
            }
        },
        error: empty_func
    });
};


MDVAccountSettings.prototype.displayAccountSettings = function (obj) {
    $('#name').val(obj.FirstName)
    $('#surname').val(obj.Name)
    $('#email').val(obj.Email)
};


// Change name or password
MDVAccountSettings.prototype.updateUserRequest = function (obj) {
    var username = $.cookie("EFA_User").substring($.cookie("EFA_User").indexOf('#')),
        realName = $("#name").val() + ' ' + $("#surname").val(),
        _data = JSON.stringify(getPersonFromForm());

    $('#realUserName').html(realName);
    $.cookie("EFA_User", realName + username);
    $.efapers.updateObject({
        uri: this.uri,
        data: _data,
        success: function (msg) {
            $('#myDataMessage').html('Die Daten wurden aktualisiert.');
            $('#myDataMessage').show();
        },
        error: function (msg) {
            if (msg.responseText === '') {
                this.success();
            }
        }
    });
    if ($('#password').val() != '' || $('#password2').val() != '') {
        this.changePassword();
    }
};


MDVAccountSettings.prototype.changePassword = function () {
    var _data;

    if ($('#oldPassword').val() === '') {
        $('#myDataMessage').html('Bitte überprüfen Sie Ihr Passwort!');
        $('#myDataMessage').css('display', 'block');
    } else if ($('#password').val() !== $('#password2').val()) {
        $('#myDataMessage').html('Bitte überprüfen Sie Ihr Passwort!');
        $('#myDataMessage').css('display', 'block');
    } else {
        _data = {
            Username: $('#username').val(),
            OldPassword: $('#oldPassword').val(),
            NewPassword: $('#password2').val()
        };
        $.efapers.changePassword({
            uri: this.uri,
            passwordData: JSON.stringify(_data),
            success: function (msg) {
                if (msg.ChangePasswordResult === 'Success') {
                    $('#myDataMessage').html('Passwort geändert!');
                    $('#myDataMessage').css('display', 'block');
                }
            },
            error: function (msg) {
                $('#myDataMessage').html('Bitte überprüfen Sie Ihr Passwort!');
                $('#myDataMessage').css('display', 'block');
            }
        });
    }
};


MDVAccountSettings.prototype.deleteProfile = function () {
    var user = $.base64.decode($.cookie("Authorization").replace('Basic ', '')).split(':'),
        _data = {
            Username: user[0],
            Password: user[1]
        };
    $.efapers.deleteProfile({
        deleteData: JSON.stringify(_data),
        success: function (msg) {
            location.href = 'XSLT_TRIP_REQUEST2?language=de';
        },
        error: empty_func
    });
};



function MDVNotification() {
    this.profile = null;
    this.mobileUri = null;
    this.mobileExisting = null;
    this.oldNotification = '';
    this.oldNumber = '';
    this.isModified = false;
    this.success_msg = 'Ihre Daten wurden erfolgreich aktualisiert.';
    this.error_msg = 'Das Aktualisieren der Daten ist leider fehlgeschlagen.'
}


// activate / deactivate notification settings
MDVNotification.prototype.activate = function () {
    var _data, 
        _notification, 
        info = $('#myDataMessage'),
        sms = $('#messagesms'),
        email = $('#messageemail'),
        mobile_val = $('#mobilenumber').val(),
        notification_val = getNotificationFromForm(),
        cc_val = '49';
    
    // enforce valid mobile number for SMS
    if (notification_val > 1) {
        if (mobile_val.length === 0) {
            info.html('Bitte geben Sie eine Telefonnummer an.').show();
            return false;
        }
        if (getMobileNumber(mobile_val) === null) {
            info.html('Die eingegebene Telefonnummer hat kein gültiges Format (Nummer ohne vorangestellte 0, mindestens 8 Stellen).').show();
            return false;
        }
    }
    info.hide();
    // handle mobile phone number
    if (mobile_val !== this.oldNumber) {
        _data = JSON.stringify({
            Number: mobile_val,
            CountryCode: cc_val
        });
        if (this.mobileExisting === true) {
            $.efapers.updateObject({
                uri: this.mobileUri.replace(service_domain, proxied_domain),
                data: _data,
                success: function (msg) {
                    info.html(this.success_msg).show();
                }.bind(this),
                error: function (msg) {
                    info.html(this.error_msg).show();
                }.bind(this)
            });
        } else {
            $.efapers.createMobilePhone({
                data: _data,
                success: function (msg) {
                    info.html(this.success_msg).show();
                }.bind(this),
                error: function (msg) {
                    info.html(this.error_msg).show();
                }.bind(this)
            });
        }
    }
    // handle notification type
    if (notification_val !== this.oldNotification) {
        _notification = JSON.stringify({
            Notification: notification_val,
            Language: 'de'
        });
        $.efapers.updateObject({
            uri: this.profile.__metadata.uri.replace(service_domain, proxied_domain),
            data: _notification,
            success: function (msg) {
                info.html(this.success_msg).show();
            }.bind(this),
            error: function (msg) {
                info.html(this.error_msg).show();
            }.bind(this)
        });
    }
};


MDVNotification.prototype.getMobileNumber = function () {
    $.efapers.getProfile({
        success: function (msg) {
            if (msg.d[0] !== undefined) {
                mdvNotification.displayNotification(msg.d[0]);
                $.efapers.selectObject({
                    uri: msg.d[0].MobilePhones.__deferred.uri.replace(service_domain, proxied_domain),
                    success: function (msg) {
                        if (msg.d[0]) {
                            mdvNotification.displayMobileNumber(msg.d[0])
                        }
                    },
                    error: empty_func
                });
            }
        },
        error: empty_func
    });
};


MDVNotification.prototype.displayNotification = function (obj) {
    var sms = $('#messagesms'),
        email = $('#messageemail');

    this.profile = obj;
    this.oldNotification = obj.Notification;
    
    // 0=keine Benachrichtigung, 1=email, 2=sms, 4=email+sms
    if (obj.Notification == '4') {
        sms.attr('checked', true);
        email.attr('checked', true);
        return;
    }
    if (obj.Notification == '2') {
        sms.attr('checked', true);
        email.attr('checked', false);
        return;
    }
    if (obj.Notification == '1') {
        sms.attr('checked', false);
        email.attr('checked', true);
        return;
    }
    sms.attr('checked', false);
    email.attr('checked', false);
};


MDVNotification.prototype.displayMobileNumber = function (obj) {
    this.mobileUri = obj.__metadata.uri;
    this.mobileExisting = true;
    this.oldNumber = obj.Number;
    $('#mobilenumber').val(obj.Number);
};


//display user data in the user interface
MDVNotification.prototype.findStop = function () {
    var pointId, 
        name, 
        _params, 
        info = $('#myDataMessage').empty().hide();
        
    if ($('#monitorStop').css('display') == 'block') {
        pointId = $('#monitorStop').val();
        name = $('#monitorStop option:selected').text();
        mdvNotification.monitorStop(pointId, name);
        $('#neueSuche').hide();
        $('#abo').text('Suchen');
        return;
    }
    _params = {
        language: 'de',
        locationServerActive: '1',
        anyObjFilter_sf: '2',
        type_sf: 'any',
        name_sf: $('#monitorOdvName').val(),
        stateless: '1',
        outputFormat: 'JSON'
    };
    $.ajax({
        type: "POST",
        url: "XML_STOPFINDER_REQUEST",
        data: _params,
        success: function (response) {
            var sf, efa;
            try {
                efa = JSON.parse(response);
            } catch (e) {
                info.html('Die Antwort kann leider nicht verarbeitet werden (JSON ' + e.name + ').').show();
                return;
            }
            sf = efa.stopFinder;
            // build list
            if (sf.length > 1) {
                $('#monitorStop').html('')
                $('#monitorStop').css('display', 'block')
                $('#inputStop').css('display', 'none')
                $.tmpl("findStopTemplate", sf).appendTo("#monitorStop");
                $('#neueSuche').show();
                $('#abo').text('Abonnieren');
                return;
            }
            // full hit
            if (sf.length === 1) {
                mdvNotification.monitorStop(sf[0].stateless, sf[0].name);
                $('#neueSuche').hide();
                $('#abo').text('Suchen');
                return;
            }
            // empty result
            if (sf.length === 0) {
                info.html('Ihre Eingabe ergab keinen Treffer.').show();
            }
        },
        error: empty_func
    });
}
MDVNotification.prototype.findLine = function () {
    var opt_val, 
        opt_txt,
        desc,
        line,    
        _params, 
        info = $('#myDataMessage').empty().hide();
    //select list is visible, submit current entry
    if ($('#monitorLine').css('display') == 'block') {
        opt_val = $('#monitorLine').val();
        desc = $('#monitorLine option:selected').text();
        opt_val = opt_val.split('|');
        opt_txt = desc.split(' - ');
        line = {
            ServiceID : opt_val[0],
            Description : desc,
            Name : opt_txt[0] + ' ' + opt_val[1]
        };
        mdvNotification.monitorLine(line);
        $('#neueSuche').hide();
        $('#abo').text('Suchen');
        return;
    }
    // verify input
    _params = {
        language: 'de',
        deleteAllLines: '1',
        mergeDir: '1',
        mergeSup: '1',
        lineName: $('#monitorLineName').val(),
        lineReqType: '1',
        outputFormat: 'JSON'
    };
    $.ajax({
        type: "POST",
        url: "XML_SELTT_REQUEST",
        data: _params,
        success: function (response) {
            var input, 
                buf = {},
                m = [], 
                efa, 
                _serviceId, 
                _name;
            try {
                efa = JSON.parse(response);
            } catch (e) {
                info.html('Die Antwort kann leider nicht verarbeitet werden (JSON ' + e.name + ').').show();
                return;
            }
            
            // make lines unique (only H or R) until mergeDir is available
            $(efa.modes).each(function(idx, elem) {
                var diva = elem.mode.diva;
                if (buf[diva.network + diva.line] === undefined) {
                    buf[diva.network + diva.line] = 1;
                    m.push(elem);
                }
            });
            // build select list
            if (m.length > 1) {
                $('#monitorLine').html('');
                $('#monitorLine').css('display', 'block');
                $('#inputLine').css('display', 'none');
                $.tmpl("findLineTemplate", m).appendTo("#monitorLine");
                $('#neueSuche').show();
                $('#abo').text('Abonnieren');
                return;
            }
            // handle full hit
            if (m.length === 1) {
                line = {
                    ServiceID : m[0].mode.diva.network + ':' + m[0].mode.diva.line,
                    Description : m[0].mode.name + ' - ' + m[0].mode.desc,
                    Name : m[0].mode.name + ' ' + m[0].mode.diva.dir
                };
                mdvNotification.monitorLine(line);
                $('#neueSuche').hide();
                $('#abo').text('Suchen');
                return;
            }
            // no hit
            if (m.length === 0) {
                info.html('Ihre Eingabe ergab keinen Treffer.').show();
            }
        },
        error: empty_func
    });
};


MDVNotification.prototype.monitorStop = function (pointId, name) {
    var point, 
        type = 'monitored';
    
    if (!pointId || !name) {
        return;
    }
    $('#myDataMessage').hide();
    point = {
        PointID: pointId,
        Type: '7',
        Name: name,
        Usage: '' + $.efapers.restriction[type] // cast as str
    };
    $.efapers.createPoint({
        point: JSON.stringify(point),
        success: function (msg) {
            var txt, 
                msgTxt = {
                    'MaxMonitoredPoints': 'Die maximale Anzahl ist bereits erreicht.',
                    'PointAlreadyUsed': 'Die Haltestelle ist bereits abonniert.'
                };
            if (msg.error && msg.error.message) {
                txt = msgTxt[msg.error.code] || msg.error.message.value;
                $('#myDataMessage').html(txt).show();
            } else {
                $('#monitorStop').empty().hide();
                $('#inputStop').show();
                $('#monitorOdvName').val('Haltestelle');
                mdvNotification.isModified = true;
                mdvNotification.getMonitoredStops();
            }
        },
        error: empty_func
    });
};


MDVNotification.prototype.monitorLine = function (line) {
    var service, 
        type = 'monitored';
    
    if (!line) {
        return;
    }
    $('#myDataMessage').hide();
    
    service = line;
    service.Usage = '' + $.efapers.restriction[type]; // cast as str

    $.efapers.createService({
        service: JSON.stringify(service),
        success: function (msg) {
            var txt, 
                msgTxt = {
                    'MaxMonitoredServices': 'Die maximale Anzahl der überwachten Linien ist bereits erreicht.',
                    'ServiceAlreadyUsed': 'Die Linie ist bereits abonniert.'
                };
            if (msg.error && msg.error.message) {
                txt = msgTxt[msg.error.code] || msg.error.message.value;
                $('#myDataMessage').html(txt).show();
            } else {
                $('#monitorLine').empty().hide();
                $('#inputLine').show();
                $('#monitorLineName').val('Linie');
                mdvNotification.isModified = true;
                mdvNotification.getMonitoredLines();
            }
        },
        error: empty_func
    });
};


MDVNotification.prototype.getMonitoredStops = function (type) {
    $.efapers.selectObject({
        uri: $.efapers.baseUrl + '/Data/Point?$filter=Usage eq 7&$orderby=Position',
        success: function (msg) {
            $("#savedMonitoredStops").empty();
            if (msg.d.length > 0) {
                $.tmpl("displayMonitoredStopTemplate", msg.d).appendTo("#savedMonitoredStops");
                // delete link
                $('#savedMonitoredStops .trashImg').click(function () {
                    var uri = this.parentNode.parentNode.id;
                    document.getElementById(uri).style.display = 'none';
                    mdvProfile.delObjWithUri(uri);
                });
            } else {
                $('#savedMonitoredStops').html('<tr><td colspan="2">Keine Haltestellen abonniert.</td></tr>');
            }
        },
        error: empty_func
    });
};


MDVNotification.prototype.getMonitoredLines = function (type) {
    $.efapers.selectObject({
        uri: $.efapers.baseUrl + '/Data/Service?$filter=Usage eq 7&$orderby=Name',
        success: function (msg) {
            $("#savedMonitoredLines").empty();
            if (msg.d.length > 0) {
                var html = '';
                $(msg.d).each(function(idx, obj) {
                    html += markupMonitoredLine.replace(/#(ID|Description)#/g, function(fullhit, cg) {
                        if (cg==='ID') {
                            return obj.ID;
                        }
                        // desc starts with name (e.g. "Bus 101 H")-> newly created
                        if (obj.Description.indexOf(obj.Name.slice(0,-2))===0) {
                            return obj.Description;
                        }
                        // desc without name -> imported
                        return obj.Name + ' - ' + obj.Description;
                    }); 
                })
                $(html).appendTo('#savedMonitoredLines');
                //$.tmpl("displayMonitoredLinesTemplate", msg.d).appendTo("#savedMonitoredLines");
                // delete link
                $('#savedMonitoredLines .trashImg').click(function () {
                    var uri = this.parentNode.parentNode.id;
                    document.getElementById(uri).style.display = 'none';
                    mdvProfile.delObjWithUri(uri);
                });
            } else {
                $('#savedMonitoredLines').html('<tr><td colspan="2">Keine Linien vorhanden.</td></tr>');
            }
        },
        error: empty_func
    });
};
