var vgroup = {}; // vgroup custom namespace

vgroup.events = jQuery({}); // bind custom events to this

vgroup.var_cache = {
    last_hash : null,
    last_page_num : 1
}; // cache some commonly used elements 

vgroup.constants = {
    
    VG_DOMAIN           : 'http://www.vgroup.com/',
    AJAX_CONTENT_ELM    : '#contents',
    PAGE_LOAD_SPEED     : 400,
    LOADER_IMG          : '/uploads/images/ajax-loader.gif',
    
    COLOUR_BODY_BG      : '#FFF',
    COLOUR_NAV_HILITE   : '#0099CC',
    
    SLIDESHOW_TEXT_SHOW : 'project information',
    SLIDESHOW_TEXT_HIDE : 'hide project information'
}

vgroup.log = function( msg ){
    window.console && console.log && console.log(msg);
};

vgroup.test = {
    
    ie6 : jQuery.browser.msie && jQuery.browser.version < 7
}

vgroup.analytics = {
    
    trackUrl : function( url )
    {
       url = url || location.hash.replace('#','').replace('//','/');
       _gaq.push(['_trackPageview', url ]);
       vgroup.log('Tracking page view for URL: '+url);
    }
    
}

vgroup.init = function(){
    
    
    if ( ! vgroup.test.ie6 )
    {
        // if the URl is not a hash URL, redirect to the hash version
        if ( location.href.indexOf('#/') === -1 && location.href.replace(vgroup.constants.VG_DOMAIN,'') != '' )
        {
            location.href = vgroup.constants.VG_DOMAIN+'#/'+location.href.replace('#/','').replace(vgroup.constants.VG_DOMAIN,'').replace('//','/');
            return;
        }
    }
    
     var cnsts   = vgroup.constants,
         vc      = vgroup.var_cache,
         ev      = vgroup.events;

    // pre-onload
    
    swfobject.embedSWF("/uploads/flash/masthead.swf", "masthead", "155", "100", "9.0.0", null, {}, {wmode:"transparent"});

    if ( ! vgroup.test.ie6 )
    {
        jQuery('a').live('click', function(){
        
            var _this   = jQuery(this),
                href    = _this.attr('href'),
                domain;
        
            if ( _this.is(':internal') && href.indexOf('#') === -1 && href.indexOf('.pdf') === -1 )
            {
                // internal link does not have a hash in it - prevent default and ajax load content instead
                var newUrl = '#/'+href.replace('#/','').replace(cnsts.VG_DOMAIN,'');
                vgroup.log(cnsts.VG_DOMAIN+newUrl.replace('//','/'));
                location.href = cnsts.VG_DOMAIN+newUrl.replace('//','/');
                return false;
            }
            else if ( _this.is(':external') || href.indexOf('.pdf') !== -1 )
            {
                window.open(href);
                return false; 
                // return true;
            }
        
        });        
    }

    // on hash change event, grab the required content, put it into a container 'behind' the
    // current content, and then cross fade the old and new conent.
    // once fade is done do a bit of a cleanup ready for next page load...
    
    if ( ! vgroup.test.ie6 )
    {
        jQuery(window).bind('hashchange', function(){
        
            var pageless_url = location.hash.replace(/\/\d+\/$/, '').replace(/\/$/,''),
                page_num     = location.hash.match(/\/(\d+)\/$/);
      
            if ( vc.last_hash !== pageless_url )
            {
                var url        = location.href.replace('#/',''),
                    shim       = vc.shim,
                    ajaxTarget = vc.ajaxTarget;
        
                vgroup.loader.show();
            
                ev.trigger('start.pageload');
                ajaxTarget.css('opacity',1);
       
                $.get( url, {}, function( data ){
                    
                        vc.last_hash = pageless_url; // remove page number from URL
                    
                        if ( data != "" )
                        {
                            var contents = jQuery(data).find(cnsts.AJAX_CONTENT_ELM).contents(),
                                pos      = ajaxTarget.position(),
                                oldHeight,
                                newHeight;
    
                            shim.css({ top : pos.top+'px', left : pos.left+'px' }).empty().append(contents);
                            
                            if (jQuery.browser.msie) shim.fixClearType();
                            
                            ev.trigger('domLoaded.pageload'); // trigger an event that can be hooked into
                    
                            oldHeight = ajaxTarget.height();    
                            newHeight = shim.height();
        
                            if ( oldHeight < newHeight ) 
                            {
                                ajaxTarget.height( newHeight ); // targetent area is getting bigger, so adjust height first to give it room
                            }
                            
                            ajaxTarget.fadeOut(cnsts.PAGE_LOAD_SPEED, function(){
                                if (jQuery.browser.msie) $(this).fixClearType();
                                vgroup.events.trigger('oldContentHidden.pageload');
                            });
          
                           shim.fadeIn(cnsts.PAGE_LOAD_SPEED, function(){
                             
                                ajaxTarget.empty().append( shim.contents() ).show();
                                
                                if (jQuery.browser.msie) ajaxTarget.fixClearType();  
                                
                                shim.hide().empty();
                                                    
                                if ( oldHeight > newHeight ) 
                                {
                                    ajaxTarget.height( newHeight ); // content area is getting smaller
                                }

                                ev.trigger('complete.pageload');

                                ajaxTarget.css( 'height', 'auto'); // reset height back to auto
                           
                               vgroup.loader.hide();
 
                               return false;
                       
                           });
                           
                          
                           
                        }
                    }
                );
            }
            else if ( vc.last_page_num != page_num )
            {
                vc.last_page_num = page_num ? page_num[1] : 1;
                vgroup.events.trigger('paginate_change.pageload', vc.last_page_num );
            }
        });
    }
    
    vgroup.events.bind( 'oldContentHidden.pageload', function(){

        vgroup.setup.nav();
        
        // update the flash masthead, if necessary
        var hash      = location.hash.replace('#/',''),
            section = false;
        
        jQuery.each( ['marketing','branding','design','interactive'], function( i, val ){
            if ( hash && hash.indexOf(val) === 0 ) section = val;
        });
        
        if ( jQuery('html').hasClass('hasFlash') ) document.getElementById('masthead').jsPageChange( section ? section : 'main' );

    });

    vgroup.events.bind( 'domLoaded.pageload', function(){
        
        var projects = jQuery('#projects');
        
        if ( projects.length) projects.css({opacity:0});
    });
    
    vgroup.events.bind( 'complete.pageload', function(){

        vgroup.setup.flash();
        
        if ( jQuery('.extended').length || jQuery('.map').length ) jQuery('#quick_contact').hide();
        else jQuery('#quick_contact').show();
        
        if ( jQuery("#case_study").length ) vgroup.setup.case_study();
        else if ( jQuery("#landing_slideshow").length ) vgroup.setup.section_landing();  
        else if ( jQuery('ol#projects').length ) vgroup.setup.projects_list();
        else if ( jQuery('.quote_wrapper').length ) vgroup.setup.clients();
        else if ( jQuery('#services').length ) vgroup.setup.services();
        else if ( jQuery('.map').length ) vgroup.setup.maps();
        else if ( jQuery('#overview').length ) vgroup.setup.overview();
        
        if ( jQuery('#newscast').length ) vgroup.setup.newscast();
        
        vgroup.analytics.trackUrl(); // track the page URl via google analytics
    });
    
    // inital onload function, should only be called once... 
    jQuery(function(){
       
        var shim       = vc.shim = jQuery('<div class="shim" ></div>'),
            ajaxTarget = vc.ajaxTarget = jQuery(vgroup.constants.AJAX_CONTENT_ELM),
            body       = vc.body = jQuery('body');
        
        if ( swfobject.hasFlashPlayerVersion("9") ) jQuery('html').addClass('hasFlash');
        
        jQuery('#main_signup input[type=text]').inlineLabels();
        
        vgroup.loader.setup();        
         
        if ( vgroup.test.ie6 )
        {
            vgroup.events.trigger( 'complete.pageload' );
        } 
        else
        {
            jQuery('#main_nav li.current').removeClass('current');
            
            ajaxTarget.css('opacity',0).after(shim.hide());
            jQuery(window).trigger('hashchange');            
        }
    });
    
};

