function subscribeByGuid(guid) {

    try {
        var allSubsChannel;
        allSubsChannel = document.getElementsByTagName("a");
        var subsChannel = new Array();
        for (i = 0; i < allSubsChannel.length; i++) {
            if (allSubsChannel[i].getAttribute('id') == guid) {
                subsChannel.push(allSubsChannel[i]);
            }
        }

        var allImgEls;
        var imgEls = new Array();
        allImgEls = document.getElementsByTagName("img");
        for (i = 0; i < allImgEls.length; i++) {
            if (allImgEls[i].getAttribute('id') == (guid + "-sub-img")) {
                allImgEls[i].setAttribute('src', 'img/btn-process.gif');
                imgEls.push(allImgEls[i]);
            }
        }

        var remoteSubBaseUrl = "subscribe.action";
        var remoteSubUrl = remoteSubBaseUrl + "?channelGuid=" + guid;

        var deferred = dojo.xhrGet({
            url: remoteSubUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                for (i = 0; i < imgEls.length; i++) {
                    imgEls[i].setAttribute('src', 'img/btn-unsubscribe.png');
                }
                for (i = 0; i < subsChannel.length; i++) {
                    subsChannel[i].setAttribute('onclick', 'unsubscribeByGuid("'+guid+'");return false;');
                }
                createSubscribeDialog();
            },

            error: function(response, ioArgs) {
                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }

                var msg = "Subscription failed: " + response;
                alert(msg);
                for (i = 0; i < imgEls.length; i++) {
                    imgEls[i] = document.getElementById(guid + "-sub-img");
                    imgEls[i].setAttribute('src', "img/btn-subs-add.gif")
                }

                logError(response);
            }

        });

    } catch(ex) {
        alert("Subscription failed:" + ex + " - " + ex.message);
    }
}

function unsubscribeByGuid(guid) {
    try {
        var allSubsChannel;
        allSubsChannel = document.getElementsByTagName("a");
        var subsChannel = new Array();
        for (i = 0; i < allSubsChannel.length; i++) {
            if (allSubsChannel[i].getAttribute('id') == guid) {
                subsChannel.push(allSubsChannel[i]);
            }
        }

        var allImgEls;
        var imgEls = new Array();
        allImgEls = document.getElementsByTagName("img");
        for (i = 0; i < allImgEls.length; i++) {
            if (allImgEls[i].getAttribute('id') == (guid + "-sub-img")) {
                allImgEls[i].setAttribute('src', 'img/btn-process.gif');
                imgEls.push(allImgEls[i]);
            }
        }

        var remoteSubBaseUrl = "unsubscribeChannel.action";
        var remoteSubUrl = remoteSubBaseUrl + "?guid=" + guid;

        var deferred = dojo.xhrGet({
            url: remoteSubUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                for (i = 0; i < imgEls.length; i++) {
                    imgEls[i].setAttribute('src', 'img/btn-subs-add.gif');
                }
                for (i = 0; i < subsChannel.length; i++) {
                    subsChannel[i].setAttribute('onclick', 'subscribeByGuid("'+guid+'");return false;');
                }
            },

            error: function(response, ioArgs) {
                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }

                var msg = "Subscription failed: " + response;
                alert(msg);
                for (i = 0; i < imgEls.length; i++) {
                    imgEls[i] = document.getElementById(guid + "-sub-img");
                    imgEls[i].setAttribute('src', "img/btn-unsubscribe.png")
                }

                logError(response);
            }

        });

    } catch(ex) {
        alert("Subscription failed:" + ex + " - " + ex.message);
    }
}

function successfulSubscription(imgEls, subsChannel) {
}

function addToInbox(guid) {

    try {
        var itemA = document.getElementById(guid + "-inbox-item");
        var img = document.getElementById(guid + "-inbox-item-img");

        var remoteSubBaseUrl = "addChannelClipToInbox.action";
        var remoteSubUrl = remoteSubBaseUrl + "?guid=" + guid;

        var deferred = dojo.xhrGet({
            url: remoteSubUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                img.setAttribute('src', 'img/btn-minus-gray.jpg');
                itemA.setAttribute('onclick', 'removeFromInbox("'+guid+'");return false;');
                createAddClipToInboxDialog();
            },

            error: function(response, ioArgs) {
                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }
                var msg = "Failed to add item to Inbox: " + response;
                alert(msg);
                logError(response);
            }

        });

    } catch(ex) {
        alert("Subscription failed:" + ex + " - " + ex.message);
    }
}

