var Gallery = function($gallery) {
  this.timer = 500;
  this.numImages = 0;
  this.images = new Array();
  this.thumbs = new Array();
  this.currIndexPosition = 0;
  this.marginLeft = 0;
  this.obj = $gallery;
  this.slider = $gallery.find('ul.gallery_slide');
  this.increment = this.obj.width();
  this.thumbSliderObj = false;
  this.startup = function() {
    var that = this;
    this.obj.find('ul.gallery_slide li').css({
      'width': this.increment,
      'float': 'left'
    });
    this.numImages = this.obj.find('ul.gallery_slide li').length;
    if (this.increment === null) {
      this.increment = this.obj.width();
    }
    this.slider.width(this.increment * this.numImages);
    this.slider.find('li').each(function (i, el) {
      that.images[i] = $(el);
      that.images[i].css('padding-left', '0px');
      if (that.isVideo(i) !== false) {
        that.adjustVideo($(el).find('iframe'));
      } else {
        that.images[i].find('img').load(function(){ that.showImage(that.images[i].find('img')); });
      }
    });
    if (this.numImages === 1) {
      this.obj.find('div.thumb_slider, div.goleft, div.goright, .pagenum').remove();
    } else {
      this.obj.find('div.thumb_slider').find('li').each(function (i, el) {
        that.thumbs[i] = $(el);
        that.thumbs[i].click(function () {
          that.goToImage(i);
        });
      });
      // make binds
      this.obj.find('div.goleft').click(function () {
        that.goLeft();
      });
      this.obj.find('div.goright').click(function () {
        that.goRight();
      });
      if (this.numImages > 1) {
        this.startupThumbSlider();
      }
      this.thumbs[0].addClass("active");
    }
    // $('.gallery_slide, .gallery_container, .image_gallery, img, .image_gallery ul, .image_gallery ul li, .goleft, .goright').disableTextSelect();
  };
  this.showImage = function($obj) {
    var that = this;
    $obj.fadeIn(250, function(){
      that.adjustImageMargins($obj);
    });
  };
  this.isVideo = function(imageIndex) {
    if (this.images[imageIndex].find('iframe').length === 0) {
      return false;      
    }  else {
      return true;
    }
  };
  this.adjustVideo = function ($iframe) {
    // $iframe.parents('li').css({position: 'relative'});
    $iframe.css({width: this.increment, height: this.increment*0.75});
  };
  this.goLeft = function () {
    this.thumbs[this.currIndexPosition].removeClass("active");
    if (this.currIndexPosition%3 == 0 && this.currIndexPosition > 0) {
      this.moveThumbsLeft();
    }
    if (this.currIndexPosition <= 0) {
      this.marginLeft = -parseInt(this.numImages - 1, 10) * this.increment;
      this.currIndexPosition = parseInt(this.numImages - 1, 10);
      this.moveThumbsRight(this.thumbSliderObj.find('ul').width() - (this.increment + (this.thumbsSliderUlLiSize * 3)));
    } else {
      this.marginLeft += this.increment;
      this.currIndexPosition -= 1;
    }
    this.slider.stop(true).animate({'margin-left': this.marginLeft }, this.timer, 'easeOutQuart');
    this.thumbs[this.currIndexPosition].addClass("active");
    this.adjustImageMargins(this.images[this.currIndexPosition].find('img'));

    this.updateInfo();
    return true;
  };
  this.goRight = function () {
    this.thumbs[this.currIndexPosition].removeClass("active");
    var hasMoved = false;
    if (this.currIndexPosition === this.numImages - 1) {
        this.marginLeft = 0;
        this.currIndexPosition = 0;
        this.moveThumbsLeft( 24 );
        hasMoved = true;
    } else {  
        this.marginLeft -= this.increment;
        this.currIndexPosition += 1;
    }
    this.thumbs[this.currIndexPosition].addClass("active");
    this.slider.stop(true).animate({'margin-left': this.marginLeft}, this.timer, 'easeOutQuart');
    this.adjustImageMargins(this.images[this.currIndexPosition].find('img'));
    // this.preloadImage(parseInt(this.currIndexPosition + 1, 10));

    if( this.currIndexPosition%3 == 0 && ! hasMoved )
        this.moveThumbsRight();

    this.updateInfo();
    return true;
  };
  this.startupThumbSlider = function () {
    var that = this;
    this.thumbSliderObj = this.obj.find('div.thumb_slider');
    this.thumbSliderUl = this.thumbSliderObj.find('ul');
    this.thumbsSliderUlInitialLeft = 24;
    this.thumbsSliderUlLiSize = 108;
        this.thumbsViewable = 5;
    this.thumbsNum = this.thumbSliderUl.children().length;
    this.thumbsMinLeft = -(((this.thumbsNum-this.thumbsViewable)*this.thumbsSliderUlLiSize)-this.thumbsSliderUlInitialLeft);
    this.thumbsWidth = this.thumbsSliderUlLiSize*this.thumbsNum;
    this.thumbSliderUl.css({left: this.thumbsSliderUlInitialLeft+'px'});
    this.thumbsCurrLeft = this.thumbsSliderUlInitialLeft;
    this.thumbSliderObj.find(".back").click(function() {
      that.moveThumbsLeft();
    });
    this.thumbSliderObj.find(".forward").click(function() {
      that.moveThumbsRight();
    });
    return true;
  };
  this.moveThumbsLeft = function( diff ) {
    var that = this;
    var start_left = parseInt(that.thumbSliderObj.find('ul').css('left'), 10);
    if (this.thumbsCurrLeft < this.thumbsSliderUlInitialLeft) {
      this.thumbsCurrLeft += this.thumbsSliderUlLiSize*3; // *3 moves 3 thumbs for each click
      if( diff !== undefined )
          this.thumbsCurrLeft = diff;
      that.thumbSliderObj.find('ul').stop(false, true).animate({'left': this.thumbsCurrLeft+"px"}, that.timer/2, 'easeOutQuart');
    }  else {
      return false;      
    }
    return true;
  };
  this.moveThumbsRight = function( diff ) {
    var that = this;
    var start_left = parseInt(that.thumbSliderObj.find('ul').css('left'), 10);
    if (this.thumbsCurrLeft > this.thumbsMinLeft) {
      this.thumbsCurrLeft -= this.thumbsSliderUlLiSize*3; // *3 moves 3 thumbs for each click
      if( diff !== undefined )
          this.thumbsCurrLeft = -diff;
      that.thumbSliderObj.find('ul').stop(false, true).animate({'left': this.thumbsCurrLeft+"px"}, that.timer/2, 'easeOutQuart');
    } else {
      return false;      
    }
    return true;
  };
  this.updateInfo = function() {
    if (this.images[this.currIndexPosition].find('img').attr('alt') && this.images[this.currIndexPosition].find('img').attr('alt') !== '') {
      this.obj.find('.caption').html(this.images[this.currIndexPosition].find('img').attr('alt'));
    } else {
      this.obj.find('.caption').html("&nbsp;");
    }
    if (this.isVideo(this.currIndexPosition) === true) {
      this.obj.find('.infobar').fadeOut();
    } else {
      this.obj.find('.infobar').fadeIn();
    }
    this.obj.find('.pagenum').text(parseInt(this.currIndexPosition + 1, 10) + "/" + this.numImages);
    return true;
  };
  this.preloadImage = function(imageIndex) {
    var that = this;
    if (this.images[imageIndex] === undefined) {
      return false;
    }
    var $hidden = this.images[imageIndex].find('input[type="hidden"]');
    var image_src = $hidden.attr('value');
    if (!$hidden || image_src === undefined) {
      return false;
    }
    var image_caption = $hidden.attr('alt');
    var image = new Image();
    var $image = false;
    $(image).load(function(){
      var $image = $(this);
      $image.attr('alt', image_caption);
      that.images[imageIndex].append($image);
      $image.fadeIn(250);
      if ($image.height() > that.images[imageIndex-1].find('img').height()) {
        that.adjustImageMargins(that.images[imageIndex-1].find('img'));
      }
      $hidden.remove();
    }).error(function(){ $(this).remove(); }).attr('src', image_src);  
    return true;
  };
  this.adjustImageMargins = function(image, horizontal, vertical) {
    var that = this;
    // horizontal
    if (horizontal !== false) {
      if (image.width() < this.obj.width()) {
        var new_left_margin = parseInt(parseInt(this.obj.width()-image.width(),10)/2,10);
        if (new_left_margin < parseInt(that.increment/2, 10)) {
          image.css('margin-left', new_left_margin+'px');
        }
      }
    }
    // vertical
    if (vertical !== false) {
      var ul_height = image.parent().parent().height();
      if (image.height() < ul_height) {
        var new_top_margin = parseInt(parseInt(ul_height-image.height(),10)/2,10);
        image.css('margin-top', new_top_margin+'px');
      }
    }
  };
  this.goToImage = function(imageIndex) {
    if (imageIndex !== this.currIndexPosition) {
      var slots_to_move = imageIndex - this.currIndexPosition;
      var move_count = 0;
      if (slots_to_move > 0) {
        for (move_count = slots_to_move; move_count > 0; move_count--) {
          this.goRight();
        }
      } else {
        for (move_count = slots_to_move; move_count < 0; move_count++) {
          this.goLeft();
        }
      }
    }
    this.updateInfo();
  };

  // make some calls...
  this.startup();
};
var galleries = new Array();

