function refreshPage() {
    location.reload(true);
}

// Refresh every 30 minutes
setTimeout('refreshPage()', 1800000);

var headlineTwistOpenStyle = "topic-collapse";
var headlineTwistCollapsedStyle = "topic-collapse-closed";

var channelCollapseStyle = "mod-collapse";
var channelCollapseClosedStyle = "mod-collapse-closed";

var channelHeadlineOpenStyle = "channel-Headlines";
var channelHeadlineClosedStyle = "channel-Headlines-closed";

var emailHeadlineOpenStyle = "email-headline";
var emailHeadlineClosedStyle = "email-headline-closed";

var editHeadlineOpenStyle = "edit-headline";
var editHeadlineClosedStyle = "edit-headline-closed";

function compexpHeadline(hlid, twist) {
    // hlid is a combo string of the channel number and headline number "chnum-hlnum"
    var imgElem = document.getElementById("img-"+hlid);
    var styleClass = "";
    var contentElem = document.getElementById("content-"+hlid);
    var editHeadlineLink = document.getElementById("editheadline-"+hlid);
    var emailHeadlineLink = document.getElementById("emailheadline-"+hlid);
    var twitterHeadlineLink = document.getElementById("twitterheadline-"+hlid);

    if (contentElem != null) {
        if (contentElem.className == "topic-stat-closed") {
            contentElem.className = "topic-stat";
            styleClass = headlineTwistOpenStyle;
            emailHeadlineStyle = emailHeadlineOpenStyle;
            editHeadlineStyle = editHeadlineOpenStyle;
            twitterHeadlineStyle = editHeadlineOpenStyle;
        } else {
            contentElem.className = "topic-stat-closed";
            styleClass = headlineTwistCollapsedStyle;
            emailHeadlineStyle = emailHeadlineClosedStyle;
            editHeadlineStyle = editHeadlineClosedStyle;
            twitterHeadlineStyle = editHeadlineClosedStyle;
        }
    }

    if (imgElem != null) {
        if ((styleClass == headlineTwistOpenStyle) && (hlCompressionSetting == 1))  {
            imgElem.className = "imgChanger";
        } else {
            imgElem.className = "imgChanger-closed";
        }
    }


    twist.className = styleClass;
    emailHeadlineLink.className = emailHeadlineStyle;
    if (editHeadlineLink != null) editHeadlineLink.className = editHeadlineStyle;
    if (twitterHeadlineLink != null) twitterHeadlineLink.className = twitterHeadlineStyle;
    
}

// Compress or expand a channel
function compexpChannel(chid, twist, direction) {
    var headlines = new Array;
    var i;
    var aHeadline;
    var className;
    
    for (i=0;i<500;i++) {
        aHeadline = document.getElementById("channel-Headlines-"+chid+"-"+i);
        if (aHeadline != null) {
            headlines.push(aHeadline);
        } else {
            break;
        }
    }
    
   if (typeof direction != "undefined") {
        if (direction == "collapse") {
            className = channelCollapseClosedStyle;
            channelHeadlineStyle = channelHeadlineClosedStyle;
        } else if (direction == "expand") {
            className = channelCollapseStyle;
            channelHeadlineStyle = channelHeadlineOpenStyle;
        }
        twist.className = className;
   } else {
        if (twist.className == channelCollapseClosedStyle) {
            channelHeadlineStyle = channelHeadlineOpenStyle;
        } else {
            channelHeadlineStyle = channelHeadlineClosedStyle;
        }
        twist.className = (twist.className == channelCollapseClosedStyle) ? 
            channelCollapseStyle : channelCollapseClosedStyle;
   }
    
    if (headlines.length > 0) {
        for (i=0;i<headlines.length;i++) {
            headlines[i].className = channelHeadlineStyle;
        }
    }
}

function collapseAllChannels() {
    var i;
    var twist;
    var aChannel;
    // Channel numbers are one based
    for (i=1;i<500;i++) {
        aChannel = document.getElementById("channel-content-"+i);
        if (aChannel != null) {
            twist = document.getElementById("twist-"+i);
            compexpChannel(i, twist, "collapse");
        } else {
            break;
        }
    }
    ajax("services/setmychannelprops.php", "&chcomp=0", handleCollapseChannelsResponse);
}

