/**
 * Conexus Javascript File
 * By Alex Berriman <alexb@fishvision.com>
 */

var mcFields = new Array();

(function($) {
  $(document).ready(function() {    
    // Backgrounds on the hub login fields
    $("#hub .left div input").change(function() {
      if ( $(this).val().length > 0 ) {
        $(this).addClass('noBg');
      }
      else if ( $(this).hasClass('noBg') ) {
        $(this).removeClass('noBg');
      }
    });
    
    // Make the hub box scroll down and up
    $("#loginBox a").click(function() {
      return true;
      var height = ( parseInt( $("#hub").css("height") ) == 0 ) ? "80" : "0";
      $("#hub").animate({
        "height": height + "px"
      }, 400);
      
      return false;
    });
    
    // The posts widget at the base of pages
    $("#footerPosts .categories li a").click(function() {
      if ( $(this).attr('rel').length > 0 ) {
        // What vars are we using?
        var catId = $(this).attr('rel');
        var url = '/?ajax_cat_new=' + parseInt( catId ) + '&page=1&od=0';
        
        // Active link
        $("#footerPosts .categories li").removeClass('active');
        $("#footerPosts .categories li:first").addClass('active');
        $(this).parent().addClass('active');
        
        // If we've already fetched content for that category, let's just display it
        if ( $("#posts" + catId).length > 0 ) {
          $(".posts").hide();
          $("#posts" + catId).show();
        }
        // Else, send the ajax request
        else {
          $("#footerPosts .categories .load").css("visibility", "visible");
          $.ajax({
            url: url,
            success: function(data) {
              $("#footerPosts .posts").hide();
              if ( $("#posts" + catId).length > 0 ) {}
              else {
                $("#footerPosts .categories .load").css("visibility", "hidden");
                var app = "<div class='posts' id='posts" + catId + "'><div class='jax'></div>";
                if ( sums[catId] > 9 ) {
                  app += "<div class='clear'></div><div class='loadMore'><a href='#back' rel='1' rev='" + catId + "' class='base'><em>Load More</em></a><div class='snake'></div><div class='clear'></div></div>";
                }
                $("#footerPosts").append(app);
                $("#posts" + catId).find('.jax').prepend( data );    
              }
            }
          });
        }
        
        return false;
      }
      return true;
    });
    
    // Load more posts for a given category
    $("#footerPosts .loadMore a").live('click', function() {
      // Some vars
      var cats = $(this).attr("rev");
      var page = parseInt( $(this).attr("rel") ); page++;
      var href = $(this).attr('href');
      var perPage = $(this).parent().attr('rel') ? $(this).parent().attr('rel') : 9;
      var url = '/?ajax_cat_new=' + cats + '&page=' + page + "&perPage=" + perPage + "&offset=" + 11;
      
      if ( href == "#back" ) {
        url += "&back=false";
      }
      var postsBox = $(this).parent().parent();
      var link = $(this);
      $(".snake").css("visibility","visible");
      
      // Send the request
      $.ajax({
        url: url,
        success: function(data) {
          data = "" + data;
          
          matches = data.match(/\=\"featured/g);
          if( matches ) {
            // Don't have any more pages
            if( matches.length < 9 ) {
              $(link).parent().remove();
            }
            $(postsBox).find('.jax').append('<div class="jaxPage page' + page + '">' + data + '</div>');
            $(postsBox).find('.page' + page).slideDown();

            // Update the page
            $(link).attr("rel", page);
          }
          else {
            $(link).parent().remove();
          }
          $(".snake").css("visibility","hidden");
        },
        error: function() {
          $(".snake").css("visibility","hidden");
        }
      });
      
      return false;
    });
    
    // JS navigation on the posts widget
    $("#widgetNav ul li a").click(function() {
      var box = $(this).parent().attr('rel');
     
      $("#boxes div").hide();
      $("#" + box).show();
      $("#widgetNav ul li.active").removeClass('active');
      $(this).parent().addClass('active');
      
      return false;
    });
    
    // Css fix
    var maxHeight = 0;
    $(".story").each(function() {
      var height = parseInt( $(this).css('height') );
      if ( height > maxHeight ) {
        maxHeight = height;
      }
    });
    $(".story").css("height", maxHeight + "px");
    
    // Magazine page navigation
    $("body.page-id-11624 .entrycontent .nav ul li a").click(function() {
      var pageId = $(this).attr('rel');
      
      $("body.page-id-11624 .entrycontent .nav ul li.active").removeClass('active');
      $(this).parent().parent().addClass('active');
      
      $("#.leftBlock div.active").removeClass('active');
      $("#subpage-" + pageId).addClass('active');
      return false;
    });
    
    // Comment refresh
    if ( $("#rssFeed").length > 0 ) {
      setTimeout( 'commentRefreshFunc()', commentRefresh * 1000 );
    }
    
    // Show the contributor information
    $(".contributor").hover(function() {
      $(this).find('.popup').show();
    }, function() {
      $(this).find('.popup').hide();
    });
    
    $(".jcarousel-item a").live( 'click', function() {
      return false;
    });
    
    // Read more categories
    $(".categories .loadMore a").click(function() {
       $(".categories .hidden:first").slideDown( 700, function() {
        $(this).removeClass('hidden');
       });
      return false;
    });
    
    //this is the floating content
    var $floatingbox = $('#leftContainer');

    if($('body').length > 0 && $floatingbox.length > 0){
      var bodyY = parseInt( $floatingbox.css('margin-top').replace('px','') ) + 380;
      var originalX = $floatingbox.css('margin-left');
  
      $(window).scroll(function () { 
        var scrollY = $(window).scrollTop();
        var isfixed = $floatingbox.find('#leftSidebar').css('position') == 'fixed';
   
       if($floatingbox.length > 0){
         if ( scrollY + 5 > bodyY && !isfixed ) {
           $floatingbox.stop().find('#leftSidebar').css({
             position: 'fixed',
             top: 5
           });
         } else if ( scrollY + 5 < bodyY && isfixed ) {
           $floatingbox.find('#leftSidebar').css({
             position: 'static'
           });
         }		
       }
      });
    }

    // Read more of a post
    $(".readMore").click(function() {
      $(".hidden").slideDown(1000, function() {
        $(".readMore").parent().slideUp(700, function() {
          $(this).remove();
        });
      });
      return false;
    })
    
    // Left/right fix for tooltips
    $("#footerPosts .categories .main").each(function() {
      var divWidth = $(this).css('width').replace('px','');
      var parentWidth = $(this).parent().css('width').replace('px','');
      
      if ( parentWidth < 140 ) {
        margin = ( 140 - parentWidth ) / 2;
        $(this).css('left', -margin);
      }
    });

    // html5 jquery fallback
    if(jQuery.support.placeholder == false){
      jQuery(':input[placeholder]').each(function(){
        var $this = $(this);
        if(!$this.val()){
          $this.val($this.attr('placeholder'));
          $this.addClass('input-placeholder');
        }
      }).live('focus', function(e){
        var $this = $(this);
        if($this.hasClass('input-placeholder')){
          $this.val('');
          $this.removeClass('input-placeholder')
        }
      }).live('blur', function(e){
        var $this = $(this);
        if(!$this.val()){
          $this.addClass('input-placeholder');
          $this.val($this.attr('placeholder'));
        }
      });
    }
    
    // Mailchimp submit function
    $(".mailchimp form").submit(function() {
      var errors = 0;
      
      $(".requiredMC").each(function() {
        var obj = $(this).get(0).tagName.toLowerCase();
        switch( obj ) {
          case 'input':
            var val = $(this).val();
            break;
          case 'select':
            var val = $(this).find('option:selected').val();
            break;
        }
        
        if ( val == '' || ( $(this).hasClass('email') && validateEmail( val ) == false ) ) {
          $(this).addClass('error');
          errors++;
        }
        else {
          $(this).removeClass('error');
        }
      });
      
      if ( errors > 0 ) {
        $(".mailchimp .submit div").show();
        return false;
      }
      else {
        $(".mc_load").css("visibility","visible");
      }

      $(".mailchimp .submit div").hide();      
      return true;
    });
    
    // Mailchimp other dropdown
    $(".mailchimp form select").change(function() {
      if( $(this).find("option:selected").attr('dtext') == 'true' ) {
        // Store previous html in an array
        var found = false;
        for ( var x = 0; x < mcFields.length; x++ ) {
          if ( mcFields[x][0] == $(this).attr('id') ) {
            found = true;
            break;
          }
        }
        if ( found == false ) {
          mcFields.push([$(this).attr('id'), $(this).parent().html(), $(this).find('option:first').text()]);
          x = 0;
        }
        
        // Wipe it
        var replacement = "<input type='text' name='" + $(this).attr('id').toUpperCase() + "' placeholder='" + mcFields[x][2] + "' id='" + $(this).attr('id') + "' class='requiredMC' /><span class='required'>*</span>";
        $(this).parent().html(replacement);
      }
      
      else if ( $(this).find('option:selected').attr('rel') ) {
        var className = $(this).find('option:selected').attr('rel');
        $("." + className).show();
      }
      
      else {
        $(this).find('option').each(function() {
          if ( $(this).attr('rel') ) {
            $("." + $(this).attr('rel')).hide();
          }
        })
      }
    });
    
    $(".mailchimp .checkBoxes input[type=checkbox]").click(function() {
      if ( $(this).val().toLowerCase() == 'other' ) {
        if ( $(this).attr('checked') == true ) {
          $(this).parent().find('input.other').show();
        }
        else {
          $(this).parent().find('input.other').val('').hide();
        }
      }
    });
    
    // Left navigation tooltips
    $("#leftSidebarTop ul.main li").each(function() {
      var title = $(this).find('a').attr("title");
      if ( title != "" ) {
        $(this).append('<div class="tooltip">' + title + '<div class="bottom"></div></div>');
        $(this).find('a').attr('title','');
      }
    });
    $("#leftSidebarTop ul.main li").hover(function() {
      $(this).find(".tooltip").toggle();
    });
    
  });
  
}(jQuery));

// Email validation
function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(email);
}

// Comment refresh function
function commentRefreshFunc() {
  
  jQuery.ajax({
    url: '/?comments_ajax',
    success: function(data) {
      var commentRegExp = new RegExp("\#comment\-[0-9]+");
      var comments = "_";
      jQuery("#rssFeed li").each(function() {
        comments += parseInt( ("" + jQuery(this).html().match(commentRegExp)).substr(9) ) + "_";
      });
      
      jQuery(data).find('comment').each(function() {
        if( comments.indexOf( "_" + jQuery(this).attr('id') + "_" ) == -1 ) {
          jQuery("#rssFeed li:last").remove();
          jQuery("#rssFeed ul").prepend( jQuery(this).text() );
          jQuery("#rssFeed ul li:first").hide().slideDown();

          comments +=  jQuery(this).attr('id') + "_";
        }
      });
    }
  });
  
  setTimeout( 'commentRefreshFunc()', commentRefresh * 1000 )
}

jQuery.support.placeholder = (function(){
    var i = document.createElement('input');
    return 'placeholder' in i;
})();

