var GK = function() {
    return {
        /**
         * Master initialization function for all pages.
         */
        init: function() {
            if (jQuery("body").hasClass("qa")) {
                jQuery("DIV.copy-container A").bind("click", GK.qaClick);
                jQuery("DIV.copy-container A.qa-question:first").trigger("click");
            }

            GK.externalLinkHandler();

            GK.popupLinkHandler();

            GK.pngFix();

            GK.commentsToggle();

            GK.contentPromo();

            GK.newsletterToggle();

            GK.siteSearchHandler();

            GK.paginationAdjuster();

            GK.slideshowHandler();

            GK.video.init();

        },

        slideshowHandler: function() {
            var updateSlideshow = function() {
                jQuery("#slideshow-thumbnails LI").removeClass("active");
                jQuery(this).parent().addClass("active");
                var thumbnails = jQuery(this).find("IMG");
                var photos = jQuery("#slideshow-photos .rounded-body IMG");
                var regex = new RegExp(/(w|h)=\d+/g);

                for (var i=0; i < thumbnails.length; i++) {
                    var photo_src = thumbnails[i].src;
                    photo_src = photo_src.replace(regex, "$1=230");
                    photos[i].src = photo_src;
                }
            };


            jQuery("#slideshow-thumbnails LI A").click(updateSlideshow);


            var showNext = function(e) {
                var target = jQuery("#slideshow-thumbnails LI.active").next("LI");
                if (target.length > 0) {
                    jQuery("#slideshow-thumbnails LI").removeClass("active");
                    jQuery(target).addClass("active");
                    jQuery(target).children("A:first").trigger("click");
                }
                return false;
            };

            var showPrevious = function(e) {
                var target = jQuery("#slideshow-thumbnails LI.active").prev("LI");
                if (target.length > 0) {
                    jQuery("#slideshow-thumbnails LI").removeClass("active");
                    jQuery(target).addClass("active");
                    jQuery(target).children("A:first").trigger("click");
                }
                return false;

            };

            jQuery("#slideshow-previous").click(showPrevious);
            jQuery("#slideshow-next").click(showNext);
        },

        /**
         * Update the visible images in a slideshow upon click of a thumbnail
         */
        updateSlideshow: function() {
        },


        /**
         * Replaces the next/previous pagination links with
         * images. We're doing it client-side to avoid hacking the plugin
         * files, and because it's otherwise awkward server-side.
         */
        paginationAdjuster: function() {
            jQuery("div.wp-pagenavi A:contains('previous')").html('<img src=\"' + GK_THEME_ROOT + '/images/pagination-arrow-left.gif\" alt=\"previous\"/>');
            jQuery("div.wp-pagenavi A:contains('next')").html('<img src=\"' + GK_THEME_ROOT + '/images/pagination-arrow-right.gif\" alt=\"previous\"/>');
        },

        /**
         * Clear and restore the default value of the search box
         */
        siteSearchHandler: function() {
            var callback = function(e) {
                if (e.type == "focus" && jQuery.trim(this.value) == "search") this.value = "";
                else if (e.type == "blur" && jQuery.trim(this.value) == "") this.value = "search";
            };

            jQuery("#s").focus(callback).blur(callback);
            jQuery("#search-form").submit(function() {
                                         var term = jQuery.trim(jQuery("#s").attr("value"));
                                         var valid_search = (term.length > 0 && term != "search");
                                         if (valid_search === false) { alert('Please enter a search term.'); }
                                         return valid_search;
                                     });

        },

        /**
         * Toggle the visibility of the newsletter signup form
         */
        newsletterToggle: function() {
            var callback = function() {
                jQuery("#mc_embed_signup").toggleClass("hidden");
                return false;
            };
            jQuery("#newsletter-signup-trigger").click(callback);
        },

        /**
         * Toggle the visibility of the comments and comment form
         */
        commentsToggle: function() {
            if (jQuery("#comments-trigger").length > 0) {
                var callback = function() {
                    var comments_div = jQuery("#comments");
                    var respond_div = jQuery("#respond");
                    var url_hash = window.location.hash;
                    if (comments_div.hasClass("hidden")) {
                        jQuery("#comments").removeClass("hidden");
                        jQuery("#respond").removeClass("hidden");
                        if (url_hash.length < 2 || url_hash.indexOf("no-comments") > -1) {
                            window.location.hash = "comments";
                        }
                    } else {
                        jQuery("#comments").addClass("hidden");
                        jQuery("#respond").addClass("hidden");
                        window.location.hash = '#no-comments';
                    }
                    return false;
                };
                jQuery("#comments-trigger").click(callback);
                if (window.location.hash.length > 1 && window.location.hash.indexOf("no-comments") == -1) {
                    jQuery("#comments-trigger").trigger("click");
                }
            }
        },

        /**
         * Open links with rel="external" in a new window.
         */
        externalLinkHandler: function() {
            jQuery("a[rel*='external']").attr("target","_blank");
        },

        /**
         * Open links with rel="popup" in a new window.
         */
        popupLinkHandler: function() {
            //jQuery("a[rel='popup']").attr("target","_blank");
        },

        /**
         * When a QA question is clicked, add or remove the visible class
         * on all P tags between the clicked question and the next question.
         */
        qaClick: function(e) {

            var p_tags = jQuery(e.target).nextAll();
            for (var i=0; i < p_tags.length; i++) {
                if (p_tags[i].nodeName == "A") break;
                jQuery(p_tags[i]).toggleClass("visible");
            }
            return false;
        },

        /**
         * For IE6, apply the AlphaImageLoader filter to PNGs that use transparency.
         * The optimized images produced by pngnq
         * based on http://allinthehead.com/retro/338/supersleight-jquery-plugin
         */
        pngFix: function() {
            // target IE6 only
		    if (!(jQuery.browser.msie && parseInt(jQuery.browser.version) < 7)) return;

            var spacer = GK_THEME_ROOT + '/images/spacer.gif';

            var imageCallback = function() {
                var obj = jQuery(this);
                var src = obj.attr('src');
                if (obj.hasClass('needs-24')) src = src.replace(/.png$/, "-24.png");
                if (obj.hasClass('ie6-special')) {
                    // an alternate image is being provided to IE6 and the AlphaImageLoader
                    // is not needed
                    src = src.replace(/.pngjQuery/, "-ie6.png");
                    obj.attr('src', src);
                } else {
                    var styles = {
					    'width': obj.width() + 'px',
					    'height': obj.height() + 'px',
					    'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"
				    };
                    obj.css(styles).attr('src', spacer);
                }
            };
            jQuery('body img.uses-alpha').each(imageCallback);
        },

        contentPromo: function() {
            var callback = function() {
                var index = jQuery("#vc-images IMG").index(this);
                jQuery("#vc-nav IMG").addClass("hidden");
                jQuery("#vc-nav IMG:eq(" + index + ")").removeClass("hidden");
                jQuery("#vc-text DIV").addClass("hidden");
                jQuery("#vc-text DIV:eq(" + index + ")").removeClass("hidden");
                jQuery("#vc-frame").attr("href", jQuery("#vc-nav IMG:eq(" + index + ")").attr("rel"));
                //alert(jQuery("#vc-frame").attr("href"));
            };
            var options = {
                timeout: 6000,
                speed: 1000,
                pause: 1,
                before: callback
            };
            jQuery("#vc-images").cycle(options);

            var clickHandler = function() {
                jQuery("#vc-images").cycle({timeout:900000});
                var index = jQuery("#vc-map AREA").index(this);
                jQuery("#vc-nav IMG").addClass("hidden");
                jQuery("#vc-nav IMG:eq(" + index + ")").removeClass("hidden");
                jQuery("#vc-text DIV").addClass("hidden");
                jQuery("#vc-text DIV:eq(" + index + ")").removeClass("hidden");
                jQuery("#vc-images IMG").css("display", "none");
                jQuery("#vc-images IMG:eq(" + index + ")").css({"opacity": 1, "display": "block"});
                jQuery("#vc-frame").attr("href", jQuery("#vc-nav IMG:eq(" + index + ")").attr("rel"));
                return false;
            };

            jQuery("#vc-map AREA").click(clickHandler);
        },


        video: {
            player: null,

            init: function() {
                jQuery("A.video-trigger").bind("click", GK.video.showPlayer);
                jQuery("#video-close").bind("click", GK.video.hidePlayer);
                jQuery("#video-knob-container").bind("click", GK.video.knobClick);

                //jQuery("A.video-trigger:first").trigger("click");

            },

            knobClick: function(e) {
                if (GK.video.player === null) {
                    return false;
                }

                switch (e.target.id) {
                    case "video-knob-play":
                    // Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
                    var player_state = GK.video.player.getPlayerState();
                    if (player_state == 1) {
                        GK.video.player.pauseVideo();
                        jQuery(e.target).removeClass("alt");
                    } else {
                        GK.video.player.playVideo();
                        jQuery(e.target).addClass("alt");
                    }
                    break;

                    case "video-knob-stop":
                    GK.video.player.seekTo(0, false);
                    GK.video.player.pauseVideo();
                    jQuery("#video-knob-play").removeClass("alt");
                    break;

                    case "video-knob-volume":
                    if (GK.video.player.isMuted()) {
                        GK.video.player.unMute();
                        jQuery(e.target).removeClass("alt");
                    } else {
                        GK.video.player.mute();
                        jQuery(e.target).addClass("alt");
                    }
                    break;
                }

                return false;
            },

            showPlayer: function(e) {
                var popup = jQuery("#video-popup");
                var container = jQuery(e.target).closest("div.video-promo");
                var offset = container.offset();
                jQuery("#video-title").html(container.find("A.caption").html());
                jQuery("#video-duration").html(container.find("SPAN.video-duration").html());
                jQuery("#video-url").attr("href",jQuery(e.target).closest("A").attr("href"));
                popup.show();

                if (GK.video.player === null) {
                    var flashvars = {};
                    var params = { allowScriptAccess: "always" };
                    var atts = { id: "gkplayer" };
                    var playerUrl = 'http://www.youtube.com/apiplayer';
                    playerUrl += "?enablejsapi=1";
                    playerUrl += "&playerapiid=" + atts.id;

                    swfobject.embedSWF(playerUrl,
                                       "video-file",
                                       "495", "278",
                                       "9.0.0",
                                       GK_THEME_ROOT + "/swf/expressInstall.swf",
                                       flashvars, params, atts);
                }

                offset.left += container.width() - popup.width() + 5;
                offset.top -= 7;
                popup.css(offset);
                var window_y = offset.top - (jQuery(window).height() - popup.height())/2;
                window.scrollTo(0, window_y);
                return false;
            },

            hidePlayer: function(e) {
                if (GK.video.player !== null) {
                    GK.video.player.stopVideo();
                }
                jQuery("#video-popup").hide();
                return false;
            },

            playerReady: function(playerId) {
                GK.video.player = document.getElementById(playerId);
                GK.video.player.loadVideoByUrl(jQuery("#video-url").attr("href"));
                jQuery("#video-knob-play").addClass("alt");

            }
        }
    };
}();

jQuery(document).ready(GK.init);

function onYouTubePlayerReady(playerId) {
    GK.video.playerReady(playerId);
}