function removeFromInbox(guid) {
    try {
        var itemA = document.getElementById(guid + "-inbox-item");
        var img = document.getElementById(guid + "-inbox-item-img");

        var remoteSubBaseUrl = "removeItemFromInbox.action";
        var remoteSubUrl = remoteSubBaseUrl + "?originalChannelItemGuid=" + guid;

        var deferred = dojo.xhrGet({
            url: remoteSubUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                img.setAttribute('src', 'img/btn-plus.jpg');
                itemA.setAttribute('onclick', 'addToInbox("'+guid+'");return false;');
            },

            error: function(response, ioArgs) {
                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }
                var msg = "Failed to add item to Inbox: " + response;
                alert(msg);
                logError(response);
            }
        });
    } catch(ex) {
        alert("Subscription failed:" + ex + " - " + ex.message);
    }
}

function displayElement(elementId) {
    var subscribingMessage = document.getElementById(elementId);
    subscribingMessage.style.display = "";
}

function hideElement(elementId) {
    var e = document.getElementById(elementId);
    e.style.display = "none;";
}

function subscribeByUrl(url, isPrivate) {
    try {
        var subscribingMessage = document.getElementById('subscribing-message');
        subscribingMessage.innerHTML = "<p>Subscribing to channel <img src='img/progress1.gif'/></p>";
        subscribingMessage.style.display = "";

        var feedUrlField = document.getElementById('importfeed-url');

        var remoteBaseUrl = "subscribe.action";
        var remoteUrl = remoteBaseUrl + "?channelUrl=" + url + "&privateFeed=" + isPrivate;

        var deferred = dojo.xhrGet({
            url: remoteUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                subscribingMessage.innerHTML = "<p>Subscription successful!</p>";
                feedUrlField.value = "";

                createSubscribeDialog();
            },

            error: function(response, ioArgs) {

                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }

                var msg = "Subscription failed: " + response;
                subscribingMessage.innerHTML = "<p>" + msg + "</p>";
                subscribingMessage.className = "error";

                logError(response);
            }
        });

    } catch(ex) {
        alert("Subscription failed:" + ex);
    }
}

function logError(response) {
    if (response.dojoType == "cancel") {
        console.debug("Request canceled.");
    } else if (response.dojoType == "timeout") {
        console.debug("Request timed out.");
    } else {
        console.error(response);
    }

}

function addFriendByName(userName) {

    try {
        friend = document.getElementById(userName);
        friend.firstChild.nodeValue = 'Processing';
        var remoteBaseUrl = "addFriend.action";
        var remoteUrl = remoteBaseUrl + "?userName=" + userName;


        var deferred = dojo.xhrGet({
            url: remoteUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                friend.parentNode.innerHTML = '<i>A friend of yours</i>';
            },

            error: function(response, ioArgs) {

                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }

                friend = document.getElementById(guid);
                var msg = "Add friend failed: " + response;
                alert(msg);
                friend.firstChild.nodeValue = 'Add to friends';

                logError(response);
            }
        });

    } catch(ex) {
        alert("Failed to add friend:" + ex);
    }
}

function submitSubscribeSearchFeedUrl(query, isPrivate) {
    try {

        var yahooUrl = "http://api.search.yahoo.com/VideoSearchService/rss/videoSearch.xml?appid=ysearchblog&adult_ok=1&results=50&format=mpeg&query="
            + URLencode(query);
        var remoteBaseUrl = "subscribe.action";
        var remoteUrl =
            remoteBaseUrl +
            "?title=Search Feed: " + query +
            "&privateFeed=" + isPrivate +
            "&channelUrl=" + URLencode(yahooUrl);

        var subscribingMessage = document.getElementById('subscribing-message');
        subscribingMessage.innerHTML = "<p>Subscribing to channel <img src='img/progress1.gif'/></p>";
        var keywordsField = document.getElementById('searchfeed-keywords');

        subscribingMessage.style.display = "";

        var deferred = dojo.xhrGet({
            url: remoteUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                subscribingMessage.innerHTML = "<p>Subscription successful!</p>";
                keywordsField.value = "";
                updateSearchLink();
                createSubscribeDialog();
            },

            error: function(response, ioArgs) {

                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }

                var msg = "Subscription failed: " + response;
                subscribingMessage.innerHTML = "<p>" + msg + "</p>";
                subscribingMessage.className = "error";

                logError(response);
            }
        });

    } catch(ex) {
        alert("Subscription failed:" + ex);
    }
}


