$(document).ready(function(){
 var outer='#gallery #outer',inner='#inner',gallery_block='#gallery div',arrow=gallery_block+'.arrow',img='#gallery figure',dot='#gallery nav li',width_img=$(outer).width()+10,num_start=1,img_count=$(img).length,time_fade=0;
 $(outer).css({'overflow':'hidden'});

 $(arrow).bind('click',move);
 $(dot).bind('click',move_dot);

 function dot_toggle(x,y,z){
  $(x).toggleClass(y,true).toggleClass(z,false)
 };

 function dot_now(num_start){
  fade_arrow(num_start);
  dot_toggle(dot,'other','now');
  dot_toggle(dot+'[role="'+num_start+'"]','now','other');
 };

 function fade_arrow(num_start){
  function fade_first(){
   $(outer).css({'margin-left':3});
   $(gallery_block+'.prev').fadeIn(time_fade)
  }
  if(num_start==img_count){
   $(gallery_block+'.next').fadeOut(time_fade);
   fade_first();
  }
  else{
   $(gallery_block+'.next').fadeIn(time_fade);
   if(num_start==1)$(gallery_block+'.prev').fadeOut(time_fade,function(){$(outer).css({'margin-left':33})})
   else fade_first();
  }
 }

 function move(){
  if($(this).attr('title')=='влево'){sign=1;num_start--}else{sign=-1;num_start++}
  width_move=sign*width_img;
  dot_now(num_start);
  $(inner).animate({'marginLeft':'+='+width_move})
 }

 function move_dot(){
  var role=$(this).attr('role'),coef=(role-1)*width_img;
  num_start=role;
  dot_now(num_start);
  $(inner).animate({'marginLeft':-coef});
 }
});
