var g_id = 0;
var g_contextId = 0;
var g_placeForDetails = true;
var g_issue = null;
var pageTracker = null;
var g_largeDialogWidth = 860;
var g_largeDialogWrapMarginTopBottom = 20;
var g_largeDialogWidthwrap = 920;

function orig(elm) {
    elm.src = elm.src.replace('http://cache.coverbrowser.com/', 'http://www.coverbrowser.com/');
}

function buyClick(name, issue) {
    if (pageTracker) { pageTracker._trackPageview('/buy-click/' + name + '/' + issue); }
}

function toggleGroup(id) {
    var group = document.getElementById("group" + id);
    var groupSwitch = document.getElementById("groupSwitch" + id);
    if (group && groupSwitch) {
        if (group.style.display == "inline") {
            groupSwitch.innerHTML = groupSwitch.innerHTML.replace("ga2.png", "ga.png");
            group.style.display = "none";
            // window.location.href = '/#';
        }
        else {
            groupSwitch.innerHTML = groupSwitch.innerHTML.replace("ga.png", "ga2.png");
            group.style.display = "inline";
            // parent.location.hash = id.toLowerCase(id);
        }
    }
}

function toggleGroup_loadDynamic(id, groupName) {
    var group = document.getElementById("group" + id);
    var groupSwitch = document.getElementById("groupSwitch" + id);
    if (group && groupSwitch) {
        if (group.style.display == "inline") {
            groupSwitch.innerHTML = groupSwitch.innerHTML.replace("&lt;&lt;", "&gt;&gt;");
            group.style.display = "none";
        }
        else {
            groupSwitch.innerHTML = groupSwitch.innerHTML.replace("&gt;&gt;", "&lt;&lt;");
            group.style.display = "inline";
            if ( group.innerHTML.indexOf('href') == -1 && g_id == '' ) {
                g_id = id;
                var url = "/?mode=getGroup&submode=" + escape(groupName);
                if (window.XMLHttpRequest) {
                    req = new XMLHttpRequest();
                }
                else if (window.ActiveXObject) {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                }
                req.onreadystatechange = processGroupLoad;
                req.open("GET", url, true);
                req.send(null);
            }
        }
    }
}

function processGroupLoad() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var addElm = document.getElementById('group' + g_id);
            addElm.innerHTML = req.responseText;
            g_id = 0;
        }
    }
}

function addWithLittlePlace(id, contextId, issue) {
    g_placeForDetails = false;
    if (issue) { g_issue = issue; }
    add(id, contextId);
}

function add(id, contextId) {
    if (g_id == 0) {
        if (!contextId) { contextId = id; }
        g_contextId = contextId;

        g_id = id;
        var url = "/?mode=addToMyCollection&submode=" + escape(g_id) + getCachePrevent();
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        req.onreadystatechange = processAdd;
        req.open("GET", url, true);
        req.send(null);
    }
}

function processAdd() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var d = req.responseXML.getElementsByTagName("status");
            if (d.length > 0) {
                n = 0;
                var html = "";

                switch (d[n].firstChild.data) {
                    case "added":
                        if (g_placeForDetails) {
                            html += " | <strong>Added.</strong>";
                            html += "<br /><a href=\"javascript:edit(" + g_id + ")\" style=\"font-style: italic\">Edit tags/ comment</a>";
                        }
                        else {
                            html += ' | <strong><a href="javascript:add(' + g_id + ',' + g_contextId + ')" ' +
                                    'id="add' + g_issue + '" style="text-decoration: none">Added.</a></strong>';
                        }
                        break;

                    case "alreadyAdded":
                        if (g_placeForDetails) {
                            html += " | <strong>Already added.</strong>";
                            html += "<br /><a href=\"javascript:edit(" + g_id + ")\" style=\"font-style: italic\">Edit tags/ comment</a>";
                        }
                        else {
                            html += ' | <strong><a href="javascript:add(' + g_id + ',' + g_contextId + ')" ' +
                                    'id="add' + g_issue + '" style="text-decoration: none">Already</a></strong>';
                        }
                        break;

                    case "maxCoversReached":
                        html = "<strong>Can't add: your collection reached the maximum allowed size.</strong>";
                        break;

                    case "falseReferrer":
                        html = "<strong>False referrer field.</strong>";
                        break;

                    case "notFound":
                        html = "<strong>Cover not found.</strong>";
                        break;

                    case "signedOut":
                        document.location.href = "/account/signin";
                        break;

                    default:
                        html = "<strong>Response:</strong> " + d[n].firstChild.data;
                }

                if (html != "") {
                    var addElm = document.getElementById("add" + g_contextId);
                    if (addElm) { addElm.innerHTML = html; }
                }
                g_id = 0;
            }
        }
    }
}

