function dexml(string) {
    return string.replace(/&amp;/g, "&").replace(/&quot;/g, "\"");
}

function set_messages(msg) {
    if ($("messages")) {
        $("messages").innerHTML = msg;
    }
}

function clear_messages() {
    set_messages("");
}

function set_spinner(div) {
    var spinner = '<img src="/admin/i/spinner.gif" alt="" width="31" height="30" border="0" />';
    if (div) {
        $(div).innerHTML = spinner;
    } else {
        set_messages(spinner);
    }
}

function load_content_into(container, url, callback) {
    var params = "&hash=" + Math.random();
    set_spinner();

    var contentAjax = new Ajax.Updater( {success: container},
        url, {
            method: 'get',
            parameters: params,
            evalScripts: true,
            onComplete: callback ? function() { callback(); clear_messages(); } : clear_messages
        }
    );
}

function bg_load(url) {
    load_content_into("bg_loader", url);
}

function bg_post_form(form) {
    post_form_into("bg_loader", form);
}

function post_form_into(container, form) {
    var params = "";
    set_spinner();

    for (var i = 0; i < form.elements.length; i++) {
        var el = form.elements[i];
        if (i > 0) {
            params += "&";
        }
        params += el.name + "=";
        if (el.type == "checkbox") { // TODO: radio buttons also?
            if (el.checked) {
                params += "1";
            } else {
                params += "0";
            }
        } else {
            params += encodeURIComponent(el.value || " "); // no empty fields
        }
    }

    var contentAjax = new Ajax.Updater( {success: container},
                                        form.action, {
            method: 'post',
            postBody: params,
            evalScripts: true,
            onComplete: clear_messages
        }
    );
}

function sanelySerializeSortable(id) {
    var text = Sortable.serialize(id);
    text = text.replace(/wpt_sort_list.*?=/gi, ",");
    text = text.replace(/bit_reorder_cut.*?=/gi, ",");
    text = text.replace(/[^0-9,]/gi, "");
    return text;
}


function toggle_highlight(togdiv, hiddiv) {
    if (Element.visible(hiddiv)) {
//        new Effect.Highlight (togdiv, {duration: 0.5, startcolor:'#d6d6d6', endcolor:'#ffffff', restorecolor:'#ffffff'});
    } else {
 //       new Effect.Highlight (togdiv, {duration: 0.5, startcolor:'#ffffff', endcolor:'#d6d6d6', restorecolor:'#d6d6d6'});
    }
    Effect.toggle(hiddiv, 'blind', {duration: 0.2});
    if ($('bit_blurb_preview_' + togdiv)) {
        Effect.toggle('bit_blurb_preview_'+togdiv, 'blind', {duration: 0.2});
    }
}

function save_node(node) {
        if (!document.nodecache) {
                document.nodecache = new Object();
        }
        document.nodecache[node.id] = node.innerHTML;
}

function load_node(node) {
        if (document.nodecache && document.nodecache[node.id]) {
                node.innerHTML = document.nodecache[node.id];
        }
}

function load_soundbite(div, dateString, filename) {
        // cache the div's contents
        save_node(div);

        // load the soundbite into the div
	var url = "/media/preview-sb.html?d=" + encodeURI(dateString) + "&f=" + encodeURI(filename);
	load_content_into(div, url);
}

function replaceSoundbitePreviews(parent) {
        // replaces each dynamically-loaded quicktime element with the
        // div's cached original content
        document.getElementsByClassName("saveddiv", parent).each(load_node);
}

function disable_preview(previewdiv, bit_id, prefix, bed_id, pro) {
//	alert($(previewdiv).innerHTML);
	if ($(previewdiv)) {
		if ($(previewdiv).has_content) {
			if (document[prefix+"_preview_"+bit_id]) {
        			document[prefix+"_preview_"+bit_id].Stop();
                        }
			$(previewdiv).innerHTML="&nbsp;";
			$(previewdiv).has_content = 0;
		} else {
                        var params = "";
                        if (pro) {
                                params = "&forcelogin=1";
                        }
			$(previewdiv).has_content = 1;
                        if (bed_id) {
                                // Use bit_id for everything but the actual preview
        			load_content_into(previewdiv, "/media/preview.html?bit_id=" + bed_id + "&prefix=" + prefix + params);
                        } else {
        			load_content_into(previewdiv, "/media/preview.html?bit_id=" + bit_id + "&prefix=" + prefix + params);
                        }
		}
	}
}


function logout() {
	// remove session cookie
	document.cookie = "comexis_session=0; path=/";
        window.location = "/";
}

