var NERD = NERD || {};

$(function(){
	
	$(function(){
        if ($('#slides').length > 0)
        {
            $('#slides').slides({
                preload: true,
                play: 8000
            });
        }
	});
	
	$('a[rel="print"]').click(function(e) {
	    window.print();
	    e.preventDefault();
	});
	
	// disable shipping fields in checkout form by default
	var checkboxEle = $('input[name="same_as_billing"]');
	if (checkboxEle[0]) {
	    var checkShipping = function(checkboxEle) {
	        var newState = 'disabled';
            if(checkboxEle.checked) newState = null;
            $('input[name*="_shipping"]').attr('disabled', newState)
        }
        
    	checkboxEle.click(function(e) {
    	    checkShipping(e.target);
    	});
    	
    	checkShipping(checkboxEle[0]);
    }
    // end shipping field code
    
    // force captcha field to be blank upon page load
    $('#captcha').val("");
    
	var home = false;
    if ($('body').hasClass('home')) {
        home = true;
    }
    
    // main navigation
    // if home
    if (home) {
        // set initial element positions and top and bottom orientations
        $("#nav-main li").eq(0).addClass('up').attr('rel','16').find('span').css('top','16px');
        $("#nav-main li").eq(1).addClass('down').attr('rel','30').find('span').css('top','30px');
        $("#nav-main li").eq(2).addClass('up').attr('rel','6').find('span').css('top','6px');
        $("#nav-main li").eq(3).addClass('down').attr('rel','30').find('span').css('top','30px');
        $("#nav-main li").eq(4).addClass('up').attr('rel','0').find('span').css('top','0px');
        $("#nav-main li").eq(5).addClass('down').attr('rel','30').find('span').css('top','30px');
        $("#nav-main li").eq(6).addClass('up').attr('rel','8').find('span').css('top','8px');
        $("#nav-main li").eq(7).addClass('down').attr('rel','30').find('span').css('top','30px');
        
        $("#nav-main li").hover(function() {
            var originalPos = $(this).attr('rel');
            originalPosTxt = originalPos + "px";
            var overPosTxtUp = (parseInt(originalPos)+10) + "px";
            var overPosTxtDown = (parseInt(originalPos)-10) + "px";
            if ($(this).hasClass('up')) {
                $(this).find('span').stop().animate({top: overPosTxtUp}, 250);
            } else {
                $(this).find('span').stop().animate({top: overPosTxtDown}, 250);
            }            
        }, function() {
            $(this).find('span').stop().delay(200).animate({top: originalPosTxt}, 250);
        });
        
    } else {
        $("#nav-main li").hover(function() {
            if ($(this).hasClass('active')) {
            } else {
                $(this).find('span').stop().animate({top: "18px"}, 250);
            }        
        }, function() {
            if ($(this).hasClass('active')) {
            } else {
                $(this).find('span').stop().delay(200).animate({top: "28px"}, 250);
            }
        
        });
    }
    
    $("#nav-main li").css('cursor','pointer').click(function() {
        var linkURL = $(this).find('a').attr('href');
        window.location = linkURL;
    });
    //END main navigation
    
    $('.whatsthis').hover(function() {
        $('#cvc-image').show();
    }, function() {
        $('#cvc-image').hide();
    });
    
    NERD.AutoReplace.init();
    NERD.HasJS.init();
});


/* ---------------------------------------------------------------------
    Carousel
    Authors: Nick Le Guillou, Brian Bell

    Generic carousel functionality
------------------------------------------------------------------------ */

