$(document).ready(function(){
    
    checkVerifyCookie();
    
    // 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>');
    
    
    $('#ok').click(function() { 
        $.unblockUI(); 
        return false; 
    }); 
        // 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();
        }
        // js validate for UK entry form
        if( $("#entry-uk").length ){
              $("#entry-uk").validate({
                        submitHandler: function(form) {
                         form.submit();
                        }
             });    
        }
        
        
        // 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');

                // 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() );
             
            
        }
        
        if ( $("#entryform").length > 0 ) {
        	// Add Mask
        	if( $("#profile-dob").length ) {
        		$("#profile-dob").mask("99-99-9999");
			}
        	
            // Add js form validation
            $("#entryform").validate({
                rules: {
                'profile[primaryEmail]': {
                      required: true,
                      email: true,
                      remote: {
                        url: "/check-email-address",
                        type: "post"
                      }
                    }
                  }
            }); 
        }
        
        // js validate for register form
        if ( $("#registerform").length > 0 ) {
                $("#registerform").validate({
                    rules: {
                    'primaryEmail': {
                          required: true,
                          email: true,
                          remote: {
                            url: "/check-email-address",
                            type: "post"
                          }
                        }
                      }
                });  
        }
       
        
        
        // js validate for loginform
        if( $("#login-form").length ) {
            
            $("#login-form").validate({
                     submitHandler: function(form) {
                       // some other code
                       // maybe disabling submit button
                       // then:
                       $("#login-element").append('<div class="spinner" />');
                       $("#formresult").html("");
                        $.getJSON(    '/cwc/check-login',
                                    {
                                    email:$('#email').val(),
                                    password:$('#password').val()
                                    }, function(valid) {
                                        // if valid load either the profile page or the add reg page
                                        if (valid){ 
                                            if( $("#registerFormContainer").length ) {
                                                document.location = "/Member/";
                                            } else { document.location.reload(); } 
                                            
                                            $("#login-element div.spinner").remove();
                                        } 
                                        else { 
                                            //alert('fail'); 
                                            $("#formresult").html('<span class="error" style="padding-left:10px;">Invalid email or password</span>');
                                            $("#login-element div.spinner").remove();
                                        }
                        });
                       //$(form).submit();
                 }
                });
        }        
        
        
        function ApplyCorrectTC(location){        
            
            if(location == "United States" ){
                $("#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 if( location == "New Zealand") {
                $("#accept_tc-label a").attr('href','/Entry/Legal-NZ');
            }            
            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( $("a[rel='#overlay']").length ){
            $("a[rel='#overlay']").colorbox({iframe:true, innerWidth:620, innerHeight:490});
        }
       
        if( $("#cboxContent").length ) {
            $("#cboxContent").append('<div id="cblizard" />');
        }

        
        // 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( $(".overlaygallery").length > 0 ) {
            $(".overlaygallery a").colorbox({transition:"elastic", rel:'group'});
        }
        
        // lightbox for news images
        
        if( $("#newsView .newsImage").length > 0 ) {
            $('#newsView  .newsImage a').colorbox({transition:"elastic"});
        }
        

        // 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");
        }    
        
        $("#nav li a:last").css("background","none");
        /*
        // 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);
            }
        }
    */
        
        $("div.gallery div.video").append('<div class="playicon"></div>');
        
        /*
        if( $("blockquote").length ){
            $("blockquote").each( function(){ 
                $(this).append("<span class='open'>");
                $(this).find("em").insertAfter($(this)).wrap("<span class='quoteLabel'>");
            });
        }
        */
        

        if( $(".tweet").length ) {
            $(".tweet").tweet({
                username: "42belowcwc",
                join_text: "auto",
                avatar_size: 32,
                count: 5,
                auto_join_text_default: "we said,",
                auto_join_text_ed: "we",
                auto_join_text_ing: "we were",
                auto_join_text_reply: "we replied to",
                auto_join_text_url: "we were checking out",
                loading_text: "<div class='spinner'></div>"
            });
        }
      if ($.browser.msie && $.browser.version.substr(0,1)<7) {
          if( ! $.cookies.get('ie6OK') ) {
                $.blockUI.defaults.css.top = '60px'; 
                $.blockUI.defaults.css.left = '0px'; 
                $.blockUI.defaults.css.border = 'none';  
    
                $('#ie6Content').load('/ie6 #ie6-panel', function() {
                    
                     $('#continue').click(function() { 
                            $.unblockUI(); 
                            $.cookies.set('ie6OK', 'warned');
                            return false; 
                     }); 
                });
                $.blockUI({ message: $('#ie6'), css: { width: 'auto', height: 'auto' } }); 
                 

          }
        }

});

function showSlidingDiv(){
    $("#slidingDiv").animate({"height": "toggle"}, { duration: 750 });
}
// 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();
}

