var selectedPic = 0;

/* Max width of photo displays (for default display) */
var maxWidth = 550;
/* Width of client window before forcing small stylesheet */
var CLIENT_WIDTH_TOO_SMALL = 975;
function ecardInfo() {
    alert("Sorry, only the owner of the account can send an eCard.");
}

function selectField(me) {
    me.focus();
    me.select();
}

function picClicked(link) {
    setScrollOffset(link);
    return true;
}

function setScrollOffset(el) {
    try {
        var list = document.getElementById("photoThumbList");
        var link = el.href;
        var top = list.scrollTop;
        var idx1 = link.indexOf("#");
        if (top > 0) {
            if ( idx1 > 0 ) {
                var p1 = link.substr(0, idx1);
                var p2 = link.substr(idx1);
              if ( p1.indexOf("?") > 0 )
                    p1 += "&offset=" + top;
                else
                    p1 += "?&offset=" + top;
                link = p1 + p2;
            } else {
                if ( link.indexOf("?") > 0 )
                    link += "&offset=" + top;
                else
                    link += "?&offset=" + top;
            }
        }
        el.href = link;
    } catch(e) { alert(e); }
}

function nextPic() {
    if ( selectedPic >= imgOrder.length - 1 )
        selectedPic = -1;
    loadPic(imgOrder[++selectedPic]);
}

function prevPic() {
    if ( selectedPic <= 0 )
        selectedPic = imgOrder.length;
    loadPic(imgOrder[--selectedPic]);
}

function loadPic(imgid) {
/* Async pic load code:
    try {
        var img = imgList[imgid];
        setURL(imgid);
        var imgEl = document.getElementById("mainImg");
        imgEl.onerror = function(e) { alert(e); };
        var newImg = new Image();
        newImg.onload = function() {
            imgEl.src = newImg.src;
            var width = newImg.width > maxWidth ? maxWidth : newImg.width;
            imgEl.width = width;
            imgEl.style.width = width + "px";
        };
        newImg.src = img["imgPath"];

        for ( var i = 0; i < imgOrder.length; i++ ) {
            if ( imgOrder[i] == imgid ) { 
                selectedPic = i; 
                break;
            }
        }
        document.getElementById("photoTitle").innerHTML = img["title"];
        document.getElementById("photoDescription").innerHTML = img["descr"];
        document.getElementById("imgid").value = imgid;
        if ( img["title"] || img["descr"] ) {
            document.getElementById("photoFrame").style.paddingTop = "1em";
            if ( !img["title"] )
                document.getElementById("photoTitle").style.display = "none";
            else
                document.getElementById("photoTitle").style.display = "block";
            if ( !img["descr"] )
                document.getElementById("photoDescription").style.display = "none";
            else
                document.getElementById("photoDescription").style.display = "block";
            document.getElementById("photoDetails").style.display = "block";
        } else {
            document.getElementById("photoDetails").style.display = "none";
            document.getElementById("photoFrame").style.paddingTop = "3em";
        }
        loadComments(imgid);
        checkAds();
    } catch(e) { };
    return false;
*/
}

function loadComments(imgid) {
    var commentDiv = document.getElementById("commentList");
    if ( commentDiv ) {
        commentDiv.innerHTML = "<img src=\"/gallery/indicator.gif\" alt=\"\"/> Loading...";
        getRemoteDoc("/gallery.fcgi?p=100&imgid=" + imgid, loadCommentList);
    }
}

var req;
function loadCommentList(req) {
    try {
        var commentDiv = document.getElementById("commentList");
        if ( req.responseText.length > 26 ) {
            document.getElementById("commentBox").style.display = "";
            commentDiv.innerHTML = req.responseText;
        } else {
            commentDiv.innerHTML = "";
            hideCommentBox();
        }
    } catch(e) { alert(e); }
}


function getRemoteDoc(url, callback) {
    req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                req = false;
            }
        }
    }
    if(req) {
        req.onreadystatechange = function() {
            if ( req.readyState == 4 && req.status == 200 ) {
                callback(req);
            }
        }
        req.open("GET", url, true);
        req.send("");
    }
}

function handleOptions() {
}