function edit(id) {
    if (g_id == 0) {
        g_id = id;
        var url = "/?mode=getDescriptionAndTags&submode=" + escape(g_id) + getCachePrevent();
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        req.onreadystatechange = processEditLoad;
        req.open("GET", url, true);
        req.send(null);
    }
}

function processEditLoad() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var description = "";
            var tags = "";
            var d = req.responseXML.getElementsByTagName("description");
            if (d.length > 0) {
                description = d[0].firstChild.data;
            }

            d = req.responseXML.getElementsByTagName("tags");
            if (d.length > 0) {
                tags = d[0].firstChild.data;
            }

            showDialog(description, tags);
        }
    }
}

function showDialog(description, tags) {
    var dialog = document.getElementById("dialog");
    var dialogShadow = document.getElementById("dialogShadow");
    if (dialog && dialogShadow) {
        var html = "";
        html += '<a href="javascript:editClose()" class="cancelButton"><img src="/image/close.png" alt="[Close]" /></a><br />' + "\r";
        html += '<strong>Comment:</strong><br /><textarea id="inputDescription">' + description + '</textarea><br /><br />' + "\r";
        html += '<strong>Tags:</strong> <input type="text" id="inputTags" value="' + tags + '" onKeyPress="checkEnter(event)" /><br />' + "\r";
        html += '<span class="footnote">Separate with comma (e.g. <em>wishlist, john byrne, horse, funny, got it</em>)</span>' + "\r";
        html += '<p class="editSave"><input type="button" value="Save" onclick="editSave()" />' +
                ' &nbsp; <span class="error" id="dialogInfo" style="visibility: hidden;">&nbsp;</span>' +
                '</p>' + "\r";
        dialog.innerHTML = html;

        var y = getDialogTop();
        dialog.style.top = y + "px";
        dialogShadow.style.top = (y - 10) + "px";

        dialog.style.display = "block";
        dialogShadow.style.display = "block";
        focusElm("inputTags");
    }
}

function focusElm(id) {
    var elm = document.getElementById(id);
    if (elm) {
        elm.focus();
    }
}

function editClose() {
    hideElm("dialog");
    hideElm("dialogShadow");
    g_id = 0;
}

function checkEnter(e)
{
    var characterCode;

    if(e && e.which) {
        e = e;
        characterCode = e.which;
    }
    else {
    e = event;
    characterCode = e.keyCode;
    }

    var characterEnter = 13;
    if(characterCode == characterEnter) {
        editSave();
        return false;
    }
    else {
        return true;
    }
}

function editSave() {
    if (g_id != 0) {
        var elmDescription = document.getElementById("inputDescription");
        var elmTags = document.getElementById("inputTags");
        if (elmDescription && elmTags) {

            var description = elmDescription.value;
            var tags = elmTags.value;

            var elmPageDescription = document.getElementById("coverDescription" + g_id);
            if (elmPageDescription) {
                elmPageDescription.innerHTML = textToHtml(description);
            }

            var url = "/?mode=saveDescriptionAndTags&submode=" + escape(g_id) +
                    "&tags=" + escape(tags) + "&description=" + escape(description) + getCachePrevent();
            if (window.XMLHttpRequest) {
                req = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            req.onreadystatechange = processSave;
            req.open("GET", url, true);
            req.send(null);
        }
    }
}

function textToHtml(s) {
    s = toXml(s);
    // Regex to replace line breaks doesn't work: s = s.replace(/[\r\n|\n\r|\n|\r]/, '<br />');
    return s;
}

function toXml(s) {
    s = s.replace(/&/, "&amp;");
    s = s.replace(/>/, "&gt;");
    s = s.replace(/</, "&lt;");
    return s;
}

function processSave() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var d = req.responseXML.getElementsByTagName("status");
            if (d.length > 0) {
                n = 0;
                var issueHtml = "";

                switch (d[n].firstChild.data) {
                    case "saved":
                        break;

                    case "falseReferrer":
                        issueHtml = "<strong>False referrer field.</strong>";
                        break;

                    case "notFound":
                        issueHtml = "<strong>Cover not found.</strong>";
                        break;

                    case "signedOut":
                        document.location.href = "/account/signin";
                        break;

                    default:
                        issueHtml = "<strong>Saving problems:</strong> " + d[n].firstChild.data;
                }

                if (issueHtml != "") {
                    var infoElm = document.getElementById("dialogInfo");
                    if (infoElm) {
                        infoElm.innerHTML = issueHtml;
                        infoElm.style.visibility = "visible";
                    }
                }
                else {
                    g_id = 0;
                    editClose();
                }
            }
        }
    }
}