NERD.Carousel = {
    $carouselContainer: undefined,
    $slideContainer:    undefined,
    $prev:              undefined,
    $next:              undefined,
    $slides:            undefined,
    $slideWidth:        undefined,
    $firstSlide:        undefined,
    $currentSlide:      undefined,
    $lastSlide:         undefined,
    $autoRotate:        undefined,
    $intervalId:        undefined,
    $startRandom:       undefined,

    init: function(carouselContainer, slideContainer, slides, autoRotate, startRandom) {
        var self = this;

        if ($(carouselContainer).length !== 0) {
            self.$carouselContainer = $(carouselContainer);
            self.$slideContainer    = self.$carouselContainer.find(slideContainer);
            self.$slides            = self.$carouselContainer.find(slides);
            self.$slideWidth        = self.$slideContainer.css('width');

            self.$prev = $('<div id="previous"><a href="#">Previous</a></div>');
            self.$next = $('<div id="next"><a href="#">Next</a></div>');

            if (self.$slides.length >= 2) {
                self.$carouselContainer.prepend(self.$prev);
                self.$carouselContainer.append(self.$next);

                var navHeight      = self.$prev.find('a').outerHeight();
                var navWidth       = self.$prev.find('a').outerWidth();
                var viewportHeight = self.$carouselContainer.outerHeight();

                self.$prev.css({
                    'position' : 'absolute',
                    'top'      : ((viewportHeight / 2) - (navHeight / 2)),
                    'left'     : -(navWidth + 14)
                });
                self.$next.css({
                    'position' : 'absolute',
                    'top'      : ((viewportHeight / 2) - (navHeight / 2)),
                    'right'    : -(navWidth + 14)
                });

            }

            self.$autoRotate    = autoRotate;
            self.$startRandom   = startRandom;
            self.$firstSlide    = self.$slides.first();

            var startSlide = self.$startRandom
                                ? Math.floor(Math.random() * self.$slides.length)
                                : 0;

            self.$currentSlide  = self.$slides.eq(startSlide);
            self.$lastSlide     = self.$slides.last();

            self.$slides.hide();
            self.$currentSlide.fadeIn(1000);

            self.bind();
        }
    },

    bind: function() {
        var self = this;

        self.$next.click(
            function(e) {
                self._rotateForward();

                if (self.$intervalId) {
                    clearInterval(self.$intervalId);
                }

                e.preventDefault();
            }
        );

        self.$prev.click(
            function(e) {
                if ($('.slide:animated').length > 0) {
                    return false;
                }

                var prevSlide;

                if (self.$currentSlide.prev().length === 0) {
                    prevSlide = self.$lastSlide;
                } else  {
                    prevSlide = self.$currentSlide.prev();
                }

                self.showPrev(prevSlide);

                if (self.$intervalId) {
                    clearInterval(self.$intervalId);
                }

                e.preventDefault();
            }
        );

        if (self.$autoRotate) {
            self.$intervalId = setInterval(
                function() {
                    self._rotateForward();
                },
                8000
            );
        }
    },

    showNext: function(nextSlide) {
        var self = this;

        nextSlide
            .show()
            .css('left', self.$slideWidth);

        self.$currentSlide
            .animate({
                'left' : '-' + self.$slideWidth
            },
            1200,
            'easeInOutQuint',
            function() {
            }
        );

        nextSlide
            .animate({
                'left' : 0
            },
            1200,
            'easeInOutQuint',
            function() {
            }
        );

        self.$currentSlide = nextSlide;
    },

    showPrev: function(prevSlide) {
        var self = this;

        prevSlide
            .show()
            .css('left', '-' + self.$slideWidth);

        self.$currentSlide
            .animate({
                'left' : self.$slideWidth
            },
            1200,
            'easeInOutQuint',
            function() {
            }
        );

        prevSlide
            .animate({
                'left' : 0
            },
            1200,
            'easeInOutQuint',
            function() {
            }
        );

        self.$currentSlide = prevSlide;
    },

    _rotateForward:function() {
        var self = this;

        if ($('.slide:animated').length > 0) {
            return false;
        }

        var nextSlide;

        if (self.$currentSlide.next().length !== 0) {
            nextSlide = self.$currentSlide.next();
        } else {
            nextSlide = self.$firstSlide;
        }

        self.showNext(nextSlide);
    }
};

