var SHADMI = SHADMI || {};

// Modules

(function (s) {
    
    "use strict"; 
    
    // jQuery imagesLoaded plugin v1.0.3
    
    $.fn.imagesLoaded = function( callback ) {
        var $this         = this,
        $images       = $this.find('img').add( $this.filter('img') ),
        len           = $images.length,
        blank         = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

        function triggerCallback() {
            callback.call( $this, $images );
        }

        function imgLoaded() {
            if ( --len <= 0 && this.src !== blank ){
                setTimeout( triggerCallback );
                $images.unbind( 'load error', imgLoaded );
            }
        }

        if ( !len ) {
            triggerCallback();
        }

        $images.bind( 'load error',  imgLoaded ).each( function() {
            // cached images don't fire load sometimes, so we reset src.
            if (this.complete || this.complete === undefined){
                var src       = this.src;
                // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
                // data uri bypasses webkit log warning (thx doug jones)
                this.src      = blank;
                this.src      = src;
            }
        });

        return $this;
    };

    
    // Menu
    
    s.menu = function () {
        
        var $menu = $('#menu'),
            $items = $menu.find('li:has(ul)'),
            $helpers = {
                template : function () {
                    
                    var html = '';
                    
                    html += '<span id="helpers">';
                     html += '<a class="up">&uarr;</a>';
                     html += '<a class="down">&darr;</a>';
                    html += '</span>';
                    
                    return html;
                
                },
                init : function () {
                
                    var $news = $('ul.news'),
                        $up = $('#helpers').find('a.up'),
                        $down = $('#helpers').find('a.down'),
                        $active = $menu.find('a.active').parent();
                    
                    if ( $active.length ) {
                        
                        var positionTop = $active.position().top,
                            activeHeight = $active.height() + 2,
                            offsetTop = String(positionTop - activeHeight);

                        $news.animate({ scrollTop : '+=' + offsetTop }, 0);
                        
                    }
                    
                    $up.click(function () {
                        
                        $news.animate({ scrollTop : '-=180px' }, 500);
                    
                    });
                    
                    $down.click(function () {
                    
                        $news.animate({ scrollTop : '+=180px' }, 500);
                    
                    });
                
                }
            };
        
        $items.each(function () {        
        
            var $item = $(this),
                $trigger = $item.find('h2'),
                open = function (obj) {
                    
                    var $children = obj.children(),
                        totalHeight = (function () {
                            
                            var y = 0;
                            
                            $children.each(function () {

                                y += $(this).height();

                            });
                            
                            return y;
                            
                        }());
                    
                    if ( obj.hasClass('news') ) {
                        
                        obj.parent().append($helpers.template);
                        
                        $helpers.init();
                        
                        $('#helpers').css('opacity', '1');
                        
                        obj.css({
                            height : 175,
                            opacity : 1
                        });
                    
                    } else {
                    
                        obj.css({
                            height : totalHeight,
                            opacity : 1
                        });
                    
                    }
                    
                };
        
            if ( $item.hasClass('open') ) {
                
                open($item.children('ul'));
                
            }
            
            $trigger.click(function () {   
        
                var $element = $(this),
                    $menu = $element.siblings('ul'),
                    menuHeight = $menu.height(),
                    $siblings = $element.parent().siblings().find('ul'),
                    siblingsHeight = $siblings.height(),
                    duration = 300,
                    $items = $menu.find('li'),
                    itemsHeight = 0;
        
                $items.each(function () {
        
                    itemsHeight += $(this).height();
        
                });
        
                function Options(opacity,operator,height) {
                    this.opacity = opacity;
                    this.height = operator + height;
                    return this;
                }
                
                var close = new Options(0,'-=',itemsHeight),
                    open = new Options(1,'+=',itemsHeight),
                    reset = new Options(1,'-=',siblingsHeight);   
                
                if ( menuHeight > 0 ) { 
                
                    if ( $menu.hasClass('news') ) {
                
                        $('#helpers').animate({ opacity : 0 }, 500);
                        $menu.stop(true,true).animate({ opacity : 0, height : 0 }, duration);
                
                    } else {
                
                        $menu.stop(true,true).animate(close,duration);
                
                    }
                
                    $menu.parent().removeClass('open');
                    
                    $menu.siblings('h2').find('a').removeClass('active-header');
                
                } else {
                
                    if ( $menu.hasClass('news') ) {
                
                        if ( $menu.children().length > 8 && !$('#helpers').length ) {
                
                            $menu.parent().append($helpers.template);
                            $helpers.init();
                
                        }
                
                        $menu.stop(true,true).animate({ opacity : 1, height : 175 }, duration);
                        $('#helpers').animate({ opacity : 1 }, 500);
                
                    } else {
                
                        $menu.stop(true,true).animate(open,duration);
                        $('#helpers').animate({ opacity : 0 }, 500);
                
                    }
                
                    $menu.parent().addClass('open');
                    
                    $menu.siblings('h2').find('a').addClass('active-header');
                    
                }
                
                $siblings.animate(reset,duration, function() {
                
                    $(this).animate({ 
                        opacity : 0,
                        height : 0 
                    });
                
                    $(this).parent().removeClass('open');
                    
                    $(this).siblings('h2').find('a').removeClass('active-header');
                    
                });
                
                return false;
            
            });
    
        });
    
    };

    // Slideshow
    
    s.slideshow = {
        
        api : function (slides) {
            
            this.slides = slides;
            this.current = 0;

            var self = this,
                total = self.slides.length,
                current = 0,
                index;

            return {

                get : function (callback) {

                    var $slide = self.slides.eq( callback() ),
                        slide_height = $slide.height();

                    self.slides.eq( current ).stop(true, true).animate({ opacity : 'toggle' }, 150, function () {

                        $(this).hide();

                    });

                    $slide.parent().stop(true, true).animate({

                        height : slide_height

                    }, 300, function () {

                        $slide
                            .stop(true, true)
                            .animate({ opacity : 'toggle' }, 150, function () {

                                $(this).show();

                            });

                    });

                    current = callback();

                },
                next_slide : function () {

                    index = current === total - 1 ? 0 : current + 1;

                    return index;

                },
                prev_slide : function () {

                    var index = current === 0 ? total - 1 : current - 1;

                    return index;

                }

            };
            
        },
        books : function () {
            
            var $slides = $('#books-slideshow img'),
                api = new s.slideshow.api($slides);

            $slides
                .eq(0)
                .css({ height : function (index, value) { $(this).parent().css({ height : value }); } })
                .imagesLoaded(function () {
                    
                    $(this).show();
                    
                });

            if ( $slides.length <= 1 ) { return; }

            $slides.click(function () { api.get(api.next_slide); });
            
        },
        store : function () {
            
            var $slideshow = $('#store-slideshow'),
                $slides = $slideshow.find('img'),
                $nav = $slideshow.find('nav'),
                $next = $nav.find('.next'),
                $prev = $nav.find('.prev'),
                api = new s.slideshow.api($slides);
            
            $slides
                .eq(0)
                .css({ height : function (index, value) { $(this).parent().css({ height : value }); } })
                .imagesLoaded(function () {

                    $(this).show();

                });
            
            if ( $slides.length <= 1 ) { return; }
            
            $slides
                .each(function () {
                
                    var $slide = $(this);
                
                    var slide_width = $slide.outerWidth(),
                        container_width = 638,
                        offset_left = (container_width - slide_width) / 2;
                
                    $slide.css({
                    
                        left : offset_left
                    
                    });
                
                })
                .click(function () { api.get(api.next_slide); });
            
            $nav.show();
            
            $next.click(function () { api.get(api.next_slide); });
            
            $prev.click(function () { api.get(api.prev_slide); });
            
        }
        
    };
    
    // Newsletter
    
    s.newsletter = {
        
        placeholder : function (id) {
            
            var $form = $(id),
                $inputs = $form.find('input:text');
            
            $inputs.each(function () {
                
                var $input = $(this);
                
                var default_value = $input.attr('value');
                
                $input.bind({
                    
                    focus : function () {
                        
                        if ( $(this).val() === default_value ) {
                            
                            $(this).val('');
                        }
                    
                    },
                    blur : function () {
                        
                        if ( $(this).val() === '' ) {
                            
                            $(this).val( default_value );
                        
                        }
                    }
                
                });
                
            });
            
        },
        
        validate : function (id, callback) {

            var $form = $(id),
                $inputs = $form.find('.required');
            
            $form.submit(function (e) {

                var is_valid = false,
                    states = [];
                
                $inputs.each(function (i) {

                    var $input = $(this),
                        $error = $input.siblings('.error');
                        
                    var input_value = $input.val(),
                        input_type = $input.attr('name'),
                        field = {

                            is_empty : function (value) {

                                return value === '' ? true : false;

                            },
                            
                            is_email : function (value) {

                                var regex = /^((([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;

                                return regex.test(value);
                            }

                        };

                    $input
                        .val( input_value.trim() )
                        .focus(function () { 
                            
                            $error.hide(); 
                        
                        });
                    
                    $error.click(function () { $(this).hide(); $input.focus(); });
                    
                    if ( !field.is_empty( input_value ) ) {

                        switch (input_type) {

                            case 'email' :

                                if ( !field.is_email( input_value ) ) {
                                    
                                    $error.text('Invalid Email').show();

                                    states.push('false');

                                } else {

                                    states.push('true');

                                }

                                break;
                                
                            default : 

                                break;

                        }

                    } else {

                        $error.text('Field Is Empty').show();

                        states.push('false');

                    }

                });

                Array.prototype.contains = function (obj) {

                    var i = this.length;

                    while (i--) {

                        if ( this[i] === obj ) {

                            return true;

                        }

                    }
                    return false;
                };

                if ( !states.contains('false') ) { is_valid = true; }

                e.preventDefault();

                if (is_valid) {

                    $.ajax({
                        type    : 'POST',
                        url     : $(this).attr('action'),
                        data    : $(this).serialize(),
                        success : callback()
                    });

                }

                return states;

            });
            
        },
        
        init : function () {
            
            var success_handler = function () {
                    
                    $('#newsletter').find('p').empty().append('<span class="success">You have been successfully added to my mailing list.</span>');
                    
                };
            
            s.newsletter.placeholder('#newsletter');
            
            s.newsletter.validate('#newsletter', success_handler);
            
        }
        
    };
    
    // Utilities
    
    s.utils = {
        
        fx : function () {
            
            var $images = $('.fx img');
            
            $images.imagesLoaded(function () {

                var $image = $(this);
                
                $image.animate({

                    opacity : 1

                }, 250, function () {

                    $image.show();

                });
                
            });
            
            
        },
        
        grid : function () {
            
            var $images = $('#grid img');

            $images.each(function () {

                var $image = $(this),
                    image_X = $image.parent().width(),
                    image_Y = $image.parent().height();

                $image.hover(
                    function () {

                        $(this).css({ left : -2, top : -2, height : '+=4', width : '+=4' });

                    },
                    function () {
        
                        $(this).css({ left : 0, top : 0, height : image_Y, width : image_X });

                    }

                );

            });
            
        },
        
        add_this : function () {
            
            var at = document.createElement('script'),
                s = document.getElementsByTagName('script')[0];

            at.type = 'text/javascript';
            at.async = true;
            at.src = 'http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e4e5ce049a5b8b8';

            s.parentNode.insertBefore(at,s);
            
        },
        
        external_links : function () {
            
            $('a[rel*=external]').live('click', function () {
                
                window.open(this.href);
                
                return false;
                
            });
            
        }
        
    };
    
}(SHADMI));

// Implementation

(function (s) {
    
    "use strict"; 
    
    $(window).load(function () {
        
        $('#page img').removeAttr('title');
        
    });
    
    $(function () {
        
        s.menu();
        s.utils.fx();
        s.utils.external_links();
        
    });
    
}(SHADMI));
