
(function($) {
    $.extPictGallery = {};
    // === basic options ===
    $.extPictGallery.Options = {
    	bigImages: {},
    	smallImages: {},
    	initialPosition: 0,
		smallerPicturesZIndex: 110010,
		centerPictureZIndex:110011,
		posAnimateSpeed: 100,
    	gutterWidth: -160,
    	onInit: function(){},
    	onCenterImageLoad: function(){},
    	onExit: function (index){},
    	imagesTitle: null
    };
    // === internal values ===
    $.extPictGallery.lastSlideValue = 0; // current image index
    $.extPictGallery.wWidth = 0; // current window width
    $.extPictGallery.wHeight = 0; // current window height
    $.extPictGallery.miniaturesContainerWidth = 0; // miniatures container width (visual width)
    $.extPictGallery.miniaturesWidth = 0; // miniatures width (list of all images)
    $.extPictGallery.bottomAreaHeight = 0; // height a area in bottom, where scroll & miniatures
    $.extPictGallery.miniaturesOnScreen = 0; // count of maximum visible miniatures
    $.extPictGallery.miniaturesCount = 0; // count of maximum visible miniatures
    $.extPictGallery.singleImageMode = false; // if display a single image - not need Sliding Gallery

    // constructor
    $.fn.extPictureGallery = function(options) {
		//global settings
		$.extend($.extPictGallery.Options, options);
		var options = $.extPictGallery.Options;
		// if single image mode
    	if (options.bigImages.length==1){
    		$.extPictGallery.singleImageMode = true;
    	}
		// create a dom structure
		$.extPictGallery.buildDom(this);
		// create a images
		$.extPictGallery.createImages(options.bigImages, options.smallImages, options.initialPosition);

		// init a basic dimensions
		$.extPictGallery.calculateDimensions ();
		// init a dimensions of small miniatures
		$.extPictGallery.calculateSmallImagesWidth ();
		$.extPictGallery.bottomAreaHeight = $('#carousel_place').outerHeight(true);

		if ($.extPictGallery.singleImageMode){
			$.extPictGallery.resizeHandler();
		}

		// --- basic logic initializing ---
		// create a image gallery
		if (!$.extPictGallery.singleImageMode){
			var maxPictureHeight = $(window).height() - ($.extPictGallery.bottomAreaHeight + 50);// get a maximal height of image
		    $('#gallery_container img').slidingGallery({
		    	gutterWidth: options.gutterWidth,
		        Lheight: maxPictureHeight,
		        Lwidth: Math.round(maxPictureHeight*1.3333),
		        Pheight: maxPictureHeight,
		        Pwidth: Math.round(maxPictureHeight/1.3333),
		        Lshrink:
		            function(dimension) {
		                return dimension * 0.6;
		        },
		        Pshrink:
		            function(dimension) {
		                return dimension * 0.6;
				},
				smallerPicturesZIndex: options.smallerPicturesZIndex,
				centerPictureZIndex: options.centerPictureZIndex,
				posAnimateSpeed: options.posAnimateSpeed,
				leftCallback: $.extPictGallery.galleryLeft,
				rightCallback: $.extPictGallery.galleryRight,
				useOrigSizeIfNotBigger: true,
				computeResizeInternal: false,
				centerImageReady: $.extPictGallery.computeArrows
		    });
	    	// create a slider
			$('#slider_container').slider({
									min: 0,
									max: $.extPictGallery.miniaturesCount-1,
									slide: $.extPictGallery.listHandler,
									stop: $.extPictGallery.listHandler
			});
	    	$('#slider_container').slider('value',options.initialPosition);
		}
	    // if pop-up already opened - unbind routines, to prevent a miltiple calling
		$('#carousel_place, #left_button, #right_button', '#previews_list > li > img').unbind();

		// --- binding ---
		// prevent close to click on bottom area
		$('#carousel_place').bind('click',function(e){
														e.preventDefault();
	        											e.stopPropagation();
												});
		// click on small images
		if (!$.extPictGallery.singleImageMode){
			$('#previews_list > li > img').bind('click',$.extPictGallery.smallClickHandler);
			// make a buttons "left" and "right"
			$("#left_button").bind('click',$.extPictGallery.leftButtonHandler);
			$("#right_button").bind('click',$.extPictGallery.rightButtonHandler);
			// init a mouse scroll functionality
			$("#new_images_popup").unbind('mwheelIntent').bind('mwheelIntent', $.extPictGallery.mouseScrollHandler);
		}
		// resize event computing
        $(window).resize($.extPictGallery.resizeHandler);
        // add number
        $('#image_number').html('Image '+(($.extPictGallery.lastSlideValue/1)+1)+' of '+$.extPictGallery.Options.bigImages.length);
		// all done. call callback
		options.onInit();
    };

	// function to build a basic dom structure
	$.extPictGallery.buildDom = function (container){
		// create a overlay
		container.append($('<div id="cs_fancybox-overlay" class="cs_fancy_overlay_new" ></div>'));
		$('#cs_fancybox-overlay').unbind();
		$('#cs_fancybox-overlay').bind('click',$.extPictGallery.close);
		// create a images div
		container.append($('<div id="new_images_popup" class="new-images-popup"> <div class="overlay-close-button"></div> </div>'));
		$('#new_images_popup').append('<div id="gallery_container" class="gallery-container"></div>');
		$('#new_images_popup').bind('click',$.extPictGallery.close);
		// create a div's to slider
		$('#new_images_popup').append('<div id="carousel_place" class="carousel-place"> </div>');
		$("#carousel_place").append('<div id="top_center" class="top-center"></div>');
		if ($.extPictGallery.Options.imagesTitle != null){
			$("#top_center").append('<div id="center_title" class="center-title">'+$.extPictGallery.Options.imagesTitle+'</div>');
		}
		$("#top_center").append('<div id="image_number" class="image-number"></div>');
		if (!$.extPictGallery.singleImageMode){
			$('#new_images_popup').append('<div id="left_button_div" class="left-button-div"></div>');
			$('#new_images_popup').append('<div id="right_button_div" class="right-button-div"></div>');
			$('#left_button_div').append('<div id="left_button" class="left-button">&lt;&lt; previous</div>');
			$('#right_button_div').append('<div id="right_button" class="right-button">next &gt;&gt;</div>');
			$('#left_button, #right_button').css('z-index',$.extPictGallery.Options.centerPictureZIndex+2)
											.css({'position':'fixed','display':'none'});
			$('#left_button_div, #right_button_div').css('z-index',$.extPictGallery.Options.centerPictureZIndex+1)
											.css({'position':'fixed','display':'none'});
			// bind functionality for arrows
			$('#left_button_div').mouseenter($.extPictGallery.leftArrowDivEnter).mouseleave($.extPictGallery.leftArrowDivLeave);
			$('#right_button_div').mouseenter($.extPictGallery.rightArrowDivEnter).mouseleave($.extPictGallery.rightArrowDivLeave);
		}
		$('#carousel_place').append('<div id="previews_container" class="previews-container"></div>');
		$('#carousel_place').append('<div id="carousel_container" class="carousel-container"></div>');
		$('#carousel_container').append('<div id="slider_visual_border" class="slider-visual-border"></div>');
		$('#slider_visual_border').append('<div id="slider_container" class="slider-container"></div>');
		// create a div's to previews
		$('#previews_container').append('<div id="previews_body" class="previews-body"> '+
									'<ul id="previews_list" class="previews-list clearfix"></ul> </div>');
	};

	// compute a arrows
	$.extPictGallery.computeArrows = function (image){
		// dimensions
		image = $('#gallery_container .center-sliding');
		var position = image.offset();
		position = {left: position.left-$(window).scrollLeft(), top: position.top-$(window).scrollTop()};
		var dimensions = {width: image.width(), height: image.height()};
		// position for arrows
		$('#left_button').css({left: (position.left+10)+'px', top: (position.top+dimensions.height/2-$('#right_button').width()/2)+'px'});
		$('#right_button').css({left: ((position.left+dimensions.width)-10-$('#right_button').width())+'px', top: (position.top+dimensions.height/2-$('#right_button').height()/2)+'px'});
		// position for arrows div's
		$('#left_button_div').css({left: position.left, top:position.top});
		$('#right_button_div').css({left: ((position.left+dimensions.width)-120)+'px', top:position.top});
		$('#left_button_div, #right_button_div').css({width: '120px', height: dimensions.height+'px', 'display':'block'});
	};

	// function to create a images for plugins
	$.extPictGallery.createImages = function (listBig, listSmall, initialPosition){
		// create a big images
		var index = 0;
		for (var k in listBig){
			if (index == initialPosition){
				var image = $('<img src="'+listBig[k]+'" class="start" />').bind('load',$.extPictGallery.centerImageReady);
				$('#gallery_container').append(image);
			}
			else{
				$('#gallery_container').append($('<img src="'+listBig[k]+'" />'));
			}
			index++;
		}
		// create a small images
		index = 0;
		for (var k in listSmall){
			if (index == initialPosition){
				$('#previews_list').append($('<li class="current-item"><img src="'+listSmall[k]+'" index="'+index+'" /></li>'));
			}
			else{
				$('#previews_list').append($('<li><img src="'+listSmall[k]+'" index="'+index+'" /></li>'));
			}
			index++;
		}
		$.extPictGallery.miniaturesCount = index;
		// if single image mode
		if (index==1){
			$.extPictGallery.singleImageMode = true;
			$('#new_images_popup').addClass('single-image-popup');
			$('#gallery_container').addClass('single-image-container');
			$('#gallery_container img').addClass('single-image');
		}
	};

	// setting a correct width and height of container
	$.extPictGallery.calculateDimensions = function(){
		$.extPictGallery.wWidth = $(window).width();
		$.extPictGallery.wHeight = $(window).height();
	};

	// setting a correct width and height of container
	$.extPictGallery.calculateSmallImagesWidth = function(){
	    $.extPictGallery.miniaturesContainerWidth = 0; // miniatures container width (visual width)
	    $.extPictGallery.miniaturesWidth = 0; // miniatures width (list of all images)
	    //
	    var miniaturesWidth = 0;
	    $.extPictGallery.miniaturesOnScreen = 0;
	    $('#previews_list li').each (function(){
	    	miniaturesWidth += $(this).outerWidth(true);
	    	if (miniaturesWidth < $.extPictGallery.wWidth-50){
	    		$.extPictGallery.miniaturesOnScreen++;
	    	}
	    });
	    $.extPictGallery.miniaturesWidth = miniaturesWidth = miniaturesWidth+5;
	    $('#previews_list').css('width',miniaturesWidth);
	    //
	    var calcMiniaturesVisibleWidth = function(width){
	    	var newWidth = 0;
		    $('#previews_list li').each (function(){
		    	var currentItemW = $(this).outerWidth(true);
		    	if (newWidth + currentItemW < width){
		    		newWidth += $(this).outerWidth(true);
		    	}
		    });
		    return newWidth;
	    };
	    // alert(miniaturesWidth);
	    if (miniaturesWidth < $.extPictGallery.wWidth-50){
	    	$.extPictGallery.miniaturesContainerWidth = calcMiniaturesVisibleWidth(miniaturesWidth+10);
	    	$.extPictGallery.needMiniaturesScroll = false;
	    }
	    else{
	    	$.extPictGallery.miniaturesContainerWidth = calcMiniaturesVisibleWidth($.extPictGallery.wWidth-40);
	    	$.extPictGallery.needMiniaturesScroll = true;
	    }
	    $('#slider_visual_border, #carousel_container').css('width',$.extPictGallery.miniaturesContainerWidth+'px');
	    $('#top_center').css('width',$.extPictGallery.miniaturesContainerWidth+'px');
	    $('#slider_container').css('width',($.extPictGallery.miniaturesContainerWidth-180)+'px');
	    $('#previews_container, #previews_body').css('width', $.extPictGallery.miniaturesContainerWidth+'px');
	    $('#carousel_place').css('width',$.extPictGallery.wWidth+'px');
	    // not display a slider container if single image mode
	    if ($.extPictGallery.singleImageMode){
	    	$('#slider_visual_border').hide();
	    }
	};

	// change current miniature
	$.extPictGallery.changeActiveMiniature = function(index){
		$('#previews_list li').removeClass('current-item');
		$('#previews_list img[index='+index+']').parent().addClass('current-item');
// ! need to implement a scrolling miniatures feature !
		if ($.extPictGallery.needMiniaturesScroll){
			var leftOffset = 0;
			if (index > Math.round($.extPictGallery.miniaturesOnScreen/2)){
				if (index==$.extPictGallery.miniaturesCount-1) leftOffset += 4;
				// if index very close to end - prevent clear space in right
				if (index > $.extPictGallery.miniaturesCount - Math.round($.extPictGallery.miniaturesOnScreen/2)){
					index = $.extPictGallery.miniaturesCount - Math.round($.extPictGallery.miniaturesOnScreen/2);
				}
				// calculate a count of hidden elements on left
				var leftHidden = index - Math.round($.extPictGallery.miniaturesOnScreen/2);
				// calculate a offset in pixels
			    $('#previews_list li').each (function(){
			    	leftHidden--;
			    	if (leftHidden >=0){
			    		leftOffset += $(this).outerWidth(true);
			    	}
			    });
			}
			// set the left to <ul>
			$('#previews_list').css('left','-'+leftOffset+'px');
		}
        // change number
        $('#image_number').html('Image '+((index/1)+1)+' of '+$.extPictGallery.Options.bigImages.length);
	}

    $.extPictGallery.getOriginalImageSize = function (image){
		var prevDimensions = {
					width: image.width(),
					height: image.height()
		};
		image.css({'width':'','height':''});
		var origDimensions = {
					width: image.width(),
					height: image.height()
		};
		image.css({'width':prevDimensions.width+'px','height':prevDimensions.height+'px'});
		return origDimensions;
    };

	$.extPictGallery.leftArrowDivEnter = function (event){
    	$('#left_button').css('display','block');
	};

	$.extPictGallery.rightArrowDivEnter = function (event){
    	$('#right_button').css('display','block');
	};

	$.extPictGallery.leftArrowDivLeave = function (event){
    	$('#left_button').css('display','none');
	};

	$.extPictGallery.rightArrowDivLeave = function (event){
    	$('#right_button').css('display','none');
	};

	$.extPictGallery.hideArrows = function (){
    	$('#left_button_div, #right_button_div').css('display','none');
    	$('#left_button, #right_button').css('display','none');
	};


/* ======= Handlers ======= */

    // handler to list event (slider)
    $.extPictGallery.listHandler = function (event, ui){
		if (ui.value != $.extPictGallery.lastSlideValue){
	    	$.extPictGallery.hideArrows ();
			$.galleryUtility.pos(ui.value);
			$.extPictGallery.lastSlideValue = ui.value;
			$.extPictGallery.changeActiveMiniature(ui.value);
		}
	};

    // handler to "left" click on gallery
    $.extPictGallery.galleryLeft = function (index){
    	// current not need a custom logic for two buttons
    	$.extPictGallery.galleryRight(index);
	};

    // handler to "right" click on gallery
    $.extPictGallery.galleryRight = function (index){
    	$.extPictGallery.hideArrows ();
    	$('#slider_container').slider('value',index);
    	$.extPictGallery.changeActiveMiniature(index);
	};

    // handler to click on small pictures
    $.extPictGallery.smallClickHandler = function (event){
    	$.extPictGallery.hideArrows ();
	   	var index = $(this).attr('index');
    	$.extPictGallery.pos(index);
    	event.preventDefault();
		event.stopPropagation();
	};

    // handler to "left" button on gallery
    $.extPictGallery.leftButtonHandler = function (event){
    	$.extPictGallery.hideArrows ();
    	$.extPictGallery.lastSlideValue = $.galleryUtility.leftHandler(event);
    	$.extPictGallery.changeActiveMiniature($.extPictGallery.lastSlideValue);
	};

    // handler to "right" button on gallery
    $.extPictGallery.rightButtonHandler = function (event){
    	$.extPictGallery.hideArrows ();
    	$.extPictGallery.lastSlideValue = $.galleryUtility.rightHandler(event);
    	$.extPictGallery.changeActiveMiniature($.extPictGallery.lastSlideValue);
	};

	// handler to mouse scroll event
    $.extPictGallery.mouseScrollHandler = function (event, delta, deltaX, deltaY) {
		if (deltaY > 0){
			$.extPictGallery.leftButtonHandler(event);
		}
		else if (deltaY < 0){
			$.extPictGallery.rightButtonHandler(event);
		}
	};

    // handler to resize browser window event
    $.extPictGallery.resizeHandler = function (event){
    	// changing a size of miniatures, slider
    	$.extPictGallery.calculateDimensions();
    	$.extPictGallery.calculateSmallImagesWidth();
    	if (!$.extPictGallery.singleImageMode){
	    	$.extPictGallery.changeActiveMiniature ($.extPictGallery.lastSlideValue);
	    	$.extPictGallery.computeArrows();
	    	// changing a size of gallery
			var maxPictureHeight = $(window).height() - ($.extPictGallery.bottomAreaHeight + 50);
	        var newDimensions = {
		        Lheight: maxPictureHeight,
		        Lwidth: Math.round(maxPictureHeight*1.3333),
		        Pheight: maxPictureHeight,
		        Pwidth: Math.round(maxPictureHeight/1.3333)
	        }
			$.galleryUtility.changeOptions(newDimensions);
	        $.galleryUtility.onResize(event);
    	}
    	else{
			var imageAreaD = {
				width: $.extPictGallery.wWidth,
				height: $.extPictGallery.wHeight-$.extPictGallery.bottomAreaHeight
			};
			var imageD = $.extPictGallery.getOriginalImageSize($('#gallery_container > img'));
			// if source image bigger
			if (imageD.width > imageAreaD.width || imageD.height > imageAreaD.height){
				var aspect = imageD.width/imageD.height;
				if (imageD.height > imageAreaD.height){
					imageD.height = imageAreaD.height - 40;
					imageD.width = imageD.height*aspect;
				}
				else{
					imageD.width = imageAreaD.width - 40;
					imageD.height = imageD.width/aspect;
				}
			}
			//set dimensions
			$('#gallery_container > img').css({'width': imageD.width+'px', 'height': imageD.height+'px', 'position': 'fixed'});
			// set left & top
			var imageLeft = imageAreaD.width/2 - imageD.width/2;
			var imageTop = imageAreaD.height/2 - imageD.height/2;
			$('#gallery_container > img').css({'left': imageLeft+'px', 'top': imageTop+'px'});
    	}
    }

    $.extPictGallery.centerImageReady = function(event){
    	// calc positions
    	if (!$.extPictGallery.singleImageMode){
    		$.galleryUtility.onResize(event);
	    	$.extPictGallery.computeArrows();
    	}
    	else{
    		$.extPictGallery.resizeHandler(event);
    	}
    	$.extPictGallery.Options.onCenterImageLoad();
    }

/* ======= User functions ======= */

	// closing the gallery
    $.extPictGallery.close = function (){
		var currIndex = $.extPictGallery.lastSlideValue;
		$('#cs_fancybox-overlay').remove();
		$('#new_images_popup').remove();
		$.extPictGallery.Options.onExit(currIndex);
		return currIndex;
	}

	// random seek a gallery by index
	$.extPictGallery.pos = function(index){
		$.extPictGallery.changeActiveMiniature(index);
		$.galleryUtility.pos(index);
		$('#slider_container').slider('value',index);
	}

})(jQuery);