function expandAllChannels() {
    var i;
    var twist;
    var aChannel;
    // Channel numbers are one based
    for (i=1;i<500;i++) {
        aChannel = document.getElementById("channel-content-"+i);
        if (aChannel != null) {
            twist = document.getElementById("twist-"+i);
            compexpChannel(i, twist, "expand");
        } else {
            break;
        }
    }
    ajax("services/setmychannelprops.php", "&chcomp=1", handleCollapseChannelsResponse);
}

function handleCollapseChannelsResponse(contents) {
}

var currentHLId;
var currentWPId;
var currentChannelNum;
var currentHLNum;
var hasWP;
function setHeadlineId(channelNum, hlNum) {
    var address = "hl_"+channelNum+"_"+hlNum;
    currentHLId = hlInfo[address]["hlid"];
    currentWPId = hlInfo[address]["wpid"];
    currentChannelNum = channelNum;
    currentHLNum = hlNum;
    hasWP = hasWatchPoint(channelNum, hlNum);
}

function setPersonalItems(hlId, markasread, markasremove, markasflagged) {
    var vars = "&hlid="+hlId+"&markasread="+markasread+"&removeitem="+markasremove+"&hlflagged="+markasflagged;
    ajax("./services/setPersonalItem_srvc.php", vars, finishPersonalItem);
}
function finishPersonalItem(contents, responseDoc) {
    var headlineDiv = document.getElementById("channel-Headlines-"+currentChannelNum+"-"+currentHLNum);
    headlineDiv.className = "channel-Headlines-closed";
}
function hideHeadline() {
    setPersonalItems(currentHLId, 1, 1, 0);
}
function subscribeChannel(chid) {
     ajax("./services/dosubscribe_srvc.php", "&chid="+chid, handleSubscribeChannelResponse);
}
function handleSubscribeChannelResponse(contents, responseDoc) {
    var statusElems = responseDoc.getElementsByTagName("status");
    if (statusElems.length > 0) {
        var status=statusElems[0];
        var statusValue = status.getAttribute("value");
        var statusDesc = status.getAttribute("desc");
        if (status.getAttribute("value") == "1") {
            window.location.href = "/?wp=my";
        } else {
            alert(statusDesc);
        }
    }
 }
function unsubscribeChannel(chid) {
     ajax("./services/dounsubscribe_srvc.php", "&chid="+chid, handleUnsubscribeChannelResponse);
}
function handleUnsubscribeChannelResponse(contents, responseDoc) {
    var statusElems = responseDoc.getElementsByTagName("status");
    if (statusElems.length > 0) {
        var status=statusElems[0];
        var statusValue = status.getAttribute("value");
        var statusDesc = status.getAttribute("desc");
        if (status.getAttribute("value") == "1") {
            window.location.href = "/?wp=my";
        } else {
            alert(statusDesc);
        }
    }
 }