/*
 * Setup functions for the different kinds of page interactions.
 * Most of these are called when the 'complete.pageload' event fires.
 *
 */
vgroup.setup = {};

vgroup.setup.flash = function()
{
    var hp_flash = jQuery('#intro_flash'),
        slideshow_flash = jQuery('.slideshow .flashcontent'),
        quick_contact   = jQuery('#quick_contact');
    
    if ( hp_flash.length ) swfobject.embedSWF("/uploads/flash/video_950x500.swf", "intro_flash", "945", "497", "9.0.0", null, {}, {'bgcolor':'#333333'});
    
    if ( slideshow_flash.length )
    {    
        slideshow_flash.each(function(){
            var _this = jQuery(this);
            swfobject.embedSWF( _this.attr('href').replace('#/',''), _this.attr('id'),
                                "720", "500", "9.0.0",
                                null, {}, {wmode:"transparent", 'bgcolor':'#333333'});
        });
    }
    
    // if ( quick_contact.length )
    // {
    //     swfobject.embedSWF("/uploads/flash/sidenav_contacts.swf", "quick_contact", "100", "65", "9.0.0", null, {}, {'bgcolor':'#FFFFFF'});
    // }
};

vgroup.setup.newscast = function()
{    
    var nav   = jQuery('#newscast .nav'),
        links = nav.find('a'),
        ols   = nav.find('ol');
    
    links.die('click').bind('click', function(){
       
        var _this  = jQuery(this),
              temp = jQuery('<div ></div>', {className:'temp'}),
              bc   = jQuery('#breadcrumbs span'),
              lis  = nav.find('li');
              
        vgroup.loader.show();
              
        jQuery('body').append(temp);
      
        temp.load(_this.attr('href')+' #newscast .inner', function(){
              
            jQuery('#newscast .inner').html( temp.find('.inner').html() );
            temp.remove();
            lis.removeClass('current');
            _this.closest('li').addClass('current');
            bc.text(_this[0].rel)
            vgroup.loader.hide();
        });
  
        return false;
    });
    
    
    nav.find('h3').each(function(){
         
         var _this = jQuery(this),
             ol    = _this.next('ol');
             
         ol.hide();
         _this.css('cursor','pointer');

        _this.bind('click', function(){
            
            if ( ol.is(':visible') )
            {
                ols.slideUp();
            }
            else
            {
                ols.slideUp();
                ol.slideDown();
            }

        });
      });
      
      nav.find('h3:eq(0)').next('ol').slideDown();
};