/* ---------------------------------------------------------------------
    Incubator
    Author: Nick Le Guillou

    Cycles through "pages" of incubator projects. Displays a selected
    project's GiveMN widget in a modal window.
------------------------------------------------------------------------ */
NERD.Incubator = {
    $carouselContainer: undefined,
    $slideContainer:    undefined,
    $thumbs:            undefined,
    $dialog:            undefined,

    init: function() {
        var self = this;

        if ($('#widget_container').length !== 0) {

            self.$carouselContainer = $('#widget_container');
            self.$slideContainer    = self.$carouselContainer.find('#grid');
            var items               = self.$slideContainer.children();
            self.$thumbs            = items.find('.thumb');


            for (i = 0; i < Math.ceil(items.length / 12); i++) {
                var times   = i * 12;
                var group   = items.slice(times, (times + 12));
                var slide   = $('<li class="slide"></li>');
                var contain = $('<ul></ul>');

                group.each(
                    function(i) {
                        contain.append($(this));
                    }
                );

                slide.append(contain);
                self.$slideContainer.append(slide);
            }

            self.bind();
        }
    },

    bind: function() {
        var self = this;

        NERD.Carousel.init('.viewport', '#grid', '.slide');

        self.$thumbs.click(function(e) {
           e.preventDefault();

            var me = $(this);
            var dialog        = $('<div><iframe src="http://givemn.razoo.com/widgets/orders/'+me.attr('href')+'" scrolling="no" marginheight="0" marginwidth="0" width="300" height="500" frameborder="0" style="width:300px; height:500px; padding:0; margin:0; border:0; overflow:hidden"></iframe><a href="" class="close_modal">Close Window</a></div>').dialog({
                                    autoOpen: false,
                                    modal: true,
                                    width: 350
                                });
            var dialogWindow  = $('body');

            dialog.dialog({
                open: function() {
                    var dialogOverlay = $('.ui-widget-overlay');
                    dialogWindow.css('overflow', 'hidden');
                    dialogOverlay.css({
                        'width'  : '100%',
                        'height' : '100%'
                    });

                    if ($.browser.msie && $.browser.version < 8) {
                        window.scrollTo(0, 0);
                    }

                    $('.close_modal').click(function(e) {
                        e.preventDefault();
                        dialog.dialog('close');
                    });
                },
                close: function() {
                    dialog.dialog('destroy');
                    dialog.remove();
                    dialogWindow.css('overflow', 'auto');

                }
            });

            dialog.dialog('open');

            var uiDialog          = $('.ui-dialog');
            var uiDialogMinHeight = parseInt(uiDialog.css('min-height'), 10);
            var uiDialogTop       = parseInt(uiDialog.css('top'), 10);
            var titleBar          = uiDialog.find('.ui-dialog-titlebar');
            var titleBarMargin    = parseInt(titleBar.css('margin-top'), 10);
            var uiContentHeight   = uiDialog.outerHeight();

            var topOffset         = (uiDialogTop - ((uiContentHeight - uiDialogMinHeight) / 2));
            titleBar.css('height', uiContentHeight - (titleBarMargin * 2));
            uiDialog.css('top', topOffset);

            // May also need to use PIE.js to give border-radius
            // and box-shadow to dialog box in IE.
        });
    }
};

/* ---------------------------------------------------------------------
HasJS
Author: Nerdery Boilerplate

Replaces "no-js" class with "has-js" on the body if JavaScript
is present. This allows you to style both the JavaScript enhanced
and non JavaScript experiences. 
------------------------------------------------------------------------ */

NERD.HasJS = {
    init: function() {
        $('body').removeClass('no-js');
        $('body').addClass('has-js');
    }
};

/* ---------------------------------------------------------------------
AutoReplace
Author: Nerdery Boilerplate

Mimics HTML5 placeholder behavior

Additionally, adds and removes 'placeholder-text' class, used as a styling
hook for when placeholder text is visible or not visible

Additionally, prevents forms from being
submitted if the default text remains in input field - which we may 
or may not want to leave in place, depending on usage in site
------------------------------------------------------------------------ */
NERD.AutoReplace = {
    $fields: undefined,

    init: function() {
        var $fields = $('[placeholder]');

        if ($fields.length !== 0) {
            var self = this;
            self.$fields = $fields.addClass('placeholder-text');
            self.bind();
        }
    },

    bind: function() {
        var self = this;

        self.$fields.each(
            function() {
                var me = $(this);
                var defaultText = me.attr('placeholder');
                me.attr('placeholder', '').val(defaultText);

                me.focus(
                    function() {
                        if (me.val() === defaultText) {
                            me.val('').removeClass('placeholder-text');
                        } 
                    }
                );

                me.blur(
                    function() {
                        if (me.val() === '') {
                            me.val(defaultText).addClass('placeholder-text');
                        }
                    }
                );

                me.parents('form').submit(
                    function() {
                        if (me.is('.required') && (me.val() === defaultText || me.val() === "")) {
                            return false;
                        }
                    }
                );
            }
        );
    }
};

