$(document).ready(function() {
    if ($("#production h2:contains('baby grand')").length > 0) {
        $(".page-bg").removeClass("page-bg").addClass("page-bg-babygrand");
    }

    // Add shims to the header and first paragraph so they countour to the page design
    $(".inner #content p:first").prepend("<img src='/App_Themes/GrandWilm/Images/transparent.gif' style='width: 100px; height: 20px; float: right;' />");
    $(".inner #content h1:first").prepend("<img src='/App_Themes/GrandWilm/Images/transparent.gif' style='width: 250px; height: 20px; float: right;' />");

    // Shift the featured circles out so they can all be seen
    $("#circles li:eq(1)").css({ left: '136px', top: '70px' });
    $("#circles li:eq(2)").css({ left: '280px', top: '100px' });

    $(".result").click(function() {
        document.location.href = $(this).find("a:first").attr("href");
    });

    // Search scrolling
    var searchScroll = $.cookie("search-scroll");
    if (searchScroll != undefined) {
        $("#searchresults").scrollTop(searchScroll);
    }

    $("#searchresults").scroll(function() {
        $.cookie("search-scroll", $("#searchresults").scrollTop());
    });

    // Fix top nav markup and add hoverIntent
    $("#nav").addClass("topnav").show().find("ul").addClass("subnav");
    $("ul.topnav > li").hoverIntent(
		function() {
		    $(this).stop().addClass("active").find("ul.subnav").slideDown({ duration: 350, easing: "easeOutBack" });
		},
		function() {
		    $(this).stop().removeClass("active").find("ul.subnav").slideUp({ duration: 350, easing: "easeInBack" });
		}
	);

    // ColorBoxes
    $(".links a").colorbox({ iframe: true, opacity: 0.5, initialWidth: 400, initialHeight: 400, width: getWidth(), height: $(window).height() - 50 });

    SetUpAccordion();
    $("#accordion").before("<a href='#' class='view-all'>View all</a>").after("<a href='#' class='collapse-all'>Collapse all</a>");

    $(".view-all").click(function() {
        $("#accordion div").slideDown();
        $("#accordion").accordion('destroy');
        return false;
    });

    $(".collapse-all").click(function() {
        $("#accordion div").slideUp();
        SetUpAccordion();
        return false;
    });

    // Children should all have the same height
    equalHeight($("#children li"));

    $('#gallery').galleryView({
        panel_width: 550,
        panel_height: 400,
        frame_width: 87,
        frame_height: 60,
        overlay_opacity: 0.75,
        transition_interval: 7000,
        pause_on_hover: true
    });

    // Production media
    $("div.scrollable").scrollable({ size: 4 }).find("div.items").prepend("<div><a href='#' class='info'><img src='/Media/Images/info' style='margin: 0px' /></a></div>").find("a").click(function() {
        var href = $(this).attr("href");
        var info = $(this).hasClass("info");
        // alert("yes");
        if (window.href != null && window.href == href) {
            return false;
        }
        window.href = href;
        $("#prod-content .inside").animate({ top: 500 }, 250, function() {
            setTimeout(function() {
                $("#prod-content .inside").animate({ top: 0 }, 250);
            }, 250);
            if (info) {
                $("#media-element").html("");
                $("#text").show();
            }
            else {
                $("#text").hide();
                if (href.indexOf(".flv") > -1) {
                    flowplayer("media-element", { src: "/Site/Flash/flowplayer-3-1-5.swf", width: 408, height: 281 }, {
                        clip: {
                            autoPlay: true,
                            autoBuffering: true
                        },
                        playlist: [href, { url: href, autoPlay: true}],
                        plugins: {
                            controls: { url: "flowplayer-controls-3-1-5.swf" }
                        }
                    });
                    flowplayer("media-element", { src: "/Site/Flash/flowplayer-3-1-5.swf", width: 408, height: 281 }, {
                        clip: {
                            autoPlay: true,
                            autoBuffering: true
                        },
                        playlist: [href, { url: href, autoPlay: true}],
                        plugins: {
                            controls: { url: "flowplayer-controls-3-1-5.swf" }
                        }
                    });

                }
                else if (href.indexOf("youtube.com") > -1) {
                    embedVideo(href, "#media-element");
                }
                else {
                    $("#media-element").html("<img src='" + href + "' />");
                }
            }
        });
        return false;
    });

    var videoItem = $("#media-items a[href$='.flv']:first");
    if (videoItem.length > 0) {
        videoItem.trigger("click");
    }
    else {
        videoItem = $("#media-items a[href*='youtube.com']:first");
        if (videoItem.length > 0) {
            videoItem.trigger("click");
        }
    }

    // Pull latest Facebook status
    // TOOD: Let's not do this unless the user hovers?
    $("#sm a[href^='http://www.facebook.com']").each(function() {
        var $anchor = $(this);
        $.ajax({
            type: "GET",
            url: "/Utilities/Proxy.ashx?url=http://graph.facebook.com/thegrandwilmington/feed",
            data: "limit=1",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $anchor.qtip({ content: "<p><img src='http://graph.facebook.com/thegrandwilmington/picture' align='left' width='50' height='50' style='margin: 0px 8px 4px 0px;' /><strong>Latest from Facebook:</strong> " + msg.data[0].message + "</p><p><a href='" + $anchor.attr("href") + "'>Connect with us on Facebook.</a></p>", api: { onShow: function() { } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true }, position: { adjust: { x: 4, y: 0 }, corner: { target: 'leftBottom', tooltip: 'topRight'} }, style: { width: 400, background: '#FFFFFF', border: { width: 2, radius: 4, color: "#E7D1A0" }, tip: { corner: 'topRight', color: '#E7D1A0'}} });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                window.status = textStatus + ": " + errorThrown;
            }
        });
    });

    // Pull latest tweet
    // TOOD: Let's not do this unless the user hovers?
    $("#sm a[href^='http://twitter.com']").each(function() {
        var $anchor = $(this);
        $.ajax({
            type: "GET",
            url: "/Utilities/Proxy.ashx?url=http://api.twitter.com/1/statuses/user_timeline/thegrandwilm.json",
            data: "count=1",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                window.status = msg[0].user.profile_image_url;
                $anchor.qtip({ content: "<p><img src='" + msg[0].user.profile_image_url + "' align='left' width='50' height='50' style='margin: 0px 8px 8px 0px;' /><strong>Latest from Twitter:</strong> " + msg[0].text + "</p><p><a href='" + $anchor.attr("href") + "'>Follow us on Twitter here.</a></p>", api: { onShow: function() { } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true }, position: { adjust: { x: 4, y: 0 }, corner: { target: 'leftBottom', tooltip: 'topRight'} }, style: { width: 400, background: '#FFFFFF', border: { width: 2, radius: 4, color: "#E7D1A0" }, tip: { corner: 'topRight', color: '#E7D1A0'}} });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                window.status = textStatus + ": " + errorThrown;
            }
        });
    });

});

function getWidth() {
    windowWidth = $(window).width() - 50;
    return (windowWidth > 1100) ? 1100 : windowWidth;
}

function SetUpAccordion(){
	$("#accordion").accordion({ event: 'click', header: 'h3', autoHeight: false, active: false, collapsible: true });
}

function embedVideo(videoURL, previewContainer) {
	if (videoURL.indexOf('youtube') >= 0) {
		var videoID = videoURL.match(/watch\?v=(.+)+/)[1].replace(" ", "");
		var content = '<div id="youtube-embed-' + videoID + '">You need Flash player 8+ to view this video.</div>';
		$(previewContainer).html(content);
		var params = { allowScriptAccess: 'always' };
		var attrs = { id: 'ytplayer-' + videoID };
		swfobject.embedSWF('http://www.youtube.com/v/' + videoID + '?rel=0&autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer-' + videoID, 'youtube-embed-' + videoID, '408', '281', '8', null, null, params, attrs);
	}
}

function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}