vgroup.setup.services = function()
{
    var services = jQuery('#services');
    
    services.find('> div:first').css('margin-top', '10px');
    
    jQuery('div h3', services).bind('click',function(){
        
        var _this = jQuery(this),
            div   = _this.parent('div');
        
        if ( jQuery('p:hidden, ul:hidden', div).length )
        {
            jQuery('#services div p, #services div ul').hide();
            jQuery('div h3', services).removeClass('open');
            jQuery('p, ul', div).show();
            _this.addClass('open');
        }
        else
        {
            jQuery('#services div p, #services div ul').hide();
            _this.removeClass('open');
        }
        
    }).css('cursor','pointer');
};

vgroup.setup.clients = function()
{
    jQuery('body').click(function(){
        jQuery('.quote_wrapper').hide();
    });
    
    jQuery('.quotelink').click(function(){
        
        var _this = jQuery(this);
        
        jQuery('div.quote_wrapper:not(#'+_this.attr('href')+')').hide();
        _this.parent('p').next('div.quote_wrapper').toggle();
        
        return false;
    });
};

vgroup.setup.overview = function()
{
    var slideshow    = jQuery("#overview")
        wrapper      = jQuery('.slideshow'),
        prev         = jQuery('a[rel=prev]'),
        next         = jQuery('a[rel=next]'),
        currentSlide = 0,
        total        = 0;

    wrapper.append('<a href="#" rel="prev" class="prev overlay_button"><</a><a href="#" rel="next" class="overlay_button next">></a>');
    
    function gooo( col )
    {
        if ( col == 1 || col == 'prev' ) slideshow.trigger( 'prev.evtslideshow');
        if ( (col == 2  || col == 'next') && currentSlide !== total ) slideshow.trigger( 'next.evtslideshow');
        else if ( (col == 2  || col == 'next') && currentSlide === total ) slideshow.trigger('jump',1); 
        return false;
    }

    jQuery('a[rel=next], a[rel=prev]').click(function(){
        // slideshow.trigger( jQuery(this).attr('rel')+'.evtslideshow');
        return gooo(jQuery(this).attr('rel'));
    });
    
    slideshow.bind("initialized.evtslideshow", function( e, startNum, totalNum ){
        total = totalNum;
        jQuery('#overview_slides .count').html('<span class="start">'+(startNum)+'</span> / <span class="total">'+total+'</span>')
    });
    
    // after each transition, update slide number and add/remove disabled links
    slideshow.bind('finished.evtslideshow', function( e, slideNum ){
        jQuery('.start').html(slideNum);
        
        currentSlide = slideNum;
        
        prev.removeClass('disabled');
            next.removeClass('disabled');
            
          if ( slideNum == 1 ) prev.addClass('disabled');
            
          if ( slideNum == total )
          {
              next.text('start');
              next.one('click', function(){
                 slideshow.trigger('jump',1); 
              });
          }
          else
          {
              next.text('next');
          }
        
    });
    
    // click on left or right of the image to trigger prev/next
    wrapper.bind('clicked.hotspot', function( e, row, col ){
        return gooo(col);
    });
    
    wrapper.bind('changed.hotspot', function( e, row, col ){
          if ( col == 1  && currentSlide !== 1 ) wrapper.removeClass('goright').addClass('goleft');
          else if ( col == 2 ) wrapper.removeClass('goleft').addClass('goright');
          else wrapper.removeClass('goright goleft');
          return false;
    });
        
    wrapper.hotspot({ rows:1, cols:2 });
  
    slideshow.evtslideshow({transition: 'fade', autoPlay : true, atEnd: 'stop', speed : 800 });
};

