// All script (C)1998-2007 Digital Photography Review
// Author: Phil Askey
// No code may be used elsewhere without permission
//

var navname,navvers,newsnavc=0,sidebarcnt;

navname=navigator.appName;
navvers=parseInt(navigator.appVersion);

js_ok = ((navname == "Microsoft Internet Explorer") && (navvers >= 4 )) || ((navname == "Netscape") && (navvers >= 4 )) || ((navname == "Opera") && (navvers >= 8 ));

function breakout_of_frame()
{
	if(top.location!=location)	top.location.href=document.location.href;
}

function help_popup(section) {
	window.location='/learn/key=' + section;
}

function fresh(time) {
	setTimeout("freshnow()",time*1000);
}

function freshnow() {
	window.location.reload();
}

function jumpto(me) {
	meval=me.options[me.selectedIndex].value;
	if(meval!="") window.location=meval;
}

function inputswap(me,def,setto) {
	if(js_ok) {
		if(me.value==def) {
			me.value=setto;
		}
	}
}

function newsnavcell(href,title) {
	var ahref;
	
	ahref='<a href="/news/' + href +'">';
	
	document.writeln('<td class="tdnewsnav">&nbsp;' + ahref + title + '</a></td>');
}

// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
//
// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
	var ol=el.offsetLeft;
	while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
	return ol;
	}
function AnchorPosition_getWindowOffsetLeft (el) {
	return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
	}	
function AnchorPosition_getPageOffsetTop (el) {
	var ot=el.offsetTop;
	while((el=el.offsetParent) != null) { ot += el.offsetTop; }
	return ot;
	}
function AnchorPosition_getWindowOffsetTop (el) {
	return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
	}


// ------------------------------------
// cookie utils, based on
// jquery.cookie.js
// Klaus Hartl/klaus.hartl@stilbuero.de
// ------------------------------------

