/*global jQuery, FancyBox 

*/
$(document).ready(function(){
	
	initShop88Gallery();
});

function photoOnloadSetting(img){
	
	var div = img.parent();
	var left ;
	var top ;
	
	if(div.width() > img.width()){
		div.width(img.width()) ;
	} else {
		left = img.width()/2 - div.width()/2 ;
		img.css('left', '-'+ left +'px');
	}
	
	if(div.height() > img.height()){
		div.height(img.height()) ;
	} else {
		top = img.height()/2 - div.height()/2;
		img.css('top', '-'+ top +'px');
	}
	img.attr('init', true);
	img.show();
}

function initShop88Gallery(){
	
	var croppingMap = {
		square : {width : 1, length : 1},
		rect : {width : 4, length : 3}		
	};
	
	var countGallery = 0;
	
	function isInt(input){
		return ((input)!== undefined && parseInt(input)==input);
	}
		
	function buildMultiPhoto(obj){
		try{
			// check for valid datasrc
			var dataSrc = [];
			try{
				var tempData = eval(obj.attr('datasrc'));
				
				for(var i=0; i<tempData.length; i++){
					if(tempData[i] !== undefined){
						dataSrc.push(tempData[i]);
					}
				}			
			}
			catch(e) {
				var urlVal = $.deparam.querystring();
				if(urlVal['hideAlert'] == undefined || urlVal['hideAlert'] !== '1'){
					alert('"datasrc" contained unaccepted value. Slider cannot be displayed.'); 
				}
			}
			
			var width = (isInt(obj.attr('width')))? parseInt(obj.attr('width')) : obj.width();
			var spacing = (isInt(obj.attr('spacing')))? parseInt(obj.attr('spacing')) : 5;
			var border = (isInt(obj.attr('border')))? parseInt(obj.attr('border')) : 0;
			var column = (isInt(obj.attr('column')))? parseInt(obj.attr('column')) : 2;
			var cropping = (obj.attr('cropping') && croppingMap[obj.attr('cropping')]!== undefined)? obj.attr('cropping') : 'rect';
	
			var availWidthForPhotos = width - (2 * column * (1 + spacing + border)); 
			
			obj.width(width);
			
			var thrumbWidth = (availWidthForPhotos / column);
			var thrumbHeight = (availWidthForPhotos / column) * (croppingMap[cropping]['length'] / croppingMap[cropping]['width']);
	
			var photoStr = '';
			var small;
			var big;
			var currentCol =0;
			
			if(Math.floor(thrumbWidth)<=0){
				obj.append('<div>photo gallery has not enough space to display photos.</div>');
				return;
			}
			
			for(var i=0; i<dataSrc.length; i++){
				if(dataSrc[i] !== undefined && (dataSrc[i]["big"] !== undefined && dataSrc[i]["big"] || dataSrc[i]["small"] !== undefined && dataSrc[i]["small"])){
						
					small = (dataSrc[i]["small"] == undefined || !dataSrc[i]["small"])? dataSrc[i]["big"] : dataSrc[i]["small"];
					big = (dataSrc[i]["big"] == undefined || !dataSrc[i]["big"])? dataSrc[i]["small"] : dataSrc[i]["big"];
										
					if(currentCol == 0){
						photoStr += '<div>';
					}
					
					photoStr += '<a class="gallery_'+ countGallery +' dbShop-ui-imgThumb" ';
							
					var spacing = obj.attr('spacing');
					if(isInt(spacing))
					{
						spacing = spacing != '0' ? spacing + 'px' : spacing; 
						photoStr += 'style="margin: ' + spacing + ' ' + spacing + ' 0 ' + spacing + '" ';
					}
					
					photoStr += (obj.attr('slider'))? 'rel="gallery_'+ countGallery +'" ' : '';
					photoStr += (dataSrc[i]["title"])? 'title="'+ dataSrc[i]["title"] +'" ' : '';
					photoStr += 'href="'+ big +'">';
					
					photoStr += '<div ';
					photoStr += 'style="overflow: hidden; ';
					photoStr += (thrumbWidth !== 0)? 'width:'+ Math.floor(thrumbWidth) +'px; ' : '';
					photoStr += (thrumbHeight !== 0)? 'height:'+ Math.floor(thrumbHeight) +'px; ' : '';					
					photoStr += (isInt(obj.attr('border')))? 'margin: '+ parseInt(obj.attr('border')) +'px; ' : '';
					photoStr += 'position:relative;">';
					
					photoStr += '<img ';
					photoStr += 'onLoad = "photoOnloadSetting($(this));" ';
					photoStr += 'src="'+ small +'" ';
					photoStr += 'style="';
					photoStr += 'position: relative; ';
					photoStr += 'left: 0; ';
					photoStr += 'top: 0; ';
					photoStr += 'display: none; ';
					photoStr += '"';
					photoStr += '/>';
					
					photoStr += '</div>';
					photoStr += '</a>';				
					
					
					if(++currentCol == column){
						photoStr += '</div>';
						currentCol = 0;
					}
				}
			}
			obj.attr('id', 'dbShop-ui-gallery_c');
			obj.attr('class', '88shop_gallery');
			obj.attr('popup', (obj.attr('popup') == undefined || obj.attr('popup') == 'true'));
			obj.removeAttr('datasrc');
		    obj.removeAttr('width');
		    obj.html('');
			obj.append(photoStr);
			
			galleryPopupEffect();
		}
		catch(e) {
			var urlVal = $.deparam.querystring();
			if(urlVal['hideAlert'] == undefined || urlVal['hideAlert'] !== '1'){
				alert(e+ ', Gallery cannot be displayed.'); 
			}
		}
	}
	
	function buildSinglePhoto(obj){		
		try{		
			var photoStr = '';
						
			photoStr += '<a class="gallery_'+ countGallery +'" ';
			photoStr += (obj.attr('title'))? 'title="'+ obj.attr('title') +'" ' : '';
			photoStr += 'href="' + ((obj.attr('big') !== undefined )? obj.attr('big') : obj.attr('small')) +'" ';
			photoStr += '>';
			
			photoStr += '<div  ';
			photoStr += 'style="overflow: hidden; ';			
			photoStr += 'position:relative;">';
			
			photoStr += '<img  ';
			photoStr += 'src="' + ((obj.attr('small') !== undefined )? obj.attr('small') : obj.attr('big')) +'" ';	
			photoStr += (isInt(obj.attr('width')))? 'width="'+ obj.attr('width') +'" ' : '';
			photoStr += (isInt(obj.attr('height')))? 'height="'+ obj.attr('height') +'" ' : '';					
			photoStr += '/>';
			
			photoStr += '</div>';
			photoStr += '</a>';				

			obj.removeAttr('small');
			obj.removeAttr('big');
			obj.removeAttr('title');
		    obj.removeAttr('width');
		    obj.removeAttr('height');
		    obj.html('');
			obj.append(photoStr);	    		
		}
		catch(e) {
			var urlVal = $.deparam.querystring();
			if(urlVal['hideAlert'] == undefined || urlVal['hideAlert'] !== '1'){
				alert(e+ ', Gallery cannot be displayed.'); 
			}
		}
	}
		
	$(".shop88_Gallery").each(function(){
		var _obj = $(this), obj;
				
		if(_obj.attr('init') === 'true'){
			return;
		}
		
		if (this.nodeName == "IMG") {
			obj = $('<div/>');
			
			var allowAttrList = ['class', 'width', 'slider', 'column', 'spacing', 'cropping', 'border', 'popup', 'datasrc'];

			for (var i = 0; i < this.attributes.length; i++) {
 				if($.isArray(this.attributes[i].name, allowAttrList) != -1 && this.attributes[i].value && this.attributes[i].value !== 'null')
				{
					obj.attr(this.attributes[i].name, this.attributes[i].value);					
				}
			}
			
			_obj.replaceWith(obj);
		} else {
			obj = _obj;
			obj.html("");
		}
				
		// build needed HTML
		if(obj.attr('small') !== undefined || obj.attr('big') !== undefined){
			
			buildSinglePhoto(obj);
		} else {
			
			if(obj.attr('datasrc') === undefined) {
				return;
			}
			
			buildMultiPhoto(obj);
		}			
		
		// apply FancyBox API from attr (not attr to set this in this version)
		$(".gallery_"+ countGallery).fancybox({
			'centerOnScroll'	: true,
			'titlePosition' 	: 'inside'
			
		});
		
		obj.attr('init','true');
		
		countGallery++;
	});		
}