function remove(id) {
    if (g_id == 0) {
        if ( confirm("Remove cover and its comments/ tags?") ) {
            g_id = id;
            var url = "/?mode=removeCover&submode=" + escape(g_id) + getCachePrevent();
            if (window.XMLHttpRequest) {
                req = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            req.onreadystatechange = processRemove;
            req.open("GET", url, true);
            req.send(null);
        }
    }
}

function processRemove() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var d = req.responseXML.getElementsByTagName("status");
            if (d.length > 0) {
                n = 0;
                var issue = "";

                switch (d[n].firstChild.data) {
                    case "removed":
                        break;

                    case "falseReferrer":
                        issue = "False referrer field.";
                        break;

                    case "notFound":
                        issue = "Cover not found.";
                        break;

                    case "signedOut":
                        document.location.href = "/account/signin";
                        break;

                    default:
                        issueHtml = "Removing problems: " + d[n].firstChild.data;
                }

                if (issue != "") {
                    alert(issue);
                }
                else {
                    hideElm("coverDescription" + g_id);
                    hideElm("cover" + g_id);
                }
                g_id = 0;
            }
        }
    }
}

function getDialogTop() {
    var divHeight = 340;
    var y = Math.round( (viewportGetHeight() - divHeight) / 2 ) + viewportGetScrollY();
    return y;
}

function viewportGetHeight() {
    var retval = 0;
    if (window.innerHeight)
        retval = window.innerHeight - 18;
    else if (document.documentElement && document.documentElement.clientHeight) 
        retval = document.documentElement.clientHeight;
    else if (document.body && document.body.clientHeight) 
        retval = document.body.clientHeight;
    return retval;    
}


function viewportGetScrollY() {
    var retval = 0;
    if (typeof window.pageYOffset == "number")
        retval = window.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
        retval = document.documentElement.scrollTop;
    else if (document.body && document.body.scrollTop) 
        retval = document.body.scrollTop; 
    else if (window.scrollY)
        retval = window.scrollY;
    return retval;
}

function handleCategoryExpand() {
    var category = '';
    category = self.document.location.hash.substring(1);
    if (category != '') {
        // category = category.replace(/_/i, ' ');
        category = ucFirst(category);
        var elm = document.getElementById('groupSwitch' + category);
        if (elm) {
            var js = elm.getAttribute('href');
            js = js.replace('javascript:', '');
            eval(js);
        }
    }
}

function ucFirst(str) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1, str.length - 1);
}

function getCachePrevent() {
    return "&rand=" + escape( Math.round( Math.random() * 10000 ) );
}

function showElm(id) {
    var elm = document.getElementById(id);
    if (elm) {
        elm.style.display = "block";
    }
}

function hideElm(id) {
    var elm = document.getElementById(id);
    if (elm) {
        elm.style.display = "none";
    }
}

function toggleElm(id) {
    var elm = document.getElementById(id);
    if (elm) {
        if (elm.style.display == "block") {
            elm.style.display = "none";
        }
        else {
            elm.style.display = "block";
        }
    }
}

function imageLoaded() {
    var detailsElm = document.getElementById('details' + g_issue);
    if (detailsElm) {
        detailsElm.style.backgroundImage = 'none';
    }
}

function switchVariant(name, issue, id, subnumber, subtitle, number, contextId, referrerUrl) {
    var maxVariants = 10;
    var filepath = '/image/' + name + '/' + issue + '-' + subnumber + '.jpg';
    var imageElm = document.getElementById('img' + issue);
    imageElm.src = filepath;

    if (issue != g_issue) { imageLoaded(); }
    g_issue = issue;

    document.images['img' + issue].onload = function() {
        imageLoaded();
    } 

    var detailsElm = document.getElementById('details' + issue);
    if (subtitle != '') {
        detailsElm.style.display = 'block';
        detailsElm.innerHTML = subtitle;
    }
    else {
        detailsElm.style.display = 'none';
        detailsElm.innerHTML = '&nbsp;';
    }
    detailsElm.style.backgroundImage = 'url(/image/progress.gif)';

    var addElm = document.getElementById('add' + issue);
    if (addElm) {
        addElm.href = 'javascript:addWithLittlePlace(' + id + ',' + contextId + ',' + issue + ')';
        addElm.innerHTML = 'add';
        addElm.style.textDecoration = 'underline';
    }

    var viaElm = document.getElementById('via' + issue);
    if (viaElm) { viaElm.href = referrerUrl; }

    for (i = 0; i <= maxVariants; i++) {
        var linkElm = document.getElementById('i' + issue + '_' + i);
        if (linkElm) {
            if (number == i) {
                linkElm.style.textDecoration = 'none';
                linkElm.style.fontWeight = 'bold';
            }
            else {
                linkElm.style.textDecoration = 'underline';
                linkElm.style.fontWeight = 'normal';
            }
        }
        else {
            break;
        }
    }
}

