$(document).ready(function() {
    if (typeof(locale) == 'undefined') {
        locale = "en";
    }
    var tinymceOpts = {
       script_url: '/bundles/hwsplatform/tinymce/tiny_mce.js',
        theme : "advanced",
        theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,formatselect",
        theme_advanced_buttons2 : "bullist,numlist,|,sub,sup,|,outdent,indent,|,undo,redo,|,pastetext",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_resizing : true,
        plugins: 'paste',
        paste_auto_cleanup_on_paste : true,
        paste_remove_styles: true,
        paste_remove_styles_if_webkit: true,
        paste_strip_class_attributes: true,
        paste_text_sticky : true,
        paste_postprocess : function(pl, o) {
            if (pl.editor.pasteAsPlainText) {
                // If in plain-text mode, Remove the paragraphs but append the trimmed text trailed by one whitespace
                var content = $(o.node);
                o.node.innerHTML = content.text().replace('\n', '');
            }
        },
        //select pasteAsPlainText on startup
        setup : function(ed) {
            ed.onInit.add(function(ed) {
                ed.pasteAsPlainText = true;
            });
        },
        mode: 'specific_textareas',
        editor_selector: 'nicedit'
    };

    var searchForm = $(".search");
    searchForm.find('select').change(function() {
        searchForm.submit();
    });

    // show login box on profile detail screen
    $("#showLogin").click(function() {
        $("#inlineLoginBox").show();
    });

    // help tooltips
    var helps = $(".help");
    helps.find("dt a").click(function() {
        var dt = $(this).parent();
        dt.toggleClass('visible');
        dt.next("dd").toggleClass('visible');
        return false;
    });

    // dashboard tabs and ajax functionality.
    $("#hws-dashboard-tabs").tabs();
    var changeVisibility = function() {
        $.ajax({
            url: $(this).attr('href'),
            success: function() {
                $("#hws-dashboard-tabs").tabs("load", $("#hws-dashboard-tabs").tabs('option', 'selected'));
            }
        });
        return false;
    };
    var profileDeleteDialog = $('<div id="profileDeleteDialog"></div>');
    profileDeleteDialog.appendTo("body");
    profileDeleteDialog.dialog({autoOpen:false, title: "Delete profile?", width: 400});
    var profileDelete = function() {
        $.ajax({
            url: $(this).attr('href'),
            success: function(data) {
                profileDeleteDialog.html(data).dialog('open');
                data.find('form').submit(function() {
                    $.ajax({
                        url: $(this).attr('action'),
                        type: 'POST',
                        success: function() {
                            profileDeleteDialog.dialog('close');
                            $("#hws-dashboard-tabs").tabs("load", $("#hws-dashboard-tabs").tabs('option', 'selected'));
                        }
                    })
                });
            }
        });
        return false;
    };
    $("#hws-dashboard-tabs").ajaxSuccess(function() {
        $("a.profile_toggle_visibility").unbind('click', changeVisibility).bind('click', changeVisibility);
        $("a.profile_delete").unbind('click', profileDelete).bind('click', profileDelete);
    });

    $(".choice_group a.mark_all").click(function() {
        $(this).parents(".choice_group").find('input[type="checkbox"]').attr('checked', true);
        return false;
    });
    $(".choice_group a.unmark_all").click(function() {
        $(this).parents(".choice_group").find('input[type="checkbox"]').attr('checked', false);
        return false;
    });

    $(".help-tooltip").each(function() {
        var content = $(this).attr('title');
        $(this).attr('title', '');
        $(this).qtip({
            position: {corner: {target: 'bottomLeft', tooltip: 'topRight'}},
            content:content,
            style: {
                tip:true,
                padding:5,
                fontSize: "12pt",
                name:'cream',
                width: 420
            },
            hide: {
                fixed: true
            }
        });
    });

    /** Display the alternative translation fields yes or no depending on the radio "hasAlternative" */
    $("#profile_hasAlternative").find("input").change(function() {
        var displayFn;
        if ($("#profile_hasAlternative").find("input:checked").val() == 1) {
            displayFn = function() {
                $(this).show();
            };
        } else {
            displayFn = function() {
                $(this).hide();
            };
        }

        $("#profile_hasAlternative_row").nextUntil('#profile_keywordsAlt_row').each(displayFn).next().each(displayFn);
    }).trigger('change');

    var isDev = window.location.href.indexOf('main_dev') != -1;
    var profileId = $("article").attr('data-profile-id');
    var trackingUrl = isDev ? '/main_dev.php' : '';
    if (typeof profileId == 'undefined') {
        trackingUrl += '/trk.gif';
    } else {
        trackingUrl += '/trk.gif?profile=' + profileId;
    }
    $.ajax({url: trackingUrl, type: 'POST'});

    $("#alert").each(function() {
        var alertForm = $(this);
        var keywords = alertForm.find('#alert_keywords').val();
        var name = alertForm.find('#alert_name').val();
        var allowChange = (keywords == name);

        alertForm.find('#alert_keywords').keyup(function() {
            if (allowChange) {
                alertForm.find('#alert_name').attr( 'value', alertForm.find('#alert_keywords').val().replace("\n", ", ") );
            }
        });
        $(this).find('#alert_name').keyup(function() {
            allowChange = false;
        });
    });

    tinyMCE.init(tinymceOpts);

    var opts = {'format': 'm/d/Y'};
    if (typeof(locale) != 'undefined' && locale == "de") {
        opts = {
            closeText: 'schließen',
            prevText: '&#x3c;zurück',
            nextText: 'Vor&#x3e;',
            currentText: 'heute',
            monthNames: ['Januar','Februar','März','April','Mai','Juni',
            'Juli','August','September','Oktober','November','Dezember'],
            monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
            'Jul','Aug','Sep','Okt','Nov','Dez'],
            dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
            dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
            dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
            weekHeader: 'Wo',
            dateFormat: 'dd.mm.yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        };
    }
    opts.changeYear = true;
    opts.changeMonth = true;
    $(".datepicker").datepicker(opts);

    if (typeof(hws) != 'undefined' && typeof(hws.noteProviderUrl) != 'undefined') {
        $("article[data-profile-id]").each(function() {
            var id = $(this).attr('data-profile-id');
            $(this).hwsNotes({url: hws.noteProviderUrl, 'type': 'profile', 'id': id});
        });
        $("div[data-user-id]").each(function() {
            var id = $(this).attr('data-user-id');
            $(this).hwsNotes({url: hws.noteProviderUrl, 'type': 'user', 'id': id});
        });
    }
});

function decryptCharcode(n,start,end,offset){n=n+offset;if(offset>0&&n>end){n=start+(n-end-1);}else if(offset<0&&n<start){n=end-(start-n-1);}
return String.fromCharCode(n);}
function decryptString(enc,offset){var dec="";var len=enc.length;for(var i=0;i<len;i++){var n=enc.charCodeAt(i);if(n>=0x2B&&n<=0x3A){dec+=decryptCharcode(n,0x2B,0x3A,offset);}else if(n>=0x40&&n<=0x5A){dec+=decryptCharcode(n,0x40,0x5A,offset);}else if(n>=0x61&&n<=0x7A){dec+=decryptCharcode(n,0x61,0x7A,offset);}else{dec+=enc.charAt(i);}}
return dec;}
function linkTo_UnCryptMailto(s){location.href=decryptString(s,-3);}

