function truncateCookies() {
    $.cookies.set('42BelowAgeVerification', null);
    $.cookies.set('42BelowRedirect', null);
    $.cookies.set('42BelowCountry', null);
}

$(document).ready(function(){

    /*
    var check = new Date();
    check.setFullYear(check.getFullYear() - 18);
    $("#answer").html((new Date("12/4/1985").getTime() - check.getTime() < 0) ? "Under 18":"Over 18");
    */
    
    // Add subscribe small print to subscribe form
    $('#fieldset-subscribe').append('<p class="subscribeSmallPrint">By entering your details you agree to receive information from us and comply with website terms and conditions</p>');
    $('#fieldset-subscribe > legend').after('<p class="subscribeDescription">For updates and dates of regional finals, please subscribe here</p>');
    
    // Setup default cookie stuff
    $.cookies.setOptions({path: '/', domain: '.cocktailworldcup.com'});
    
    var mainURL = null;
    var exp = new RegExp('^http://local.');
    if (exp.test(new String(document.location))) {
        mainURL = "http://local.cocktailworldcup.com";
    } else {
        mainURL = "http://www.cocktailworldcup.com";
    }
    
    var deleteCookieTest = new RegExp('\\?change$');
    if (deleteCookieTest.test(location.toString())) {
        truncateCookies();
        window.location = mainURL;
    }
    
    if (! $.cookies.get('42BelowAgeVerification') || $.cookies.get('42BelowCountry') != "USA"){
        if (! $.cookies.get('42BelowAgeVerification')){
            truncateCookies();
        }
        
        $.cookies.set('isFromUSA', 'true');
        window.location = mainURL;
    } 
    
    $("#lda-form").submit(function(){
        var day = $("#day").val();
        var month = $("#month").val();
        var year = $("#year").val();
        var remember = $('#remember_me').attr('checked');
        var country = $("#country").val();
        var age = 18;

        if ( country == "-------------------" || country == "Mordor" || country == "Uranus" || country == ""   ) {
            alert("Sorry, valid country required");
            return false;
        }
 
        // check for countries that need 21 years of age
        if (country == "United States" || country ==  "Oman" || country ==  "Pakistan" || country ==  "Sri Lanka" || country ==  "United Arab Emirates" || country ==  "Kiribati" || country ==  "Japan") {
            age = 21;
        } else {
            age = 18;
        }
        
        // Validate Age
        var mydate = new Date();
        mydate.setFullYear(year, month-1, day);

        var currdate = new Date();
        currdate.setFullYear(currdate.getFullYear() - age);
        if ((currdate - mydate) < 0){
            alert("Sorry, only persons over the age of " + age + " may enter this site");
            return false;
        }
        
        // Set Pass / Location  cookies
        if( remember ) {
            // alert('Valid Age. Remember cookie set!');
            $.cookies.set('42BelowAgeVerification', 'remember', {hoursToLive: 24 });
        } else {
            // alert('Valid Age. Session cookie set!');
            $.cookies.set('42BelowAgeVerification', 'session');
        }
        
        $.cookies.set('42BelowCountry', country, {hoursToLive: 24 });
        
        $("#lda-form").slideUp();
        return true;
    });
    

        // initialize slider on homepage
        if( $("div.scrollable").length > 0 ) {
            
            $("div.scrollable").hover(
                      function () {
                        $(this).find("div.sliderNavContainer").slideDown('fast');
                        //alert( $(this).find("div.sliderNavContainer").html());
                      }, 
                      function () {
                          $(this).find("div.sliderNavContainer").slideUp('fast');
                      }
                    );

            var sliderDivs = '<div class="navi"></div><div class="sliderNavContainer"></div>';
                        
            $("div.scrollable").after( sliderDivs );
            
            $("div.scrollable").scrollable({ 
                size: 1, 
                items: '#thumbs',   
                hoverClass: 'hover', 
                
                // items are auto-scrolled in 2 secnod interval 
                interval: 4000, 
                 
                // when last item is encountered go back to first item 
                loop: true,  
                 
                // make animation a little slower than the default 
                speed: 1200, 
                 
                // when seek starts make items little transparent 
                onBeforeSeek: function() { 
                    this.getItems().fadeTo(600, 0.2);         
                }, 
                 
                // when seek ends resume items to full transparency 
                onSeek: function() { 
                    this.getItems().fadeTo(600, 1); 
                }  
            });
                        
            
            $("div.sliderNavContainer").append( $("div.navi") );
            $("div.scrollable").append( $("div.sliderNavContainer") );
            $("div.sliderNavContainer").hide();
        }
        
        // Add some validation & Form extras
        $('label.required').append(' <em>*</em>'); 
        
        //$("label.required").parent().find("input").addClass("required");
        $('label.required').parent().next('dd').find('input').addClass("required");
        $("input[type$='hidden']").removeClass("required");
        
        $('label.required').parent().next('dd').find('select').addClass("required");
        $('label.required').parent().next('dd').find('textarea').addClass("required");

        // If the entry form is on the page... 
        if ( $("#entry").length > 0 ) {
            $("#accept_tc-element input[type$='hidden']").attr('name','hidden_accept_tc');
                
                $("input.customDate").mask("9999-99-99");            
            
                // Add js form validation
                $("#entry").validate({
                           submitHandler: function(form) {
                               // do other stuff for a valid form
                                $("#accept_tc-element input[type$='hidden']").attr('name','accept_tc');
                            form.submit();
                           }
                });    
            
            // Move description 
            $("p.description").each(function(){
                // console.log($(this));
                $(this).parent("dd").prev("dt").append($(this)); 
            });
             
            $("#accept_tc-label label").html('I have read and agree to the contest rules and <a rel="#overlay" href="/Entry/Legal" >terms and conditions</a>.<em>*</em>');            
             $("#country").change(function () {
                 ApplyCorrectTC( $("#country option:selected").text() );
             });
             ApplyCorrectTC( $("#country option:selected").text() );
             
            
        }
        
        function ApplyCorrectTC(location){        
            
            if(location == "USA" ){
                $("#accept_tc-label a").attr('href','/Entry/Legal-US');
            }
            else if( location == "Ireland") {
                $("#accept_tc-label a").attr('href','/Entry/Legal-Ireland');
            }            
            else if( location == "United Kingdom") {
                $("#accept_tc-label a").attr('href','/Entry/Legal-UK');
            }
            else if( location == "Australia") {
                $("#accept_tc-label a").attr('href','/Entry/Legal-AU');
            }            
            else {
                $("#accept_tc-label a").attr('href','/Entry/Legal');
            }
            
            $("a[rel]").overlay(function() {
                // grab wrapper element inside content
                var wrap = this.getContent().find("div.wrap");
    
                // load only for the first time it is opened
                //if (wrap.is(":empty")) {
                wrap.load(this.getTrigger().attr("href"));
                
                //}
            });
        }
        
        // if the function argument is given to overlay, it is assumed to be the onBeforeLoad event listener
        $("a[rel]").overlay(function() {

            // grab wrapper element inside content
            var wrap = this.getContent().find("div.wrap");

            // load only for the first time it is opened
            //if (wrap.is(":empty")) {
                wrap.load(this.getTrigger().attr("href"));
            //}
        });
        
        /* adds focus class to form fields on focus */
        $('.input, .select, .textarea').each( function(){
            
            var dtLabel = $(this).parent('dd').prev('dt').find('label');
            var prevLabel = $(this).prev('label');
            
            
            $(this).focus( function(){
                $(this).addClass('focus');
                
                if( dtLabel.length > 0 )
                    dtLabel.addClass('focus');

                if( prevLabel.length > 0 )
                    prevLabel.addClass('focus');    
            });
            $(this).blur( function(){
                
                $(this).removeClass('focus');
                if( dtLabel.length > 0 )
                    dtLabel.removeClass('focus');

                if( prevLabel.length > 0 )
                    prevLabel.removeClass('focus');    

            });
        });
        
        // show / hide a tags
        $("#datesTable tr.tbl_content").hide();
        $("#datesTable a.showHide").click(function(){
            nextRow =  $(this).parent("td").parent("tr").next('tr');
            
            if( $(this).html() == "+ expand" && $(nextRow+":visible").length > 0  ){
                nextRow.show();
                $(this).html("- collapse");
                $(this).next("span").hide();
            } else {
                nextRow.hide();
                $(this).html("+ expand");
                $(this).next("span").show();
            }
        });
        
        // initialize gallery if need be
        if( $(".gallery").length > 0 ) {
            $('.gallery a').lightBox({
                imageLoading: '/asset/images/lightbox/lightbox-ico-loading.gif',
                imageBtnClose: '/asset/images/lightbox/lightbox-btn-close.gif',
                imageBtnPrev: '/asset/images/lightbox/lightbox-btn-prev.gif',
                imageBtnNext: '/asset/images/lightbox/lightbox-btn-next.gif',
                fixedNavigation:true
            }); // Select all links with lightbox class
        }
        
        // lightbox for news images
        if( $(".newsImage").length > 0 ) {
            $('.newsImage a').lightBox({
                imageLoading: '/asset/images/lightbox/lightbox-ico-loading.gif',
                imageBtnClose: '/asset/images/lightbox/lightbox-btn-close.gif',
                imageBtnPrev: '/asset/images/lightbox/lightbox-btn-prev.gif',
                imageBtnNext: '/asset/images/lightbox/lightbox-btn-next.gif',
                fixedNavigation:true
            }); // Select all links with lightbox class
        }

        // Add the quote tags for IE
        if (jQuery.browser.msie/*&&jQuery.browser.version<#*/) jQuery('q').each(function(){
            jQuery(this).parents('q').length>0?jQuery(this).prepend('&lsquo;').append('&rsquo;'):jQuery(this).prepend('&ldquo;').append('&rdquo;');
        });

        // Add safari class to html if browser safari
        if( $.browser.safari ) {
            $('html').addClass("safari");
        }    
        /*
        // Add fancy sub navigation
        $("div#navigation ul#nav li:not('#nav_node2','#nav_node3')").each(function(){
              if( $(this).children("ul").children("li").length > 0 ) {
                  
                  var currentID = $(this).attr('id');        
                  
                  // Copy ul to subnavbox
                  $("#subNavBox").append( $(this).children("ul").attr('id',"sub"+currentID) );
              
                  $("#sub"+currentID).hide();
                  
                  // Remove link from parent
                  var link = $(this).find("a");
                  link.attr('href', 'javascript:void(0);');
                  
                  
                  // Add slide down to parent
                  link.click(function(){
                      clickParent( $("#sub"+currentID), link );
                });
            }
            
         });
        
        
        $("div#navigation ul#nav li a").each(function(){
            if( $(this).attr('href') != 'javascript:void(0);'){
                // console.log($(this).attr('href'));
                $(this).click(function () { 
                    //alert( $("#subNavBox ul:visible").length );
                    if( $("#subNavBox ul:visible").length > 0 ){
                        $("#subNavBox ul:visible").slideUp();
                    }
                  });
            }
        });
        
        $('#subNavBox li.active').parent().show();
        
        function clickParent(subnav, parent){

            
            $("#nav li a").each(function(){
                $(this).removeClass('activeParent');
            });
            
            if( $("#subNavBox ul:visible").length > 0 ){
                parent.addClass('activeParent');
                if( $("#subNavBox ul:visible").attr('id') != subnav.attr('id')  ){
                        $("#subNavBox ul:visible").slideUp("slow", function () {
                            subnav.slideDown(300);
                         });
                }
            } else {
                parent.addClass('activeParent');
                subnav.slideDown(300);
            }
        }
    */
});

// Vertical Align of images.
function imageHeight(img) {
    var h = img.height;
    var oh = $(img).parent().height();
    //console.log( "h = " + h );
    //console.log( "oh = " + oh );    
    //var mt = (h + (oh - h)) / 2;
    var mt = ((oh - h) / 2);
    //console.log( "mt = " + mt );    
    if( h > oh ) {
        $(img).css("margin-top", + mt + "px");    
    }
}


/*
 * Pretty forms
 */
function prettyform(){
  /*
   * Hide forms
   */
  $( 'form.prettyform' ).hide().end();
  /*
   * Label & list formatting
   */
  $( 'form.prettyform' ).find( 'label' ).not( '.noprettyform' ).each( function( i ){
    var labelContent = this.innerHTML;
    var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
    var labelSpan = document.createElement( 'span' );
        labelSpan.style.display = 'block';
        labelSpan.style.width = labelWidth;
        labelSpan.innerHTML = labelContent;
    this.style.display = '-moz-inline-box';
    this.innerHTML = '';
    this.appendChild( labelSpan );
  } ).end();
  
  /*
   * Show forms
   */
  $( 'form.prettyform' ).show().end();
}