var $j = jQuery.noConflict();

$j(function() {

	// some vars
	var marg_to_move = parseInt($j('div.itemee').outerWidth());
	var divee = $j('div.divee');
	var animated = false;
	var ivl = 0;
	
	// adjust margin and elements on the start
	divee.css('left', -marg_to_move);
	$j('div.divee div:first').before($j('div.divee div:last'));
	
	// interval
	function turn_on_ivl () { ivl = setInterval(slidethem_l, 7000); }
	
	function slidethem_r() {
		divee.clearQueue();
		slidethem("right");
		animated = true;
	}
	
	function slidethem_l() {
		divee.clearQueue();
		slidethem("left");
		animated = true;
	}
	
	function slidethem(where_to) {
		if (!animated) {
			var marg_to_animate = (where_to == 'right') ? 0 : -(marg_to_move*2);
			divee.animate({'left': marg_to_animate}, 300, 'linear', function () {
				// callback
				if (where_to == 'right') {
					$j('div.divee div:first').before($j('div.divee div:last'));
					divee.css('left', -(marg_to_move));
				} else {
					$j('div.divee div:last').after($j('div.divee div:first'));
					divee.css('left', -(marg_to_move));
				}
				animated = false;
			});
		}
	}
	
	
	// buttons and mouse -enters / -leaves
	
	var b_prev = $j("img.emslider_arrow_prev");
	var b_next = $j("img.emslider_arrow_next");
	
	b_prev.fadeOut(1);
	b_next.fadeOut(1);
		
	b_prev.mouseenter(function() {
	    clearInterval(ivl);
	    buttons_show();
	});
	
    b_prev.mouseleave(function() {
        turn_on_ivl();
        buttons_hide();
    });

    b_next.mouseenter(function() {
        clearInterval(ivl);
        buttons_show();
    });

	b_next.mouseleave(function() {
	    turn_on_ivl();
	    buttons_hide();
	});
    
    b_prev.click(function() { slidethem_r(); });
    b_next.click(function() { slidethem_l(); });
    
    $j('div.img_wrapper').mouseenter(function () {
        clearInterval(ivl);
        buttons_show();
    });
    $j('div.img_wrapper').mouseleave(function () {
        turn_on_ivl();
        buttons_hide();
    });
    
    function buttons_show() {
        b_prev.css('display', 'block');
	    b_next.css('display', 'block');
    }
    
    function buttons_hide() {
        b_prev.css('display', 'none');
	    b_next.css('display', 'none');
    }
    
    // start animating
    turn_on_ivl();

});

