var thumbsData;
var thumbs;

function initImages(){
	
	// HIGHSLIDE
	
	hs.graphicsDir = 'images/highslideGraphics/';
	hs.align = 'center';
	hs.transitions = ['expand', 'crossfade'];
	hs.outlineType = 'drop-shadow'; //'glossy-dark' 'rounded-white'
	hs.fadeInOut = true;
	hs.wrapperClassName = 'dark borderless floating-caption';
	hs.captionEval = 'this.thumb.alt';
	hs.marginBottom = 105;
	allowMultipleInstances = false;
//	hs.dimmingDuration = 200;
	hs.dimmingOpacity = .5;
//	hs.expandDuration = 200;
	hs.easingClose = true;
	hs.showCredits = false;
	 
	
	// Add the controlbar
	if (hs.addSlideshow && hs.slideshows.length == 0) {
		hs.addSlideshow({
			slideshowGroup: 'group1',
			interval: 5000,
			repeat: false,
			useControls: true,
			fixedControls: 'fit',
			overlayOptions: {
				position: 'bottom right',
				hideOnMouseOut: true
			},
			thumbstrip: {
				position: 'bottom center',
				mode: 'horizontal',
				relativeTo: 'viewport'
			}
		});
	}
		
	hs.stripItemFormatter = function(a) {
		var aCloned = $(a).clone();
		var image = aCloned.children(":first");
		var newHeight = 80;
		var height = image[0].height;
		var width = image[0].width;
		if (width == 0){
			height = $(a).children(":first").height();
			width = $(a).children(":first").width();
		}
			
		var ratio = width / height;
		
		var newW, newH;
		if (ratio >= 1){ 
			newH = newHeight;
			newW = ratio * newHeight; 
		}
		else { // portrait
			newH = newHeight;
			newW = ratio * newHeight;
		}
		$(image).height(parseInt(newH) + 'px');
		$(image).width(parseInt(newW) + 'px');
		return aCloned.html();
	};

	hs.registerOverlay({
		html: '<div class="closebutton" onclick="return hs.close(this)" title="Close"></div>',
		position: 'top right',
		fade: 2 // fading the semi-transparent overlay looks bad in IE
	});
	hs.blockRightClick = true;
	
	if (config.toolTipEffect != 'none'){
		$(".contenu").tooltip({
			offset: [-195,-20],
			effect: config.toolTipEffect,
			tipClass: 'tool',
			delay: 30
		});
	}
}