function registerAndSubscribe(chid) {
    window.location.href="/?wp=join&subscribe="+chid;
}
// Channel editing
function editChannelProps(e) {
    if (document.body.style.overflow == "hidden") {
        scrim.style.width = "1024";
        scrim.style.height = "100%";
    }
    
    var delChannelButton = document.getElementById("delChannel");
    if (!getIsOwner(currentChannelNum)) {
        delChannelButton.style.display="none";
    } else {
        delChannelButton.style.display="";
    }

    var pos = Spry.Widget.Utils.getAbsoluteMousePosition(e);
    editPropsDiv.style.top = (pos.y+20)+"px";
    editPropsDiv.style.left = "25px";
    editPropsDiv.style.zIndex=50;

    scrim.style.top = "0px";
    scrim.style.height = "100%";
    scrim.style.display = "block";

    ajax("services/getchannelprops_srvc.php", "&chid="+currentchid, handleGetChannelPropsResponse);
}
function handleGetChannelPropsResponse(content, responseDoc) {
    var statusElems = responseDoc.getElementsByTagName("status");
    var status = (statusElems.length > 0) ? statusElems[0] : null;
    
    if (status.getAttribute("value") != "0") {
        alert("Error retrieving channel information: "+status.getAttribute("desc"));
        scrim.style.display = "";
        return;
    }
    var channelElems = responseDoc.getElementsByTagName("channel");
    var channel = (channelElems.length > 0) ? channelElems[0] : null;
    
    var channelName = "";
    var channelDesc = "";
    var channelTags = "";
    var channelRSS = 0;
    var channelPublish = 0;
    
    if (channel != null) {
        document.getElementById("chpropsname").value = channel.getAttribute("name");
        document.getElementById("chpropsdesc").value = channel.getAttribute("desc");
        document.getElementById("chpropstags").value = channel.getAttribute("tags");
        document.getElementById("chalias").value = channel.getAttribute("chalias");
        document.getElementById("chaliasexample").innerHTML = "http://webpartner.com/"+channel.getAttribute("chalias");
        var allowcontact = channel.getAttribute("allowcontact");
        var radios = document.getElementsByName("challowcontact");
        var i;
        for (i=0;i<radios.length;i++) {
            radios[i].checked = (radios[i].value == allowcontact) ? true : false;
        }

        var publishState = channel.getAttribute("pubstate");
        var selected = "";
        selected = (publishState == "4") ? true : false;

        var publicOption = document.getElementById("chpublic");
        publicOption.selected = selected;

        selected = (publishState == "4") ? false : true;
        var privateOption = document.getElementById("chprivate");
        privateOption.selected = selected;
        
        channelRSS = channel.getAttribute("pubrssfeed");
        document.getElementById("chrsspub").checked = (channelRSS == "1") ? true : false;
    }

    editPropsDiv.style.display="block";
}

