$(document).ready(function() {
  
  $.each($('.pg_slide'), function() {
    var idSlider = this.id;
    if(!idSlider) {
      var idSlider = 'pg_slide_' + uniqId();
      $(this).attr('id',idSlider);
    }
    initSlider(idSlider);
  });
    
  function initSlider(idSlider){
    checkButtons(true, idSlider, widthChildren, ShowEach, numberChildren);    
    
    var widthElement = $('#'+idSlider+' .wrap').width();  
    var scrollAdd = 0;
    var scrollToMove = widthElement + scrollAdd;
    var numberChildren = $('#'+idSlider+' .wrap').children().size();
    var widthChildren = $('#'+idSlider+' .wrap').children().width();
    var ShowEach = Math.round(widthElement / widthChildren);

    $('#'+idSlider+' .arrow#left').click(function(){
      var scrollLeft = $('#'+idSlider+' .wrap').scrollTo( '-='+scrollToMove, {duration: 600, margin:false, easing: 'easeInOutQuint', axis:'x',onAfter:function(){      
        $('#'+idSlider+' .arrow#left').blur();
        checkButtons(false, idSlider, widthChildren, ShowEach, numberChildren);
      }});    
    });
    $('#'+idSlider+' .arrow#right').click(function(){    
    	$('#'+idSlider+' .wrap').scrollTo( '+='+scrollToMove, {duration: 600, margin:false, easing: 'easeInOutQuint', axis:'x',onAfter:function(){
        $('#'+idSlider+' .arrow#right').blur();
        checkButtons(false, idSlider, widthChildren, ShowEach, numberChildren);      
      }});    
    });  
  }
  
  function checkButtons(reset, idSlider, widthChildren, ShowEach, numberChildren){
    var position = $('#'+idSlider+' .wrap').scrollLeft();
    if(position == 0 || reset == true) $('#'+idSlider+' .arrow#left').fadeTo("slow", 0.33);
    else $('#'+idSlider+' .arrow#left').fadeTo("slow", 1);
    
    var showed = Math.round(position / widthChildren) + ShowEach;
    if(showed >= numberChildren) $('#'+idSlider+' .arrow#right').fadeTo("slow", 0.33);
    else $('#'+idSlider+' .arrow#right').fadeTo("slow", 1);    
  }

  function uniqId(){
	  var newDate = new Date;
	  return newDate.getTime();
	}
});