function imagesThumbnails(){
	
	$('.mainFileLinkActivate').click(function(){
		$(".mainFileLink").toggle();
	});
	
	$(".mainFileLinkActivate").tipTip({
		delay: 0,
		edgeOffset: 7,
		defaultPosition: "top"
	});
	
	var easingStyle = "easeInSine";
	
	/***********
	 * OPTIONS *
	 **********/
	
	$('#optionsButton').button();
	$('#filter, #sort, #show').buttonset();
	
	$('#optionsButton').click(function(){
		$('#options').toggle();
		return false;
	});
	
	initImages();
	
	resizeImagesAbsoluteOnLoad(config.slider, thumbWidthMax, thumbWidthMin);
	
	if (config.showThumbsTitle == true){
		var thumbH = $('.thumbnail').height();
		$('.thumbnailTitle').show();
		$('.thumbnail').height(thumbH + 15);
		thumbsData.find('li').each(function (){
			$(this).height(thumbH + 15);
			$(this).find('.thumbnailTitle').show();
		});
		$("#showThumbnailsName").click();
	}
	
	$("#uploadLinkImg, #enlargeImagesSize, #decreaseImagesSize").tipTip({
		delay: 0,
		edgeOffset: 5,
		defaultPosition: "top"
	});
	
	(function($) {
		$.fn.sorted = function(customOptions) {
			var options = {
				reversed : false,
				by : function(a) {
					return a.text();
				}
			};
			$.extend(options, customOptions);
			$data = $(this);
			arr = $data.get();
			arr.sort(function(a, b) {
				var valA = options.by($(a));
				var valB = options.by($(b));
				if (options.reversed) {
					return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
				} else {
					return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
				}
			});
			return $(arr);
		};
	})(jQuery);
	
	$(function() {

		// bind radiobuttons in the form
		var optionsType = $('#options input[name="type"]');
		var optionsSort = $('#options input[name="sort"]');
		
		// attempt to call Quicksand on every form change
		optionsType.add(optionsSort).change(
			function(e) {
				if ($('#options input[name="type"]:checked').val() == 'all') {
					var filteredData = thumbsData.find('li');
				} else {
					var filteredData = thumbsData.find('li[data-type="' + $('#options input[name="type"]:checked').val() + '"]');
				}

				// if sorted by size
				if ($('#options input[name="sort"]:checked').val() == "size") {
					var sortedData = filteredData.sorted( {
						by : function(v) {
							return parseFloat($(v).find('span[data-type=size]').text());
						}
					});
				// if sorted by name
				} else if ($('#options input[name="sort"]:checked').val() == "name") {
					var sortedData = filteredData.sorted( {
						by : function(v) {
							return $(v).find('.thumbnailTitle').text().toLowerCase();
						}
					});
				// if sorted by downloads
				} else if ($('#options input[name="sort"]:checked').val() == "downloads") {
					var sortedData = filteredData.sorted( {
						by : function(v) {
							return $(v).find('td[data-type=downloads]').text().toLowerCase();
						}
					});
				}

				thumbs.quicksand(sortedData, {
					duration : 800,
					easing : easingStyle,
					adjustHeight: 'dynamic',
					useScaling: true
				}, function(){
					var addHeight = 0;
					if ($('#showThumbnailsName').attr('checked'))
						addHeight += 15;
					if ($('#showThumbnailsSize').attr('checked'))
						addHeight += 10;
					initImages();
				});
			}
		);
	});
	
	$("#slider").slider({
		value: config.slider,
		min: thumbWidthMin,
		max: thumbWidthMax,
		step: 10,
		slide: function(event, ui) {
			resizeImagesAbsolute(ui.value, thumbWidthMax, thumbWidthMin);
			$("#sliderValue").val(ui.value);
		},
		stop: function(event, ui){
			config.slider = ui.value;
			uploadConfig();
//			if ((thumbWidthMax < ui.value) || (thumbWidthMin > ui.value))
//				return;
			
			var heightAjust = 0;
			if (!$('.thumbnailTitle').is(':hidden'))
				heightAjust += 15;
			if (!$('.thumbnailSize').is(':hidden'))
				heightAjust += 10;
			
			thumbsData.find('li').each(function (){
				$(this).width(ui.value + thumbWidthDelta);
				$(this).height(ui.value + thumbWidthDelta + heightAjust);
				$(this).find('.thumbnailTitle').width(ui.value + thumbWidthDelta - 5);
				

				var img = $(this).find('img');
				var widthAndHeight = getWidthAndHeight($(img));
				var split = widthAndHeight.split("|");
				var width = parseInt(split[0]);
				var height = parseInt(split[1]);
				var ratio = width / height;
				var newW, newH;
				if (ratio >= 1){
					newW = ui.value;
					newH = newW / ratio; 
				}
				else { 
					newH = ui.value;
					newW = ratio * newH;
				}
				$(img).height(newH + 'px');
				$(img).width(newW + 'px');
				$(img).attr('width', parseInt(newH) + 'px');
				$(img).attr('height', parseInt(newW) + 'px');
			});
		}
	});
	
	$("#showThumbnailsName").click(function(){
		var thumbH = $('.thumbnail').height();
		if ($(this).attr('checked')){
			$('.thumbnailTitle').show();
			$('.thumbnail').height(thumbH + 15);
			thumbsData.find('li').each(function (){
				$(this).height(thumbH + 15);
				$(this).find('.thumbnailTitle').show();
			});
			config.showThumbsTitle = true;
			uploadConfig();
		}
		else {
			$('.thumbnailTitle').hide();
			$('.thumbnail').height(thumbH - 15);
			thumbsData.find('li').each(function (){
				$(this).height(thumbH - 15);
				$(this).find('.thumbnailTitle').hide();
			});
			config.showThumbsTitle = false;
			uploadConfig();
		}
		
	});
	
	$("#showThumbnailsSize").click(function(){
		var thumbH = $('.thumbnail').height();
		if ($(this).attr('checked')){
			$('.thumbnailSize').show();
			$('.thumbnail').height(thumbH + 10);
			thumbsData.find('li').each(function (){
				$(this).find('.thumbnailSize').show();
				$(this).height(thumbH + 10);
			});
		}
		else {
			$('.thumbnailSize').hide();
			$('.thumbnail').height(thumbH - 10);
			thumbsData.find('li').each(function (){
				$(this).height(thumbH - 10);
				$(this).find('.thumbnailSize').hide();
			});
		}
	});
	
	$("#switchViewThumb2").tipTip({
		delay: 0,
		edgeOffset: 5,
		defaultPosition: "top"
	});
	
	$("#sliderValue").val(config.slider);
	
	$('#zoomIn').click(function(){
		var delta = -10; // used the opposite value to prevent concatenation instead of addition 2 lines below 
		if (resizeImagesDelta(-delta, thumbWidthMax, thumbWidthMin)){
			$("#sliderValue").val($("#sliderValue").val() - delta);
			$("#slider").slider("value", $("#sliderValue").val());
		}
		return false;
	});
	
	$('#zoomOut').click(function(){
		var delta = 10;// used the opposite value to prevent concatenation instead of addition 2 lines below
		if (resizeImagesDelta(-delta, thumbWidthMax, thumbWidthMin)){
			$("#sliderValue").val($("#sliderValue").val() - delta);
			$("#slider").slider("value", $("#sliderValue").val());
		}
		return false;
	});
	
	removeAjaxEvents = function(){
		$('#page,.thumbnail,.highslide,.closebutton,.highslide,#slider').unbind();
		$("#tiptip_holder").remove();
	};
	
};