$(document).ready(function () {
  // BROWSER DETECTION
  // Figure out what browser is being used
  var userOSAgent = navigator.userAgent.toLowerCase();
  jQuery.platform = {
          mac: /mac/.test(userOSAgent),
          osx: /mac os x/.test(userOSAgent),
          win: /win/.test(userOSAgent),
          linux: /linux/.test(userOSAgent)
  };
  // change default foint
  if( jQuery.platform.mac == true )
  {
    $('body').not("iframe body").css( 'fontFamily' , "Courier, Arial, sans-serif");
    $('input[type="text"]').css( 'fontFamily' , "Courier, Arial, sans-serif");
    $('textarea').css( 'fontFamily' , "Courier, Arial, sans-serif");
  }
  else if( jQuery.platform.win == true )
  {
    // display old-browsers (IE6 & 7) alert
    jQuery.each(jQuery.browser, function(i) {
      jQuery.each(jQuery.browser, function(i, val) {
        if(val == true)
          $.browser.versionName = i;
      });
      if($.browser.msie){
        if( $.browser.version == '6.0' ||  $.browser.version == '7.0')
          $( ".browser_alert" ).slideDown( 500 );
      }
    });  
  }
  
  // general swap B&W image to COLOR on mouseover
  $( 'a.image_swap' ).hover( function(){
    $( this ).find( 'img.original' ).css( 'display' , 'none' );
    $( this ).find( 'img.hidden_image' ).css( 'display' , 'block' );
  }, function(){
    $( this ).find( 'img.original' ).css( 'display' , 'block' );
    $( this ).find( 'img.hidden_image' ).css( 'display' , 'none' );
  });
  $( '.ministerio a.image_swap' ).hover( function(){
    $( this ).parent().find( 'p.caption:not(.hover)' ).css( 'display' , 'none' );
    $( this ).parent().find( 'p.caption.hover' ).css( 'display' , 'block' );
  }, function(){
    $( this ).parent().find( 'p.caption:not(.hover)' ).css( 'display' , 'block' );
    $( this ).parent().find( 'p.caption.hover' ).css( 'display' , 'none' );
  });
  
  // clean up search fields on focus
  (function($){
    $.fn.clearDefault = function(){
      return this.each(function(){
        var default_value = $(this).attr('value');
        var original_value = $( this ).attr('original_value');
        if( original_value == default_value )
        {
          $(this).focus(function(){
            if ($(this).attr('value') == default_value) $(this).attr('value', '');
          });
          $(this).blur(function(){
            if ($(this).attr('value') == "") $(this).attr('value', default_value);
          });
        }
      });
    };
  })(jQuery);
  $('.search input[type="text"]').clearDefault();
  // general dropdown
  $( '.options_container , .options_trigger' ).click( function(){
    $( this ).parents( '.dropdown' ).find( '.options' ).slideToggle(150);
  });
  $( '.dropdown .options li' ).click( function(){
    $res_id = $( this ).attr( 'id' );
    if ($res_id == undefined) return false;
    $res_id = $res_id.substr( $res_id.lastIndexOf( '_' ) + 1 );
    $( this ).parents( '.dropdown' ).find( '.hidden_value' ).attr('value',$res_id);
    $( this ).parents( 'form' ).submit();
  });
  // header dropdown
  $( '.header_options_container , .header_options_trigger' ).click( function(){
    $( this ).parents( '.header_dropdown' ).find( '.header_options' ).slideToggle(150);
  });
  $( '.header_dropdown .header_options li' ).click( function(){
    $scope_label = $( this ).parents('.header_dropdown').find( '.scope_label' );
    $scope_id = $( this ).parents( '.header_dropdown' ).find( '.hidden_value' );
    // get NEW scope label & id
    $new_id = $( this ).attr( 'id' );
    $new_label = $( this ).html();
    // get OLD scope label & id
    $old_label = $scope_label.html();
    $old_id = $scope_id.attr('value');
    // set new scope label
    $scope_label.html( $new_label );
    $scope_id.attr('value',$new_id);
    // replace old
    $( this ).attr( 'id' , $old_id );
    $( this ).html( $old_label );
  });
  // form submit button
  $( '.form_submit' ).click( function(){
    $( this ).parents( 'form' ).submit();
  });
  
  // GENERAL HOVER COLOR
  $(".cover-entry").mouseover(function(){
    $(this).find('h1.rule-two').addClass('ativo');
  });
  $(".cover-entry").mouseout(function(){
    $(this).find('h1.rule-two').removeClass('ativo');
  });
  
  // JOURNAL HOVER 
  $( '.line-block .entry' ).hover( function(){
    $( this ).find( 'img.original' ).css( {'display': 'none'} );
    $( this ).find( 'img.hidden_image' ).css( {'display': 'block'} );
  }, function(){
    $( this ).find( 'img.original' ).css( 'display' , 'block' );
    $( this ).find( 'img.hidden_image' ).css( 'display' , 'none' );
  });
  // $( '.line-block .entry , .line-pagination .entry' ).hover( function(){
  $( '.entry' ).hover( function(){
    $( this ).find( 'h1, h2, h2 > a, h3:not(.index,.author,.date), p.lead' ).addClass( 'ativo' ).css( {'text-decoration': 'underline'} );
    $( this ).find('h3').addClass( 'ativo' );
  }, function(){
    $( this ).find( 'h1, h2, h2 > a, h3:not(.index,.author,.date), p.lead' ).removeClass( 'ativo' ).css( {'text-decoration': 'none'} );
    $( this ).find('h3').removeClass( 'ativo' );
  });
  
  // FORMAT USER NAME DISPLAY ON PROFILE
  $('.contribution-form .firstname, .contribution-form .lastname').keyup(function() {
    var first = $('.contribution-form .firstname').attr('value');
    var last = $('.contribution-form .lastname').attr('value');
    $('#showname').html( first + ' ' + last );
    $('#showname_cit').html( last.toUpperCase() + ', ' + first );
  });
  
  // LOAD GALLERIES
  $("div.image_gallery").each(function(i, el){
    galleries[i] = new Gallery($(el));
  });
  
  // ADJUST IMAGE CAPTIONS SIZE
  $("div.text").find("img:last").load(function () {
    $("div.text").find("div.image").each(function (i, el) {
      var $img_container = $(el);
      var $img = $img_container.find("img");
      if ($img.width() > 200) {
        $img_container.find(".caption").width($img.width()-4);
      }
    });
  });
});