function zoom(zoomPath) {
    var dirtyMagicNumber = 54;
    var height = viewportGetHeight() - dirtyMagicNumber;
    var html = '<div class="zoomImage" id="zoomImage" style="height: ' + height + 'px;">' +
            '<img src="' + zoomPath + '" alt="" id="zoomImageImg" onload="scrollZoom()" /></div>';
    showLargeDialog(html);
    return false;
}

function scrollZoom() {
    var dirtyMagicNumber = 54;
    var height = viewportGetHeight() - dirtyMagicNumber;
    var elm = document.getElementById('zoomImage');
    var elmImage = document.getElementById('zoomImageImg');
    if (elm && elmImage) {
        var imageHeight = elmImage.height;
        var scrollTo = Math.round( (imageHeight - height) / 2 );
        if (scrollTo >= 1) { elm.scrollTop = scrollTo; }
    }
}

function readBook(bookId) {
    var height = viewportGetHeight() - g_largeDialogWrapMarginTopBottom * 2;
    var frameSource = 'http://books.google.com/books?id=' + bookId + '&amp;lpg=PP1&amp;dq=x&amp;pg=PP1&amp;output=embed';
    var html = '<iframe class="readFrame" frameborder="0" src="' + frameSource + '" ' +
            'width="' + (g_largeDialogWidth- 40) + '" height="' + (height - 10) + '">' +
            '</iframe>';
    showLargeDialog(html);
}

function showLargeDialog(html) {
    closeLargeDialog();
    var height = viewportGetHeight() - g_largeDialogWrapMarginTopBottom;

    var closeButton = '<a href="javascript:closeLargeDialog()" class="largeDialogCancelButton">' +
            '<img src="/image/close.png" alt="[Close]" /></a>';

    var bodyElm = document.body;

    var wrapShade = document.createElement('div');
    bodyElm.appendChild(wrapShade);
    wrapShade.id = 'largeDialogWrapperShade';
    wrapShade.style.top = getLargeDialogTop(g_largeDialogWrapMarginTopBottom) + 'px';
    wrapShade.style.height = ( viewportGetHeight() - g_largeDialogWrapMarginTopBottom ) + 'px';
    wrapShade.style.left = ( viewportGetWidth() / 2 - g_largeDialogWidthwrap / 2) + 'px';
    wrapShade.innerHTML = '&nbsp;';

    var wrap = document.createElement('div');
    bodyElm.appendChild(wrap);
    wrap.id = 'largeDialogWrapper';
    wrap.style.top = getLargeDialogTop(g_largeDialogWrapMarginTopBottom) + 'px';
    wrap.style.height = ( viewportGetHeight() - g_largeDialogWrapMarginTopBottom ) + 'px';
    wrap.style.left = ( viewportGetWidth() / 2 - g_largeDialogWidthwrap / 2) + 'px';

    wrap.setAttribute( 'onclick', 'closeLargeDialog()' );
    wrap.onclick = function() { closeLargeDialog(); };

    wrap.innerHTML = closeButton + html;
}

function closeLargeDialog() {
    var elm = document.getElementById('largeDialogWrapper');
    if (elm) {
        document.body.removeChild(elm);
        document.body.removeChild( document.getElementById('largeDialogWrapperShade') );
    }
}

function getLargeDialogTop(wrapperMarginTopBottom) {
    return Math.round( viewportGetScrollY() + wrapperMarginTopBottom );
}

function viewportGetWidth() {
    var retval = 0;
    if (window.innerWidth)
        retval = window.innerWidth - 18;
    else if (document.documentElement && document.documentElement.clientWidth) 
        retval = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth) 
        retval = document.body.clientWidth;
    return retval;    
}