// Used with buttons
function resizeImagesDelta(delta, maxWidth, minWidth){
	var divThumbW = $('.thumbnail').width();
	var divThumbH = $('.thumbnail').height();
	var thumbW = divThumbW - thumbWidthDelta;
	var thumbH = divThumbH - thumbWidthDelta;
	if ((maxWidth < (thumbW + delta)) || (minWidth > (thumbW + delta))){
		return false;
	}
	$('.thumbnail').width(divThumbW + delta);
	$('.thumbnail').height(divThumbH + delta);
	$('.thumbnailTitle').width(divThumbH + delta - 5);
	$('.highslide img').each(function (){
		var height = $(this).height();
		var width = $(this).width();
		var ratio = width / height;
		var newW, newH;
		if (ratio >= 1){
			newW = width + delta;
			newH = newW / ratio; 
		}
		else { 
			newH = height + delta;
			newW = ratio * newH;
		}
		$(this).height(parseInt(newH) + 'px');
		$(this).width(parseInt(newW) + 'px');
	});
	
	thumbsData.find('li').each(function (){
		$(this).width(divThumbW + delta);
		$(this).height(divThumbH + delta);
		$(this).find('.thumbnailTitle').width(divThumbH + delta - 5);
		
		var img = $(this).find('img');
		var widthAndHeight = getWidthAndHeight($(img));
		var split = widthAndHeight.split("|");
		var width = parseInt(split[0]);
		var height = parseInt(split[1]);
		var ratio = width / height;
		var newW, newH;
		if (ratio >= 1){
			newW = width + delta;
			newH = newW / ratio; 
		}
		else { 
			newH = height + delta;
			newW = ratio * newH;
		}
		$(img).height(newH + 'px');
		$(img).width(newW + 'px');
		$(img).attr('width', parseInt(newH) + 'px');
		$(img).attr('height', parseInt(newW) + 'px');
	});
	
	return true;
}

function getWidthAndHeight (img){
	var style = img.attr("style");
	var iWidth = style.indexOf("width");
	var iHeight = style.indexOf("height");
	var width = style.substr(iWidth + 7, 3);
	var height = style.substr(iHeight + 8, 3);
	if (!is_int(width))
	    width = style.substr(iWidth + 7, 2);
	if (!is_int(height))
	    height = style.substr(iHeight + 8, 2);
	return width + "|" + height;
};

function is_int(input){
	return parseInt(input) == input;
}

function setStyle(width, height){
	return "width: " + width + "px; height: " + height + "px";
}

// Used with slider
function resizeImagesAbsolute(newWidth, maxWidth, minWidth){
	if ((maxWidth < newWidth) || (minWidth > newWidth))
		return;
	
	var heightAjust = 0;
	if (!$('.thumbnailTitle').is(':hidden'))
		heightAjust += 15;
	if (!$('.thumbnailSize').is(':hidden'))
		heightAjust += 10;
	
	$('.thumbnail').width(newWidth + thumbWidthDelta);
	$('.thumbnail').height(newWidth + thumbWidthDelta + heightAjust);
	$('.thumbnailTitle').width(newWidth + thumbWidthDelta - 5);
	
	$('.highslide img').each(function (){
		var height = this.height; 
		var width = this.width;
		var ratio = width / height;
		var newW, newH;
		if (ratio >= 1){
			newW = newWidth;
			newH = newW / ratio; 
		}
		else { 
			newH = newWidth;
			newW = ratio * newH;
		}
		$(this).height(parseInt(newH) + 'px');
		$(this).width(parseInt(newW) + 'px');
	});
}

