function hidePreview() {
	$("#modal,#gallery").fadeOut("medium");
	//$("body").css("overflow","auto");
}
function showPreview() {
	$("#gallery").html($("#product-image-wrap").html());
	//$("body").css("overflow","hidden");
	var bodyHeight = $("body").height();
	var bodyWidth = $("body").width();
	$("#modal").css('height',bodyHeight).css('width',bodyWidth);
	var elementHeight = ($(window).height() - $("#gallery").height()) / 2;
	var elementWidth = ($(window).width() - $("#gallery").width()) / 2;
	$("#gallery").css("top",elementHeight).css("left",elementWidth);
	$("<span>X</span>").addClass("closeGallery").prependTo("#gallery").click(function(){
		hidePreview();
	});
	$("#modal,#gallery").fadeIn("medium");
}
function switchPreview() {
	if($("#modal").css('display') == 'none') {
    	showPreview();
	} else {
		hidePreview();
	}
}
$(document).ready(function(){
    var images = $('ul.multiple img').size();
	$("#modal").click(function(){
    	hidePreview();
    });
	$(".multiple a, .ProductImage").live("click",function() {
		if($("#product-image-wrap .ProductImage img").attr('src') != $(this).attr('href')) {
    		$(".ProductImage img").attr('src',$(this).attr('href'));
    		$(".ProductImage").attr('href',$(this).attr('href'));
			if($("#modal").css('display') == 'none') {
    			showPreview();
    		}
		} else {
			switchPreview();
		}
    	return false;
    });

    if(images>2)
    {
      $(".nextImage").live("click",function(){
  		$(".multiple").each(function(){
  			$(this).find("li:visible:eq(0)").attr('style','margin-left:7px').hide().appendTo($(this));
  			$(this).find("li:visible:eq(0)").attr('style','margin-left:0px');
  			$(this).find("li:visible:eq(1)").attr('style','margin-right:7px');
  			$(this).find("li:hidden:eq(0)").attr('style','margin-right:0px').show();
  		});
      });

      $(".previousImage").live("click",function(){
  		$(".multiple").each(function(){
  		    var Hideimages = $(this).find('li:hidden:last').index();
  			$(this).find("li:eq("+Hideimages+")").attr('style','margin-left:0px').show().prependTo($(this));
  			$(this).find("li:visible:eq(1)").attr('style','margin-left:7px');
  			$(this).find("li:visible:eq(2)").attr('style','margin-right:0px');
              var Showimages = $(this).find('li:visible:last').index();
  			$(this).find("li:eq("+Showimages+")").hide();
  		});
      });
    }
});

