// edited_page: initialiseren variabele zodat deze kan worden gebruikt om te 'tracken' of men een pagina verlaat zonder op te slaan.  
var edited_page;
function getParentNode(node, tag)
{
    tmpNode = node;
    tag = tag.toLowerCase();

    while(tmpNode && tmpNode.parentNode && tmpNode.tagName && tmpNode.tagName.toLowerCase()!=tag)
        tmpNode = tmpNode.parentNode;

    if(tmpNode && tmpNode.tagName && tmpNode.tagName.toLowerCase()==tag)
        return tmpNode;
    else
        return null;
}

function getById(divID, oDoc) {
    if( document.getElementById )
    {
        return document.getElementById(divID);
    }if( document.all )
        return document.all[divID];
    if( !oDoc ) {oDoc = document;}
    if( document.layers )
    {
        if( oDoc.layers[divID] )
            return oDoc.layers[divID];
        else
        {
            //repeatedly run through all child layers
            for( var x = 0, y; !y && x < oDoc.layers.length; x++ )
            {
                //on success, return that layer, else return nothing
                y = getById(divID, oDoc.layers[x].document);
            }
            return y;
        }
    }
    alert("(functions.js) : Invalid element: " + id);
    return null;
}

function getElementsByClass(searchClass,node,tag) 
{
    var classElements = new Array();
    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function selectField(field) {
    try {
        el = getById(field);
        el.focus()
        el.select();
        therange=el.createTextRange();
        return true;
    }catch(e) {}
    return false;
}

function toggleSubscribers(n, mid)
{
    if(typeof n == 'undefined') n = 'mailing-step-4';
    el = document.forms[n].elements['subscribers'];
    sel = '';
    for(i=0;i<el.length;i++)
        if(el[i].checked)
            sel = el[i].value;

    el = getById('gids');
    if(el)
    {
        el.style.display = (sel=='groups'?'block':'none');
        el.disabled = (sel!='groups');
    }
    el = getById('tas');
    if(el)
    {
        el.style.display = (sel=='test'?'block':'none');
        el.disabled = (sel!='test');
    }
    el = getById('splitrun');
    if(el)
    {
        // Waarom stond dit er? Dan kan de splitrun optie uit worden gezet, maar dit kan niet als hij eenmaal is aangemaakt
        // srDisabled = (sel=='segments' || sel=='zombie');
        // el.style.display = (srDisabled?'none':'block');
        // el = getById('use_splitrun');
        // if(el) el.disabled = srDisabled;
    }
    el = getById('zombiemail_desc');
    if(el)
    {
        el.style.display = ((sel=='zombie')?'block':'none');
    }

    if(document.forms[n].elements['sendRest']) {
        document.forms[n].elements['sendRest'].value = mid;
    }
}
function parsePie(pp, p)
{
    document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="125" height="125" id="circle" align="middle">');
    document.write('<param name="allowScriptAccess" value="sameDomain" />');
    document.write('<param name="movie" value="'+pp+'img/circle.swf?p='+p+'" />');
    document.write('<param name="quality" value="high" />');
    document.write('<param name="bgcolor" value="#ffffff" />');
    document.write('<embed src="'+pp+'img/circle.swf?p='+p+'" quality="high" bgcolor="#ffffff" width="125" height="125" name="circle" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.write('</object>');
}
function toggleType(el)
{
    var tmp = getById("textrow");
    tmp.style.display = (el.value=="h")?"none":"block";
    tmp = getById("textrow2");
    tmp.style.display = (el.value=="h")?"none":"block";
    tmp = getById("htmlrow");
    tmp.style.display = (el.value=="t")?"none":"block";
    tmp = getById("htmlrow2");
    tmp.style.display = (el.value=="t")?"none":"block";
}

function toggleLiveFeedType(type)
{
    types = new Array("url", "mysql", "mail");
    for(var i=0;i<types.length;i++)
    {
        el = getById("livefeed_" + types[i]);
        if(el)    el.style.display = (type==types[i])?"block":"none";
    }
}

function setHiddenOptionValue(hiddenfield, selectbox, addHTMLSep) 
{
    hiddenfield.value = getHiddenOptionValue(selectbox, addHTMLSep);
}

function getHiddenOptionValue(selectbox, addHTMLSep) 
{
    value = "";
    separator = "**";
    for(i=0;i<selectbox.length;i++)
    {
        add = "";
        if(typeof addHTMLSep != "undefined")
            add = addHTMLSep + selectbox[i].innerHTML;
        value += (value!=''?separator:'') + selectbox[i].value + add;
    }
    return value;
}


/* Vrije velden*/
function changeExtraVeldType(type) {
    el = document.forms['ff'].elements['type'];
    if(el)
    for(i=0;i<el.length;i++) {
        el2 = getById("standaard_waarde_" + el[i].value);
        if(el2)
            el2.style.display = (type==el[i].value)?"block":"none";
    }
}
function addExtraVeldSelection(f, name, forceVal) {
    if(typeof f == 'undefined') f = 'ff';
    if(typeof name == 'undefined') name = 'tmp_standaard_waarde_selection';
    var elOptNew = document.createElement('option');

    val = document.forms[f].elements['tmp_value'].value;
    if(typeof forceVal == 'undefined') forceVal = val;

    elOptNew.text = val;
    elOptNew.value = forceVal;
    var elSel = document.forms[f].elements[name];

    if(f!='ff' || (elSel.length<63))
    {
        //alert(elOptNew.value +"    " + elOptNew.text);
        try {
            elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch(ex) {
            elSel.add(elOptNew); // IE only
        }
        document.forms[f].elements['tmp_value'].value = '';
    }else
    {
        alert(LANG_ERROR_MAX_OPTIONS_REACHED);
    }
}
function changeExtraVeldSelection(f, name, setVal) {
    if(typeof f == 'undefined') f = 'ff';
    if(typeof name == 'undefined') name = 'tmp_standaard_waarde_selection';
    if(typeof setVal == 'undefined') setVal = true;

    var val = document.forms[f].elements['tmp_value'].value;
    var elSel = document.forms[f].elements[name];
    try {
        del = elSel.selectedIndex;
        if(del==-1 && elSel.length>0)
            del = 0;
        if(del!=-1) {
            if(setVal) elSel[del].value = val;
            elSel[del].innerHTML = val;
            //alert(elSel[del].value +"    " + elSel[del].innerHTML);

            maxV = 0;
            for(var i=0;i<elSel.length;i++)
                maxV = Math.max(maxV, elSel[i].innerHTML.length);
            elSel.style.width = Math.max(maxV * 8, 20)+"px";
        }
    }
    catch(ex)
    {
    }
}
function removeExtraVeldSelection(f, name) {
    if(typeof f == 'undefined') f = 'ff';
    if(typeof name == 'undefined') name = 'tmp_standaard_waarde_selection';
    var elSel = document.forms[f].elements[name];
    try {
        del = elSel.selectedIndex;
        if(del==-1 && elSel.length>0)
            del = 0;
        elSel.remove(del);
    }
    catch(ex) {
    }
}
/* / Vrije velden*/
helpWin = newWin = null;
function openHelp(url)
{
    newWin = openCenteredWindow(url, 'newWin', 710, 600, 'directories=0,location=0,menubar=0,resizable=1,toolbar=0,titlebar=0,scrollbars=1');
}
function openWin(url, w, h)
{
    if(typeof w == 'undefined') w = 750;
    if(typeof h == 'undefined') h = 600;
    newWin = openCenteredWindow(url, 'newWin', w, h, 'directories=0,location=0,menubar=0,resizable=0,toolbar=0,titlebar=0,scrollbars=1');
}
function openResizableWin(url, w, h, html)
{
    if(typeof w == 'undefined') w = 750;
    if(typeof h == 'undefined') h = 600;

    newWin = openCenteredWindow(url, 'newWin', w, h, 'directories=0,location=0,menubar=0,resizable=1,toolbar=0,titlebar=0,scrollbars=1');
    if(typeof html!='undefined')
    {
        newWin.document.write(html);
    }
}
function openCenteredWindow(url, windowname, width, height, options) 
{
  var theHeight = height;
  var theWidth = width;
  var theTop=(screen.height/2)-(theHeight/2);
  var theLeft=(screen.width/2)-(theWidth/2);
  var features= 'height='+theHeight+
               ',width='+theWidth+
               ',top='+theTop+
               ',left='+theLeft+
               "," + options;
  xtraWin = window.open(url, windowname, features);
  xtraWin.focus();
  return xtraWin;
}

interval = null;
function loadedMailPreview()
{
    el = getById('preview');
    h = el.contentWindow.document.body.scrollHeight+50;
    el.style.height = h+"px";
}
function doSetHeight(h)
{
    el = getById('preview');
    el.style.height = h+"px";
    clearInterval(interval);
}
function moveItemUpOrDown(el, dir, hasdummy)
{
    ind = el.selectedIndex;

    if(dir == -1 && ind>0 && ind!=(el.length-(hasdummy?0:1))) // up
        newind = ind-1;
    else if(dir == 1 && ind!=(el.length-(hasdummy?1:2))) // down
        newind = ind+1;
    else
        return false;

    var o = new Option(el[ind].innerHTML, el[ind].value);
    o.selected="selected";
    el.remove(ind);
    try {
        el.add(o, newind);
    }catch(e) {
        el.add(o, el[newind]);
    }
}
/* Rollen */
function moveItem(from, to, item, select)
{
    if(to.getAttribute("enginerights") <= item.getAttribute("engineadd"))
    {
        var o = new Option(item.innerHTML, item.value);
        o.className = item.className;
        if(typeof select != 'undefined')
            o.selected = "selected";
        o.setAttribute("engineadd", item.getAttribute("engineadd"));
        try {
            to.add(o);
        }catch(e) {
            if(to.appendChild)
                to.appendChild(o);
        }

        from.remove(item.index);
        return true;
    }
    return false;
}

function moveSelectedItems(from, to, select) {
    from = document.forms['role'].elements['tmp_rights_'+from];
    to     = document.forms['role'].elements['tmp_rights_'+to];
    ok = true;
    for(i=from.length-1;i>=0;i--)
        if(from[i].selected)
            ok = ok & moveItem(from, to, from[i], select);
    return ok;
}

// Move all item from selectlist 'from' to selectlist 'to'
function moveAll(from, to, select) {
    from = document.forms['role'].elements['tmp_rights_'+from];
    to     = document.forms['role'].elements['tmp_rights_'+to];
    ok = true;
    for(i=from.length-1;i>=0;i--)
        ok = ok & moveItem(from, to, from[i], select);

    return ok;
}
/* / Rollen */

function toggleColumns(cols2, txt)
{
    cols = (cols2 != 'unsubscribe');
    a = document.forms['export'].elements['cols[]'];
    a.style.display = cols?'block':'none';
    b = document.forms['export'].elements['unsubcols[]'];
    b.style.display = !cols?'block':'none';
    if(typeof txt != "undefined")
    {
        c = getById("period_date");
        c.value = cols?'datum_bevestigd':'datum_afgemeld';
        /*
        if(c.length==3 && c[2].value == "datum_afgemeld")
            c.remove(2);
        else if(!cols)
        {
            try {
                c.add(new Option(txt, 'datum_afgemeld'));
                c[2].selected = "selected";
            }catch ( e) {
                c.add(new Option(txt, 'datum_afgemeld'), null);
                c[2].selected = "selected";
            }
        }*/
    }
    el = getById('unsubscribe_statusses');
    if(el)
    {
        el.style.display = (cols2=='unsubscribe'?'block':'none');
    }
}

function changePeriod(el, s, e)
{
    if(typeof s != "undefined" && typeof e != "undefined")
    {
        el1 = getById(s);
        el2 = getById(e);
        val = (""+el[el.selectedIndex].value).split(" ");

        if(val.length == 2)
        {
            el1a = getById(s+"_cell");
            el2a = getById(e+"_cell");
            if(val[0]=='' && val[1]=='')
            {
                el1a.style.visibility = 'hidden';
                el2a.style.visibility = 'hidden';
            }else
            {
                el1a.style.visibility = 'visible';
                el2a.style.visibility = 'visible';
            }
             el1.value = val[0];
             el2.value = val[1];
        }
    }else
    {
        a = getById("date_selector");
        b = getById("month_selector");
        a.style.display = (el[el.selectedIndex].value=='p')?"block":"none";
        b.style.display = (el[el.selectedIndex].value=='month')?"block":"none";
    }
}

function hoverIn(el, pp, img)
{
    el.src = pp + 'img/img.php?t=' + img + '&c=2';
}
function hoverOut(el, pp, img)
{
    el.src = pp + 'img/img.php?t=' + img;
}

function openImageBrowser(field_name, url, type, win)
{
    if(type!='image') return false;
    var fileBrowserWindow = new Array();

    /* If you work with sessions in PHP and your client doesn't accept cookies you might need to carry
     the session name and session ID in the request string (can look like this: "?PHPSESSID=88p0n70s9dsknra96qhuk6etm5").
     These lines of code extract the necessary parameters and add them back to the filebrowser URL again. */

    var searchString = window.location.search;    // possible parameters
    if (searchString.length < 1) {
        // add "?" to the URL to include parameters (in other words: create a search string because there wasn't one before)
        searchString = "?";
    }

    tinyMCE.activeEditor.windowManager.open({
        file     : pp + '../../../../pages/images/images.php' + searchString + "&simple=1&type=tiny", // PHP session ID is now included if there is one at all
        title : "Browser",
        width    : 750,
        height : 500,
        scroll : "yes",
        scrollbars : "yes",
        close_previous : 0
    }, {
        window : win,
        input : field_name,
        resizable : "yes",
        inline : "yes",    // This parameter only has an effect if you use the inlinepopups plugin!
        editor_id : tinyMCE.selectedInstance.editorId
    });

    return false;
}

function addFolder(show)
{
    if(typeof show == 'undefined')
    {
        show = true;
    }

    el = getById("new_dir_div");
    el.style.display = show?'block':'none';

    if(show)
    {
        document.forms['imgform'].elements['new_dir'].focus();
    }else
    {
        document.forms['imgform'].elements['new_dir'].value = '';
    }
/*
    if(el)
    {
        r = el.insertRow(el.rows.length);
        c = 0;
        if(el.rows[0].cells.length==3)
        {
            c1 = r.insertCell(c++);
            c1.innerHTML = '&nbsp;';
        }
        c2 = r.insertCell(c++);
        c2.style.paddingRight = '20px';
        c2.innerHTML = '<img src="/img/dir.gif" alt="" /><input type="text" name="newdir" id="newdir" onkeypress="e = event; if(!e)e=window.event; if(e.keyCode == 13 && this.value!=\'\')this.blur();" onblur="if(this.value!=\'\')document.location=\'?dir='+dir+'&newdir=\'+this.value+\'&mlid=\'+SESSION_MAILINGLISTID;else{el = getById(\'table\');el.deleteRow(el.rows.length-1);}" value="" />';
        c3 = r.insertCell(c++);
        c3.align = "right";
        c3.innerHTML = '0 kB';
        el = getById("newdir");
        if(el)
            el.focus();
    }*/
}
lastFile = null;
function previewImage(dir, fn, n, d, s)
{
    el = getById("filePreview");
    if(d!='')
        d = '\n\n' + d;
    if(el)
        el.innerHTML = '<img src="'+dir+fn+'" alt="'+n+' ('+s+')'+d+'" />';

    el = getById("filePreview2");
    if(el)
        el.style.display="block";

    lastFile = {dir: dir, filename: fn, name: n, desc: d, size: s};
}
function insertLastFile()
{
    if(lastFile != null)
    {
        var win = tinyMCEPopup.getWindowArg("window");
        if(win && win.mcTabs)
            win.mcTabs.displayTab('general_tab','general_panel');
        // insert information now
        if(a = win.document.getElementById(tinyMCEPopup.getWindowArg("input"))) a.value = lastFile["dir"]+lastFile["filename"];
        if(a = win.document.getElementById("alt")) a.value = lastFile["desc"];
        if(a = win.document.getElementById("title")) a.value = lastFile["name"];

        // for image browsers: update image dimensions
        if (win.ImageDialog && win.ImageDialog.showPreviewImage)
            win.ImageDialog.showPreviewImage(lastFile["dir"]+lastFile["filename"]);

        //tinyMCEPopup.setWindowArg('editor_id','mce_editor_0');
        // close popup window
        tinyMCEPopup.close();
    }
}
function addEvent(el, event, func)
{
    if (el.attachEvent)
        el.attachEvent("on" + event, func);
    else
        el.addEventListener(event, func, false);
}
function removeEvent(obj,evt,fn) 
{
    if (obj.removeEventListener)
        obj.removeEventListener(evt,fn,false);
    else if (obj.detachEvent)
        obj.detachEvent("on"+evt,fn);
}
function hoverHeader(el, type)
{
    oc = el.getAttribute("originalClassName");
    cn = el.className;
    if(oc == null)
    {
        el.setAttribute("originalClassName", cn);
        oc = cn;
    }
    el.className = oc + '_hover';
    func = function () {
        el.className = el.getAttribute("originalClassName");
    };
    if(el)
    {
        addEvent(el, "mouseout", func);
        if(typeof type !='undefined')
            addEvent(el, "click", function () {document.location = type;});
    }
}
linkState = 0;
function toggleLinks()
{
    iframe = getById('preview');
    if(iframe.contentWindow.linkIds)
    {
        a = iframe.contentWindow.linkIds;
        linkState++;
        if(linkState > 2) linkState = 0;
        for(i=0;i<a.length;i++)
        {
            el = iframe.contentWindow.document.getElementById('link_'+a[i]);
            if(el)
            {
                if(linkState != 2)
                {
                    el.parentNode.style.display = 'block';
                    el.style.display = (linkState?'block':'none');
                }else
                {
                    el.parentNode.style.display = 'none';
                }
            }
        }
    }
}
function setImportExample()
{
    f = document.forms['fileform'];
    sep = f.elements['separator'].value;
    enc = f.elements['enclosed'].value;
    ex = new Array("John", "Doe", "Doe, John", "Livingstonestreet", "1", "Londen", "UK", "1954-12-30");
    txt = '';
    regexp = new RegExp(sep, 'g');
    for(var i=0;i<ex.length;i++)
    {
        var t = ex[i];
        if(sep!='')
            t = t.replace(regexp, '\\' + sep);
        txt += (i!=0?sep:'') + enc + t + enc;
    }
    el = getById("example");
    el.innerHTML = txt;
}
function doCheckImportForm(startInd)
{
    f = document.forms['doimport'];
    ok = -1;

    for(var i=0;i<f.elements.length;i++)
    {
        if(("" + f.elements[i].name).indexOf('column[')===0)
        {
            if(f.elements[i].selectedIndex!=0 && f.elements[i][f.elements[i].selectedIndex].value=='col_email')
            {
                ok = (f.elements[i].name).substring(7, (f.elements[i].name).length-1);
                break;
            }
        }
    }
    if(ok!==-1) // email found at index: i
    {
        i = ok;
        ok = 1;
        el = getById('ex_table');
        for(a=(1+startInd);ok==1 && a<el.rows.length;a++)
        {
            c = el.rows[a].cells[i];
            if(c)
            {
                r = checkEmail(c.innerHTML);
                if(!r)
                    ok = -2;
            }
        }
    }
    //alert(ok);
    res = doSubmit('doimport');
    if(ok == 1)
        return res;

    if(ok == -1) // No email found
        alert(LANG_SELECT_EMAIL_BEFORE_IMPORT);
    else // Invalid email found in testadressed
        return res && confirm(LANG_INVALID_EMAIL_FOUND_CONTINUE);

    return false;
}

function doSubmitStep2() // Checken of de domeinen van het afzender adres en replyto adres gelijk zijn. zo niet: confirmen
{
    f = document.forms["mailing-step-2"];
    a = f.elements["afzender_email"].value;
    a = a.substring(a.lastIndexOf("@"), a.length);
    r = f.elements["replymail"].value;
    r = r.substring(r.lastIndexOf("@"), r.length);
    if(a != r && !confirm(LANG_SENDER_REPLY_DOMAIN_INEQUAL))
        return false;

    f.elements["text"].value = tinyMCE.selectedInstance.getContent();
    return doSubmit(true, 'mailing-step-2');
}

function changeSegmentsTo(nr_of_segments, tot_abos)
{
    if(((nr_of_segments*2)/2)==nr_of_segments && nr_of_segments>0)
    {
        var el = document.forms['form'].elements['segment'];
        var sel = el.selectedIndex;

        while(el.length > 0)
            el.remove(0);

        for(var i=1;i<=nr_of_segments;i++)
        {
            o = new Option(i, i);
            ind = (el.length?el.length:0);
            try {
                el.options[ind] = o;
            }catch(e) {
                el.add(o, ind);
            }
        }
        el.selectedIndex = ((sel>-1 && sel < el.length)?sel:0);

        el = getById("nrabos");
        el.innerHTML = Math.round(tot_abos / nr_of_segments);
    }
}
function toggleTabs(t, cookie, prefix)
{
    if(typeof prefix == "undefined")
        prefix = "tabs_";
    el = getById(prefix + t);
    off = el.style.display=='none';
    if(typeof cookie == "undefined" || cookie)
    {
        if(off)
            createCookie("Engine_tabs_" + t, 1, 100);
        else
            eraseCookie("Engine_tabs_" + t);
    }
    if(el)el.style.display = (off?'block':'none');
    el = getById("img_"+t);
    if(el)el.src = pp+'img/new/'+(off?'min':'plus')+'.gif';
}
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
lastSpam = null;
function toggleSpamResults(id)
{
    if(id!=lastSpam)
    {
        if(lastSpam != null)
        {
            el = getById("spam_table_"+lastSpam);
            if(el) el.style.display = 'none';
        }
        el = getById("spam_table_"+id);
        if(el) el.style.display = 'block';

        lastSpam = id;
    }
}

request_complete = false;
last_url = http_request = null;
opening = openingSpam = false;
function addComment(com)
{
    if(c = getById('comments'))
    {
        c.innerHTML = new Date() + " - " + com + "<BR>" + c.innerHTML;
    }
}
function doCheckSpam(id)    {
    url = pp+"pages/spamcheck.php?mlid="+SESSION_MAILINGLISTID+"&mid="+id;

    addComment("Start check " + id + ", todo: " + checkSpamIds.length);
    if(!openingSpam)
    {
        initiated = false;
        openingSpam = true;
        async = true;
        request_complete = false;
        try {http_request = new ActiveXObject("Msxml2.XMLHTTP.6.0");}
        catch (e) {try {http_request = new ActiveXObject("Microsoft.XMLHTTP");}
        catch (e) {try {http_request = new XMLHttpRequest();}
        catch (e) {try {http_request = window.createRequest();}
        catch (e) {http_request = false;}}}}

        if (!http_request) {
            // Throw error
            alert("Please upgrade browser. XMLHttp object can't be created...");
            return false;
        }

        http_request.open("GET", url, async);
        
        http_request.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');

        functie = function(){
        addComment("Ready state - " + http_request.readyState);
        if (http_request.readyState == 4 && !request_complete) {
            request_complete = true;
            openingSpam = false;
            addComment("Stop check " + id);
            spamChecked(id, http_request);
        }
        };
        set = false;
        try {http_request.onload                         = functie;set = true;}catch(e) {}
        if(!set)
            try {http_request.onreadystatechange = functie;set = true;}catch(e) {}

        http_request.send('');
    //    }    catch(z) { alert(z.description);return false; }
    }
}
function spamChecked(id, result)
{
    if (result.status == 200)
    {
        txt = (""+result.responseText);
        ar = txt.split("\n");
        points = req = spam = 0;
        rules = new Array();
        ok = true;
        if(ar !== "false")
        {
            for(i = 0; i < ar.length; i++)
            {
                if(ar[i].indexOf("POINTS_TOTAL=")===0)
                {
                    points = ar[i].replace("POINTS_TOTAL=", "");
                }
                else if(ar[i].indexOf("POINTS_REQUIRED=")===0)
                {
                    req = ar[i].replace("POINTS_REQUIRED=", "");
                }
                else if(ar[i].indexOf("IS_SPAM=")===0)
                {
                    spam = ((""+ar[i].replace("IS_SPAM=", ""))=="1");
                }
                else if(ar[i].indexOf("RULES_MATCHED=")===0)
                {
                    rule = ar[i].replace("RULES_MATCHED=", "");
                    rule = rule.split("****");
                    rules[rules.length] = rule;
                }
            }
            el = getById("spamtitle_" + id);
            if(el)
            {
                el.className = !spam?"ok":"err";
                el.innerHTML = !spam?LANG_NOT_MARKED_AS_SPAM:LANG_MARKED_AS_SPAM;
            }
            el = getById("spam_message");
            if(el)
            {
                msg = LANG_POINTS_DESCRIPTION;
                msg = msg.replace("**POINTS_TOTAL**", points);
                msg = msg.replace("**POINTS_REQUIRED**", req);
                el.innerHTML = msg;
            }
            el = getById("spam_points_"+ id);
            if(el)
                el.innerHTML = points + "/" + req;
        }else
        {
            ok = false;
            el = getById("spam_error");
            if(el) el.style.display = "block";
            el = getById("spam_ok_table");
            if(el) el.style.display = "none";
        }
        el = getById("spam_table_"+id)
        if(el)
        {
            if(checkSpamLarge && rules.length>0) el.style.display = 'block';
            for(i=0;i<rules.length;i++)
            {
                r = el.insertRow(el.rows.length);
                c1 = r.insertCell(0);
                c2 = r.insertCell(0);
                c3 = r.insertCell(0);
                c1.innerHTML = rules[i][0];
                c2.innerHTML = rules[i][1];
                c3.innerHTML = rules[i][2];
            }
        }
        isSpam = isSpam || spam;

        if(checkSpamIds.length > 0)
        {
            id = checkSpamIds.shift();
            setTimeout("doCheckSpam('" + id + "');", 500);
        }else if(!isSpam)
        {
            el = getById("spam_ok");
            if(el) el.style.display = "block";
            el = getById("spam_loading");
            if(el) el.style.display = "none";
        }
    } else
    {
        // Empty result ? Or error
    }
}
isSpam = null;
checkSpamIds = new Array();
checkSpamLarge = true;
function checkSpam(ids)
{
    checkSpamIds = ids.split(",");
    checkSpamLarge = (checkSpamIds.length==1);
    if(checkSpamIds.length > 0)
    {
        doCheckSpam(checkSpamIds.shift());
    }
}

function printGraph(url, type)
{
    r = Math.random();
    df = escape(pp+url);
    url = pp+'img/graph/graphs.swf';
    w = '100%';
    h = 250;
    if(type=='wide')
    {
        url = pp+'img/graph/graphs.swf';
        w = '100%';
        h = 200;
    }else if(type=='small')
    {
        w = '100%';
        h = 200;
    }
    url = url+'?dataFile='+df+'&path_pre='+pp+'&var='+r+'&noDataMsg='+escape(LANG_INSUFFICIENT_DATA);
    document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+w+'" height="'+h+'">');
    document.write('<param name="movie" value="'+url+'" />');
    document.write('<param name="quality" value="high" />');
    document.write('<param name="wmode" value="opaque" />');
    document.write('<embed src="'+url+'" quality="high" width="'+w+'" height="'+h+'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.write('</object>');
}
var HEARTBEATINTERVAL = null;
function heartBeat()    {
    var url = pp+"pages/heartbeat.php?mlid="+SESSION_MAILINGLISTID+"&r="+Math.random();

    // Beat every 10min so session isnt destroyed
    heartBeatTimeout = 1000*60*3;
    if(HEARTBEATINTERVAL == null)
    {
        HEARTBEATINTERVAL = window.setTimeout(heartBeat, heartBeatTimeout);
    }else if(!opening)
    {
        var initiated = false;
        var opening = true;
        var request_complete = false;
        try {http_request = new ActiveXObject("Msxml2.XMLHTTP");}
        catch (e) {try {http_request = new ActiveXObject("Microsoft.XMLHTTP");}
        catch (e) {try {http_request = new XMLHttpRequest();}
        catch (e) {try {http_request = window.createRequest();}
        catch (e) {http_request = false;}}}}

        if (!http_request) {
            // Throw error
            alert("Please upgrade browser. XMLHttp object can't be created...");
            return false;
        }
        http_request.open("GET", url, false);

        functie = function(){
        if (http_request.readyState == 4 && !request_complete) {
            request_complete = true;
            opening = false;
            if(http_request.status==200)
            {
                if(HEARTBEATINTERVAL != null)
                {
                    window.clearTimeout(HEARTBEATINTERVAL);
                }
                HEARTBEATINTERVAL = window.setTimeout(heartBeat, heartBeatTimeout);
            }
        }};
        set = false;
        try {http_request.onload                         = functie;set = true;}catch(e) {}
        if(!set)
            try {http_request.onreadystatechange = functie;set = true;}catch(e) {}

        http_request.send('');
    }
}
function toggleSendDate()
{
    show=!document.forms['mailing-step-2'].elements['verzend_datum'][1].checked;
    el=getById('sendon');
    if(el)
        el.style.display=show?'none':'block';
    /*show=document.forms['mailing-step-2'].elements['verzend_datum'][2] && !document.forms['mailing-step-2'].elements['verzend_datum'][2].checked;
    el=getById('variableDiv');
    if(el)
        el.style.display=show?'none':'block';*/
}
function openSimpleBlocks(el)
{
    win = openWin(pp+'pages/simpleblocks.php?func=doInsertSimpleBlock&variable='+el+'&mlid='+SESSION_MAILINGLISTID, 700, 125);
}
function doInsertSimpleBlock(txt, variable)
{
    el = getById(variable);
    if(el) el.value += txt;
}
function openXMLTemplates(el, replaceOption, func, add)
{
    if (typeof add == 'undefined') {
        add = '';
    }
    if (typeof replaceOption == 'undefined') {
        replaceOption = true;
    }
    if (typeof func == 'undefined') {
        func = 'doInsertXMLTemplate';
    }
    win = openWin(pp+'tinymce/jscripts/tiny_mce/plugins/enginexml/enginexml.php?func='+func+'&flatten=1&replace_on_create='+replaceOption+'&variable='+el+'&mlid='+SESSION_MAILINGLISTID+'&'+add, 500, 550);
}
function doInsertXMLTemplate(txt, variable)
{
    el = getById(variable);
    if(el) el.value += txt;
}
function doInsertXMLAutomatedDate(txt, variable, exampleValue)
{
    el = getById(variable);
    if(el) el.value = txt;

    ex = getById(variable+"_example");
    if (ex) {
        ex.value = exampleValue;
    }
}
function doInsertTinySimpleBlock(txt, variable)
{
    tinyMCE.execCommand('mceInsertRawHTML', false, txt);
    ed = tinymce.EditorManager.get(variable);
    if(ed) ed.focus();
}
function printMessage(msg)
{
    if(msg!='' && msg!= ' ' && msg!= '&nbsp;') alert(msg);
}

function toggleDiv(checkBoxEl, divId)
{
    toggle(divId, checkBoxEl.checked);
}
function toggleTableRow(trId, on)
{
    tr = getById(trId);
    if(tr)
    {
        if(typeof on == 'undefined')
        {
            if(tr.style.display == 'none')
                on = true;
            if(tr.style.display == 'block')
                on = false;
        }
        tr.style.display = on?'table-row':'none';
        return on;
    }
    return false;
}
function toggle(divId, on, newMode)
{
    div = getById(divId);
    if(typeof newMode == 'undefined') {
        newMode = 'block';
    }
    if(div)
    {
        if(typeof on == 'undefined')
        {
            if(div.style.display == 'none')
                on = true;
            if(div.style.display == newMode)
                on = false;
        }
        div.style.display = on?newMode:'none';
        return on;
    }
    return false;
}
function toggleXMLTree(clickedEl, id, rec)
{
    if(typeof rec == 'undefined') rec = true;
    onOff = toggle(id);
    if(getById(id) && getById(id).childNodes && clickedEl && clickedEl.childNodes && clickedEl.childNodes[0])
    {
        clickedEl.childNodes[0].src = pp + 'img/' + (onOff?'min':'plus') + '.gif';
        clickedEl.childNodes[1].src = pp + 'img/dir' + (onOff?'_open':'') + '.gif';

        divChildNode = null;
        for(var i=0;i<getById(id).childNodes.length;i++)
        {
            if(getById(id).childNodes[i] && getById(id).childNodes[i].tagName && getById(id).childNodes[i].tagName.toLowerCase()=='div' && getById(id).childNodes[i].className=='fileContainer')
            {
                if(divChildNode != null)
                {
                    divChildNode = null;
                    break;
                }
                divChildNode = getById(id).childNodes[i];
            }
        }
        if(rec && divChildNode != null)
        {
            clickedEl = getById(divChildNode.id.replace('_children',''));
            clickedEl = clickedEl.childNodes[0];
            toggleXMLTree(clickedEl, divChildNode.id);
        }
    }

    if(window.event) window.event.cancelBubble=true;
}

function loadAction(actieid, edit)
{
    openWin('actions-edit.php?mlid='+SESSION_MAILINGLISTID+'&actieid='+actieid+'&edit='+edit);
}
function changePageDivs(sel)
{
    ENGINE_ACTIVE_PAGE_TYPE = sel;

    el = getById('defaultDiv');
    el.style.display=(sel=='message'?'none':'');
    el = getById('urlDiv');
    el.style.display=((sel=='profile'||sel=='maf'||sel=='unsubscription')?'':'none');
    el = getById('actionDiv');
    el.style.display=((sel=='maf'||sel=='profile')?'table-row':'none');
}
var lastSelectionEl = lastType = '';
var currentSelectionType = 'field';
function changeGroupSelectionField(el)
{
    if(el.selectedIndex > 0)
    {
        label = el[el.selectedIndex].innerHTML;
        value = el[el.selectedIndex].value;
        if(el.getAttribute('id') == 'tmp_mailing')
        {
            label = el[el.selectedIndex].innerHTML;
            value = 'mailing';
        }else if(el.getAttribute('id') == 'tmp_surveyParticipation')
        {
            label = el[el.selectedIndex].innerHTML;
            value = 'surveyParticipation';
        }
        getById('example[field]').innerHTML = label;

        img = 'vraagteken';
        if(typeof fieldTypes[value] != 'undefined')
        {
            if(fieldTypes[value][1]!='')
                img = fieldTypes[value][1];

            type = fieldTypes[value][0];
            if(type=='')type = 'default';

            defSelOn = (type=='selection_single'||type=='selection_multiple') && type!='mailing' && type!='surveyParticipation';
            defInpOn = (type!='selection_single'&&type!='selection_multiple') && type!='mailing' && type!='surveyParticipation';
            el = getById("tmp_"+currentSelectionType+"_value[default]");
            if(el) el.style.display = (!defInpOn?'none':'block');
            if(lastSelectionEl!='')
            {
                el = getById("tmp_"+currentSelectionType+"_value["+lastSelectionEl+"]");
                if(el) el.style.display = "none";
            }
            lastSelectionEl = value;
            if(defSelOn)
            {
                el = getById("tmp_"+currentSelectionType+"_value["+value+"]");
                if(el) el.style.display = "block";
            }
            if(lastType != type)
            {
                cons = (typeof typeContraints[type]!='undefined'?typeContraints[type]:typeContraints['default']);
                el = getById("tmp_constraint_" + currentSelectionType);

                selConst = (el.selectedIndex>=0?el[el.selectedIndex].value:'');;
                while(el.length > 0)
                    el.remove(0);

                var o = new Option('', '');
                try {
                    el.add(o, el.options.length);
                }catch(e) {
                    el.add(o, el[el.options.length]);
                }

                for(var i=0;i<cons.length;i++)
                {
                    cVal = contraints[cons[i]];
                    var o = new Option(cVal, cons[i]);
                    o.selected = (selConst==cons[i]?"selected":'');
                    try {
                        el.add(o, el.options.length);
                    }catch(e) {
                        el.add(o, el[el.options.length]);
                    }
                }
            }
        }
        getById('example[image]').src = pp + "img/icons/nobox/" + img + ".gif";
    }else
    {
        getById('example[field]').innerHTML = '';
    }
}
function changeGroupSelectionContraint(el)
{
    labelEl = getById('tmp_'+currentSelectionType);
    changeGroupSelectionField(labelEl);

    if(el.selectedIndex > 0)
    {
        label = el[el.selectedIndex].innerHTML;
        value = el[el.selectedIndex].value;

        getById('example[contraint]').innerHTML = label;

        if(lastSelectionEl!='')
            el = getById("tmp_"+currentSelectionType+"_value["+lastSelectionEl+"]");
        else
            el = getById("tmp_"+currentSelectionType+"_value[default]");

        if(el)
        {
            if(value=='IS_ODD' || value=='IS_EVEN')
                 el.style.display = "none";
            else
                 el.style.display = "block";
        }

        if(currentSelectionType == 'mailing' || currentSelectionType == 'surveyParticipation')
        {
            img = 'vergrootglas';
            if(value.indexOf('CLICKED') != -1)
                img = 'pijl';
            getById('example[image]').src = pp + "img/icons/nobox/" + img + ".gif";
        }
    }else
    {
        getById('example[contraint]').innerHTML = '';
    }
}
function changeGroupSelectionValue(el)
{
    if(el.tagName.toLowerCase()=='select')
    {
        txt = new Array();
        for(var i=0;i<el.options.length;i++)
        {
            if(el[i].selected)
                txt[txt.length] = el[i].innerHTML;
        }
        txt = txt.join(", ");
    }else
    {
        txt = el.value;
    }
    getById('example[value]').innerHTML = txt;
}
function getGroupSelectionValue(el, html)
{
    if(el.tagName.toLowerCase()=='select')
    {
        txt = new Array();
        for(var i=0;i<el.options.length;i++)
        {
            if(el[i].selected)
                txt[txt.length] = (html?el[i].innerHTML:el[i].value);
        }
        txt = txt.join("****");
    }else
    {
        txt = el.value;
    }
    return txt;
}
function addGroupSelection()
{
    f = c = null;
    f = getById("tmp_" + currentSelectionType);
    if(f)
    {
        orifield = field = (f.selectedIndex>0?f[f.selectedIndex].value:null);
        fieldLabel = (f.selectedIndex>0?f[f.selectedIndex].innerHTML:null);
    }
    c = getById("tmp_constraint_" + currentSelectionType);
    if(c)
    {
        constraint = (c.selectedIndex>0?c[c.selectedIndex].value:null);
        constraintLabel = (c.selectedIndex>0?c[c.selectedIndex].innerHTML:null);
    }
    err = new Array();
    err[0] = new Array(); // Required
    err[1] = new Array(); // Numeric
    err[2] = new Array(); // Numeric - Commas
    err[4] = new Array(); // Date
    err[5] = new Array(); // General error
    err[15] = new Array(); // Date
    if(field==null || field=='')
        err[0][err[0].length] = f.getAttribute("error");
    if(constraint==null || constraint=='')
        err[0][err[0].length] = c.getAttribute("error");

    if(currentSelectionType == 'mailing' || currentSelectionType == 'surveyParticipation')
        field = currentSelectionType;

    if(typeof fieldTypes[field] != 'undefined')
    {
        type = fieldTypes[field][0];
        if(type=='')type = 'default';

        if(type == 'mailing' || type == 'surveyParticipation')
        {
            types = new Array('start', 'end');
            values = new Array();
            for(var i=0;i < types.length;i++)
            {
                date_type = types[i];
                startDateTypeEls = document.forms['group'].elements["tmp_"+currentSelectionType+"_"+date_type+"_type"];
                startDateType = null;
                for(var a=0;a<startDateTypeEls.length;a++)
                {
                    if(startDateTypeEls[a].checked)
                        startDateType = startDateTypeEls[a];
                }
                if(startDateType!=null)
                {
                    values[date_type] = startDateType.value;
                    if(startDateType.value == 'vast')
                    {
                        startValue = getById("tmp_"+currentSelectionType+"_"+date_type+"_vast_value");
                        if(!checkDate(startValue.value) && startValue.value!="")
                        {
                            err[4][err[4].length] = startValue.getAttribute("error");
                        }else
                        {
                            values[date_type] += '--' + startValue.value;
                        }
                    }else if(startDateType.value == 'dynamic')
                    {
                        startValue = getById("tmp_"+currentSelectionType+"_"+date_type+"_dynamic_value[num]");

                        value = startValue.value;
                        res =    checkNumeric(value);
                        if(res < 0 || value < 0 || value == '')
                        {
                            if(res < -1)
                                err[2][err[2].length] = startValue.getAttribute("error");

                            err[1][err[1].length] = startValue.getAttribute("error");
                        } else
                        {
                            values[date_type] += '--' + getById("tmp_"+currentSelectionType+"_"+date_type+"_dynamic_value[compare]").value + "--" + startValue.value + "--" + getById("tmp_"+currentSelectionType+"_"+date_type+"_dynamic_value[period]").value;
                        }
                    }
                }

            }

            valueTxt = '';
            value = values['start'] + '****' + values['end'];
        }else
        {
            if(type=='selection_single'||type=='selection_multiple')
                newSelectionEl = getById('tmp_'+currentSelectionType+'_value['+field+']');
            else
                newSelectionEl = getById('tmp_'+currentSelectionType+'_value[default]');
            value = getGroupSelectionValue(newSelectionEl, false);

            if(type=='date' && (!checkDate(value) && value!=""))
                err[4][err[4].length] = newSelectionEl.getAttribute("error");
            if(type=='datetime' && (!checkDateTime(value) && value!=""))
                err[15][err[15].length] = newSelectionEl.getAttribute("error");
            if(type=='number')
            {
                res =    checkNumeric(value);
                if(res < 0)
                {
                    if(res < -1)
                        err[2][err[2].length] = newSelectionEl.getAttribute("error");

                    err[1][err[1].length] = newSelectionEl.getAttribute("error");
                }
            }
            valueTxt = (getGroupSelectionValue(newSelectionEl, true)).replace(/\*\*\*\*/g, ', ');
        }
        total_errs = 0;
        for(a=0;a<err.length;a++)
            total_errs += (err[a]?err[a].length:0);
        if(total_errs==0)
        {
            sel = getById("selection");
            nw = document.createElement("div");
            nw.className = "child";
            nw.innerHTML = '<span style="float:right;"><input type="hidden" name="field[]" value="'+orifield+'" /><input type="hidden" name="constraint[]" value="'+constraint+'" /><input type="hidden" name="values[]" value="'+escape(value)+'" /><a href="#" onclick="this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);">X</a>&nbsp;</span><div style="text-align:center"><img src="'+pp+'img/icons/nobox/'+img+'.gif" style="width: 75px;height:75px" alt="" /><br/>'+fieldLabel+'<br/>'+constraintLabel+'<br/>'+valueTxt+'</div>';
            sel.insertBefore(nw, sel.childNodes[sel.childNodes.length-1]);
            return;
        }
    }

    err_txt = labels[5] + ":\n\n";
    for(a=0;a<err.length;a++)
    {
        if(err[a] && err[a].length>0)
        {
            err_txt += labels[a] + ":\n" + err[a].join(", ") + "\n\n";
        }
    }
    alert(err_txt);
}

function unSelectRadio(name, form)
{
    if (!form || form == '')
    {
        form = 0;
    }
    e = document.forms[form].elements[name];
    for (i=0; i<e.length; i++)
    {
        e[i].checked = false;
    }
}

function linksChecked()
{
    e = getById("linkStatus");
    e.style.display = 'none';

    getById('rapport').focus();
}

function toggleRows(id, force, parent, nr)
{
    img = getById("img_" + id);
    if(img)
    {
        minSrc  = img.src.replace('/plus.',    '/min.');
        plusSrc = img.src.replace('/min.',    '/plus.');
    }
    var counter = 0;
    var el = null;
    while(el = getById(parent + id + '_' + counter))
    {
        sDisplay = (el.nodeName == 'TR') ? 'table-row' : 'block';
        newDisplay = (el.style.display=='none'? sDisplay :'none');
        newDisplay = force!=false?force:newDisplay;
        if(img)
        {
            img.src = newDisplay=='none'?plusSrc:minSrc;
        }
        el.style.display = newDisplay;

        if(el.style.display=='none')
        {
            toggleRows(id + '_' + counter, 'none', parent);
        }
        counter++;
    }
}

var slideActive = false;
var slider = null;
var mousePos = null;
var slideLinkedVars = null;
var slideValueEl = null;
function getMousePosition(e)
{
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY)     {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)    {
        posx = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    }
    return new Array(posx, posy);
}
function startSlide(el, ev, linkVars, valueEl)
{
    slideActive = true;
    slider = el;
    if(!el.getAttribute("slide_init"))
    {
        el.setAttribute("slide_init", "1");
        addEvent(el,       "dragstart", function () {return false;});
        addEvent(el,       "drag",            function () {return false;});
        addEvent(document, "mousemove", moveSlide);
        addEvent(document, "mouseup",     endSlide);
        addEvent(document, "enddrag",     endSlide);
    }
    el.setAttribute("slide_start_pos", slider.style.left.replace('px', ''));
    mousePos = getMousePosition(ev);
    linkVars[0] = getById(linkVars[0]);
    slideLinkedVars = linkVars;
    slideLinkedVars[4] = getById(slideLinkedVars[4]);
    slideValueEl = getById(valueEl);
}
function moveSlide(e)
{
    if(slideActive && slider)
    {
        newMousePos = getMousePosition(e);
        oldX = mousePos[0];
        newX = newMousePos[0];
        oldL = Math.round(slider.getAttribute("slide_start_pos"));
        newL = (oldL + newX - oldX);
        maxL = Math.round(slider.parentNode.style.width.replace('px',''))-Math.round(slider.style.width.replace('px',''));
        newL = Math.max(0, newL);
        newL = Math.min(newL, maxL);

        if(slideLinkedVars && slideLinkedVars[0])
        {
            isPart1 = slideLinkedVars[2]!=100;
            percSel = (newL / maxL);
            nrSel = Math.floor(percSel * slideLinkedVars[2]);
            slideValueEl.value = nrSel + ' %';

            msg = getById('perc_part' + (isPart1?1:2));
            msg.innerHTML = Math.floor(nrSel);

            if(isPart1)
            {
                nrSel *= slideLinkedVars[1];
                if(percSel == 1) nrSel = 100;
            }

            otherMaxNr = 100 - nrSel;
            if(!isPart1)
                otherMaxNr /= slideLinkedVars[1];
            if (slideLinkedVars[4].value)
            {
                slideLinkedVars[4].value = Math.floor(otherMaxNr) + ' %';
                otherMaxPerc = otherMaxNr / slideLinkedVars[3];

                maxL = Math.round(slideLinkedVars[0].parentNode.style.width.replace('px',''))-Math.round(slideLinkedVars[0].style.width.replace('px',''));

                newPos = Math.round(maxL * otherMaxPerc);
                newPos = Math.max(0, newPos);
                newPos = Math.min(newPos, maxL);
                slideLinkedVars[0].style.left = newPos + "px";

                msg1 = getById('part2_active');
                msg2 = getById('part2_inactive');
                if((isPart1 && otherMaxNr==0) || (!isPart1 && nrSel==0))
                {
                    msg1.style.display = 'none';
                    msg2.style.display = 'block';
                }else
                {
                    msg1.style.display = 'block';
                    msg2.style.display = 'none';
                }
                msg = getById('perc_part' + (isPart1?2:1));
                msg.innerHTML = Math.floor(otherMaxNr);

                msg = getById('total_part1');
                msg.innerHTML = Math.floor(isPart1?nrSel:(100-nrSel));
            }
        }

        slider.style.left = newL + "px";
    }
}
function endSlide(e)
{
    if(slideActive && slider)
    {
        slideActive = false;
    }
}
function toggleSendTables(onoff)
{
    nr = 0;
    while(e = getById('sendonTable'+nr))
    {
        e.style.display = (nr==0 || onoff)?'block':'none';
        nr++;
    }
}
function toggleAllDivs(checkBoxEl, divId)
{
    n = 0;
    while(div = getById(divId + n))
    {
        div.style.display = checkBoxEl.checked?'block':'none';
        n++;
    }
}
var XML_CURRENT_SELECTED_FIELD = null;
function setXMLFeedData(colName, main, attr, data)
{
    XML_CURRENT_SELECTED_FIELD = colName;

    el = getById('xml_feed_main');
    el.style.display = (main==''?'none':'block');
    el.rows[0].cells[0].innerHTML = main;

    el = getById('xml_feed_data');
    el.style.display = (data==''?'none':'block');
    el.rows[1].cells[0].innerHTML = data;

    el = getById('xml_feed_attr');
    el.style.display = (attr==''?'none':'block');
    el.rows[1].cells[0].innerHTML = '<table cellspacing="0" cellpadding="0">' + attr + '</table>';

    if(window.parent && window.parent.EngineXMLDialog)
    {
        window.parent.EngineXMLDialog.setActiveField(colName, data);
    }
}
var ENGINEXML_SELECT_IMAGE_BY_DRAGGING = false;
function checkInvalidTinyNode(editor_id, node, undo_index, undo_levels, visual_aid, any_selection)
{
     // Debug to Firebug in FF
     ed = tinyMCE.get(editor_id);
     if(!ENGINEXML_SELECT_IMAGE_BY_DRAGGING && any_selection==false && tinymce.isIE && ed.dom.hasClass(node, 'ENgine_input'))
     {
        alert(ed.getLang('engine.enginexml_select_image_by_dragging', 'ERROR_MISSING_TRANSLATION'));
        ENGINEXML_SELECT_IMAGE_BY_DRAGGING = true;
     }
}

function checkUnsubscribeLink()
{
    is_valid = true;
    for(var i=0; i< document.forms['custform'].elements.length; i++)
    {
        el = document.forms['custform'].elements[i];
        n = el.name;
        if(n.indexOf('confirm_unsublink')==0)
        {
            if(!el.checked)
            {
                is_valid = false;
                break;
            }
        }
    }
    document.forms['custform'].elements['unsubscribe_link_valid'].value = (is_valid?'1':'');
    document.getElementById('unsub_image').src= pp + 'img/vink_' + (is_valid ? 'on' : 'off') + '.gif';
}

function setActiveSelectionType(type)
{
    types = new Array('field', 'mailing', 'surveyAnswers', 'surveyParticipation');
    for(var i=0; i< types.length;i++)
    {
        el = getById(types[i] + '_selection');
        if(el) el.style.display = (type==types[i]?'block':'none');
    }

    currentSelectionType = type;
    changeGroupSelectionContraint(getById('tmp_constraint_' + currentSelectionType));
}

function togglePeriodDates(startend, type)
{
    el = getById('tmp_'+currentSelectionType+'_'+startend+'_dynamic');
    el.style.display = (type=='dynamic'?'block':'none');
    el = getById('tmp_'+currentSelectionType+'_'+startend+'_vast');
    el.style.display = (type=='vast'?'block':'none');
}

function setActiveDesignTestResult(id, url)
{
    els = getById('designtestresults').getElementsByTagName('div');
    for(var i=0;i<els.length;i++)
    {
        if(els[i].className == 'active' && els[i].id!=id)
        {
            els[i].className = '';
        }
    }
    cell = getById(id);
    cell.className = 'active';

    lastDesignTestResultActive = cell;

    img = getById('designtestimage');
    img.src = url
}
function fixFixedBox()
{
    uAgent = navigator.userAgent
    fixed  = getById('fixedbox');
    if (uAgent.match(/MSIE/))
    {
        fixed.style.top = document.body.scrollTop + 'px';
    }
    else
    {
        parent = fixed.parentNode;
        parent.style.height = '100%';

        if (document.body.scrollTop + fixed.offsetHeight < parent.offsetHeight)
        {
            fixed.style.top = document.body.scrollTop + 'px';
        }
        else
        {
            fixed.style.top = (parent.offsetHeight - fixed.offsetHeight - 6) + 'px';
        }
    }
}

function checkEditedPage()
{
    if(typeof edited_page != 'undefined' && edited_page)
    {
        return confirm(LANG_CONFIRM_UNSAVED_EDITS);
    }
    return true;
}

function toggleActiveActionMail(el)
{
    amID = el.name.replace('action_mail_active[', '');
    amID = amID.replace(']', '');

    thisType = document.forms['action_form'].elements['action_mail_type['+amID+']'].value;

    var foundActive = new Array()
    var foundInactive = new Array();
    for(var i=0;i<document.forms['action_form'].elements.length;i++)
    {
        if(document.forms['action_form'].elements[i].name.indexOf('action_mail_type')!=-1)
        {
            if(document.forms['action_form'].elements[i].value == thisType)
            {
                tmpAmID = document.forms['action_form'].elements[i].name.replace('action_mail_type[', '');
                tmpAmID = tmpAmID.replace(']', '');

                if(tmpAmID != amID)
                {
                    if(document.forms['action_form'].elements['action_mail_active[' + tmpAmID + ']'].checked)
                    {
                        foundActive[foundActive.length] = tmpAmID;
                    }else
                    {
                        foundInactive[foundInactive.length] = tmpAmID;
                    }
                }
            }
        }
    }
    // IF we're checking the box: check for other inactive mails
    if(!el.checked && foundActive.length==0 && foundInactive.length > 0)
    {
        if(confirm(LANG_ACTIVATE_OTHER_ACTIVE_ACTION_MAIL))
        {
            document.forms['action_form'].elements['action_mail_active['+foundInactive[0]+']'].checked = true;
        }
    }else if(foundActive.length==1)
    {
        if(confirm(LANG_INACTIVATE_OTHER_ACTIVE_ACTION_MAIL))
        {
            document.forms['action_form'].elements['action_mail_active['+foundActive[0]+']'].checked = false;
        }else
        {
            el.checked = false;
        }
    }
    return true;
}

function toggleSends(uid)
{
    img = getById('pl_' + uid);
    if(img)
    {
        off = img.src.indexOf('min')===-1;

        el = getById('m_' + uid);
        el.style.display = off?'block':'none';
        el = getById('s_' + uid);
        el.style.display = off?'block':'none';

        img.src = pp + 'img/new/'+(off?'min':'plus')+'.gif';
    }
}

function setPageEvents()
{
    $('[id*=row_] input').click(function() {
       checkActiveActionPage();
    });
    checkActiveActionPage();
}

function checkActiveActionPage()
{
    isSelected = $('#row_url_aanmeldpagina_bedankt input:checked').val() == 'page';
    $('#row_url_verrijkpagina_error').css('display', isSelected ? 'none' : 'table-row');
    $('#row_url_verrijkpagina_bedankt').css('display', isSelected ? 'none' : 'table-row');
}

function resetExampleDate()
{
    frm = document.forms['mailing-step-2'];
    vd = frm.elements['verzend_datum'].value;
    if (vd == 'automated') {
        nr = parseInt(frm.elements['automated_date2[num]'].value);
        tp = frm.elements['automated_date2[period]'].value;
        cmp = frm.elements['automated_date2[compare]'].value;
        format = frm.elements['automated_format'].value;

        if (nr === '' || isNaN(nr)) {
            ex = '-';
            add = '';
        } else {
            if (cmp == '-') {
                nr = nr * -1;
            }

            diffDays = 0;
            diffMonth = 0;
            diffYear = 0;
            switch (tp) {
                case "day":
                    diffDays = nr;
                    break;
                case "week":
                    diffDays = nr * 7;
                    break;
                case "month":
                    diffMonth = nr;
                    break;
                case "year":
                    diffYear = nr;
                    break;
            }
            diffMonth += 0;

            n = new Date();
            n.setDate(n.getDate() + diffDays);
            n.setMonth(n.getMonth() + diffMonth);
            n.setFullYear(n.getFullYear() + diffYear);

            m = n.getMonth() + 1;
            m = (m < 10 ? '0' : '') + m;
            d = n.getDate();
            d = (d < 10 ? '0' : '') + d;
            ex = m + "-" + d;
            if (format == 'Ymd'){
                ex = n.getFullYear() + "-" + ex;
            }
            add = "<BR>D " + diffDays
                + "<BR>M " + diffMonth
                + "<BR>Y " + diffYear
                + "<BR>CUR:" + n
                + "<BR>CUR:" + n.getMonth()
                + "<BR>CUR:" + n.setMonth(n.getMonth())
                + "<BR>CUR:" + n.getMonth();
        }
        $('#automatedExample').html(ex);// + add);
    }
}