function searchFeedTimeoutHandler() {
    if (searchFeedTimeoutId) {
        clearTimeout(searchFeedTimeoutId);
        searchFeedTimeoutId = 0;
    }
    if (searchFeedNameUrl.length > 0 && searchFeedNameUrl != searchFeedNameUrlNow) {
        searchFeedNameUrlNow = searchFeedNameUrl;
    }
}

function URLencode(sStr) {
    return escape(sStr).
        replace(/\+/g, '%2B').
        replace(/\"/g, '%22').
        replace(/\'/g, '%27').
        replace(/\//g, '%2F');
}

function showBookmarkletInstallLink(browser) {
    var aie = document.getElementById('ie-link');
    var aff = document.getElementById('ff-link');
    var asaf = document.getElementById('safari-link');
    var aop = document.getElementById('opera-link');
    aie.style.display='none'
    aff.style.display='none'
    asaf.style.display='none'
    aop.style.display='none'

    if (browser == 'ie') {
        aie.style.display='block'
    } else if (browser == 'ff') {
        aff.style.display='block'
    } else if (browser == 'saf') {
        asaf.style.display='block'
    } else if (browser == 'op') {
        aop.style.display='block'
    }
}


function updateSearchLink() {
    try {
        var t = document.f.feed.value;
        var privateChannel = "no";
        if (document.f.isPrivate.checked) {
            privateChannel = "yes";
        }
        var a2 = document.getElementById("searchFeedSubscriptionLink");
        var l = document.getElementById("searchFeedLinkSpan");
        if (t.length > 0) {
            var subscribeUrl = "javascript:submitSubscribeSearchFeedUrl(\"" + t + "\",\"" + privateChannel + "\")";
            a2.href = subscribeUrl;
            a2.title = "Click to subscribe to channel"
            l.style.display = 'block';
            searchFeedNameUrl = subscribeUrl;
            if (document.f.feed.value.match(/[ ,]$/)) {
                searchFeedTimeoutHandler();
            } else {
                if (searchFeedTimeoutId) {
                    clearTimeout(searchFeedTimeoutId);
                }
                searchFeedTimeoutId = setTimeout("searchFeedTimeoutHandler()", 250);
            }
        } else {
            l.style.display = 'none';
        }
    } catch(ex) {
        alert("Subscription Failed:" + ex);
    }
}

function set_youtube_feedtype(type) {
    var label = document.getElementById("tag_user");
    var label_help = document.getElementById("tag_user_help");
    var clipiti_tags = document.getElementById("clipiti_tags");

    if (type == "tag") {
        label.innerHTML = "Tag: <span class='help-emphasize'>*</span>";
        label_help.innerHTML = "Enter a YouTube tag (for example, Funny).";
        clipiti_tags.innerHTML = "";
    } else if (type == "user") {
        label.innerHTML = "YouTube user: <span class='help-emphasize'>*</span></span>";
        label_help.innerHTML = "Enter a YouTube user name (for example, DiscoveryNetworks)";
        clipiti_tags.innerHTML =
            "<th class='with-min-width'>" +
            "   <label for='importfeed-tags'>Clipiti Tags: <span class='help'>(Optional)</span></label>" +
            "</th>"+
            "<td>" +
            "   <input id='importfeed-tags' name='tags' type='text' value=''/> " +
            "   <span class='help'>Separate the tags with commas (i.e. the character ',')</span>"+
            "</td>";
    }
}

function deleteItem(itemGuid, channelGuid, elementId) {

    try {
        itemRow = document.getElementById(elementId);
        var remoteBaseUrl = "deleteItem.action";
        var remoteUrl = remoteBaseUrl + "?itemGuid=" + itemGuid + "&channelGuid=" + channelGuid;

        var deferred = dojo.xhrGet({
            url: remoteUrl,
            handleAs: "text",
            timeout: 15000,

            load: function(response, ioArgs) {
                itemRow.style.display = "none";
            },

            error: function(response, ioArgs) {

                if (dojo.isSafari) {
                    // ugly safari workaround
                    this.load(response, ioArgs);
                    return;
                }

                alert("command failed: " + response);
                logError(response);
            }
        });

    } catch(ex) {
        alert("Delete Item Failed:" + ex);
    }
}

function getNode(nodeId) {
    if (document.getElementById) {
        return document.getElementById(nodeId);
    } else if (document.all && document.all(nodeId)) {
        return document.all(nodeId);
    } else if (document.layers && document.layers[ nodeId ]) {
        return document.layers[ nodeId ];
    } else {
        return false;
    }
}

function clearSearch(input) {
    if (input.value == "Search for video") input.value = "";
}


function createIntroDialog() {
    if (introDialog == null) {
        var introPane = document.getElementById('intro-pane');
        introPane.style.padding = "0px";
        introDialog = new dijit.Dialog({
            title: "",
            href: "/help/intro_step1.jsp"
        }, introPane);
    } else {
        introDialog.setHref("/help/intro_step1.jsp");
    }
    introDialog.show();
}

function updateIntroDialog(url) {
    introDialog.setHref(url);
}

function closeIntroDialog() {
    introDialog.hide();
}

function createSubscribeDialog() {

    var hideDialog = cookie("clipiti.web.prefs.hide-subscribe-notify");
    if (hideDialog == "true") {
        return;
    }

    if (!channelSubscribeNotify) {
        var pane = dojo.byId('channel-subscribe-notify-pane');
        pane.style.padding = "10px";
        channelSubscribeNotify = new dijit.Dialog({
            title: "Subscribed... Now what?",
            duration: 500
        }, pane);
    }

    channelSubscribeNotify.show();
    setTimeout("channelSubscribeNotify.hide()", "8000");

}

function disableSubscribeNotify() {
    var checkbox = document.getElementById('hide-subscribe-notify-cb');
    if (checkbox.checked) {
        cookie("clipiti.web.prefs.hide-subscribe-notify", "true", {expires: 1000});
    } else {
        cookie("clipiti.web.prefs.hide-subscribe-notify", "false", {expires: -1});  // delete cookie
    }
}

function createAddClipToInboxDialog() {

    var hideDialog = cookie("clipiti.web.prefs.hide-add-clip-to-inbox-notify");
    if (hideDialog == "true") {
        return;
    }

    if (!addClipToInboxNotify) {
        var pane = dojo.byId('add-clip-to-inbox-notify-pane');
        pane.style.padding = "10px";
        addClipToInboxNotify = new dijit.Dialog({
            title: "Clip Added to Inbox",
            duration: 500
        }, pane);
    }

    addClipToInboxNotify.show();
    setTimeout("addClipToInboxNotify.hide()", "8000");
}

function disableAddClipToInboxNotify() {
    var checkbox = document.getElementById('hide-add-clip-to-inbox-notify-cb');
    if (checkbox.checked) {
        cookie("clipiti.web.prefs.hide-add-clip-to-inbox-notify", "true", {expires: 1000});
    } else {
        cookie("clipiti.web.prefs.hide-add-clip-to-inbox-notify", "false", {expires: -1});  // delete cookie
    }
}


// borrowed from dojo
function cookie(name, value, props) {
    var c = document.cookie;
    if (arguments.length == 1) {
        var idx = c.lastIndexOf(name + '=');
        if (idx == -1) {
            return null;
        }
        var start = idx + name.length + 1;
        var end = c.indexOf(';', idx + name.length + 1);
        if (end == -1) {
            end = c.length;
        }
        return decodeURIComponent(c.substring(start, end));
    } else {
        props = props || {};
        value = encodeURIComponent(value);
        if (typeof(props.expires) == "number") {
            var d = new Date();
            d.setTime(d.getTime() + (props.expires * 24 * 60 * 60 * 1000));
            props.expires = d;
        }
        document.cookie = name + "=" + value
            + (props.expires ? "; expires=" + props.expires.toUTCString() : "")
            + (props.path ? "; path=" + props.path : "")
            + (props.domain ? "; domain=" + props.domain : "")
            + (props.secure ? "; secure" : "");
        return null;
    }
}

function getCategoryPath(treeItem) {
    alert(popStore.getLabel(treeItem));
}



//////////////////////////// globals /////////////////////////
var channelSubscribeNotify;
var addClipToInboxNotify;
var introDialog;