function saveChannelProps(chNum) {
    var chProps = new Object();
    chProps.chid = currentchid;
    chProps.chname = document.getElementById("chpropsname").value;
    chProps.chdesc = document.getElementById("chpropsdesc").value;
    chProps.chtags = document.getElementById("chpropstags").value;
    chProps.chpubstate = document.getElementById("publish-status").value;
    chProps.chpubrss = document.getElementById("chrsspub").checked;
    //chProps.chtwituname = document.getElementById("chtwituname").value;
    //chProps.chtwitpw = document.getElementById("chtwitpw").value;
    chProps.chalias = document.getElementById("chalias").value;
    // Enforce some rules on no spaces or punctuation on the channel alias
    if (chProps.chalias.length > 0) {
        // Collapse any spaces and punctuation we see
        chProps.chalias = chProps.chalias.replace(/[\s\!\^\@\#\$\%\&\*\(\)\+\?\\\{\}\[\]\:\;\|]*/g, "");
    }
    var radios = document.getElementsByName("challowcontact");
    var i;
    for (i=0;i<radios.length;i++) {
        if (radios[i].checked) {
            chProps.challowcontact = radios[i].value;
            break;
        }
    }
    
    var chPropsJSON = JSON.stringify(chProps);
    ajax("services/setchannelprops_srvc.php", "&json="+escape(chPropsJSON), handleSaveChannelPropsResponse);
}
function handleSaveChannelPropsResponse(contents,xmldoc){
    var wpProps = eval("("+contents+")");
    if (wpProps.status != 0) {
        alert(wpProps.desc);
    } else {
        var editChannelDiv = document.getElementById("editChannelProps");
        editChannelDiv.style.display="none";
        scrim.style.display = "none";
        window.location.reload(true);
    }
}
function cancelChannelProps(chNum) {
    editPropsDiv.style.display="none";
    scrim.style.display = "none";
}
// WatchPoint editing
function editWatchPointProps(e) {
    var editHeadlineDiv = document.getElementById("editHeadlineProps");
    if (document.body.style.overflow == "hidden") {
        scrim.style.width = "1024";
        scrim.style.height = "100%";
    }
    
    var pos = {x:0, y:0};    
    if (e != null) {
        pos = Spry.Widget.Utils.getAbsoluteMousePosition(e);
        editWatchPointDiv.style.top = pos.y+"px";
        editWatchPointDiv.style.left = pos.x+"px";
    } else {
        editWatchPointDiv.style.top = editHeadlineDiv.style.top;
        editWatchPointDiv.style.left = editHeadlineDiv.style.left;
    }
    
    scrim.style.top = "0px";
    scrim.style.height = "100%";
    scrim.style.display = "block";
   
    editHeadlineDiv.style.display="none";
    ajax("services/getwatchpointprops_srvc.php", "&wpid="+currentWPId, handleGetWatchPointPropsResponse);
}
var SYNPREPEND = 1;
var SYNFIRSTXWORDS = 2;
var SYNFIRSTIMAGE = 4;
var SYNDIFFERENCE = 16;
function handleGetWatchPointPropsResponse(contents, xmldoc) {
    var wpProps = eval("("+contents+")");
    
    if (wpProps.status == 0) {
        document.getElementById("wpname").value = wpProps.name;
        document.getElementById("wpprepend").value = wpProps.wpprepend;
        document.getElementById("wpkeywordscheck").checked = (wpProps.wpkeywords.length > 0);
        document.getElementById("wpkeywords").value = wpProps.wpkeywords;
        document.getElementById("wpgenfromimg").checked = wpProps.wpgenfromimg;
        var doFirstXWords = (wpProps.wpsyntype & SYNFIRSTXWORDS) == SYNFIRSTXWORDS;
        var doDiffXWords = (wpProps.wpsyntype & SYNDIFFERENCE) == SYNDIFFERENCE;
        document.getElementById("wpstdradio").checked = doFirstXWords;
        document.getElementById("wpdiffradio").checked = doDiffXWords;
        document.getElementById("wpstdfirst").value = doFirstXWords ? wpProps.wpsynwordlimit : "0";
        document.getElementById("wpdifffirst").value = doDiffXWords ? wpProps.wpsynwordlimit : "0";
        
        document.getElementById("wpshowlargestimg").checked = wpProps.wpsynincimage;
        var nominalChNum = getNominalSubscrChannelNum(wpProps.wpchid);
        setSelectOption(document.getElementById("wpchannelselect"), nominalChNum, true);
        setSelectOption(document.getElementById("wpinterval"), wpProps.wpinterval, true);
    }

    editWatchPointDiv.style.display="";
}
function saveWatchPointProps() {
    var wpProps = new Object();
    
    wpProps.wpname = document.getElementById("wpname").value;

    var syntype = 0;
    wpProps.wpprepend = document.getElementById("wpprepend").value ;
    if (wpProps.wpprepend.length == 0) {
        alert("Please attribute the headlines of this WatchPoint to a source.");
        return;
    }
    
    // Close the dialog
    editWatchPointDiv.style.display="none";
    scrim.style.display = "none";
    editWatchPointDiv.style.display="none";
    
    syntype = syntype | SYNPREPEND;

    if (document.getElementById("wpkeywordscheck").checked) {
        wpProps.wpkeywords = document.getElementById("wpkeywords").value;
    } else {
        wpProps.wpkeywords = "";
    }
    wpProps.wpgenfromimg = document.getElementById("wpgenfromimg").checked;
    
    var doFirstXWords = document.getElementById("wpstdradio").checked;
    var doDiffXWords = document.getElementById("wpdiffradio").checked;
    
    if (doFirstXWords) {
        syntype = syntype | SYNFIRSTXWORDS;
    } else if (doDiffXWords) {
        syntype = syntype | SYNDIFFERENCE ;
    } 
    
    var wordlimit = 0;
    if (doFirstXWords) {
        wpProps.wpsynwordlimit = document.getElementById("wpstdfirst").value
    } else if (doDiffXWords) {
        wpProps.wpsynwordlimit = document.getElementById("wpdifffirst").value
    }

    wpProps.wpsynincimage = document.getElementById("wpshowlargestimg").checked;
    if (wpProps.wpsynincimage) {
        syntype = syntype | SYNFIRSTIMAGE;
    }
    
    wpProps.wpchid = getChannelIdFromSubscriptionList(document.getElementById("wpchannelselect").value);    
    wpProps.wpinterval = document.getElementById("wpinterval").value;
    wpProps.wpsyntype = syntype;
    wpProps.wpid = currentWPId;
    
    var wpPropsJSON = JSON.stringify(wpProps);
    ajax("services/setwatchpointprops_srvc.php", "&json="+escape(wpPropsJSON), handleWatchPointPropsSave);
}
function handleWatchPointPropsSave(contents, xmldoc) {
}
function cancelWatchPointProps() {
    var editWatchPointDiv = document.getElementById("editWatchPointProps");
    editWatchPointDiv.style.display="none";
    scrim.style.display = "none";
    editWatchPointDiv.style.display="none";
}
function deleteWatchPointButton() {
    var wpid = currentWPId;
    editWatchPointDiv.style.display="none";
    scrim.style.display = "none";
    editWatchPointDiv.style.display="none";
    ajax("services/deletewatchpoint_srvc.php", "&wpid="+wpid, handleDeleteWatchPointResponse);
}
function handleDeleteWatchPointResponse(contents, responseDoc) {
    window.location.reload(true);    
}
// Headline editing
function editHeadlineProps(e) {
    var editWatchPointDiv = document.getElementById("editWatchPointProps");
    if (document.body.style.overflow == "hidden") {
        scrim.style.width = "1024";
        scrim.style.height = "100%";
    }
    
    // Turn on or off the edit watchpoint button as appropriate
    editWatchPointButton = document.getElementById("editWatchpointBtn");
    editWatchPointButton.style.display = (hasWatchPoint(currentChannelNum, currentHLNum)) ? "" : "none";
    
    var pos = {x:0, y:0};    
    if (e != null) {
        pos = Spry.Widget.Utils.getAbsoluteMousePosition(e);
        editHeadlineDiv.style.top = pos.y+"px";
        editHeadlineDiv.style.left = pos.x+"px";
    } else {
        editHeadlineDiv.style.top = editWatchPointDiv.style.top;
        editHeadlineDiv.style.left = editWatchPointDiv.style.left;
    } 

    scrim.style.top = "0px";
    scrim.style.height = "100%";
    scrim.style.display = "block";

    editWatchPointDiv.style.display="none";
    
    ajax("services/getheadlineprops_srvc.php", "&hlid="+currentHLId, handleGetHeadlinePropsResponse);
}
function handleGetHeadlinePropsResponse(contents, responseDoc) {
    var headline = eval("("+contents+")");
    var hlName = headline.hlname;
    var hlSynopsis = headline.synopsis;
    var hlImageURL = headline.imgurl;
    var hlIncludeImage = headline.incimage;
    var hlChId = headline.chid;
    var hlURL = headline.hltargeturl;

    document.getElementById("hlname").value = hlName;
    document.getElementById("hlurl").value = hlURL;
    document.getElementById("hlsynopsis").value = hlSynopsis;
    document.getElementById("hlimgurl").value = hlImageURL;
    document.getElementById("hlincimg").checked = hlIncludeImage;

    var nominalChNum = getNominalSubscrChannelNum(hlChId);
    setSelectOption(document.getElementById("hlchannelselect"), nominalChNum, true);

    editHeadlineDiv.style.display="";
}
function saveHeadlineProps() {
    var editHeadlineDiv = document.getElementById("editHeadlineProps");
    editHeadlineDiv.style.display="none";
    scrim.style.display = "none";
    editHeadlineDiv.style.display="none";
    
    var hlProps = new Object();
    
    hlProps.hlname = document.getElementById("hlname").value;
    hlProps.hlurl = document.getElementById("hlurl").value;
    hlProps.hlsynopsis = document.getElementById("hlsynopsis").value;
    hlProps.hlincludeimage = document.getElementById("hlincimg").checked;
    hlProps.hlimageurl = (hlProps.hlincludeimage) ? document.getElementById("hlimgurl").value : "";
    hlProps.hlobscureid = currentHLId;

    hlProps.hlchid = getChannelIdFromSubscriptionList(document.getElementById("hlchannelselect").value);
    
    var hlPropsJSON = JSON.stringify(hlProps);
    ajax("services/setheadlineprops_srvc.php", "&json="+escape(hlPropsJSON), handleHeadlinePropsSave);
}
function handleHeadlinePropsSave(contents, xmldoc) {
    window.location.reload(true);
}
function cancelHeadlineProps() {
    var editHeadlineDiv = document.getElementById("editHeadlineProps");
    editHeadlineDiv.style.display="none";
    scrim.style.display = "none";
    editHeadlineDiv.style.display="none";
}
function deleteHeadlineButton() {
    ajax("services/deleteheadline_srvc.php", "&hlid="+currentHLId, handleDeleteHeadlineResponse);
}
function handleDeleteHeadlineResponse(contents,xmldoc) {
    window.location.reload(true);
}
function editWatchpointButton() {
    var editHeadlineDiv = document.getElementById("editHeadlineProps");
    editHeadlineDiv.style.display="none";
    var editWatchPointDiv = document.getElementById("editWatchPointProps");
    editWatchPointDiv.style.top = editHeadlineDiv.style.top;
    editWatchPointDiv.style.left = editHeadlineDiv.style.top;
    editWatchPointProps(null);
}
function archiveHeadlineButton() {
    alert("Coming soon");
}

function removeChannel(chNum) {
    alert("coming soon");
}
var okFunction;
var cancelFunction;
function deleteChannel(e) {
    if (getIsOwner(currentChannelNum)) {
        scrim100.style.display="block"
        if (document.body.style.overflow == "hidden") {
            scrim100.style.width = "1024";
            scrim100.style.height = "100%";
        }
        var pos = Spry.Widget.Utils.getAbsoluteMousePosition(e);
        okcancel.style.top = (pos.y-100)+"px";
        okcancel.style.left = (pos.x+50)+"px";
        okcancel.style.width = "200px";
        
        okFunction = doDeleteChannel;
        cancelFunction = null;   
        var okcancelMsg = document.getElementById("okcancelmsg");
        okcancelMsg.innerHTML = "Are you sure you want to delete this channel?";
        okcancel.style.display="";
    } else {
        alert("To delete a channel you must be the owner of the channel");
    }
}
function cancelOkCancel() {
    okcancel.style.display="none";
    scrim100.style.display="none";
    if (cancelFunction != null) {
        cancelFunction();
    }
}
function confirmOkCancel() {
    okcancel.style.display="none";
    scrim100.style.display="none";
    if (okFunction != null) {
        okFunction();
    }
}
function doDeleteChannel() {
    var chid = getChannelObscureId(currentChannelNum);
    ajax("services/deletechannel_srvc.php", "&chid="+chid, handleDeleteChannelResponse);
}
function handleDeleteChannelResponse(contents,xmldoc) {
    window.location.reload(true);
}
function getChannelObscureId(nominalChannelNum) {
    return channelInfo[nominalChannelNum]["chid"];
}
function getChannelIdFromSubscriptionList(nominalChannelNum) {
    return editInfo[nominalChannelNum]["chid"];
}
function getNominalSubscrChannelNum(chid) {
    var i;
    for (var i in editInfo) {
        if (editInfo[i]["chid"] == chid) {
            return i;
        }
    }
    return -1;
}
function getChannelName(nominalChannelNum) {
    return channelInfo[nominalChannelNum]["chname"];
}
function getChannelCanEdit(nominalChannelNum) {
    return channelInfo[nominalChannelNum]["canedit"];
}
function getIsOwner(nominalChannelNum) {
    return channelInfo[nominalChannelNum]["owner"];
}
function hasWatchPoint(nominalChannelNum, nominalHeadlineNum) {
    var address = "hl_"+nominalChannelNum+"_"+nominalHeadlineNum;
    var wpid = hlInfo[address]["wpid"];
    return (wpid.length != 0);             
}
function doEdit(e) {
    if (hasWatchPoint(currentChannelNum, currentHLNum)) {
        editWatchPointProps(e);
    } else {
        editHeadlineProps(e);
    }
}
function setSelectOption(selectElem, itemValueLookup, isSelected) {
    var $i;
    for ($i=0;$i<selectElem.options.length;$i++) {
        selectElem.options[$i].selected = (selectElem.options[$i].value == itemValueLookup) ? true : false;
    }
}
function doTwitter(e) {
    var headlineId = currentHLId;
    ajax("services/sendtwitterheadline.php", "&hlid="+headlineId, handleTwitterPushResponse);
}
function handleTwitterPushResponse(contents, xmldoc) {
    alert("Tweet complete");
}
