/* Author: Kalley Powell

*/
(function($) {
    
    // Simplified getter and setter for footer state on load.
    function FooterState() {}
    FooterState.initial = false;
    FooterState.get = function(_default) {
        if( ! $.cookie('exp_footer-state')) {
            this.set(_default);
            FooterState.initial = true;
        }
        return $.cookie('exp_footer-state');
    }
    FooterState.set = function(value) {
        $.cookie('exp_footer-state', value, {expires: 7});
        return value;
    }
    var footer_state = FooterState.get('open'),
    
    root = $(document).bind('ready', function() {
        var dialog;
        root.delegate('div.ntg-dialog-close a', 'click', function() {
            dialog.remove();
        }).find('a[href*="operations-map"]').bind('click', function() {
            dialog = $('<div>', {
                css: {
                    background: 'rgba(0,0,0,.7)',
                    height: $('#container').height(),
                    left: 0,
                    position: 'absolute',
                    top: 0,
                    width: '100%',
                    zIndex: 99999,
                    behavior: 'url('+SITE_URL+'css/PIE.htc)'
                }
            }).appendTo('body');
            $.ajax({
                success: function(data) {
                    dialog.append(data);
                    mapInit(dialog);
                },
                url: this.href
            })
            return false;
        });
        root.find('p.swapper a').bind('click', function() {
            var $this = $(this).addClass('active');
            $this.siblings().removeClass('active');
            $(this.hash.replace('#', '#fans-')).show().siblings('div[id]').hide();
        }).filter('[href*="#operators"]').addClass('active');
        root.find('p.logo-links a').bind('click', function() {
            if( ! $.cookie('nglpa')) {
                var link = $(this), $dialog = $('<div>', {
                    html: '<form><fieldset><label for="logoPass">Password:</label><input type="password" id="logoPass" name="logoPass"></fieldset><p style=margin-top:5px;>If you don\'t have the password, e-mail <a href="mailto:rwilliams@newtecheng.com">rwilliams@newtecheng.com</a> for access.</p></form>',
                    title: 'Enter the password'
                }).dialog({
                    modal: true,
                    buttons: {
                        'Submit': function() {
                            var logoPass = $('#logoPass');
                            if(logoPass.val() == 'ntglogo') {
                                $.cookie('nglpa', true, {expires: 7});
                                window.open(link.attr('href'), 'logo');
                                $dialog.dialog('close');
                            } else {
                                logoPass.addClass('ui-state-error');
                            }
                        },
                        'Cancel': function() {
                            $dialog.dialog('close');
                        }
                    }
                });
                $dialog.find('form').bind('submit', function() {root.find('button:contains("Submit")').trigger('click');return false});
                return false;
            }
        }).attr('target', '_blank');
    }),
    
    mapInit = function(dialog) {
        scrollTo(0,0);
        var images = {
            'continent': {},
            'country': {}
        }, types = ['continent', 'country'],
        view = 'operations',
        dimensions = {
            'south-america': {
                height: 710,
                left: 169,
                top: -232,
                width: 1430
            },
            'north-america': {
                height: 1140,
                width: 2297
            },
            'europe': {
                height: 1144,
                left: -632,
                top: 27,
                width: 2305
            },
            'oceania': {
                height: 1371,
                left: -1788,
                top: -783,
                width: 2761
            },
            'africa': {
                height: 816,
                left: -317,
                top: -235,
                width: 1643
            },
            'middle-east': {
                height: 1365,
                left: -1075,
                top: -221,
                width: 2750
            },
            'asia': {
                height: 722,
                left: -554,
                top: -28,
                width: 1454
            }
        }, goBack = $('#go-back').bind('click', function() {
            goBack.hide();
            country = '';
            root.find('img.country-overlay').detach();
            mapCover.removeAttr('usemap');
            mapContainer.css('background', '#fff');
            zoomImage.fadeTo(500, 0, function() {
                mapCover.attr('usemap', '#continents');
                mapContainer.removeAttr('style');
                mapContent.html(offices);
                makeScrollable();
            });
            fullMap.fadeTo(300, 0, function() {
                fullMap.removeAttr('style');
            }).fadeTo(200, 1);
        }), fullMap = $('#full-map'),
            zoomImage = $('#zoom-image'),
            mapCover = $('#map-cover'),
            mapContainer = $('#map-container'),
            mapContent = $('#map-content'),
            offices = mapContent.html(),
            country = '', continent = '',
            content_pieces = {
                'operations': {},
                'jobs': {},
                'offices': {}
            },
            tpl = {
                jobs: '<div class="location">Position: <strong>{{description}}</strong><br>Title: <strong>{{title}}</strong><br>Contact: <strong>{{resource_manager}}</strong><br>Country/State: <strong>{{country}}/{{location}}</strong><br><a href="'+SITE_URL+'job-center/submit-resume/{{id}}">Apply for this position</a></div>',
                operations: '',
                offices: '{{html}}'
            },
            getData = function() {
                if( ! content_pieces[country]) {
                    mapContent.addClass('preload').html('');
                    $.ajax({
                        dataType: 'json',
                        success: function(data) {
                            var output = '<h2>'+country+'</h2><div style=clear:left>';
                            for(var p in data) {
                                var title = root.find('a[data-view="'+p+'"]').text();
                                output += '<div class="map-column clearfix"><h3 style=font-size:1.8em>'+title+'</h3>';
                                var piece = data[p];
                                if(piece.length) {
                                    for(var i = 0, l = piece.length; i < l; ++i) {
                                        var rendered = tpl[p];
                                        for(var q in piece[i]) {
                                            rendered = rendered.replace(new RegExp('{{'+q+'}}', 'g'), piece[i][q]);
                                        }
                                        output += rendered;
                                    }
                                    output += '</div>';
                                } else {
                                    output += '<div class="location">No '+title.toLowerCase()+' here at this time.</div></div>';
                                }
                            }
                            content_pieces[country] = output;
                            mapContent.removeClass('preload').html(output);
                            makeScrollable();
                        },
                        url: SITE_URL+'json/'+continent+'/'+country
                    });
                } else {
                    mapContent.html(content_pieces[country]);
                    makeScrollable();
                }
            };
        $('#map-nav').find('a').bind('click', function() {
            $(this).parent().addClass('active').siblings().removeClass('active');
            view = $(this).data('view');
            if(country) {
                getData();
            }
            return false;
        });
        $(types).each(function(i) {
            var type = types[i];
            root.find('area[id^="'+type+'-"]').each(function() {
                var suffix = this.id.replace(type+'-', '');
                images[type][this.id] = $('<img>', {
                    alt: this.alt,
                    'class': type+'-overlay',
                    id: suffix+'-overlay',
                    src: SITE_URL+'images/map/'+type+'/'+suffix+'-hover.gif'
                });
            })
            root.delegate('area[id^="'+type+'-"]', 'mouseenter mouseleave click', function(ev) {
                root.find('img.'+type+'-overlay').detach();
                root.find('div.tooltip').remove();
                if(ev.type == 'click') {
                    var suffix = this.id.replace('continent-', '');
                    if(type == 'continent') {
                        continent = suffix;
                        mapCover.removeAttr('usemap');
                        fullMap.animate(dimensions[suffix], 700, 'sineEaseOut', function() {
                            zoomImage.attr('src', SITE_URL+'images/map/continent/'+suffix+'.gif').css('opacity', 0).bind('load', function() {
                                zoomImage.unbind('load').fadeTo(500, 1, function() {
                                    mapCover.attr('usemap', '#'+suffix+'-countries');
                                    fullMap.removeAttr('style').css('opacity', 0);
                                });
                            });
                        });
                        goBack.show();
                    } else {
                        country = this.alt;
                        getData();
                    }
                    return false;
                } else {
                    var pos = mapContainer.offset();
                    if(ev.type == 'mouseenter' && $(this).data('disabled') != true) {
                        $('<div>', {
                            'class': 'tooltip',
                            css: {
                                background: '#fff',
                                left: ev.pageX-pos.left,
                                padding: '5px',
                                position: 'absolute',
                                top: ev.pageY-pos.top,
                                zIndex: 11
                            },
                            text: this.alt
                        }).prependTo(mapContainer);
                        images[type][this.id].prependTo(mapContainer);
                    } else {
                        root.find('div.tooltip').remove();
                    }
                }
            });
        });
        function makeScrollable() {
            var $main = $('#map-content').wrap('<div style="position:relative">'),
                scrollHeight = $main.get(0).scrollHeight -($.browser.safari ? parseInt($main.css('padding-top')) + parseInt($main.css('padding-bottom')) : 0),
                diff = scrollHeight-$main.outerHeight(),
                $scrollbar, disable = diff <= 0;
            var scrollContent = function(ev, ui) {
                $main.scrollTop(((100-ui.value)*diff)/100);
            };
            diff += $main.outerHeight(true)-$main.height();
            $main.addClass('scrollable').after('<div id=scrollbar><div>').bind('mousewheel DOMMouseScroll', function(ev) {
                var delta = ev.detail ? ev.detail*-1 : ev.wheelDelta/40,
                    newVal = $scrollbar.slider('value')+delta;
                $scrollbar.slider('value', newVal);
                scrollContent(ev, {value: newVal});
                return false;
            });
            $scrollbar = $('#scrollbar>div').slider({
                orientation: 'vertical',
                min: 0,
                max: 100,
                value: 100,
                slide: scrollContent
            });
            if(disable) {
                $scrollbar.slider('disable');
            }
            scrollContent(null, {value: 100});
        };
        makeScrollable();
    },
    
    win = $(window).bind('load', function() {
        var main = $('#main'),
            header = root.find('header'),
            nav = $('#main-nav'),
            footer = root.find('footer'),
            mainHeight = main.height(),
            minHeight = win.height()-(header.outerHeight()+nav.outerHeight()+footer.outerHeight()),
            maxHeight = minHeight+origHeight;
            main.height(mainHeight > minHeight ? mainHeight : minHeight);
        if( ! Modernizr.touch) {
            var body = root.find('body'),
                widgets = $('#widget-bg'),
                origHeight = 186,
                statictext = '<strong>News</strong>, <strong>Ops Map</strong> and <strong>Consultant Login</strong>',
                text = {
                    close: '<b>-</b> Click to Open '+statictext,
                    open: '<b>+</b> Click to Close '+statictext
                };
            var openClose = $('<div>', {
                html: '<a href="#">'+text[footer_state]+'</a>',
                id: 'footer-open-close'
            }).appendTo('footer').find('a').bind('click', function() {
                var zeroHeight = widgets.height() == 0;
                footer_state = FooterState.set(zeroHeight ? 'open' : 'close');
                $(this).find('a').html(text[footer_state]);
                widgets.animate({height: zeroHeight ? origHeight : 0}, 250);
                $('#main').animate({
                    'height': (mainHeight < maxHeight ? maxHeight : mainHeight > minHeight ? mainHeight : (zeroHeight ? '-' : '+')+'='+origHeight),
                    'padding-bottom': (zeroHeight ? '+' : '-')+'='+origHeight
                }, 250);
                return false;
            });
            if(FooterState.initial) {
                setTimeout(function() {
                    openClose.trigger('click');
                }, 3000);
            }
            window.log(footer_state);
        }
    });
})(window.jQuery);