function resizeImage(image, newWidth){
	var height = image.height;
	var width = image.width;
	var ratio = width / height;
	var newW, newH;
	if (ratio >= 1){
		newW = newWidth;
		newH = newW / ratio; 
	}
	else { 
		newH = newWidth;
		newW = ratio * newH;
	}
	$(image).height(parseInt(newH) + 'px');
	$(image).width(parseInt(newW) + 'px');
	
	thumbs = $('#thumbs');
	thumbsData = thumbs.clone();
}

// Used on page load
function resizeImagesAbsoluteOnLoad(newWidth, maxWidth, minWidth, addHeight){
	if ((maxWidth < newWidth) || (minWidth > newWidth)){
		return;
	}
	$('.thumbnail').width(newWidth + thumbWidthDelta);
	if (addHeight != undefined)
		$('.thumbnail').height(newWidth + addHeight + thumbWidthDelta);
	else
		$('.thumbnail').height(newWidth + thumbWidthDelta);
	$('.thumbnailTitle').width(newWidth + thumbWidthDelta - 5);
	$('.highslide img').each(function (){
		var height = this.height; 
		var width = this.width;
		var ratio = width / height;
		var newW, newH;
		if (ratio >= 1){
			newW = newWidth;
			newH = newW / ratio; 
		}
		else { 
			newH = newWidth;
			newW = ratio * newH;
		}
		if(height > 80){
			$(this).height(parseInt(newH) + 'px');
			$(this).width(parseInt(newW) + 'px');
		}
		if (isNaN(newW) || isNaN(newH) || isNaN(width) || isNaN(height)){
			$(this).load(function() { // Should execute only if images are not properly loaded in a fast way
				resizeImage(this, newWidth);
			});
		} else if (newW != width && newH != height){
			$(this).load(function() { // Should execute only if images are not properly loaded in a fast way
				resizeImage(this, newWidth);
			});
		}
	});
	
	thumbs = $('#thumbs');
	thumbsData = thumbs.clone();
}

(function ($) {
    // Monkey patch jQuery 1.3.1+ to add support for setting or animating CSS scale and rotation independently.
    // 2009 Zachary Johnson www.zachstronaut.com
    var rotateUnits = 'deg';
    
    $.fn.rotate = function(val) {
		var style = $(this).css('transform') || 'none';

		if (typeof val == 'undefined') {
			if (style) {
				var m = style.match(/rotate\(([^)]+)\)/);
				if (m && m[1]) {
					return m[1];
				}
			}
			return 0;
		}
		var m = val.toString().match(/^(-?\d+(\.\d+)?)(.+)?$/);
		if (m) {
			if (m[3]) {
				rotateUnits = m[3];
			}
			$(this).css('transform', style.replace(/none|rotate\([^)]*\)/, '') + 'rotate(' + m[1] + rotateUnits + ')');
		}
	};
    
    // Note that scale is unitless.
	$.fn.scale = function(val, duration, options) {
		var style = $(this).css('transform') || '';

		if (typeof val == 'undefined') {
			if (style) {
				var m = style.match(/scale\(([^)]+)\)/);
				if (m && m[1]) {
					return m[1];
				}
			}
			return 1;
		}
		$(this).css('transform', style.replace(/none|scale\([^)]*\)/, '') + 'scale(' + val + ')');
	};

    // fx.cur() must be monkey patched because otherwise it would always
    // return 0 for current rotate and scale values
    var curProxied = $.fx.prototype.cur;
	$.fx.prototype.cur = function() {
		if (this.prop == 'rotate') {
			return parseFloat($(this.elem).rotate());
		} else if (this.prop == 'scale') {
			return parseFloat($(this.elem).scale());
		}

		return curProxied.apply(this, arguments);
	};

	$.fx.step.rotate = function(fx) {
		$(fx.elem).rotate(fx.now + rotateUnits);
	};

	$.fx.step.scale = function(fx) {
		$(fx.elem).scale(fx.now);
	};
    
    var animateProxied = $.fn.animate;
	$.fn.animate = function(prop) {
		if (typeof prop['rotate'] != 'undefined') {
			var m = prop['rotate'].toString().match(/^(([+-]=)?(-?\d+(\.\d+)?))(.+)?$/);
			if (m && m[5]) {
				rotateUnits = m[5];
			}
			prop['rotate'] = m[1];
		}
		return animateProxied.apply(this, arguments);
	};
})(jQuery);

jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	}
});
