$(document).ready(function() {

    var currentCategory = 'all';

    //$('div.project').fadeTo(200,0.2);

    $('#contextMenu').bind({
        'showMenu': function(e,es) {
            var cm = $(this);
                
            cm.css({'left': es.pageX+'px','top':  es.pageY+'px'});

            if(cm.is(':visible')) { return false; }
            cm.fadeIn(200);

            $(window).bind('click keydown', function(e){
                 if(e.type == 'keydown' && e.keyCode == 27) {
                     cm.fadeOut(100);
                     $(window).unbind('keydown');
                     return false;
                 } else if (e.type == 'click') {
                     if($(e.target).attr('id') == 'contextMenu') {
                        return true;
                     }
                     if(!$(e.target).parents('#contextMenu').length) {
                        cm.fadeOut(100);
                        $(window).unbind('click');
                        return false;
                     }
                 }
            });
        },
        'hideMenu': function(e) {
            $(this).fadeOut();
        }
    });

    /**
     *  bind event to trigger context menu
     */
    $(document).bind('contextmenu', function(e){
        //return true;
        if($(e.target).parents('#lgGenerated').length) {
            return true;
        }
        $('#contextMenu').trigger('showMenu', e);
        return false;
    });

    
    /*
     *  Project events
     */
    $('div.project').live({
        // show project title
        'mouseenter': function() {
            var that = $(this), tit = that.children('div.title');
            tit.addClass('expanded');
            tit.find('h4').length && tit.animate({'margin-top':(390-tit.height())+'px'},100);
        },
        // hide project title
        'mouseleave': function() {
            var that = $(this), tit = that.find('div.title');
            tit.removeClass('expanded');
            tit.find('h4').length && tit.animate({'margin-top':'370px'},200);
        },
        // show project info text
        'showInfo': function(){
            $(this).find('.info').animate({height:'480px', 'margin-top': '320px'}, 300, 'linear', function(){
                $(this).addClass('expanded');
            }).find('.description, .iclose').fadeIn(700);
        },
        // hide project info text
        'hideInfo': function(){
            $(this).find('.info').animate({height:'80px', 'margin-top': '720px'}, 300, 'linear', function(){
                $(this).removeClass('expanded');
            }).find('.description, .iclose').fadeOut(300);
        },
        // Project Info button - toggle
        'toggleInfo': function() {
            $(this).trigger($(this).find('.info').hasClass('expanded')?'hideInfo':'showInfo');
        },
        // show expanded project information
        'click showProject': function(evt) {
            
            if(this != evt.target) {
                return true;
            }

            $('.project').not(this).trigger('hideProject');
            $('#contextMenu').trigger('hideMenu');

            var
            that= $(this),
            ex      = that.find('.project-ex'),
            exH     = ex.height(),
            exW     = ex.width();

            if(ex.is(':visible')) {
                return false;
            }

            if(!that.hasClass('pcat-'+currentCategory)) {
                $('div.project').fadeTo(100,1);
            }
            
            var
            availWidth  = $(document).width(),
            layerPos    = that.offset().left,
            layerLeft   = 0;

            if(layerPos+exW > availWidth) {
                layerLeft = that.width() - exW;
            }

            // set expanded info sizes
            ex.css({
                'width': that.width()+'px',
                'height': that.height()+'px'
            }).show('fast', function(){

                // set url hash
                $.history.load('!'+that.attr('id'));

                // rewind to the first image
                ex.find('.images ul').trigger('slideTo',0);
                
                // fade the new image in
                ex.find('.images').fadeIn('normal', function(){
                    // animate to expanded width
                    ex.animate({'width':exW+'px', 'margin-left':layerLeft+'px'}, 300, 'swing');
                        
                    // animate to expanded height
                    ex.animate({'height':exH+'px'}, 400, 'swing', function(){
                        $.scrollTo(Math.max(0,(ex.offset()).top-105), {'axis':'y','duration':300});
                        $('div.project').not(that).fadeTo(100, 0.4);
                    });
                    
                    // fade other areas in
                    ex.find('.info, .controls, .navi').fadeIn('fast');                    
                });
            });
            return false;           
        },
        // hide expanded project information
        'hideProject': function() {
   
            var self = $(this).find('.project-ex');

            if(!self.is(':visible')) {
                return false;
            }
           
            self.fadeOut(400, function(){
                self.find('.images ul').trigger('slideTo',0);
                self.find('.images, .controls, .navi, .info').hide();
                self.css('margin-left','0');
            });

            $('div.project').fadeTo(100,1);

            return false;
        },
        // hide expanded projects info right away
        'kill': function(){
            var self = $(this).find('.project-ex');
            self.hide();
            self.find('.images ul').trigger('slideTo',0);
            self.find('.images, .controls, .navi, .info').hide();
            self.css('margin-left','0');
            $('div.project').fadeTo(100,1);
        }
    });

    // hide expanded project information - close button
     $('.project-ex .cclose').live('click', function(){
        $(this).parents('.project').trigger('hideProject');
        return false;
    });

    // hide project info text - close button
    $('.cinfo a, .iclose').live('click', function() {
        $(this).parents('.project').trigger('toggleInfo');
        return false;
    });

    // ESCAPE key action
    $(window).bind({
        'keyup': function(e){
            if(e.keyCode != 27) {
                return true;
            }
            if($('#content-wrapper').is(':visible')) {
                $('#content-wrapper').trigger('hideContent');
                $('div.project').fadeTo(200,1);
                return true;
            }
            $('.project').trigger('hideProject');
            return false;
        },
        'keydown': function(e) {
            if((e.keyCode == 38 || e.keyCode == 40) && $('#downloads').is(':visible')) {
                e.stopPropagation();
                return false;
            }
            return true;
        }
    });

    $('#content-wrapper').bind({
        'showContent': function(e, wt) {
            var that = $(this);
            if(that.is(':visible')) { // show only if not yet visible
                //wt && that.trigger('initTimeout', 1000);
                return false;
            }
            $.scrollTo(0, {'axis':'y','duration':300});
            that.slideDown(300);
            //wt && that.trigger('initTimeout', 1000);
            return false;
        },
        'hideContent': function(e, keepProjects) {
            var that = $(this);
            that.slideUp(300);
            
            clearTimeout(that.data('contentTimeout'));
            that.data('contentTimeout', null);
            return false;
        },
        'initTimeout': function(e, ms) {
            var that = $(this);
            clearTimeout(that.data('contentTimeout'));
            that.data('contentTimeout', setTimeout(function(){
                that.trigger('hideContent');
            }, ms || 1000));
            return true;
        }        
    });

    $('#content').bind({
        'mouseleave': function(e){
            if(e.target.id == 'lgLanguage') {
                return;
            }
            $('#content-wrapper').trigger('initTimeout',1000);
        },
        'mouseenter': function(){
            var that = $('#content-wrapper');
            clearTimeout(that.data('contentTimeout'));
            that.data('contentHideTimeout', null);
        }
    });

    // switch between project images
    var bindProjectsCarousel = function() {
        $('.project-ex .images ul').carouFredSel({
            items: {
                visible: 1,
                minimum: 1,
                width: 750,
                height: 800
            },
            auto: false,
            prev: {key: "left"},
            next: {key: "right"},
            width:750,
            height:800
        });
        
    };

    // switch between project images - navi links
    $('.project-ex .navi a').live('click', function(){
        $(this).parents('.project-ex').find('.images ul').trigger($(this).parent('li').hasClass('nnext') ? 'next' : 'prev',1);
        return false;
    });

    // categories navi
    $('#categories a').bind('click', function(){
        var c = $(this).attr('href').substring(4), p1, p2, p1w, p2w;

        if(c == 'all') {
            $('div.project').fadeTo(300,1);
            return false;
        }

        $('.project').trigger('kill');
        
        var projects = $('div.project.pcat-'+c);
        var container= $('#projects');

        for(var i = 0, n = projects.length; i < n; i++) {
            p1 = container.find('div.project.pcat-'+c).eq(i);
            p2 = container.find('div.project').not('.pcat-'+c).eq(0);
            p1w = p1.width();
            p2w = p2.width();

            if(p1w != p2w) {
                p2.parents('.project-wrapper').animate({'width': p1w+'px'}, 300);
                p1.parents('.project-wrapper').animate({'width': p2w+'px'}, 300);
            } 

            $('#'+p1.attr('id')).replaceWith(p2.clone());
            $('#'+p2.attr('id')).replaceWith(p1.clone());
        }

        $('div.project.pcat-'+c).fadeTo(200,1);
        $('div.project').not('.pcat-'+c).fadeTo(200,0.3, function() {
            bindProjectsCarousel();
            $('#content-wrapper').trigger('hideContent');
        });

        currentCategory = c;        
        return true;
    });
    
    
    $('body').addClass('jsready');
    $('a[rel="external"]').attr('target', '_blank');

    // toggle website content area
    $('#menuLink').bind({
        'click': function(e){
            var c = $('#content-wrapper');
            if(c.is(':visible')) {
                $('div.project').fadeTo(200,1);
                $('#content-wrapper').trigger('hideContent');
                $('div.project').fadeTo(200,1);
                return true;
            } else {
                $('div.project').fadeTo(200,0.2);
                return $('#content-wrapper').trigger('showContent');
            }
        }
    });

    // menu
    $('#about, #categories, #downloads, #lorem, #contact').bind('togglePage', function(){
        var self = $(this);
        self.trigger(self.is(':visible') ? 'hidePage' : 'showPage');
    });
    $('#about, #categories, #contact, #downloads, #lorem').bind('hidePage', function(e, eShow){
        $(this).fadeOut(300, function(){
           eShow && $(eShow).trigger('showPage');           
        });
        $('div.project').fadeTo(200,1);
    });
    
    $('#about, #categories, #contact, #lorem, #downloads').bind('showPage', function(){
        var self = $(this);
        //$('#content-wrapper').animate({'width':'500px'}, 300, 'swing', function(){
        self.fadeIn(300);
        $('div.project').fadeTo(200,0.2);
        //});
    });
    /*
    $('#lorem').bind('showPage', function() {
        var self = $(this);
        $('#content-wrapper').animate({'width':'750px'}, 300, 'swing', function(){
            self.slideDown(300);
        });
    }
    );
    */
    /*
    $('#lorem').bind({
        'showPage': function() {
            var self = $(this);
            $('#content-wrapper').animate({'width':'750px'}, 300, 'swing', function(){
                self.slideDown(300, function() {
                    $('#loremGenerator').animate({'width':'750px'});
                });
            });
        },
        'hidePage': function(e, eShow) {
            var self = $(this);
            $('#loremGenerator').animate({'width':'0'}, 300, 'swing',function(){
                self.slideUp(300, function() {
                    eShow && $(eShow).trigger('showPage');
                });
            });
        }
    });
    */
    /*
    $('#downloads').bind('showPage', function(e, eHide) {
        var self    = $(this),
            cfs     = self.data('carouselInitiated');

        $('#content-wrapper').animate({'width':'500px'}, 300, 'swing', function(){

            var items = self.find('ul li').length;

            if(items <= 6) {
                self.slideDown(300, function(){
                    eHide && $(eHide).trigger('hidePage');
                });
                return false;
            }

            if(!cfs) {
                self.find('ul li').slice(6).addClass('hide');
            }

            self.slideDown(300, function(){
               if(!cfs) {
                    self.find('ul').carouFredSel({
                        items: {
                            visible: 6,
                            minimum: 1,
                            width: 480,
                            height: 'variable'
                        },
                        scroll: {
                            mousewheel: true
                        },
                        direction: 'down',
                        circular: false,
                        infinite: false,
                        auto: false,
                        prev: {key: "up"},
                        next: {key: "down"},
                        pagination: {
                            container: '#downloads ol',
                            anchorBuilder: function(nr) {
                                return '<li><a href="#downloads-'+nr+'">'+nr+'</a></li>';
                            }
                        }
                    });
                    self.data('carouselInitiated', true).find('li').removeClass('hide');
                }
                eHide && $(eHide).trigger('hidePage');
            });
        });
    });
    */
    // menu - switch between content pages
    $('#menu a').bind('click', function(evt){

        var hash = $(this).attr('href'), page = hash.substring(4);

        if(window.location.hash == hash) {
            $('#pages > #'+page).trigger('togglePage');
        }
        
        $.history.load('!c-'+page);
        return true;
    });

    // LOREM GENERATOR
    var lg = $('#loremGenerator');

    $('a.bclose', lg).bind('click', function(){
        $('#lorem').trigger('hidePage');
        return false;
    });

    // show language selection
    $('#lgLanguage', lg).bind('mouseover mouseout', function(e){
        var self = $(this);
        self.toggleClass('expanded', (e.type == 'mouseover'));
    });

    // select language
    $('#lgLanguage li', lg).bind('click', function(){
        var self = $(this);
        $('input[name="language"]', lg).val(self.attr('id').split('language-')[1]);
        self.parent('ul').trigger('mouseout');
        self.addClass('selected').siblings().removeClass('selected');
        self.prevAll('li').addClass('hide');
    });

    // words / paragraphs
    $('a.checkbox', lg).bind('click', function(){
        var self = $(this);
        self.siblings('a.checkbox').removeClass('selected');
        self.addClass('selected');
        $('input[name="type"]', lg).val(self.attr('href').split('#type-')[1]);
        return false;
    });

    // generate Lorem text
    $('#lgGo', lg).bind('click', function(){
       var postData = {
           'language':  $('input[name="language"]', lg).val(),
           'type':      $('input[name="type"]', lg).val(),
           'number':    $('input[name="number"]', lg).val()
       };

       if(!postData.language) {
           postData.language = "empirestrickesback";
           $('#language-empirestrickesback', lg).trigger('click');
       }
       if(!postData.type) {
           postData.type = "paragraphs";
           $('#lgParagraphs', lg).trigger('click');
       }
       if(!postData.number) {
           postData.number = 3;
           $('#lgValNumber', lg).val(3);
       }
       $.get('/index/lorem-generator', postData, function(dt, status){
           if(status == 'success') {
               var d = $('#lgGenerated > textarea');
               d.fadeOut('fast', function(){
                   d.text(dt);
                   d.fadeIn('fast');
               });
           }
       }, 'html');
       return false;
    });

    $('#lgGenerate a').bind('click', function(){
        $('#lgGenerated textarea').select();
        return false;
    });


    // contact form
    $('#contact form').bind('submit', function(){

        var c, m, e = $('#contact form span em'), 
            self = $(this),
            fe      = self.find('input[name="email"]'),
            fc      = self.find('textarea'),
            fs      = self.find('input[name="subject"]'),
            postData = {
                'email': fe.val(),
                'content': fc.val(),
                'subject': fs.val()
            };

        $.post('/index/mailer', postData, function(dt, status){
            
            if(status == 'success' && dt && dt.status == 'success') {
                c = 'success';
                m = dt.msg

                fe.val(fe.data('default'));
                fc.val(fc.data('default'));
                fs.val(fs.data('default'));

            } else if(dt && dt.status != 'success') {
                c = 'err';
                m = dt.msg;
            } else {
                c = 'err';
                m = 'Problem sending mail, please try again later';
            }
            
            if(e.length) {
                e.fadeOut('normal', function(){
                    e.removeAttr('class').addClass(c).text(m).fadeIn();
                });
            } else {
                $('<em class="'+c+'" style="display:none;">'+m+'</em>').prependTo('#contact form span').fadeIn();
            }
        }, 'json');

        return false;
    });

    // contact form defaults
    $('#contact #fEmail, #contact #fSubject, #contact textarea').bind('focus blur', function(evt){
        var that = $(this), def = that.data('default'), v = that.val();
        
        if(evt.type == 'focus') {
            !def && that.data('default', v);
            ((def == v) && that.val('')) || that.val(v);

        } else if (evt.type == 'blur') {
            (!v || v == def) && that.val(def);
        }
       
    });

    // history always at the very end, to ensure all events are attached
    var initHistory = function() {
        var h = true;
        $.history.init(function(hash){
            if(hash.indexOf('!c-') === 0) {
                var cnt = $('#content-wrapper'), pageCurr, pagePrev;
                hash = $('#menu a[href="#'+hash+'"]').length ? hash.substring(3) : 'about';
                pageCurr= $('#pages > #'+hash),
                pagePrev= pageCurr.siblings('div:visible');

                $('#menu a').removeClass('current').filter('[href="#!c-'+hash+'"]').addClass('current');

                if(pagePrev.length) {
                    pagePrev.trigger('hidePage', pageCurr);
                } else {
                    pageCurr.trigger('togglePage');
               }

                if(!cnt.is(':visible')) {
                    cnt.trigger('showContent');
                }

                //h && cnt.trigger('initTimeout',4000) && (h = !h);
            } else if (hash.indexOf('!p-') === 0) {
                var p;
                if((p = $('#'+hash.substring(1))).length) {
                    p.trigger('showProject');
                }
            } else if (hash.indexOf('!w-') === 0) {
                var w;
                
                if((w = $('#categories a[href="#'+hash+'"]')).length) {
                    //w.trigger('click');
                }
            } else if (hash === '!home') {
                $('#content-wrapper').trigger('hideContent');
                $('.project').trigger('kill');
            }

            return false;
        });
    };

    // initial projects fadeIn loader
    (function() {

        var ib, sr, im, el, pw = $.makeArray($('div.project-wrapper'));
        var iv = setInterval(function(){

            el = $(pw.shift());
            sr = el.find('div.project').css('background-image').substring(4);
            if(sr) {
                sr = sr.substring(sr.length-1, -1);
                im = new Image();
                im.src = sr.replace(/"/g,'');
                el.find('div.project div.title').fadeIn(140);
            }

            el.fadeIn(800);
            
            if((ib = el.find('div.info-box')).length && el.offset().top == 0) {
                ib.addClass('first-line');
            }

            if(!pw.length) {
                clearInterval(iv);
                var html = '';
                $('div.project-ex div.images').each(function(i,v){
                    html = '';
                    $(v).find('a').each(function(i2,v2) {
                        html += '<li><img src="'+$(v2).attr('rel')+'" alt="" /></li>';
                    });
                    $(v).html('<ul>'+html+'</ul>');
                });
                
                bindProjectsCarousel();

                $('#pages > div').css('min-height', ($(document).height() - 320) + 'px');
                initHistory();
            }
        },150);
    })();
});