function galleryPopupEffect(){
	$(".88shop_gallery").find("a").each(function() {
		if($(this).parent().parent().attr('popup') == "true")
		{		
			$(this).unbind("mouseenter mousemove");
		
			$(this).bind("mouseenter mousemove", function() { 			
				var gal = $(this);
				var offset = gal.offset();
				var div = gal.children("div");
				var img = div.children("img");
				
				if(img.attr('init') !== 'true'){
					return;
				}
				
				$('.shop88_galleryPop').remove();
				var popupStr = ''
				
				+ '<a class="shop88_galleryPop" '
				+ 'href="javascript:void(0);" '				
				+ 'style="overflow: hidden; '
				+ 'display: inline-block;'
				+ 'position:absolute; '
				+ ' border:1px solid #CCC; '
				+ 'background-color:#FFFFFF; '
				+ 'left:'+ offset.left +'px; '
				+ 'top:'+ offset.top +'px; '
				+ 'box-shadow: 0 0 15px rgba(0, 0, 0, 0.5); '
				+ 'z-index: 1099; '
				+ ' "'
				+ '>'
	
				+ '<div '
				+ 'style="'				
				+  div.attr('style')
				+ '">'
				
				+ '<img '
				+ 'src="'+ img.attr('src') +'" '
				+ 'style="'				
				+ 'position: relative; '
				+ 'left:'+ img.css('left') +'; '
				+ 'top:'+ img.css('top') +'; '
				+ '"/>'
				+ '</div></a>';
				
				if(gal.attr('title') !== undefined){
					$(".shop88_galleryPop").attr('title', gal.attr('title'));
				}
						
				$("body").append(popupStr);
				
				$(".shop88_galleryPop").bind("mouseenter", function() {
					var pop = $(this);
					var div = pop.children("div");
					var img = div.children("img");
					
					if(pop.attr('animating') == undefined){
						
						pop.attr('animating', true);
						var widthOffset = parseInt(pop.width()*1/2);
						var heightOffset = parseInt(pop.height()*1/2);
						
						setTimeout(function() {
							pop.animate({
							    left: '-='+parseInt(widthOffset/2),
							    top: '-='+parseInt(heightOffset/2)
							  }, 100, 'linear'
							 );
							
							div.animate({
							    width: pop.width()+widthOffset,
							    height: pop.height()+heightOffset
							  }, 100, 'linear'
							 );
							
							img.animate({
								left: '+='+parseInt(widthOffset/2),
								top: '+='+parseInt(heightOffset/2)
							  }, 100, 'linear'
							 );
						  }, 250);
						
																								
						pop.bind("mouseleave", function() {
														
							$(this).removeAttr('animating');							
							$(this).fadeOut(50, function () {
								  $(this).remove();
							});
						
						});
													
						pop.click( function() {
							$(this).removeAttr('animating');							
							$(this).fadeOut(50, function () {
								  $(this).remove();
							});
							gal.click();
						});
					}					
				});							
			});
		}
	}); 
	
}







