if (typeof GE === "undefined") GE = {};
(function ($) {

    GE.setup = {
        init: function () {
                
            // Activate the dropdown menus in the top nav.
            GE.dropdown.init();

            // Open rel=external links in a new window.
            $('a[rel="external"]').attr('target', '_blank');

            // Open rel=signup links in a popup window.
            var signup_popup = function() {
                var popup_width = 380;
                var popup_height = 395;

                var popup = window.open(jQuery(this).attr("href"), "signup", "width=" + popup_width + ",height=" + popup_height + ",toolbar=0,location=0,status=0,menubar=0");
                if (popup) popup.focus();
                return false;
            };

            $('a[rel="signup"]').click(signup_popup);

            // Apply the IE6 PNG transparency fix provided by
            // DD-belatedPNG.js
            // (the tag is restricted to ie6 through a conditional comment)
            if (typeof DD_belatedPNG === "object") {
                DD_belatedPNG.fix('.png-fix');
            }

            // Give the site search a dismissable default value.
            // The clearDefaults plugin is at the bottom of this file.
            $('form input.inp-txt').clearDefaults();

            jQuery("#contact-overlay-trigger, #contact-overlay-supplemental-trigger").colorbox({
                transition: "none",
                width: 675,
                onLoad: function() { jQuery("#colorbox").css("top", 20); window.scrollTo(0,0) },
                onComplete: function() {
                    if (typeof DD_belatedPNG === "object") {
                        DD_belatedPNG.fix('#cboxTopCenter');
                        DD_belatedPNG.fix('#cboxContent');
                        DD_belatedPNG.fix('#cboxBottomCenter');
                        DD_belatedPNG.fix('#cboxClose');
                    }
                },
                height: 450,
                initialWidth: 675,
                preloading: false,
                scrolling: false,
                iframe: true,
                preloading: false,
                arrowKey: false,
                loop: false
	        });

            // A development aid to display the trigger at page load
            //jQuery("#contact-overlay-trigger").click();

            GE.faq.init();

            //GE.newsletter.init();
        }
    },

    GE.faq = {
        init: function() {
            var instances = jQuery("DL.faq");
            instances.find("DT A").click(GE.faq.toggle);
            instances.find("DD A.close").click(GE.faq.hideOne);
        },

        hideOne: function() {
            jQuery(this).parent("DD").hide();
            return false;
        },

        toggle: function() {
            var node = jQuery(this);
            // hide all visible dds
            node.closest("DL").find("DD:visible").hide();
            // show the selected div
            node.parent("DT").next("DD").show();
            return false;
        }
        
    },

    GE.newsletter = {
        init: function() {
            jQuery("#email-signup").submit(GE.newsletter.submitHandler);
            jQuery("#email-signup .submit-btn").click(GE.newsletter.submitHandler);
        },

        submitHandler: function() {
            var signup_form = jQuery("#email-signup");
            var email = jQuery.trim(jQuery("INPUT[name=email_47]", signup_form).val());

            if (GE.newsletter.validate(email) === false) {
                return false;
            }
            
            var params = {
                url: signup_form.attr("action"),
                type: signup_form.attr("method"),
				data: signup_form.serialize(),
                success: GE.newsletter.onSuccess
            };

			$.ajaxSetup({
			url: signup_form.attr("action"),
			global: false,
			type: "POST"
			});
		
            $.ajax();
            return false;
        },

        validate: function(email) {
            var message = "";
            if (email === "" || email.indexOf("@") == -1) {
                message = "Please provide your email address";
            }

            if (message != "") {
                jQuery("#email-signup-error").html(message).show();
                return false;
            } else {
                jQuery("#email-signup-error").hide();
                return true;
            }
                
        },
        
        onSuccess: function() {
            jQuery("#email-signup-error").hide();
            jQuery("#email-signup").hide();
            jQuery("#email-signup-confirmation").show();
        }
    },

    GE.dropdown = {
        instances: null,

        init: function(selector) {
            GE.dropdown.instances = jQuery(".dropdown");

            // IE6 has a weird behavior when it comes to swapping
            // background images that have a png fix applied. The new image
            // only shows when you mouse out of the element. As a workaround,
            // we'll clone the element and toggle its visiblity.
            GE.dropdown.instances.find("A.trigger").each(function() {
                var trigger = jQuery(this);
                var clone = trigger.clone();
                clone.addClass("open-trigger");
                trigger.parent().prepend(clone);
                clone.hide();
                trigger.click(GE.dropdown.open);
            });

            jQuery("BODY").click(GE.dropdown.closeAll);
        },

        open: function() {
            GE.dropdown.closeAll();
            var trigger = jQuery(this);
            var parent = trigger.parent();
            parent.css("z-index", 300);
            trigger.hide();
            parent.find("A.open-trigger").show();

            parent.find("UL").show();
            return false;
        },

        closeAll: function() {
            GE.dropdown.instances.each(function() {
                var instance = jQuery(this);
                instance.find("A.trigger").show();
                instance.find("A.open-trigger").hide();
                instance.find("UL").hide();
                instance.css("z-index", 100);
            });
        }
    },

    GE.slide = {
        slide_obj: $('#case-study-slides'),

        init: function () {

            // As per GE's request, the center of the homepage will shift to the left when the window width is less than
            // the content width (1120). The intention is to keep the right side of the content visible at all times.
            var window_width = jQuery(window).width();
            var min_width = jQuery("#inner-content").width();
            var right_pad = 25;
            var offset = (min_width - right_pad) - window_width;
            if (offset > 0) {
                jQuery("#inner-content").css("margin-left", offset/2 * -1);
            }

            
            var params = {
                url: '/json/case-studies.json',
                type: 'GET',
                dataType: 'json',
                success: GE.slide.populate
            };

            $.ajax(params);
        },

        populate: function(data) {
            for (i=0; i < data.slides.length; i++) {
                data.slides[i].loaded = false;
            }
            GE.slide.slides = data.slides;

            // Create slide HTML
            GE.slide.slide_obj.html(function(i) {
                var slide_cnt = '<h1 class="title"></h1>';
                slide_cnt += '<div class="slide-text"><p></p><span></span></div>';
                slide_cnt += '<div class="reps"><p></p></div>';
                slide_cnt += '<div class="follow-study clearfix">';
                slide_cnt += '<a class="btn view-study png-fix" href="#">Vew Case Study</a>';
                slide_cnt += '<a href="#" class="next-slide">Next case study <span class="chevron">&raquo;</span></a>'
                slide_cnt += '</div>';

                var slide_prefix = '<img class="slide" src="" alt="" width="1120" height="600" />';
                slide_prefix += '<div class="slide-txt-container">'+slide_cnt+'</div>';
                var slide = '<div class="slide">'+slide_prefix+'</div>';
                return slide;
            });

            // Duplicate and append slide HTML
            $('div.slide').duplicate(data.slides.length - 1).appendTo(GE.slide.slide_obj);
            
            GE.slide.animate();
        },

        display: function(index) {
            var slide = GE.slide.slides[index];
            var slide_class = $('#case-study-slides div.slide:visible').attr('id');
            $('#case-study-slides div.slide').each(function(j) {
                if (j === index) {
                    $(this).attr('id',slide.slide_id);
                    $('span.center-desc',this).html(slide.slide_desc);
                    $('img.slide',this).attr('src',slide.slide_img);
                    $('h1.title',this).html(slide.slide_title_image);
                    
                    $('.slide-text p',this).html(slide.slide_quote);
                    $('.slide-text span',this).html(slide.slide_author);
                    $('.reps p',this).html(slide.slide_reps);
                    $('.view-study',this).attr('href',slide.case_study_url);
                    
                    $('.slide-text p',this).css("margin-top", slide.slide_quote_top_margin);
                    $("A", this).css("color", slide.colors.links);
                    $(this).css("color", slide.colors.text);
                };
            });
            $('div#inner-content').addClass(slide_class);
            GE.slide.slides[index].loaded = true;
        },
            
        animate: function () {
            var auto_cycle = true;

            // Hash slides
            var index = window.location.hash.replace(/[^0-9]/g, "");

            if (index === "") {
                index = 0;
                next_index = 1;
            } else {
                index = parseInt(index, 10);
                if (index > 0) {
                    next_index = index;
                    index--;
                    if (next_index == GE.slide.slides.length) {
                        next_index = 0;
                    }
                    auto_cycle = false;
                }
            }

            GE.slide.display(index);
            GE.slide.display(next_index);
            
            $('#case-study-slides').cycle({
                fx            : 'fade',
                // http://jquery.malsup.com/cycle/cleartype.html?v3
                // IE6/7 screws up text on fade transition
                cleartype     : 1,
                speedIn       : 1000,
                speedOut      : 500,
                easeIn        : 'easein',
                easeOut       : 'easeout',
                // delay         : -1000,
                startingSlide : index,
                timeout       : 10000,
                pause         : 1,
                next          : '.next-slide',
                prev          : '.prev-slide',
                before        : onBefore,
                after         : onAfter
            });

            function onBefore(curr,next,opts) {
                var curr_index = $(curr).index();                
                var next_index = curr_index + 1;
                if (next_index >= GE.slide.slides.length) {
                    next_index = 0;
                }

                var index_to_load = undefined;
                
                // are there any slides that need to be loaded between the current slide and the end?
                for (i=curr_index; i < GE.slide.slides.length; i++) {
                    if (GE.slide.slides[i].loaded === false) {
                        index_to_load = i;
                        break;
                    }
                }

                if (index_to_load !== undefined) {
                    // are there any slides that need to be loaded between the start and the current slide?
                    for (i=0; i < GE.slide.slides.length; i++) {
                        if (GE.slide.slides[i].loaded === false) {
                            index_to_load = i;
                            break;
                        }
                    }
                }

                if (index_to_load !== undefined) {
                    GE.slide.display(index_to_load);
                } else {
                    return;
                }
            };
            
            function onAfter(curr,next,opts) {
                //console.log('loaded after');
                var sidebar_class = $('#case-study-slides div.slide:visible').attr('id');
                $('#inner-content').removeClass().addClass(sidebar_class);
                // Set hash
                window.location.hash = opts.currSlide + 1;
            }

            // Pause and resume slides on sidebar rollover
            $('#side-bar').hover(function() {
                $('#case-study-slides').cycle('pause');
            }, function() {
                $('#case-study-slides').cycle('resume');
            });

            if (auto_cycle === false) {
                $('#case-study-slides').cycle('pause');
            }

        }

    },

    /**
       The GE.nav module is responsible for showing/hiding the
       dropdown menus on the top nav.
    */
    GE.nav = {
        // triggers are the always-visible, top-level section links
        triggers: jQuery("#top-nav A[rel=trigger]"),

        // menus belong to triggers (but not every trigger has one)
        menus: jQuery("#top-nav LI UL"),

        // sections contain triggers and menus
        sections: jQuery("#top-nav > LI"),

        init: function() {
            GE.nav.triggers.mouseenter(GE.nav.showMenu);
            GE.nav.sections.mouseleave(GE.nav.hideMenu);
        },

        showMenu: function() {
            // hide all the menus
            GE.nav.sections.each(GE.nav.hideMenu);

            // show the active menu by adding the over class to the
            // first containing div
            jQuery(this).closest("LI").children().first().addClass("over");
        },

        hideMenu: function() {
            jQuery(this).children().first().removeClass("over");
        }

    },

    GE.app = {

        init: function () {
            GE.nav.init();

            if (document.body.id === 'home') {
                GE.slide.init();
            }
        }
    }

})(jQuery);