vgroup.setup.section_landing = function()
{
    var slide = jQuery("#landing_slideshow"),
        wrapper = jQuery(".slideshow");
    
    wrapper.append('<a href="#" rel="prev" class="prev overlay_button"><</a><a href="#" rel="next" class="overlay_button next">></a>');
    
    jQuery('a[rel=next], a[rel=prev]').click(function(){
          slide.trigger( jQuery(this).attr('rel')+'.evtslideshow');
          return false;
      });
    
    wrapper.hotspot({ rows:1, cols:2 });
    wrapper.bind('clicked.hotspot', function( e, row, col ){
        if ( col == 1 ) wrapper.trigger('prev');
        else if ( col == 2 ) wrapper.trigger('next');
        return false;
    });
    
    wrapper.bind('changed.hotspot', function( e, row, col ){
          if ( col == 1 ) wrapper.removeClass('goright').addClass('goleft');
          else if ( col == 2 ) wrapper.removeClass('goleft').addClass('goright');
          else wrapper.removeClass('goright goleft');
          return false;
    });
       
    slide.evtslideshow({transition: 'fade', autoPlay : true, atEnd: 'loop', speed: 1500 });
};

vgroup.setup.projects_list = function()
{
    var list = jQuery('#projects'),
        startnum = 1;
        
    var url_num = location.hash.match(/\/([0-9][0-9]?)\//);
    
    if ( url_num ) startnum = url_num[1];
            
    list.bind("initialized.evtpaginate", function( e, startNum, totalNum  ){
        jQuery('.count').html( '<span class="start">'+(startNum)+'</span> / <span class="total">'+totalNum+'</span>' );
    });

    list.bind('finished.evtpaginate', function( e, slideNum, isFirst, isLast ){
        
        jQuery('.start').text(slideNum);
        
        if ( isFirst ) location.hash = location.hash.replace( /\/[0-9]([0-9]?)\//, '/' );
        else location.hash = location.hash.replace( /\/[0-9]([0-9]?)\//, '/' )+(slideNum)+'/';
        
        jQuery('.pager a').removeClass('disabled');
        if ( isFirst ) $('a[rel=prev]').addClass('disabled');
        else if ( isLast ) $('a[rel=next]').addClass('disabled');
        
        if ( ! list.is(':visible')) jQuery('ol#projects').animate({'opacity':1});
    });
    
    jQuery('a[rel=next], a[rel=prev]').click(function(){
        list.trigger( jQuery(this).attr('rel')+'.evtpaginate' );
        return false;
    });
    
    vgroup.events.bind('paginate_change.pageload', function(e, num){
        list.triggerHandler('show', num);
    });

    list.evtpaginate({perPage : 6, startPage : startnum });
    
    list.css({opacity:0.99999});
    
    if (jQuery.browser.msie) list.fixClearType();
};

vgroup.setup.case_study = function()
{
    var slideshow = jQuery('#case_study .slides'),
        info      = jQuery('#case_study .info'),
        infolink  = jQuery('.show_info a'),
        total     = 0,
        currentSlide = 0,
        prev      = jQuery('a[rel=prev]'),
        next      = jQuery('a[rel=next]');

    showSlideshowInfo();
    
    jQuery('.info .close').click(toggleSlideShowInfo);
    infolink.click(toggleSlideShowInfo);
    
    jQuery('a[rel=next], a[rel=prev]').click(function(){
        hideSlidehowInfo();
        slideshow.trigger( jQuery(this).attr('rel')+'.evtslideshow');
        return false;
    });
    
    slideshow.bind("initialized.evtslideshow", function( e, startNum, totalNum ){
        total = totalNum;
        jQuery('#case_study .count').html('<span class="start">'+(startNum)+'</span> / <span class="total">'+total+'</span>')
        showSlideshowInfo();
        jQuery('.gotolist').attr('href', function(){
            var last_num = vgroup.var_cache.last_page_num;
            if ( last_num ) return this.href+last_num+'/';
            else return this.href;
        });
    });
    
    // after each transition, update slide number and add/remove disabled links
    slideshow.bind('finished.evtslideshow', function( e, slideNum ){
        
        jQuery('.start').html(slideNum);
        
        currentSlide = slideNum;
        
        prev.removeClass('disabled');
        next.removeClass('disabled');
        
        if ( slideNum == 1 ) prev.addClass('disabled');
        
        if ( slideNum == total )
        {
            next.text('start');
            next.one('click', function(){
               slideshow.trigger('jump',1); 
            });
        }
        else
        {
            next.text('next');
        }
    });
    
    // click on left or right of the image to trigger prev/next
    slideshow.bind('clicked.hotspot', function( e, row, col ){
        hideSlidehowInfo();
        if ( col == 1 ) slideshow.trigger( 'prev.evtslideshow');
        if ( col == 2 && currentSlide !== total ) slideshow.trigger( 'next.evtslideshow');
        else if ( col == 2 && currentSlide === total ) slideshow.trigger('jump',1);
        return false;
    });
    
    slideshow.evtslideshow({transition: 'horizontalSlide', atEnd : 'stop', autoPlay : false, speed : 400});
    slideshow.hotspot({cols:2,rows:1});    
    
    function toggleSlideShowInfo()
    {
        if ( info.is(':visible') ) hideSlidehowInfo();
        else showSlideshowInfo();
        return false;
    }
    
    function showSlideshowInfo()
    {
        info.css('display','block').stop().fadeTo(800, 1);
        infolink.text('hide project information');
        infolink.addClass('hide');
    }
    
    function hideSlidehowInfo()
    {
        info.stop().fadeTo(800, 0, function(){
            jQuery(this).css('display','none');
        });
        infolink.text('project information');
        infolink.removeClass('hide');
    }
};

vgroup.setup.nav = function()
{
    var current     = jQuery('#main_nav a.current'),
        currentHref = current.eq(0).attr('href'),
        cnsts       = vgroup.constants,
        href        = null;
        
    if ( location.href != currentHref )
    {    
        var cnsts      = vgroup.constants,
            currenturl = cnsts.VG_DOMAIN.replace(/\/$/,''),
            segments   = location.href.replace('#/','').replace(cnsts.VG_DOMAIN,'').replace(/\/$/,'').split('/');
        
        if ( segments[0] == '' )
        {
            href = currenturl;
        }
        else
        {
           for ( var segment, i = -1; segment = segments[++i]; ) {
            
               var nexturl = currenturl + '/' + segment;

               if ( ! jQuery('#main_nav a[href='+nexturl+'/]').length )
               {
                   // the next url doesn't exist, use the current one
                   href = currenturl;
                   break;
               }
               else
               {
                   currenturl = nexturl;
                   href = currenturl;
               }
            }
            
        }
        
        href = href + '/';

        if ( currentHref != jQuery('#main_nav a[href='+href+']').attr('href') )
        {
           current.animate({backgroundColor:cnsts.COLOUR_BODY_BG}, 200, function(){
               jQuery('#main_nav a').css('backgroundColor','');
               current.removeClass('current')
           });

           jQuery('#main_nav a[href='+href+']').addClass('current').animate({backgroundColor:cnsts.COLOUR_NAV_HILITE}, 200);
        }
        else
        {
            
        }
        // else
        //    {
        //         current.removeClass('current');
        //         current.closest('li').removeClass('current');
        //    }
    }
    else
    {
        current.animate({backgroundColor:cnsts.COLOUR_BODY_BG}, 200);
    } 
};

vgroup.setup.maps = function(){
    if ( GBrowserIsCompatible() )
    {
        // Open Street Map setup
        var copyOSM = new GCopyrightCollection("<a href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>");
        copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));

        var tilesMapnik = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
        var mapMapnik = new GMapType([tilesMapnik],G_NORMAL_MAP.getProjection(),"Map");
    
        var vgroupMarker = new GIcon(G_DEFAULT_ICON);
        vgroupMarker.image = "/uploads/images/google_map_marker.png";
        markerOptions = { icon:vgroupMarker };

        // Brighton map
        var brighton = new GMap2(document.getElementById('brighton_map'),{ mapTypes: [mapMapnik, G_SATELLITE_MAP] });
        var point = new GLatLng(50.831847773300744, -0.1392817497253418);
        brighton.addControl(new GSmallMapControl());
        brighton.setCenter(point, 14);
        brighton.addOverlay(new GMarker(point, markerOptions));
    
        // London map
        var london = new GMap2(document.getElementById('london_map'),{ mapTypes: [mapMapnik, G_SATELLITE_MAP] });
        var point = new GLatLng(51.51377373466425, -0.13528794050216675);
        london.addControl(new GSmallMapControl());
        london.setCenter(point, 13);
        london.addOverlay(new GMarker(point, markerOptions));
    }
}

vgroup.loader = {
    
    setup : function()
    {
        var elm = this.elm = jQuery('<div id="loader"><img src="'+vgroup.constants.LOADER_IMG+'" width="16" height="16" /></div>');
    
        jQuery('body').append( elm.hide() );
        
        jQuery(document).mousemove( function(e){
            elm.css( 'top', ( e.pageY - 26 ) + "px" );
            elm.css( 'left', ( e.pageX + 14 ) + "px" );
        });
    },
    
    show : function()
    {
        this.elm.fadeIn('fast');
    },
    
    hide : function()
    {
        this.elm.fadeOut('fast');
    }
    
};

function flashPageChange( sectionName )
{
    if ( sectionName == 'main' ) sectionName = '/';
    else sectionName = '/'+sectionName+'/';
    location.hash = sectionName;
}

vgroup.init(); // kick things off...
