(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener )
            for ( var i=types.length; i; )
                this.addEventListener( types[--i], handler, false );
        else
            this.onmousewheel = handler;
    },
    
    teardown: function() {
        if ( this.removeEventListener )
            for ( var i=types.length; i; )
                this.removeEventListener( types[--i], handler, false );
        else
            this.onmousewheel = null;
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
    
    event = $.event.fix(event || window.event);
    event.type = "mousewheel";
    
    if ( event.wheelDelta ) delta = event.wheelDelta/120;
    if ( event.detail     ) delta = -event.detail/3;
    
    args.unshift(event, delta);

    return $.event.handle.apply(this, args);
}

})(jQuery);

function scroll(delta, scrollable) { 
    if (scrollable.scrollHeight <= scrollable.clientHeight) return false;  
    max_scroll = (scrollable.scrollHeight - scrollable.clientHeight);
    move = delta*20;
    scroll_to = scrollable.scrollTop - move;
    if (scroll_to < 0) top_to = 0;
    if (scroll_to >= max_scroll) scroll_to = max_scroll;
    scrollable.scrollTop = scroll_to;
    return false;
}

$(function() {
  
  $('input[placeholder]').placeholder();
  
  $('.gallery-small a.thumb').each(function() {
    $.get(this.href); 
  }).click(function() {
    href = this.href;
    alt = $('img', this).attr('alt');
    srel = $(this).attr('rel');
    $('#img-big img').fadeOut(200, function() { this.src = href; this.alt = alt; $(this).fadeIn(200); });
    $('#img-big a').attr('href', srel);
    return false;
  });

  $('#nav li').hover(function() {
    $(this).css('z-index', 5).find('ul').slideDown(200);
    $(this).find('a:first').addClass('hover');
  },
  function() {
    $(this).css('z-index', 1).find('ul').slideUp(100);
    $(this).find('a:first').removeClass('hover');
  });
  
  $('.sites .site').hover(function() {
    $(this).find('.info').fadeIn(200);
  },
  function() {
    $(this).find('.info').fadeOut(200);
  });
  
  $('a.contact').overlay({effect: 'apple', expose: { color: '#000', loadSpeed: 200, opacity: 0.7 }});
  
  $('#contact-form form').submit(function() {
    $(this).find('.req input, .req textarea').each(function(i, el) { 
      if ($(el).val() == '') {
        $(el).addClass('error');
      } else {
        $(el).removeClass('error');
      }
    });
    if ($('.error', this)[0]) {
      
    } else {
//       $(this).replaceWith('<h1>Ваш запрос отправлен!</h1>');
      $form = $(this);
       
      $.post("/ajax/post.php", //смени url на правильный
              $form.serialize(), 
              function(ret) {
                if (ret == '1') { // если все ок, возвращай 1
                  $form.replaceWith('<h1>Ваш запрос отправлен!</h1>');
                } else if (ret == '2') { // если капча неправильно введена, возвращай 2
                  $form.find('#captcha').addClass('error');
                 // $form.replaceWith('<h1>Ваш запрос отправлен!</h1>');
                }
              }
      ); 

    }
    return false;
  });
  
  var $scrollable = $('.scrollable');
  var velocity = 4;
  
  $scrollable.css('overflow', 'hidden').bind('mousewheel', function(e, delta)  {
    sign = 1; 
    scroll(delta > 0 ? sign : -sign, this);  
    return false;
  });
  
  $scrollable.each(function(i, el) {
    if (el.scrollHeight > el.clientHeight) {
      $(el).before('<div class="scroll-control"><a href="#" class="scroll-up">Вверх</a><a href="#" class="scroll-down">Вниз</a></div>');
    }
  });
  
  $('a.scroll-down').hover(
    function() {
      $scroll = $(this).parents('.scroll-control:first').next('.scrollable');
      var max = ($scroll.get(0).scrollHeight - $('.scrollable').get(0).clientHeight);
      var cur = $scroll.get(0).scrollTop;
      var time = Math.abs((max - cur)*velocity);
      $scroll.animate({scrollTop: max}, { 'duration': time, easing: 'linear' });
    },
    function() {
      $scrollable.stop();
    }
  ).click(function() {return false});
  
  $('a.scroll-up').hover(
    function() {
      $scroll = $(this).parents('.scroll-control:first').next('.scrollable');      
      var max = ($scroll.get(0).scrollHeight - $('.scrollable').get(0).clientHeight);
      var cur = parseInt($scroll.get(0).scrollTop);
      var time = Math.abs(cur*velocity);
      $scroll.animate({scrollTop: 0}, { 'duration': time, easing: 'linear' });
    },
    function() {
      $scrollable.stop();
    }
  ).click(function() {return false});
  
  
	if ($('#gallery').get(0)) { /* gallery scripts */
		
		$('#gallery li:first').addClass('active').css('padding-left', 350);
		var $gallery = $('#gallery .gallery-scrollable');
		$('#gallery ul').css('left', -335);
		$last_li = $('#gallery ul li:last-child').css('padding-right', 350);
		var div_width = 1216;

		$gallery.mousemove(function(e){
			ul_width = $last_li[0].offsetLeft + $last_li[0].clientWidth; 
			var left = Math.round(-1*(e.pageX - $gallery.offset().left) * (ul_width-div_width) / div_width);
			left = left+'px';
			$('#gallery ul').css('left', left);
		});
		
		$('#gallery .thumbs a').each(function() {
			$.get(this.href);
		});
	
		$('#gallery .thumbs a').click(function() {
			var href = this.href;
			$('#big img').fadeTo("normal", 0.01, function() {
				$(this).attr('src', href).fadeTo("normal",1);
			});
			$('#gallery .thumbs .cur').removeClass('active');
			$(this).parents('li').addClass('active');
			$('#big .info').html($(this).find('span').html());
			return false; 
		}).each(function() {
  		$.get(this.href);	
		});

	}
  
});