﻿// JavaScript Document
(function($){
	function appendInstance(){
		$('body').append('<div id="imagebox"><a id="image-close" href="javascript:void(0)"></a><div id="image-content"><a id="image-prev" href="javascript:void(0)"><span></span></a><a id="image-next" href="javascript:void(0)"><span></span></a><img style="display:none;" src="" alt="" /></div></div><div id="shadow"></div>');
		$('#shadow').css({opacity: "0.7"}); //set opacity for all browsers
	}		
	
  $.fn.imagebox = function(settings){
		var settings = $.extend({ //object with setting
			detectScreen: true, //detect screen option with default value = true
			showThumbs: false, //show thumbs when opened with default value = false
			circular: true
		}, settings);


    var imageArray = this; //objects array (must be an array of links)
    var imageboxTop, imageboxPaddingTop, imageboxPaddingBottom; //get padding-bottom in css of main container
		
		imageArray.click(function(event){ //loking for click event
			appendInstance();
			var imagebox = $('#imagebox'); //object of div#imagebox (main container)
			var	shadow = $('#shadow'); //object of div#shadow (black transparent box)
			var	imagePrev = $('#image-prev'); //object of link for showing prev image
			var	imageNext = $('#image-next'); //object of link for showing next image
			var	image = $('#image-content img'); //object of image that containt loaded image (main image)
			imageboxTop = parseInt(imagebox.css('top')); //get top position in css of main container
			imageboxPaddingTop = parseInt(imagebox.css('padding-top')); //get padding-top in css of main container
			imageboxPaddingBottom = parseInt(imagebox.css('padding-bottom')); //get padding-bottom in css of main container
			var imageUrl; //url of seted image
			var currentImage;
			imagebox.addClass('loader') //show loading image as background
			event.preventDefault(); //disabling default action (go to url)
			
			if(settings.showThumbs == true){
				$('body').append('<div id="imagebox-thumbs"><div id="makeMeScrollable"><div class="scrollingHotSpotLeft"></div><div class="scrollingHotSpotRight"></div><div class="scrollWrapper"><div class="scrollableArea"></div></div></div></div>');
				settings.detectScreen = true;
				imageboxPaddingBottom = imageboxPaddingBottom+100;
				$(imageArray.selector).each(function(index, element) {
					var thumbImage = $(this).attr('href').replace('/600/', '/100/');
					$('.scrollableArea').append('<a href="' + $(this).attr('href') + '"><img src="' + thumbImage + '" alt=""></a>');
					console.log(index)
					console.log(imageArray.length)
          if (index == imageArray.length - 1) {
                    console.log('ok')
						$('#makeMeScrollable').smoothDivScroll({});
					}
					$('.scrollableArea a').click(function(event){
						event.preventDefault();
						setImage($(this).index(), image);
					});
        });
			}
			//set styles, position, etc
			if(settings.detectScreen == false){
				//if detectScreen disabled - set top position to main container
				imagebox.css({top: document.documentElement.scrollTop+imageboxTop+'px', position: 'absolute'});
			}
			
			currentImage = $(imageArray.selector).index(this);
			imagebox.fadeIn(300);
			shadow.fadeIn(300);
			setImage(currentImage, image); //setting image url
			image.bind('load', function(){
				var imageWidth = image.width();
				var imageHeight = image.height();
				if(settings.detectScreen == false){
					var overalHeight = imageboxTop+imageboxPaddingTop+imageboxPaddingBottom+imageHeight;
					if(overalHeight+document.documentElement.scrollTop > $(document).height()){
					  imagebox.css({top: $(document).height()-overalHeight+'px'});
					}
				}
				imagebox.animate({
					width: image.width()+'px',
					height: image.height()+'px',
					marginLeft: -image.width()/2-10+'px'
				}, 300, function(){
					console.log('load');
					image.fadeTo(300, 1);
				});
			});
			
			imagePrev.click(function(){
				if(imageArray.length-1 == 0){
					return;
				}
				image.fadeTo(300, 0.5);
				currentImage--;
				if(settings.circular == true && currentImage == -1){
					currentImage = imageArray.length-1;
				}
				setImage(currentImage, image);
			});
			imageNext.click(function(){
				if(imageArray.length-1 == 0){
					return;
				}
				image.fadeTo(300, 0.5);
				currentImage++;
				
				if(settings.circular == true && currentImage > imageArray.length-1){
					currentImage = 0;
				}
				setImage(currentImage, image);
			});
			$('#image-close, #shadow').click(function(){
			  imagebox.remove();
				shadow.remove();
				$('#imagebox-thumbs').remove();
			});
		});
		
		//function to use
		function setImage(currentImage, image) { //set attribute src to image element and run controls(next, prev) check
            image.fadeTo(0, 0);
						if (settings.circular == false) {
                getControls(currentImage);
            }
            var imageLink = $(imageArray.selector).eq(currentImage);
            imageUrl = imageLink.attr('href');
            if (settings.detectScreen == true) {
                getRatio(imageLink, image, currentImage);
            } else {
				image.attr({src: imageUrl});
				$("#makeMeScrollable").smoothDivScroll("moveToElement", "number", currentImage);
				$('.scrollableArea div.ithumb').eq(currentImage).addClass('current').siblings('div').removeClass('current');
			}
        }
		function getControls(currentImage){ //check and disabling prev or next links
			if(currentImage <= 0){
				$('#image-prev').addClass('disabled');
			} else {
				$('#image-prev').removeClass('disabled');
			}
			if(currentImage >= imageArray.length-1){
				$('#image-next').addClass('disabled');
			} else {
				$('#image-next').removeClass('disabled');
			}
		}
		function getRatio(imageLink, image, currentImage) { //calculating image size for client window size
			var aspectRatio = imageLink.children('img').width() / imageLink.children('img').height();
			if(isNaN(aspectRatio) == true || aspectRatio <= 0){
				//alert('r:'+aspectRatio)
				check = setInterval(function(){
					aspectRatio = imageLink.children('img').width() / imageLink.children('img').height();
					if(isNaN(aspectRatio) == false || aspectRatio >= 0){
						clearInterval(check);
						adaptingImage(imageLink, aspectRatio, image, currentImage);
					}
				},1000);
			} else {
				adaptingImage(imageLink, aspectRatio, image, currentImage);
			}
        }
		function adaptingImage(imageLink, aspectRatio, image, currentImage){
			var limitSize,windowInnerWidth,windowInnerHeight;
			// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
			if (typeof window.innerWidth != 'undefined'){
				windowInnerWidth = window.innerWidth,
				windowInnerHeight = window.innerHeight
			}
			// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
			else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
				windowInnerWidth = document.documentElement.clientWidth,
				windowInnerHeight = document.documentElement.clientHeight
			}
			// older versions of IE
			else{
				windowInnerWidth = document.getElementsByTagName('body')[0].clientWidth,
				windowInnerHeight = document.getElementsByTagName('body')[0].clientHeight
			}			
			
			if (windowInnerWidth < windowInnerHeight) {
					limitSize = windowInnerWidth;
			} else {
				limitSize = parseInt((windowInnerHeight - imageboxTop - imageboxPaddingTop - imageboxPaddingBottom - 80) * aspectRatio)-30;
				if(limitSize > windowInnerWidth){
					limitSize = windowInnerWidth-60;
				}
				if(limitSize < 100){
					getRatio(imageLink, image, currentImage);
				}
			}
			
			imageUrl = imageUrl.replace('/600/', '/' + limitSize + '/');
			image.attr({src: imageUrl});
			$("#makeMeScrollable").smoothDivScroll("moveToElement", "number", currentImage);
			$('.scrollableArea div.ithumb').eq(currentImage).addClass('current').siblings('div').removeClass('current');
		}
		
		return this;
  };   
})(jQuery);
