// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || []; // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,clear,count,debug,dir,dirxml,error,exception,firebug,group,groupCollapsed,groupEnd,info,log,memoryProfile,memoryProfileEnd,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());

$(function() {
    
    $.web = $.web || {};
    $.extend($.web, {
        
        /* ----------------------------------------------------------------
            basic properties
        ---------------------------------------------------------------- */
        $document: $(document),
        
        
        /* ----------------------------------------------------------------
            cycle
        ---------------------------------------------------------------- */
        cycle: function() {
            var $cycle = $('#cycle');
            
            if ($cycle.find('> div > a').length > 1) {
                $cycle
                    .append('<div id="cycle-prev" /><div id="cycle-next" />')
                    .find(' > div')
                    .cycle({
                        timeout: 10000,
                        prev: '#cycle-prev',
                        next: '#cycle-next'
                    })
                    .mouseover(function() {
                        $cycle.cycle('pause');
                    })
                    .mouseout(function() {
                        $cycle.cycle('resume');
                    });
            }
        },
        

        /* ----------------------------------------------------------------
            dialog
        ---------------------------------------------------------------- */
        dialog: function() {
            var self = this,
                html = '<div id="gal-img" /><div id="gal-thumbs"></div>',
                $imgs = $('#gallery a');
            
            $('#gallery').on('click', 'a', function(e) {
                e.preventDefault();
                
                var trigger = this;

                $.fancybox(html, {
                    padding: 20,
                    autoScale: false,
                    autoDimensions: false,
                    width: 850,
                    height: 302,
                    onComplete: function() {
                        self.gallery.open(trigger, $imgs);
                    },
                    onClosed: function() {
                        self.gallery.close();
                    }
                });
            });
            
            $('[data-dialog]').fancybox({
                padding: 20
            });
            
            $('[data-dialog=job]').addClass('iframe').fancybox({
                padding: 20,
                autoScale: false,
                autoDimensions: false,
                width: 418,
                height: 460
            });
        },
        
        
        /* ----------------------------------------------------------------
            gallery
        ---------------------------------------------------------------- */
        gallery: {
            open: function(trigger, $imgs) {
                var self = this,
                    commands = {
                        39: 'next',
                        37: 'prev',
                        38: 'top',
                        40: 'down'
                    };
                
                self.$thumbs = $('#gal-thumbs'),
                self.$wrapper = $('#gal-img'),
                self.numImgs = $imgs.size(),
                self.openedIndex = $(trigger).index();
                
                // hide scrollbars
                $('#fancybox-content > div').css('overflow', 'hidden');
                // display header
                self.$thumbs.before('<h3 id="gal-header">Galerie</h3>');
                // display cloned image thumbs
                $imgs.clone().appendTo(self.$thumbs).hide();
                self.showThumbs(0);
                
                // display image
                self.showImage(trigger);

                self.$thumbs.on('click', 'a', function(e) {
                    e.preventDefault();

                    self.changeImage(this);
                });
                
                $.web.$document.on('keydown.gallery', function(e) {
                    if (commands[e.which]) {
                        e.preventDefault();
                        
                        var wantedIndex;
                        switch (commands[e.which]) {
                            case 'next': wantedIndex = self.openedIndex === self.numImgs - 1 ? 0 : self.openedIndex + 1; break;
                            case 'prev': wantedIndex = self.openedIndex === 0 ? self.numImgs - 1 : self.openedIndex - 1; break;
                            case 'top': wantedIndex = self.openedIndex - 2 < 0 ? self.openedIndex - 2 + self.numImgs : self.openedIndex - 2; break;
                            case 'down': wantedIndex = self.openedIndex + 2 < self.numImgs - 1 ? self.openedIndex + 2 : self.openedIndex + 2 - self.numImgs; break;
                        }
                        var wantedTrigger = self.$thumbs.find('a').eq(wantedIndex).get(0);
                        self.changeImage(wantedTrigger);
                    }
                });
            },
            close: function() {
                $.web.$document.off('.gallery');
            },
            showImage: function(trigger) {
                var self = this,
                    $trigger = $(trigger);
                
                self.openedIndex = $trigger.index();
                
                // display big image
                $.when(self.loadImg($trigger.attr('href')))
                    .done(function() {
                        self.$wrapper
                            .append(self.$img.hide())
                            .children('img').fadeIn(500);
                        
                        // highlight selected thumb
                        self.highlightThumb($trigger);
                    });
            },
            changeImage: function(trigger) {
                var self = this,
                    $trigger = $(trigger);
                
                self.openedIndex = $trigger.index();
                
                // display big image
                $.when(self.loadImg($trigger.attr('href')))
                    .done(function() {
                        self.$wrapper
                            .children('img').addClass('off')
                            .end().append(self.$img);
                        setTimeout(function() {
                            self.$wrapper.children('img:first').remove();
                        }, 500);
                        
                        // highlight selected thumb
                        self.highlightThumb($trigger);
                    });
            },
            loadImg: function(src) {
                var self = this,
                    dfd = $.Deferred();
                
                self.$img = $('<img />');
                $.fancybox.showActivity();
                self.$img
                    .load(function() {
                        $.fancybox.hideActivity();
                        dfd.resolve();
                    })
                    .error(dfd.reject)
                    .attr('src', src);
                
                return dfd.promise();
            },
            highlightThumb: function($trigger) {
                var self = this;
                
                // open
                if ($trigger.parent().attr('id') !== 'gal-thumbs') {
                    $trigger = self.$thumbs.find('a').eq($trigger.index());
                }
                
                self.$thumbs.find('img').removeClass('selected');
                $trigger.children('img').addClass('selected');
            },
            showThumbs: function(i) {
                var self = this;
                
                setTimeout(function() {
                    self.$thumbs.children('a:eq('+ i +')').fadeIn(500);
                    i++;
                    if (i < self.numImgs) {
                        self.showThumbs(i);
                    }
                }, 150);
            }
        },
        
        
        /* ----------------------------------------------------------------
            external links
        ---------------------------------------------------------------- */
        externalLinks: function() {
            $('a.external, a[href$=pdf]').on('click', function() {
                window.open(this.href);
                return false;
            });
        },
        
        
        /* ----------------------------------------------------------------
            career form
        ---------------------------------------------------------------- */
        careerForm: function() {
            var $attachements = $('#job-form .attachement'),
                $addButton = $('#add-attachement');
            
            $addButton.show();
            $attachements.addClass('hidden');
            $addButton.on('click', 'a', function(e) {
                e.preventDefault();
                $attachements.filter('.hidden:first').removeClass('hidden');
                if (!$attachements.filter('.hidden').length) {
                    $addButton.hide();
                }
            });
        }
    
    });

    /* ----------------------------------------------------------------
        init
    ---------------------------------------------------------------- */
    $.web.cycle();
    $.web.dialog();
    $.web.externalLinks();
    $.web.careerForm();
    
});
