$(function () {
	
    if( $.browser.msie && $.browser.version < 7) window.location = 'http://www.campoviejowines.co.uk/colour-your-kitchen/';

    preloader.init();
    preloader.preload();

	var AppState = Backbone.Model.extend({
        defaults : {
            state: 'home',
            slider_state: 'off',
            active_pagte: 'test',
            age: $('body').data('agecheck') == '1' ? true : false
        }
    });
    var appState = new AppState();

    var Wine = Backbone.Model.extend({
        defaults: {
            state: 'wine_one',
            wine: ''
        },

        arr: {
           'reserva': { 
                slideid: 'reserva',
                name: 'Reserva',
                name_img: 'wine-five-title.png',
                tasting_notes: '<p>This ruby-red Reserva is a smooth, full, elegant, balanced wine with a long finish. It has a complex nose with ripe fruit aromas of cherries, black plums and juicy blackberries and the spicy nuances extracted from the oak during ageing with hints of clove, pepper, vanilla and coconut.</p>',
                composition: 'Made from Tempranillo, Garnacha and Mazuelo grapes.',
                location: 'Ebro Valley, Rioja.',
                buy_at: '<a href="http://goo.gl/hrPVr" rel="nofollow" target="_blank">Tesco</a>, <a href="http://goo.gl/N65IU" rel="nofollow" target="_blank">Sainsbury&rsquo;s</a>, <a href="http://goo.gl/DOFuX" rel="nofollow" target="_blank">Ocado</a>, Budgens, Londis, Makro, Nisa',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/reds/campo-viejo-reserva.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/reds/campo-viejo-reserva.php',
                image: '/O_o/img/wines/wine-reserva.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_Reserva.pdf'
            },
           'crianza': { 
                slideid: 'crianza',
                name: 'Crianza',
                name_img: 'wine-two-title.png',
                tasting_notes: '<p>This soft and smooth Crianza just asks to be enjoyed. It&rsquo;s cherry red with golden rim, lively, clear and bright. The first sensations on the nose are of the fruit: cherries, plums, blackberries with hints of mountain herbs, accompanied by the sweetness of the vanilla and coconut. On the palate the fruit is felt again.</p>',
                composition: 'Made from Tempranillo, Garnacha and Mazuelo grapes.',
                location: 'Ebro Valley, Rioja.',
                buy_at: '<a href="http://goo.gl/zOisc" rel="nofollow" target="_blank">Tesco</a>, <a href="http://goo.gl/ENPJH" rel="nofollow" target="_blank">Sainsbury&rsquo;s</a>, <a href="http://goo.gl/oBq5L" rel="nofollow" target="_blank">Waitrose</a>, <a href="http://goo.gl/rcCMr" rel="nofollow" target="_blank">Ocado</a>, <a href="http://goo.gl/AMmUl" target="_blank" rel="nofollow">Asda</a>, Budgens, Londis, Nisa',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/reds/campo-viejo-crianza.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/reds/campo-viejo-crianza.php',
                image: '/O_o/img/wines/wine-crianza.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_Crianza.pdf'
            },
           'gran-reserva': { 
                slideid: 'gran-reserva',
                name: 'Gran Reserva',
                name_img: 'wine-three-title.png',
                tasting_notes: '<p>Maroon, cherry red in colour with aromas of jam, wood and spicy tones Gran Reserva is a smooth wine with a lot of character.</p>',
                composition: 'Made from Tempranillo, Graciano and Mazuelo grapes.',
                location: 'Ebro Valley, Rioja.',
                buy_at: '<a href="http://goo.gl/EUrfe" rel="nofollow" target="_blank">Tesco Wine Club</a>, Sainsbury&rsquo;s, Makro and Nisa',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/premiums/campo-viejo-gran-reserva.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/premiums/campo-viejo-gran-reserva.php',
                image: '/O_o/img/wines/wine-gran-reserva.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_GranReserva.pdf'
            },
            'rose-garnache': { 
                slideid: 'rose-garnache',
                name: 'Rosé (Garnacha)',
                name_img: 'wine-one-title.png',
                tasting_notes: '<p>Raspberry-pink, bright and attractive, our rosé contains a blend of fruity aromas – strawberries, plums, blackberries and floral tones of roses and violets.</p><p>On the palate, it’s a fragrant, soft and smooth wine with just the right amount of crispness.</p>',
                composition: 'Made from Tempranillo 100%.',
                location: 'Ebro Valley, Rioja.',
                buy_at: '<a href="http://goo.gl/QY2pa" rel="nofollow" target="_blank">Tesco Wine Club</a>, <a href=" http://goo.gl/8un1h" rel="nofollow" target="_blank"> Sainsbury&rsquo;s</a>, <a href="http://goo.gl/UBtPV" rel="nofollow" target="_blank">Ocado</a>, <a href="http://goo.gl/c7jzu" rel="nofollow" target="_blank">Asda</a>, Budgens, Londis, Nisa',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/whites-and-roses/campo-viejo-rose.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/whites-and-roses/campo-viejo-rose.php',
                image: '/O_o/img/wines/wine-rose.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_TempranilloRose.pdf'
            },
            'viura': { 
                slideid: 'viura',
                name: 'Viura',
                name_img: 'wine-seven-title.png',
                tasting_notes: '<p>A clear and bright white wine, Viura has complex aromas of fruit and white blossom with spicy, toasted undertones.</p><p>On the palate is it silky, fresh and easy to drink.</p>',
                composition: 'Made from Viura 100%',
                location: 'Ebro Valley, Rioja.',
                buy_at: '<a href="http://goo.gl/wOH0y" rel="nofollow" target="_blank">Tesco Wine Club</a>, Budgens',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/whites-and-roses/campo-viejo-viura.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/whites-and-roses/campo-viejo-viura.php',
                image: '/O_o/img/wines/wine-viura.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_Viura.pdf'
            },
            'domnio': { 
                slideid: 'domnio',
                name: 'Dominio',
                name_img: 'wine-eight-title.png',
                tasting_notes: '<p>A dark, deep garnet colour, Dominio has intense scents with a diverse range of aromas. The most dominant scents are of fresh red fruits blended with toasted, spicy tones.</p><p>Powerful and concentrated on the palate.</p>',
                composition: 'Made from Tempranillo, Graciano and Mazuelo grapes.',
                location: 'Ebro Valley, Rioja.',
                buy_at: 'Dominio is a limited release wine.',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/premiums/campo-viejo-dominio.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/premiums/campo-viejo-dominio.php',
                image: '/O_o/img/wines/wine-dominio.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_Dominio.pdf'
            },
            'cava-brut-rose': { 
                slideid: 'cava-brut-rose',
                name: 'Cava Brut Rosé',
                name_img: 'wine-six-title.png',
                tasting_notes: '<p>Bright, sparkling pink, the Cava Brut Rosé is pleasant on the nose with tones of ripe, red berries.</p><p>On the palate it is balanced, fruity and full of flavour.</p>',
                composition: 'Made from Trepat 100%',
                location: 'Ebro Valley, Rioja.',
                buy_at: '<a href="http://goo.gl/dsH2m" rel="nofollow" target="_blank">Waitrose</a>, Ocado, Londis, Nisa',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/sparkling/campo-viejo-cava-brut-rose.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/sparkling/campo-viejo-cava-brut-rose.php',
                image: '/O_o/img/wines/wine-cava-brut-rose.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_CavaBrutRose.pdf'
            },   
            'cava-brut-reserva': { 
                slideid: 'cava-brut-reserva',
                name: 'Cava Brut Reserva',
                name_img: 'wine-four-title.png',
                tasting_notes: '<p>Greenish-yellow with golden glints, Cava Brut Reserva is a bright, sparkling wine with complex aromas of ripe, white fruits.</p><p>Fresh and elegant on the palate.</p>',
                composition: 'Made from Xarel-lo, Macabeo and Parellada.',
                location: '40 km south of Barcelona.',
                buy_at: '<a href="http://goo.gl/gh02d" rel="nofollow" target="_blank">Tesco Wine Club</a>, Budgens, Londis, Nisa',
                facebookurl: 'http://www.campoviejowines.co.uk/wines/sparkling/campo-viejo-cava-brut-reserva.php',
                twitterurl: 'http://www.campoviejowines.co.uk/wines/sparkling/campo-viejo-cava-brut-reserva.php',
                image: '/O_o/img/wines/wine-cava-brut-reserva.png',
                thumb: '',
                download_tasting_notes_url: 'http://www.campoviejowines.co.uk/assets/pdf/tasting-note/CV_CavaBrutReserva.pdf'
            }
		},

        get_prev: function(key){
            var k = key;
            var a = new Array();

            _.each( this.arr, function(value, key){
                a.push( value.slideid );
            });

            var index = _.indexOf(a, key);
            var prev = a[index-1];

            if( typeof prev == 'undefined' ) prev = a[a.length-1];

            return prev;
        },

        get_next: function(key){
            var k = key;

            var a = new Array();

            _.each( this.arr, function(value, key){
                a.push( value.slideid );
            });

            var index = _.indexOf(a, key);
            var next = a[index+1];

            if( typeof next == 'undefined' ) next = a[0];

            return next;
        }
    });
    


    var Slider = Backbone.View.extend({
        el: $('#slider'),
        elf: $('#slider_buffer'),
        onMove: false,
        template: _.template($('#slide').html()),

        initialize: function () { 
            this.model.bind('change:wine', this.render, this);
            this.model.bind('change:slider_state', this.render, this);

            var wine = new Wine();
            var that = this;
            var html = '';

            _.each( wine.arr, function(value, key){
                
                value.next_slide_id = wine.get_next( key );
                value.prev_slide_id = wine.get_prev( key );

                html += that.template( value );

            });

            $(this.el).find('.inner').html( html );
        },

        events: {
            'click a.controls.left' : 'show_prev',
            'click a.controls.right' : 'show_next',
            'click a.controls.close' : 'close_slider' 
        },

        show_next: function() {
            var window_width = $(window).width();
            var current_slide = $('.b-wine-slide.active');
            var next_id = $('.b-wine-slide.active a.controls.right').attr('rel');

            current_slide.animate({'left': '-='+window_width}, 750, 'easeInOutQuad', function(){ 
                current_slide.removeClass('active').css({'left':'0px','display':'none'});
            });
            
            document.title = 'Campo Viejo' + $('#'+next_id+' .description .wine-name').data('name');

            $('#'+next_id ).css({'left': window_width+'px'}).addClass('active').animate({'left': '0px'}, 750, 'easeInOutQuad');
        },

        show_prev: function() {
            var window_width = $(window).width();
            var current_slide = $('.b-wine-slide.active'); 
            var prev_id = $('.b-wine-slide.active a.controls.left').attr('rel');
            
            current_slide.animate({'left': window_width}, 750, 'easeInOutQuad', function(){ 
                current_slide.removeClass('active').css({'left':'0px','display':'none'});
            });

            document.title = 'Campo Viejo' + $('#'+prev_id+' .description .wine-name').data('name');

            $('#'+prev_id ).css({'left':  '-'+window_width+'px'}).addClass('active').animate({'left':'0px'}, 750, 'easeInOutQuad');
        },

        close_slider: function(){

            var wine = this.model.get('wine');

            this.model.set({last_slide: wine, slider_state:'off', state: 'wines', reindex_carousel: '1'});
            this.model.unset('wine');
        },

        show_slide: function(b){
            var window_width = $(window).width();
            var current_slide = $('.b-wine-slide.active');
            var next_id = b.attr('rel');

            var current_slide_id = current_slide.attr('id');

            var current_slide_id_index = b.parent('li').parent('ul').find('a[rel='+ current_slide_id +']').parent('li').index();

            var next_id_index = b.parent('li').index();

            if( this.onMove == false){
                this.onMove = true;
                if( this.onMove == true){
                    if( next_id_index > current_slide_id_index ){

                        current_slide.animate({'left': '-='+window_width}, 750, 'easeInOutQuad', function(){ 
                            current_slide.removeClass('active').css({'left':'0px','display':'none'});
                        });
                        
                        $('#'+next_id ).addClass('active').css({'left': window_width+'px'}).animate({'left': '0px'}, 750, 'easeInOutQuad');
                    }
                    if(next_id_index < current_slide_id_index) {

                        current_slide.animate({'left': window_width}, 750, 'easeInOutQuad', function(){ 
                            current_slide.removeClass('active').css({'left':'0px','display':'none'});
                        });
                        
                        $('#'+next_id ).css({'left':  '-'+window_width+'px'}).addClass('active').animate({'left':'0px'}, 750, 'easeInOutQuad');
                    } 
                }

                var that = this;
                setTimeout( function(){that.onMove = false}, 1000);
            }   
        },

        render: function(){
            var state = this.model.get("state");
            var wine = this.model.get("wine");
            var slider_state = this.model.get('slider_state');

            if( typeof wine == 'undefined' ){
                $(this.elf).hide();
                $(this.el).hide();
                this.model.set({slider_state:'off'});
            }
            else {

                if( slider_state == 'off' ) {

                    this.model.set({slider_state:'on'});
                    
                    var that = this;
                    
                    $('.wineshowcase a.bottle-link').bind('click',function(){
                       that.show_slide($(this));
                    });

                    $(this.elf).show();
                    $(this.el).show();
                    $('.b-wine-slide').css({'display':'none'}).removeClass('active');
                    $('#'+ wine).addClass('active').css({'top':'-750px'}).animate({'top':'0px'}, 650, 'easeOutQuad');

                    document.title = 'Campo Viejo' + $('#'+wine+' .description .wine-name').data('name');
                }
                
                var that = this;

                $(window).bind('resize',function(){
                    that.set_block_top();
                });

                this.set_block_top();
            }

        },

        set_block_top: function(){
            var window_height = $(window).height();
            var block_height = $(this.el).height();

            var top = (window_height-block_height)/2 - 80;

            if(top < 0) top = 0;

            $(this.el).css({'top': top+'px'});
        } 
    });
    var slider = new Slider({ model: appState });



    var Block = Backbone.View.extend({
    	el :                        $('#block'),
        wineslist :                 $('#wineslist'),
        footer_bottle :             $('#footer-bottle'),
        footer_bottle_homepage :    $('#footer-bottle-homepage'),
        horizon :                   $('#.b-background.horizon'),

    	templates : {
            'home'              : _.template($('#home').html()),
    		'wines' 		    : _.template($('#wines').html()),
    		'wines_slider' 	    : _.template($('#wines_slider').html()),
    		'contact' 	        : _.template($('#contact').html()),
            'competition'       : _.template($('#competition').html()),
            'agepage'           : _.template($('#agepage').html()),
            'downloads'         : _.template($('#downloads').html())
    	},

    	initialize: function () { 
            this.model.bind('change:state', this.render, this);
            this.model.bind('change:wine', this.render, this);
        },

    	render: function () {
            var state = this.model.get("state");
            var wine = this.model.get("wine");
            var last_slide = this.model.get('last_slide');
            var that = this;
            var reindex_carousel = this.model.get('reindex_carousel');
            
            if(state)
                $(this.el).removeClass().addClass('b-content-holder '+state).html(this.templates[state](this.model.toJSON()));
            
            this.set_block_margin_top();

            $(window).bind('resize',function(){
                that.set_block_margin_top();
            });


            if( state == 'wines' ){
                if( wine ) $(this.el).fadeOut(750);
                else $(this.el).fadeIn(750);    
            }
            else {
                $(this.el).fadeIn(750);  
            }
            
            
            if( state == 'home' )   {
                $(this.footer_bottle).hide(); // fade out
                $(this.footer_bottle_homepage).fadeIn();
                
                var ww = $(window).width();

                setTimeout(function(){
                    $('div.b-promo.left').css({'margin-left':'-'+ww+'px'}).animate({
                        'margin-left':'-25px'
                    },750,'easeOutQuad');
                    
                     $('div.b-promo.right').css({'margin-right':'-'+ww+'px'}).animate({
                        'margin-right':'-25px'
                    },750,'easeOutQuad'); 
                },1000)
            }
            else if ( state == 'agepage' ){
                $(this.footer_bottle_homepage).hide();
                $(this.footer_bottle).hide();
            }
            else  {
                $(this.footer_bottle_homepage).hide();
                $(this.footer_bottle).show();
            }                  
            
            
            $('a.nav').removeClass('active');
            $('a.nav[rel='+state+']').addClass('active');
            
            if( state == 'wines' ){
                

                var slider_state = this.model.get('slider_state');
                
                if( last_slide ){
                    
                    var arr = $('ul#wineslist li');
                    var indx = $('ul#wineslist li[rel='+last_slide+']').index();

                    if(slider_state == 'on') $('.b-content.wines').hide();
                    else $('.b-content.wines').show();

                    for(indx; indx>0;indx--){
                        var x = $('ul#wineslist li').eq(0).clone();
                        $('ul#wineslist li').eq(0).remove();
                        $('ul#wineslist').append( x );
                    }
                    
                    setTimeout( 
                        function(){
                            $('ul#wineslist').Cycler({'location_size':'b'});
                            $('#title-'+last_slide).addClass('active');
                        },
                        700
                    ); 
                    $('.b-cycler-title').removeClass('active');
                    

                }
                else {
                    $('ul#wineslist').Cycler({'location_size':'b'});    
                }
                

                $('a.bottle-link')
                    .mouseover(function(){
                       $('span.up').text($(this).attr('alt'));  
                    })
                    .mouseleave(function(){
                       $('span.up').empty();
                    });

                
            }

            var that = this;

            if( state == 'agepage' ){
                
                $('input, select').bind('keydown', function(e) {
                    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
                    if(key == 13) {
                        e.preventDefault();

                        that.submit_agepage_form();
                    }
                });
                
                $('#agepage_form input, #agepage_form select').autotab_magic();

                $('a#agepage_submit').bind('click',function(){
                    $('#agepage_form').ajaxSubmit({
                        target: '#agepage_result',
                        beforeSubmit: function(){},
                        success: function(data){ 
                            if( data.status == 'error' ){
                                $('#agecheck_msg').empty().html( data.message );    
                            } 
                            if( data.status == 'ok'){
                                $('.b-content.agepage').fadeOut(function(){
                                    $('.b-top').show();

                                    var back2url = that.model.get('back2url');

                                    that.model.set({ age: true, state: back2url });
                                });
                            }
                        },
                        dataType: 'json'
                    });
                    return false;
                });
            }
            
            if( state == 'competition' ){
                $('a#mixed_cases_submit').bind('click',function(){
                    $('#mixed_cases').ajaxSubmit({
                        target: '#mixed_cases_result',
                        beforeSubmit: function(){
                            if( $('input[name=name]').val() == '' || $('input[name=email]').val() == '' || (typeof $('input[name=terms]:checked').val() == 'undefined')) {
                                alert('Please enter all fields.'); 
                                return false;
                            }
                            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                            var email = $('input[name=email]').val();

                            if(reg.test(email) == false) {
                                alert('Please enter valid email address.'); 
                                return false;
                            }
                            $('a#mixed_cases_submit .loader').show();
                        },
                        success: function(data){ 
                            $('a#mixed_cases_submit .loader').hide();

                            if( data.status == 'error' ){
                                 
                            } 
                            if( data.status == 'ok'){
                                $('.competition-form-holder').fadeOut(function(){
                                    $('.competition-form-thank-you').fadeIn(); 
                                });
                            }
                        },
                        dataType: 'json'
                    });
                    return false;
                });  
            }

            return this;
        },


        submit_agepage_form: function(){
            var that = this;

            $('#agepage_form').ajaxSubmit({
                target: '#agepage_result',
                beforeSubmit: function(){},
                success: function(data){ 
                    if( data.status == 'error' ){
                        $('#agecheck_msg').empty().html( data.message );    
                    } 
                    if( data.status == 'ok'){
                        $('.b-content.agepage').fadeOut(function(){
                            $('.b-top').show();

                            var back2url = that.model.get('back2url');
                            var back2wine = that.model.get('back2wine');
                            
                            if( back2url == 'undefined' ) back2url = 'home';
                            
                            if( back2url == 'wines' && back2wine != ''){
                                that.model.set({age: true, state: back2url, wine: back2wine}); 
                            }
                            else {
                                that.model.set({age: true, state: back2url}); 
                            }
                               
                        });
                    }
                },
                dataType: 'json'
            });
        },

        set_block_margin_top: function(){
            var window_height = $(window).height();
            var block_height = $(this.el).height();

            var margin_top = (window_height-block_height)/2;


            var state = this.model.get("state");

            if( state == 'home' ) {
                margin_top += 15;
                if( margin_top < 30 ) margin_top = 30;
            }
            if( state == 'agepage' ){
                margin_top -= 20;
                if( margin_top < 20 ) margin_top = 20;
            }
            if( state == 'wines' ) {
                margin_top -= 55; 
                if( margin_top < 20 ) margin_top = 20;
            } 
            if( state == 'downloads' ){
                margin_top -= 35; 
                if( margin_top < 20 ) margin_top = 20;
            }
            if( state == 'competition' ){
                margin_top -= 35; 
                if( margin_top < 20 ) margin_top = 20;
            }

            $(this.el).css({'margin-top': margin_top+'px'});
        } 
    });
    var block = new Block({ model: appState });


	var Dispatcher = Backbone.Router.extend({

	    routes : {
	        ''						: 'home', 
	        '!/'					: 'home', 
            '!/home'                : 'home', 
	        '!/contact'				: 'contact',
            '!/wines'               : 'wines',
            '!/wines/:wine'         : 'wines',
            '!/competition'         : 'competition',
            '!/agepage'             : 'agepage',
            '!/downloads'           : 'downloads'
	    },

        home  : function(){ 
            document.title = 'Campo Viejo Wines, from Spain’s Rioja wine region';

            if( this.check_age() ){
                appState.set({slider_state:'off'});
                appState.unset('wine');
                appState.set({state:'home'}); 
            }
            else {
                appState.set({back2url: 'home'}); 
                this.set_to_agepage();
            } 
        },
	    wines : function( wine ){ 
            document.title = 'The Campo Viejo Wine Range';

            if( this.check_age() ){
                if(wine) {
                    appState.set({last_slide: wine, state:'wines', wine : wine});
                }
                else     {
                    appState.set({slider_state:'off', state:'wines'});
                    appState.unset('wine');
                }
            }
            else {
                appState.set({back2url: 'wines'});
                if(wine){
                    appState.set({back2wine: wine});
                }
                    
                this.set_to_agepage();
            } 
        },
	    contact : function(){ 
            document.title = 'The Campo Viejo Contact';

            if( this.check_age() ){
                appState.set({state:'contact'}); 
            }
            else {
                appState.set({back2url: 'contact'}); 
                this.set_to_agepage();
            }
        },
        competition : function(){ 
            document.title = 'The Campo Viejo Competitions';

            if( this.check_age() ){
                appState.set({slider_state:'off',state:'competition'});
                appState.unset('wine');
            }
            else {
                appState.set({back2url:'competition'});
                this.set_to_agepage();
            }
        },
        agepage : function(){
            appState.get('back2url');
            if( appState.get('back2url') == 'undefined' ){
                appState.set({back2url:'home'});    
            }
            this.set_to_agepage();
        },
        set_to_agepage : function(){
            appState.set({state:'agepage'});  
            $('.b-top').hide();
            $('.b-bottle').hide();
        },
        check_age : function(){
            return appState.get('age');
        },
        downloads : function(){
            document.title = 'The Campo Viejo Downloads';

            if( this.check_age() ){
                appState.set({slider_state:'off',state:'downloads'});
                appState.unset('wine');
            }
            else {
                appState.set({back2url:'competition'});
                this.set_to_agepage();
            }
        }
        
	});
	var dispatcher = new Dispatcher(); 
	

	appState.trigger("change:state"); 
    appState.trigger("change:age"); 

    appState.bind("change:state", function () { 
        var state = this.get("state");
        
        if (state == "home") 	dispatcher.navigate("!/", false);
        else 					dispatcher.navigate("!/" + state, false);
    });


	Backbone.history.start();
    	
});


function MM_openBrWindow(theURL,winName,features) { 
    window.open(theURL,winName,features);
    return false;
}