jQuery(document).ready(function($) {
    GE.setup.init();
    GE.app.init();
});

/* PLUGINS
---------*/

jQuery.fn.duplicate = function(count, cloneEvents) {
    var tmp = [];
    for (var i = 0; i < count; i++) {
        $.merge(tmp, this.clone(cloneEvents).get());
    }
    return this.pushStack(tmp);
};
jQuery.fn.clearDefaults = function() {
    var elem = $('form input.inp-txt');
    var clearElem = [];
    // Loop through the text fields and store their
    // ID and value in an array.
    elem.each(function(i) {
        clearElem.push([$(this).attr('id'),$(this).val()]);
    });
    // Set the field's value to empty
    elem.focus(function(){
        for(i=0;i<clearElem.length;i++){
            if($(this).attr('id') === clearElem[i][0] && $(this).val() === clearElem[i][1]) {
                $(this).val('');
                $(this).addClass('active');
            }
        }
    });
    // Set the field's value back to default
    elem.blur(function(){
        for(i=0;i<clearElem.length;i++){
            if($(this).attr('id') === clearElem[i][0] && $(this).val() === '') {
                $(this).val(clearElem[i][1]);
                $(this).removeClass('active');                
            }
        }
    });
}

jQuery.fn.setAllToMaxHeight = function(){
    return this.height( Math.max.apply(this, $.map( this , function(e){ return $(e).height() }) ) )
}