function makedate(fieldtochange, datetochangeto) {
	var day = new Date();
	if (datetochangeto == "today") {
		// do nothing
	} else if (datetochangeto == "tomorrow") {
		day = new Date(day.getTime()+(1*1000*60*60*24));
	} else if (datetochangeto == "nextbusinessday") {
		// really "next business day"
		if (day.getDay() == 5) {
			// Friday: add three days to get to Monday
			day = new Date(day.getTime()+(3*1000*60*60*24));
		} else if (day.getDay() == 6) {
			// Saturday: add two days to get to Monday
			day = new Date(day.getTime()+(2*1000*60*60*24));
		} else {
			// other: add one day
			day = new Date(day.getTime()+(1*1000*60*60*24));
		}
	}

        var year = day.getFullYear();
        var month = day.getMonth() + 1; // zero-based
        var date = day.getDate();

	if (month < 10) {
		month = "0" + month;
	}

	if (date < 10) {
		date = "0" + date;
	}

        var dateString = year + "-" + month + "-" + date;

        if (fieldtochange) {
        	fieldtochange.value = dateString;
        }
        return dateString;
}

function checkreadytosend(textareatodisable, checkboxtocheck) {
		textareatodisable.disabled = checkboxtocheck.checked; 
}

function preview_newsletter() {
	$('newsletter_news_preview').innerHTML = $('newsletterText').value;
	$('newsletter_prep_preview').innerHTML = $('nightlyBits').value;
	$('newsletter_sound_preview').innerHTML = $('prepText').value;
	$('newsletter_sound_bites').innerHTML = $('soundbiteText').value;
	$('newsletter_suggested_cuts').innerHTML = $('suggestedCuts').value;
	Effect.toggle('newsletter_editor', 'blind', {duration: 0.2, queue: {position:'end', scope: 'preview_newsletter'} });
	Effect.toggle('newsletter_preview', 'appear', {duration: 0.5, queue: {position:'end', scope: 'preview_newsletter'} });
}

function edit_newsletter() {
	Effect.toggle('newsletter_preview', 'appear', {duration: 0.5, queue: {position:'end', scope: 'preview_newsletter'} });
	Effect.toggle('newsletter_editor', 'blind', {duration: 0.2, queue: {position:'end', scope: 'preview_newsletter'} });
}

function clean_dirty_form(form) {
    $A(form.elements).each(function(elt) {
        if (elt.name.indexOf("_") == 0) {
            // only dirty fields get updated
        } else {
            var dirty = $("_" + elt.id);
            if (dirty) {
                form_input_copy(elt, dirty);
            }
        }
    });
}

function form_input_copy(src, dst) {
    // dst is always a hidden field (except for textareas)
    switch (src.tagName.toLowerCase()) {
    case 'input':
        switch (src.type.toLowerCase()) {
        case 'hidden':
        case 'password':
        case 'text':
            dst.value = src.value;
            break;
        case 'checkbox':
            if (src.checked) {
                dst.value = "1";
            } else {
                dst.value = "0";
            }
            break;
        }
        break;
    case 'select':
        dst.value = src.options[src.selectedIndex].value;
        break;
    case 'textarea':
        dst.value = src.value;
        break;
    }
}

function rating_over(img, src) {
    img._src = img.src;
    img.src = src;
}

function rating_out(img) {
    img.src = img._src;
}

function vote(bit_id, rating, img) {
    img._src = img.src;
    bg_load("/pro/vote.ajax?bit_id=" + bit_id + "&rating=" + rating);
}

function add_favorite(bit_id) {
    bg_load("/pro/addfavorite.ajax?bit_id=" + bit_id);
}

function del_favorite(bit_id) {
    bg_load("/pro/delfavorite.ajax?bit_id=" + bit_id);
}

function toggle_favorite(bit_id, img) {
    if (img.src.search("Favorite.png") > -1) {
        del_favorite(bit_id);
        img.src = "/i/AddToFavs.png";
    } else {
        add_favorite(bit_id);
        img.src = "/i/Favorite.png";
    }
}

function contactsend(f) {
	Effect.BlindUp($('write_message'), { duration: 0.5 });
	Effect.BlindDown($('thankyou'), { duration: 0.5, queue: 'end'});
	bg_post_form(f);
}

function sendtoafriend(f) {
	Effect.BlindUp($('sendtoafriend'), { duration: 0.5 });
	Effect.BlindDown($('sendtoafriend_done'), { duration: 0.5, queue: 'end'});
	bg_post_form(f);
}
function signupforspam(f) {
	Effect.BlindUp($('enterform'), { duration: 0.5 });
	Effect.BlindDown($('checkyourmail'), { duration: 0.5, queue: 'end'});
//	bg_post_form(f);
}
function removefromspam(f) {
	Effect.BlindUp($('enterform'), { duration: 0.5 });
	Effect.BlindDown($('checkyourmail'), { duration: 0.5, queue: 'end'});
//	bg_post_form(f);
}

function swaponion(elt, section) {
        var style = "onionbold";
        document.getElementsByClassName(style, this.parentNode).each(function(elt) {
                    Element.removeClassName(elt, style);
        });
        Element.addClassName(elt, style);
        loadOnionSection(section);
}

function loadOnionSection(section) {
        set_spinner("onion_content");
        load_content_into("onion_content", "/pro/onion.ajax?section=" + section);
}

function chooseGroup(link, group) {
	if (link.indexOf("?") >= 0) {
		load_content_into('display_area', link + '&group=' + group);
	} else {
		load_content_into('display_area', link + '?group=' + group);
	}
}

