// JavaScript Document
$(document).ready(function () {
	
	$('#gallery-image').mouseenter(function(){
		$('.gallery-left').fadeIn();
		$('.gallery-right').fadeIn();
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        	$(document).pngFix(); 
		}
	}).mouseleave(function(){
		$('.gallery-left').fadeOut();
		$('.gallery-right').fadeOut();
	});

    var slideWidth = $(".gallery-slide").width();
	var holderWidth;
	var currLeft;
	var animation=0;
	var direction;
	var timerval;
	
	
	var imgHeight;
	var divHeight = $('.gallery-slide').css('height').replace('px','');
	
	$('.gallery-slide').each(function() {
									  
		imgHeight = $(this).children('img').css('height').replace('px','');
		
		$(this).children('img').css({'margin-top':((divHeight-imgHeight-6)/2)+'px'});
	});
	
	$('#gallery-slider').each(function() {
		var count = $(this).children('div').length;
		$(this).css({'width':(count*slideWidth)+'px', 'position': 'absolute'});
	});

    timeron();
	
	function timeron(){
		clearInterval(timerval);
		timerval = setInterval(autoMoveImage,6000);
	}
	
	function autoMoveImage() {
		holderWidth = $('#gallery-slider').width();
		currLeft = $('#gallery-slider').css('left').replace('px','');
		if(currLeft <= 0 && currLeft > -(holderWidth - slideWidth) && animation==0){
			direction= '-';
			moveImage();
		} else {
			resetImageLeft();
		};
	}

    $(".gallery-left").click(function () {
		holderWidth = $('#gallery-slider').width();
		currLeft = $('#gallery-slider').css('left').replace('px','');
		if(currLeft < 0 && currLeft >= -(holderWidth - slideWidth) && animation==0){
			direction= '+';
			moveImage();
		}else{
			resetImageLeft();
		};
		timeron();
    });

    $(".gallery-right").click(function () {
		holderWidth = $('#gallery-slider').width();
		currLeft = $('#gallery-slider').css('left').replace('px','');
		if(currLeft <= 0 && currLeft > -(holderWidth - slideWidth) && animation==0){
			direction= '-';
			moveImage();
		} else {
			resetImageLeft();
		};
		timeron();
    });
	
	
	function resetImageLeft() {
			if(currLeft==-(holderWidth - slideWidth) && animation==0){
			animation =	1;
			$('#gallery-slider').animate({'left':'0px'},500, function() {
				animation =0;
			});
			}
			if(currLeft==0 && animation==0){
			animation =	1;
			$('#gallery-slider').animate({'left':-(holderWidth - slideWidth)+'px'},500, function() {
				animation =0;
			});
			}
	}
	function moveImage() {
			animation =	1;
			$('#gallery-slider').animate({'left':direction+'='+slideWidth+'px'},500, function() {
				animation =0;
			});
	}
	
	$(document).keyup(function(event){
		if(event.keyCode == 37){
			 $(".gallery-left").trigger('click');
			 return false;
		}
		if(event.keyCode == 39){
			 $(".gallery-right").trigger('click');
			 return false;
		}
	});

});