function showCommentBox() {
    document.getElementById("addCommentBox").style.display = "";
    document.getElementById("commentBox").style.display = "";
}
function hideCommentBox() {
    document.getElementById("addCommentBox").style.display = "none";
    document.getElementById("commentBox").style.display = "none";
}

function setURL(imgid) {
    try {
        var loc = document.location.toString();
        if ( /#.*imgid=/.test(loc) ) {
            var l = loc.replace(/#(.*)imgid=(\d+)/, "#$1imgid=" + imgid);
            loc = l;
        }
        else if ( loc.indexOf("#") > 0 ) {
            loc = loc + "imgid=" + imgid;
        } else {
            loc = loc + "#imgid=" + imgid;
        }
        var ecard = document.getElementById("ecardURL");
        if ( ecard ) 
            ecard.href = ecard.href.replace(/imgid_\d+/, "imgid_" + imgid);
        document.location = loc;
    } catch(e) { }
}

var lastLoad = new Date();
function checkAds() {
    try {
        /*var checkLoad = new Date();
        if ( checkLoad.getTime() - lastLoad.getTime() > 5000 ) {
        */
            var ifr = document.getElementsByTagName("iframe");
            for ( var i = 0; i < ifr.length; i++ )
                ifr[i].src = ifr[i].src;
            lastLoad = new Date();
        /*}*/
    } catch(e) { }
}

function handleResize() {
    var list = document.getElementById("photoList");
    /* Look in the CSS for IE-specific instructions.  IE cannot handle using
    getElementById in the middle of a page load, and this function is called
    in the initialization bit.  So, "list" on IE6 or previous will return
    null and this conditional isn't executed.  We do the IE-specific code in
    the css (look for the definition of #photoList) */
    if ( list ) {
        var width = document.documentElement.clientWidth || window.innerWidth || document.body.clientWidth;
        if ( width < CLIENT_WIDTH_TOO_SMALL )
            list.style.width = "250px";
        else 
            list.style.width = "350px";
    }
    return;

    var width = document.documentElement.clientWidth || window.innerWidth || document.body.clientWidth;
    if ( width < CLIENT_WIDTH_TOO_SMALL ) {
        setSmallStylesheet(true);
    } else {
        setSmallStylesheet(false);
    }
}

function __init() {
    image = document.getElementById("mainImg");
    if ( image ) {
        var is_safari = (document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(!navigator.accentColorName)?true:false;
        if ( is_safari ) {
            image.style.maxWidth = "none";
            var factor = image.height / image.width;
            image.width = 550;
            image.height = 550 * factor;
        }
    
        image.style.display = "";
    }
    var cmtBlock = document.getElementById("commentBox");
    if ( typeof __imgid != "undefined" ) {
    	if ( __imgid && cmtBlock ) cmtBlock.style.display = "";
    }

/*
    var ar  = /#.*imgid=(\d+)/.exec(loc);
    if ( ar && ar[1] ) {
        loadPic(ar[1]);
    }
    if ( typeof __imgid == "defined" && __imgid > 0 ) {
        loadPic(__imgid);
    }
    var sel = document.getElementById("albumSelector");
    sel.onchange = setGallery;
    sel = document.getElementById("displayMode");
    sel.onchange = setSlideshow;
    sel = document.getElementById("optionList");
    sel.onchange = callOption;
*/
}

function setGallery(gid) {
    /*
    var sel = document.getElementById("albumSelector");
    var gid = sel.options[sel.selectedIndex].value;
    */
    var loc = document.location.toString();
    if ( loc.indexOf("p=") <= 0 ) {
        if ( loc.indexOf("?") >= 0 ) 
            loc += "&p=999";
        else
            loc += "?&p=999";
    }
    if ( loc.indexOf("gid=") <= 0 ) {
        if ( loc.indexOf("#") >= 0 )
            loc = loc.replace(/#/, "gid=" + gid + "#");
        else if ( loc.indexOf("?") >= 0 ) 
            loc += "&gid=" + gid;
        else
            loc += "?&gid=" + gid;
    } else {
        loc = loc.replace(/gid=\d+/, "gid=" + gid);
    }
    loc = loc.replace(/imgid=\d+/g, "");
    document.location = loc;
}

function setSlideshow() {
    var sel = document.getElementById("displayMode");
    var p   = sel.options[sel.selectedIndex].value;
    var loc = document.location.toString();
    loc = loc.replace(/p=\d+/, "p=" + p);
    loc = loc.replace(/imgid=\d+/g, "");
    document.location = loc;
}

function callOption() {
    var sel = document.getElementById("optionList");
    var loc = sel.options[sel.selectedIndex].value;
    if ( loc && optionURLs[loc] ) {
        document.location = optionURLs[loc];
    }
}

function init() {
    var f = window.onload;
    if ( typeof f != "function" ) {
        window.onload = __init;
    } else {
        window.onload = function() {
            if ( f ) f();
            __init();
        }
    }
    
    var r = window.onresize;
    if ( typeof f != "function" ) {
        window.onresize = handleResize;
    } else {
        window.onresize = function() {
            if ( handleResize ) handleResize();
            handleResize();
        }
    }
}

function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

var myWin;
function createPreview() {
    //window properties
    var winName = "";
    var width = 520;
    var height = 320;
    var toolbar = 0;
    var location = 0;
    var directories = 0;
    var status = 0;
    var menubar = 0;
    var scrollbars = 0;
    var resizable = 0;

    //create the new window
    if ( !myWin || myWin.closed ) {
        myWin = window.open('/gallery/view?p=5&uid=' + uid, winName, 'width=' + width + ',height=' + height + ',toolbar=' + toolbar + ',location=' + location + ',directories=' + directories + ',status=' + status + ',menubar=' + menubar + ',scrollbars=' + scrollbars + ',resizable=' + resizable + ',top=' + ((screen.height/2)-(height/2)) + ',left=' + ((screen.width/2)-(width/2)));
    } else {
        myWin.focus();
    }
}

function setSmallStylesheet(enabled) {
    var i, a, main;
    if ( enabled ) maxWidth = 480;
    for ( i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        if( a.getAttribute("rel").indexOf("style") != -1 &&
            a.getAttribute("href").indexOf("small") > 0 )
        {
            a.disabled = !enabled;
            if ( enabled )
                createCookie("smallSheet", "on");
            else
                createCookie("smallSheet", "off");
        }
    }
}

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 expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function checkCommentForm() {
    var form = document.getElementById("commentForm");
    if ( form.photoguest && form.photoguest.value == "" ) {
        alert("Please enter your name to post a comment.");
        return false;
    }
    if ( form.text && form.text.value == "" ) {
        alert("Please enter a comment.");
        return false;
    }
    return true;
}

function noRightClick() {
    //Disable right click script
    var message="";
    function clickIE() {if (document.all) {(message);return false;}}
    function clickNS(e) {if
    (document.layers||(document.getElementById&&!document.all)) {
    if (e.which==2||e.which==3) {(message);return false;}}}
    if (document.layers)
    {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
    else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}

    document.oncontextmenu=new Function("return false");
}

function finalizeContemporaryGallery() {
    var list = document.getElementById("photoThumbList");
    if ( list ) {
        var vOffset = 0;
        if ( foffset >= 0 ) {
            vOffset = foffset;
        } else {
            var width = list.offsetWidth;
            vOffset = parseInt((109 * (offset+1)) / width) * 105;
        }
        list.scrollTop = parseInt(vOffset);
        handleResize(list);
        list.scrollTop = parseInt(vOffset);
    }

    var is_safari = (document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(!navigator.accentColorName)?true:false;
    if ( is_safari ) {
        var img      = document.getElementById("mainImg");
        var cmtBlock = document.getElementById("commentBox");
        if ( img ) {
            img.style.display = "none";
            img.style.maxWidth = "none";
            if ( cmtBlock ) cmtBlock.style.display = "none";
            img.onload = function() {
                try {
                    img.style.display = "";
                    if ( img && img.width > 550 ) {
                        var factor = img.height / img.width;
                        img.width = 550;
                        img.height = 550 * factor;
                    }
                    if ( cmtBlock ) cmtBlock.style.display = "";
                } catch ( e ) {
                    img.style.display = "";
                    if ( cmtBlock ) cmtBlock.style.display = "";
                }
            };
        }
    }
}

init();