var DprCookieUtils = 
{

    setCookie: function(name, value, options)
    {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    },

    getCookie: function(name)
    {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

}


// ------------------------------------
// user profile
// ------------------------------------

function DprUserProfile()
{

    var status;
    var publicId;
    var userName;
    var emailMD5;
    var galleriesSaferyFilter;

    init();

    function init()
    {

        // both cookies have to be there
        var authCookie = DprCookieUtils.getCookie("auth");
        var prefCookie = DprCookieUtils.getCookie("prof");
        if (!authCookie || !prefCookie)
        {
            status = "unauthenticated";
            return;
        }

        // decode preferences
        var profTokens = decodeURIComponent(prefCookie).split("|");

        // check version
        if (profTokens.length != 7 || profTokens[0] != 3)
        {
            status = "versionError";
            return;
        }

        // public id
        publicId = decodeURIComponent(profTokens[1]);
	
        // user name
        userName = decodeURIComponent(profTokens[3]);

        // email hash
        var emailMD5Raw = decodeURIComponent(profTokens[4]);
        if (!/^[a-zA-Z0-9]{32}$/.test(emailMD5Raw))
        {
            status = "parseError";
            return;
        }
        emailMD5 = emailMD5Raw;

        // galleries safety filter
        var galleriesSaferyFilterRaw = decodeURIComponent(profTokens[5]);
        if (!/^\d+$/.test(galleriesSaferyFilterRaw))
        {
            status = "parseError";
            return;
        }
        galleriesSaferyFilter = parseInt(galleriesSaferyFilterRaw, 10);

        // ok, all went well
        status = "authenticated";

    }

    function isAuthenticated()
    {
        return status == "authenticated";
    }

    function getStatus()
    {
        return status;
    }

    function getPublicId()
    {
        return publicId;
    }
    
    function getUserName()
    {
        return userName;
    }

    function getEmailMD5()
    {
        return emailMD5;
    }

    function getGalleriesSaferyFilter()
    {
        return galleriesSaferyFilter;
    }

    function haveCookies()
    {
        return DprCookieUtils.getCookie("auth") &&
               DprCookieUtils.getCookie("pref");
    }

    function profilePageUrl()
    {
        return "/members/" + publicId;
    }

    function recentForumActivityUrl()
    {
        return "/members/" + publicId + "/forums/RecentActivity";
    }

    function forumBookmarksUrl()
    {
        return "/members/" + publicId + "/bookmarks/Bookmarked";
    }

    function galleryInboxLink()
    {
        return "/galleries/" + publicId + "/photos";
    }

    function galleryUploadLink()
    {
        return "/galleries/upload";
    }

    function defaultGravatarUrl()
    {
        return "http://a.img-dpreview.com/images/sidebar/default-gravatar.png";
    }

    function gravatarUrl(size)
    {
        return "http://www.gravatar.com/avatar/" +
            emailMD5.toLowerCase() +
            "?s=" + size + 
            "&r=" + "PG" + 
            "&d=" + encodeURIComponent(defaultGravatarUrl());
    }

    return {
        isAuthenticated: isAuthenticated,
        getStatus : getStatus,
        getPublicId: getPublicId,
        getUserName: getUserName,
        getEmailMD5 : getEmailMD5,
        getGalleriesSaferyFilter : getGalleriesSaferyFilter,
        haveCookies : haveCookies,
        gravatarUrl : gravatarUrl,
        profilePageUrl : profilePageUrl,
        recentForumActivityUrl : recentForumActivityUrl,
        forumBookmarksUrl : forumBookmarksUrl,
	galleryInboxLink : galleryInboxLink,
	galleryUploadLink : galleryUploadLink,
        defaultGravatarUrl : defaultGravatarUrl };

}


// ------------------------------------
// site search
// ------------------------------------

(function()
{

    init();

    function init()
    {
        window.dprSiteSearchFocus = focus;
        window.dprSiteSearchBlur = blur;
    }

    function isTextboxValueEmpty(value)
    {
        return !value || /^\s*$/.test(value);
    }

    function focus()
    {
        var $label = $("#site-searchbox span.label");
        $label.css("visibility", "hidden");
    }

    function blur()
    {

        var $textbox = $("#site-searchbox");
        var $label = $textbox.find("span.label");
        var $input = $textbox.find("input");

        if (isTextboxValueEmpty($input.val()))
        {
            $label.css("visibility", "visible");
        }

    }
    
})();


// ------------------------------------
// main menu
// ------------------------------------

(function()
{

    init();

    function init()
    {

        window.dprMainMenuBuild = render;
        window.dprMainMenuFixPosition = fixPosition;

    }

    function createMenuItemUrl(href)
    {
        if (window.menuurlprefix && href.substr(0, 7).toLowerCase() != "http://")
        {
            return menuurlprefix + href;
        }
        else
        {
            return href;
        }
    }

    function render()
    {

        // jQuery 1.3.2 made the following function obsolete, but we
        // need to explicitly exclude IE6 (as it does not support
        // transparent PNG’s), and jQuery browser detection is as good
        // as any other detection. As the moment (December 2009), the IE6
        // traffic at dpreview is about 10%.
        var preIE7 = $.browser == "msie" && jQuery.browser.version < 7;
        var renderSubmenus = !preIE7;

        document.write("<div id=\"main-menu\">");

        for (var i = 0; i < dprMenuOpts.length; i++)
        {

            var menu = dprMenuOpts[i];
            var subItems = menu.slice(1);

            var mainMenuItemData = menu[0].split("|");
            var mainMenuItemLabel = mainMenuItemData[0];
            var mainMenuItemHref = createMenuItemUrl(mainMenuItemData[1]);

            document.write("<div");
            document.write(" class=\"main-menu-item\"");
            document.write(" onmouseover=\"dprMainMenuFixPosition(this, arguments[0])\"");
            document.write(">");

            document.write("<a");
            document.write(" class=\"main-menu-item\"");
            document.write(" href=\"" + mainMenuItemHref + "\"");
            document.write(">");
            document.write(mainMenuItemLabel);
            document.write("</a>");

            if (renderSubmenus && subItems.length > 0)
            {

                var subitems = [];

                for (var j = 0; j < subItems.length; j++)
                {

                    var subItem = subItems[j];
                    var subItemData = subItem.split("|");
                    var subItemLabel = subItemData[0];
                    var subItemHref = createMenuItemUrl(subItemData[1]);

                    if (subItemLabel == "-")
                    {
                        subitems.push("<div");
                        subitems.push(" class=\"separator\"");
                        subitems.push(">");
                        subitems.push("</div>");
                    }
                    else
                    {
                        subitems.push("<a");
                        subitems.push(" href=\"" + subItemHref + "\"");
                        subitems.push(">");
                        subitems.push(subItemLabel);
                        subitems.push("</a>");
                    }

                }

                document.write("<table");
                document.write(" class=\"subitems-box\"");
                document.write(" cellspacing=\"0\"");
                document.write(" cellpadding=\"0\"");
                document.write(" border=\"0\"");
                document.write(">");
                document.write("<tr>");
                document.write("<td class=\"shadow11\"><div></div></td>");
                document.write("<td class=\"shadow12\"><div></div></td>");
                document.write("<td class=\"shadow13\"><div></div></td>");
                document.write("</tr>");
                document.write("<tr>");
                document.write("<td class=\"shadow21\"><div></div></td>");
                document.write("<td class=\"shadow22\">" + subitems.join("") + "</td>");
                document.write("<td class=\"shadow23\"><div></div></td>");
                document.write("</tr>");
                document.write("<tr>");
                document.write("<td class=\"shadow31\"><div></div></td>");
                document.write("<td class=\"shadow32\"><div></div></td>");
                document.write("<td class=\"shadow33\"><div></div></td>");
                document.write("</tr>");
                document.write("</table>");

            }

            document.write("</div>");

        }

        document.write("</div>");

    }

    function fixPosition(maimMenuItemElement, e)
    {

        var event = e || window.event;
        var $eventTarget = $(event.target || event.srcElement);

        if ($eventTarget.hasClass("main-menu-item"))
        {

            var $mainMenuItem = $(maimMenuItemElement);
            var $subitems = $mainMenuItem.find("> table.subitems-box");

			if ($subitems.length>0) {
				var mainMenuItemOffset = $mainMenuItem.offset();
				var subitemsOffset = $subitems.offset();
				var subitemsHeight = $subitems.height();
				var windowHeight = $(window).height();
				var documentScrollTop = $(document).scrollTop();

				if (subitemsOffset.top - documentScrollTop + subitemsHeight > windowHeight)
				{
					var top = Math.max(0, windowHeight - subitemsHeight) + documentScrollTop - mainMenuItemOffset.top;
					$subitems.css("top", top + "px");
					$subitems.find("td.shadow21").css("background-position", "0px " + (- top - 315) + "px");
				}
			}

        }

    }

})();


// ------------------------------------
// user box
// ------------------------------------

(function()
{

    init();

    function init()
    {

        // expose render function which is called 
        // from HTML from withing an inline script
        window.dprBuildUserBox = function() { renderInitial() };
        window.dprUserBoxButtonDown = buttonDown;
        window.dprUserBoxLoginButtonClick = loginButtonClick;
        window.dprUserBoxRegisterButtonClick = registerButtonClick;

        // and wait for document ready to attach events
        $(document).ready(function() { initPostRender() });

    }

    function renderInitial()
    {

        var userProfile = DprUserProfile();

        document.write("<div id=\"user-box\" class=\"user-box-top\">");
        document.write("    <div class=\"user-box-bottom\">");
        document.write("        <div class=\"user-box-content\">");

        renderAnonymousContentBox(!userProfile.isAuthenticated());
        renderLoginContentBox();
        renderAuthUserContentBox(userProfile.isAuthenticated());

        document.write("        </div>");
        document.write("    </div>");
        document.write("</div>");

    }

    function initPostRender()
    {
        attachLoginBoxEvents();
    }

    function changeContent(contentId, callback)
    {

        var $contentWrapper = $("#user-box div.user-box-content");
        var $content = $(contentId);

        // remove current content and fix the current height
        var currentHeight = $contentWrapper.height();
        $contentWrapper.stop(true, false);
        $contentWrapper.css("height", currentHeight + "px");

        // get the height of the new content
        $contentWrapper.children().hide();
        $content.css("visibility", "hidden").show();
        var targetHeight = $content.height();

        // animation
        $contentWrapper.animate(
            { height: targetHeight + "px" }, 
            "fast", "linear",
            function()
            {
                $contentWrapper.css("height", "auto");
                $content.css("visibility", "visible");
                if (callback)
                {
                    callback();
                }
            });

    }

    function openDefaultScreen()
    {
        var userProfile = DprUserProfile();
        if (userProfile.isAuthenticated())
        {
            openAuthUserScreen();
        }
        else
        {
            openAnonymousScreen();
        }
    }

    function openAnonymousScreen()
    {
        changeContent("#userBoxAnonymous");
    }

    function renderAnonymousContentBox(visible)
    {
        document.write("<div id=\"userBoxAnonymous\" style=\"font-size: 11px; width: 118px; padding-left: 16px; padding-right: 16px;" + (visible ? "" : " display: none;") + "\">");
        document.write("    <div style=\"padding-left: 2px;\">You are not logged in</div>");
        document.write("    <div style=\"padding-top: 5px\">");
        document.write("        <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
        document.write("        <tr>");
        document.write("            <td>");
        renderButton("userBoxLoginButton", "Login", "dprUserBoxLoginButtonClick");
        document.write("            </td>");
        document.write("            <td style=\"padding-left: 2px;\">");
        renderButton("userBoxRegisterButton", "Register", "dprUserBoxRegisterButtonClick");
        document.write("            </td>");
        document.write("        </tr>");
        document.write("        </table>");
        document.write("    </div>");
        document.write("</div>");
    }

    function loginButtonClick()
    {
        openLoginScreen();
    }

    function registerButtonClick()
    {
        location.href = "/members/register";
    }

    function openLoginScreen()
    {
        changeContent("#userBoxLogin");
    }

    function renderLoginContentBox(visible)
    {
        document.write("<div id=\"userBoxLogin\" style=\"font-size: 11px; width: 118px; padding-left: 16px; padding-right: 16px;" + (visible ? "" : " display: none;") + "\">");
        document.write("    <form style=\"margin: 0px;\" method=\"post\" action=\"/members/login?o=" + encodeURIComponent(location.href) + "\">");
        document.write("        <div>E-mail:</div>");
        document.write("        <div style=\"padding-top: 2px;\" class=\"textbox\"><input type=\"text\" name=\"email\"></div>");
        document.write("        <div style=\"padding-top: 4px;\">Password:</div>");
        document.write("        <div style=\"padding-top: 2px;\" class=\"textbox\"><input type=\"password\" name=\"password\"></div>");
        document.write("        <div style=\"padding-top: 6px;\">");
        document.write("            <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
        document.write("            <tr>");
        document.write("                <td>");
        document.write("                    <input type=\"checkbox\" style=\"margin: 0px;\" id=\"userBoxRememberMe\" name=\"remember\" value=\"true\"/>");
        document.write("                </td>");
        document.write("                <td style=\"padding-left: 5px;\">");
        document.write("                    <label style=\"font-size: 11px;\" for=\"userBoxRememberMe\" title=\"If you select this option a cookie will be stored on your computer with an encrypted key which will authenticate you automatically when you come back.\">Remember me</label>");
        document.write("                </td>");
        document.write("            </tr>");
        document.write("            </table>");
        document.write("        </div>");
        document.write("        <div style=\"padding-top: 5px;\">");
        document.write("            <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
        document.write("            <tr>");
        document.write("                <td><input type=\"submit\" value=\"Login\"/></td>");
        document.write("                <td style=\"padding-left: 2px;\"><input type=\"button\" name=\"cancel\" value=\"Cancel\"/></td>");
        document.write("            </tr>");
        document.write("            </table>");
        document.write("        </div>");
        document.write("    </form>");
        document.write("</div>");
    }

    function attachLoginBoxEvents()
    {
        $("#user-box input:button[name='cancel']").click(function()
        {
            openAnonymousScreen();
        });
    }

    function openAuthUserScreen()
    {

        var userProfile = DprUserProfile();

        var $authUser = $("#userBoxAuthUser");
        $authUser.find("#userBoxAuthUserUserName").attr("href", userProfile.profilePageUrl()).text(userProfile.getUserName());
        $authUser.find("#userBoxAuthThreadsLink").attr("href", userProfile.recentForumActivityUrl());
        $authUser.find("#userBoxAuthBookmarksLink").attr("href", userProfile.forumBookmarksUrl());
        $authUser.find("#userBoxAuthGravatarLink").attr("href", userProfile.profilePageUrl());
        $authUser.find("#userBoxAuthGravatarImage").attr("src", userProfile.gravatarUrl(40));

        changeContent("#userBoxAuthUser");

    }

    function renderAuthUserContentBox(visible)
    {
        var userProfile = DprUserProfile();
        document.write("<div id=\"userBoxAuthUser\" style=\"font-size: 11px; width: 118px; padding: 0px 16px;" + (visible ? "" : " display: none;") + "\">");
        document.write("    <div style=\"padding: 0px 2px; font-weight: bold;\">");
        document.write("        <a id=\"userBoxAuthUserUserName\" href=\"" + (userProfile.isAuthenticated() ? userProfile.profilePageUrl() : "#") + "\">" + (userProfile.isAuthenticated() ? htmlEncode(userProfile.getUserName()) : "") + "</a>");
        document.write("    </div>");
        document.write("    <table border=\"0\" cellspacing=\"0\" border=\"0\" style=\"margin-top: 5px;\">");
        document.write("    <tr>");
        document.write("        <td style=\"vertical-align: top\"><a id=\"userBoxAuthGravatarLink\" href=\"" + (userProfile.isAuthenticated() ? userProfile.profilePageUrl() : "#") + "\"><img id=\"userBoxAuthGravatarImage\" src=\"" + (userProfile.isAuthenticated() ? userProfile.gravatarUrl(40) : userProfile.defaultGravatarUrl()) + "\" width=\"40\" height=\"40\" border=\"0\" alt=\"Gravatar\" style=\"border: 1px solid #123\"></a></td>");
        document.write("        <td style=\"vertical-align: top; padding-left: 5px;\">");
        document.write("            <ul class=\"user-links\" style=\"padding", "0px 2px 0px 2px\">");
        document.write("                <li><a id=\"userBoxAuthThreadsLink\" href=\"" + (userProfile.isAuthenticated() ? userProfile.recentForumActivityUrl() : "#") + "\">Threads</a></li>");
        document.write("                <li><a id=\"userBoxAuthBookmarksLink\" href=\"" + (userProfile.isAuthenticated() ? userProfile.forumBookmarksUrl() : "#") + "\">Bookmarks</a></li>");
        document.write("                <li><a id=\"userBoxAuthGalleriesLink\" href=\"" + (userProfile.isAuthenticated() ? userProfile.galleryInboxLink() : "#") + "\">Galleries</a></li>");
        document.write("                <li><a id=\"userBoxAuthUploadLink\" href=\"" + (userProfile.isAuthenticated() ? userProfile.galleryUploadLink() : "#") + "\">Upload</a></li>");
        document.write("                <li><a href=\"" + "/members/logout?o=" + encodeURIComponent(location.href) + "\">Logout</a></li>");
        document.write("            </ul>");
        document.write("        </td>");
        document.write("    </tr>");
        document.write("    </table>");
        document.write("</div>");
    }

    function renderButton(buttonId, text, globalFuncName)
    {
        document.write("<div id=\"" + buttonId + "\" class=\"button\" unselectable=\"on\" onclick=\"" + globalFuncName + "()\" onmousedown=\"dprUserBoxButtonDown(this)\">");
        document.write("    <div class=\"left\" unselectable=\"on\">");
        document.write("        <div class=\"right\" unselectable=\"on\">");
        document.write("            <div class=\"middle\" unselectable=\"on\">");
        document.write("                <span class=\"text\" unselectable=\"on\">" + text + "</span>");
        document.write("            </div>");
        document.write("        </div>");
        document.write("    </div>");
        document.write("</div>");
    }

    function buttonDown(button)
    {
        var $button = $(button);
        $button.addClass("button-down");
        $(document).one("mouseup", function()
        {
            $button.removeClass("button-down");   
        });
    }

    function htmlEncode(str)
    {
        return $("<span/>").text(str).html();
    }

})();


// ------------------------------------
// universal cookie
// ------------------------------------

function DprUniversalCookie(PageId)
{

    window.amznUts = {
        DomainId : "dpreview.com",
        PageId : PageId };

    $(document).ready(function()
    {
        $("head").
            append($("<script/>").
                attr("type", "text/javascript").
                attr("src", "http://z-ecx.images-amazon.com/images/G/01/x-locale/personalization/uts/js/prod-v10.js"));
    });

}

// ------------------------------------
// block polyvore clipper
// ------------------------------------

function PolyvoreClipper()
{
	return 0;
}

PolyvoreClipper.run = function ()
{
}