$(document).ready(function() {
    
    var checkdate = function(d, m, y) {
        return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
    };
    
	function mktime() {
	    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
	    if (argc > 0){
	        d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
	    }
	    var dateManip = {
	        0: function(tt){ return d.setHours(tt); },
	        1: function(tt){ return d.setMinutes(tt); },
	        2: function(tt){ var set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
	        3: function(tt){ var set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
	        4: function(tt){ return d.setDate(tt+mb); },
	        5: function(tt){ return d.setYear(tt+ma); }
	    };
	    for( i = 0; i < argc; i++ ){
	        no = parseInt(argv[i]*1);
	        if (isNaN(no)) {
	            return false;
	        } else {
	            // arg is number, let's manipulate date object
	            if(!dateManip[i](no)){
	                // failed
	                return false;
	            }
	        }
	    }
	    return Math.floor(d.getTime()/1000);
	}
    
    var readyToGo = false;
    
    // Reset day, month & year on country change
    $("#c").change( function() {
        $("#d, #m, #yr").val('no');
        readyToGo = false;
    });
    
    $("select, input").change(function(){
        if (
            $("#d").val() != "no" &&
            $("#m").val() != "no" &&
            $("#yr").val() != "no"
        ) {
            $('div#overlay-gw-bot #gw-col-3 input').attr("src", "/img/gw-enter-on.gif");
            readyToGo = true;
        } else {
            $('div#overlay-gw-bot #gw-col-3 input').attr("src", "/img/gw-enter-off.gif");
            readyToGo = false;
        }
    }); 

    // show the navigation
    $('#page #navigation').css({'display' : 'block', 'top' : '29px'});
    $('#page #logo').css('display', 'none');
    $('#page #intro').css('display', 'none');
    
    GUINNESS.track("url", "/gateway2/displayed");
    
    // add rollover & click events to enter button
    $('div#overlay-gw-bot #gw-col-3 input')
    .mouseover(function() {
        if (readyToGo) {
            $(this).attr('src', '/img/gw-enter-over.gif');
        }
    })
    .mouseout(function() {
        if (readyToGo) {
            $(this).attr('src', '/img/gw-enter-on.gif');
        }
    });
    
    $('div#overlay-container form').submit(function (e) {
    
        var error = [];
        if (!$('#c').val()) {
            error[0] = 'country';
        }
        
        if (
            !$('#d').val() || isNaN($('#d').val()) ||
            !$('#m').val() || isNaN($('#m').val()) ||
            !$('#yr').val() || isNaN($('#yr').val()) ||
            !checkdate ($('#d').val(), $('#m').val(), $('#yr').val()) ||
            $('#yr').val() > new Date().getFullYear()
            
        ) {
            error[1] = 'date';
        }
        
        if (!error.length > 0) {
            date = mktime(0, 0, 0, $('#m').val(), $('#d').val(), $('#yr').val());
            age = Math.floor((Math.floor(new Date().getTime()/1000) - date) / (365 * 86400));
            
            var localeAge = $('#c option:selected').attr('data-age');
            var localeURL = $('#c option:selected').val();
            
            if (age >= localeAge && localeAge > 0) { // old enough
                
                // Google Analytics call to notify successful entry to site
                GUINNESS.track('url', '/gateway2/passed');
                $("#page").removeClass("gateway");
                
                $('div#overlay, div#overlay-container, #page #navigation').fadeOut('slow');
                $('#page #logo, #page #intro').fadeIn('slow');
                
                // Check if user wants to be remember and then Set gateway passed cookie
                if ($('#remember').attr('checked') === true) {
                    var current_date = new Date();
                    current_date.setTime(current_date.getTime()+(30*24*60*60*1000));
                    document.cookie = "gw=" + localeURL + "; expires=" + current_date.toGMTString() + "; path=/;";
                } else {
                    document.cookie = "gw=" + localeURL + "; path=/;";
                }
                
                if (document.location.pathname == "/") {
                    
                    // redirect to locale homepage after delay for tracking to complete
                    setTimeout(function () {
                        window.location = "/";// + localeURL;
                    }, 500);
                    
                } else {
                    
                    // do delayed tracking calls
                    $.each(GUINNESS.trackQueue, function () {
                        GUINNESS.track(this.type, this.name, this.data, this.data2, this.data3);
                    });
                    
                }
                
                return false;
            }
        }
    });
});