(function(d){d.fn.shuffle=function(c){c=[];return this.each(function(){c.push(d(this).clone(true))}).each(function(a,b){d(b).replaceWith(c[a=Math.floor(Math.random()*c.length)]);c.splice(a,1)})};d.shuffle=function(a){return d(a).shuffle()}})(jQuery);

$(document).ready(function()
{
    $.websiteURL = "http://dothereusechallenge.com";
    $.lastAcceptClicked = null;

    var randomPromo = Math.floor(Math.random() * $("#sidebar .promo").length);
    $("#sidebar .promo").hide();
    $("#sidebar .promo:eq(" + randomPromo + ")").show();

    var randomFamily = Math.floor(Math.random() * $("#sidebar .family").length);
    $("#sidebar .family").hide();
    $("#sidebar .family:eq(" + randomFamily + ")").show();

    $(".blog-thumbs ul li:nth-child(1)").addClass("active");
    $(".blog-thumbs ul li a").click(function(event)
    {
        event.preventDefault();
        if ($(this).parent().hasClass("active")) return;
        var blogThumbs = $(this).parent().parent().parent();
        blogThumbs.find("ul li").removeClass("active");
        $(this).parent().addClass("active");

        var thumbs = blogThumbs.find("a");
        var selectedIndex = Math.abs(thumbs.index($(this)) - thumbs.length) - 1;
        var gallery = $(this).parent().parent().parent().parent();
        var images = gallery.find(".blog-images");
        var image = images.find("img#blog-image-" + selectedIndex);

        image.css("opacity", 0);
        images.append(image);
        image.animate({opacity:1}, 500);
    });

    $(".facebook-login").click(function(event)
    {
        event.preventDefault();
        var presentAcceptForm = $(this).hasClass("facebook-accept") ? true : false;
        FB.login(function(response)
        {
            if (response.session)
            {
                if (presentAcceptForm)
                {
                    $.lastAcceptClicked.show();
                    $.lastAcceptClicked.parent().find(".challenge-accept-actions").hide();
                    $.presentUrlInIframe($.lastAcceptClicked.attr("href"));
                }
                else
                {
                    window.location.reload();
                }
            }
        }, {perms : "publish_stream,email,user_birthday,user_location"});
    });

    $(".facebook-logout").click(function(event)
    {
        event.preventDefault();
        FB.logout(function(response)
        {
            window.location.reload();
            //window.location = "/auth/logout";
        });
    });

    $("#challenge-email-set-form .btn, .challenge-email-set-form .btn").click(function(event)
    {
        event.preventDefault();
        var url = $(this).attr("href");
        var input = $(this).parent().find("input");
        if (input.containsValidEmail())
        {
            url += "/?email=" + input.val();
            $.presentUrlInIframe(url);
        }
        else
        {
            $(this).parent().parent().find(".comment-form-status").css("display", "block");

        }
    });

    $("#email-set-form").bind("submit", function(event)
    {
        event.preventDefault();
        if ($("#comment_email").containsValidEmail())
        {
            $(this).unbind("submit");
            $(this).submit();
        }
        else
        {
            $(this).parent().find(".comment-form-status").css("display", "block");
        }
    });

    $.fn.containsValidEmail = function()
    {
        return $.isValidEmail($(this).val());
    }

    $.isValidEmail = function(email)
    {
        return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
    }

    $.log = function()
    {
        if (window.console)
        {
            if (window.console.log) console.log.apply(null, arguments);
        }
    }

    $(".default-text").defaultText();

    $("#display-messages").animate({opacity:1}, 3500).slideUp(250).fadeOut(250);

    $.facebookWallPostForBlog = function()
    {
        var name = "Do The Reuse Challenge"; // + $("h1").text();
        var blog = $(".blog:eq(0) h3").text();
        var family = $("#family-name").text();
        var challenge = $("#challenge-name").text();
        var challengeTitle = $("#challenge-title").text();
        var url = $.websiteURL + $("#blog-permalink").text();

        var share = {
            method     : "stream.publish",
            message    : "",
            attachment : {
                name        : name,
                caption     : "{*actor*} chimed in on the " + family + " family's Do the Reuse Challenge blog.",
                description : "Doing the reuse can help you save cash, live healthier, and protect the planet. It’s a pretty cool conversation to be a part of. Click below to learn more about the Aladdin Do the Reuse Challenge, or read the blog your friend commented on.",
                href        : url
            },
            action_links: [
                {text : "About", href: $.websiteURL},
                {text : "Read the Blog", href: url}
            ]
        };

        //var images = $(".blog-gallery .blog-thumbs ul li a img:first");
        //if (images.length)
        //{
            share.attachment.media = [{
                "type" : "image",
                "src"  : $.websiteURL + "/img/impact-" + challenge + ".jpg",
                "href" : $.websiteURL
            }];
        //}

        FB.ui(share, function(response){
        });
    }

    $.facebookWallPostForChallengeComment = function()
    {
        var name = "Do The Reuse Challenge"; // + $("h1").text();
        var url = $.websiteURL + $("#challenge-permalink").text();
        var challenge = $("#challenge-name").text();
        var challengeTitle = $("#challenge-title").text();

        var share = {
            method     : "stream.publish",
            message    : "",
            attachment : {
                name        : name,
                caption     : "{*actor*} chimed in on " + challengeTitle,
                description : "Making one small change to save cash, protect our planet, and live healthier, check out the link to learn more, acceptone of Aladdin's Do the Reuse Challenges and see the impact you can make in your life, your community, and the world.",
                href        : url
            },
            action_links: [
                {text : "Do the Reuse", href: $.websiteURL}
            ]
        };

        share.attachment.media = [{
            "type" : "image",
            "src"  : $.websiteURL + "/img/impact-" + challenge + ".jpg",
            "href" : $.websiteURL
        }];

        FB.ui(share, function(response){
        });
    }

    $(".accept").click(function(event)
    {
        event.preventDefault();
        var item = $(this);
        item.parent().find(".challenge-accept-actions").show();
        item.hide();
        $.lastAcceptClicked = item;
    });

    $(".accept-logged-in").live("click", function(event)
    {
        event.preventDefault();
        $.presentUrlInIframe($(this).attr("href"));
    });

    $(".error").click(function(event)
    {
        $(this).hide();
    });

    $(".acceptee-detail").click(function(event)
    {
        event.preventDefault();
        return;
        $.presentUrlInIframe($(this).attr("href"));
    });

    $(".acceptee-detail").hover(function(event)
    {
        var username = $("<span>").text($(this).attr("title")).addClass("username");
        var location = $("<span>").text($(this).attr("rel")).addClass("location");
        var content = username.after(location);
        $("#tooltip").css({left: $(this).offset().left - 65, top: $(this).offset().top - 132});
        $("#tooltip #tooltip-inner").html(content);
        $("#tooltip").show();
    }, function(event)
    {
        $("#tooltip").hide();
    });

    $("#tooltip").mouseover(function(event){event.preventDefault();})

    $.presentUrlInIframe = function(url)
    {
        $.handleResize(null);
        $(window).bind("resize scroll", $.handleResize);
        $("#overlay").show();

        // $("#displayWindow").attr("src", url).show();
        var displayWindow = document.getElementById("displayWindow");
        displayWindow.src = url;
        displayWindow.style.display = "block";
    }

    $.handleResize = function(event)
    {
        $("#displayWindow").css("margin-top", $(document).scrollTop() + $(window).height()/2 - 180);
        $("#displayWindow").css("left", $(window).width()/2 - 200);
    }

    $(".challenge-impact-item").shuffle();
    $(".challenge-impact-item").show();
});

function facebookWallPostForChallengeResponder(share)
{
    FB.ui(share, function(response){
        if (response && response.post_id)
        {
        }
    });
}

function closeFrame()
{
    $("#overlay").hide();
    $("#displayWindow").hide().attr("src", "");
    $(window).unbind("resize");
    $(window).unbind("scroll");
    if ($.lastAcceptClicked)
    {
        $.lastAcceptClicked.parent().find(".challenge-accept-actions").hide();
        $.lastAcceptClicked.show();
        $.lastAcceptClicked = null;
    }
}

if (window.Cufon)
{
    Cufon.replace(["h1", "h2", "h3"], {
        fontFamily : "bryant",
        hover      : true
    });
}

function ucfirst(str)
{
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}
