
$(window).resize(function(){
	resizeAll();
});

resizeAll = function () {
    $('.resizable').fitOnResize();
    $('.centered').center();
    $('#text-outerbox').almostFitHeight();
    stretchBackground();
}


/*
 * Global variable should be set in the template specific javascript
 */


// the img element of the thumb in the gallery of the image actually displayed
activeThumb = null;

// the distance of the cursor from the top of the page in pixel
mouseY = null;

// Duration of the animations in milliseconds
animationDuration = 500;

// The ratio between the center of the thumb gallery and the
// height of the stage
centerGalleryThumb = 0.5;

// The ratio of the size around the center of the center of the
// thumb gallery going over which the gallery doesn't scroll
noScrollZoneSize = 0.2;

// Ratio of the stage (width / height)
ratio = 4 / 3;

// Minimum width of the stage
minWidth = 980;

// the timeout object of the scrolling task
scrollThread = null;

/** 
 * scrolls the gallery thumb basing on the Y position of the mouse to determine the velocity
 */
//beginScrollThumbs = function() {
//	var delta = 0;
//	if (mouseY) {
//	   delta = (mouseY / $('#menu').height() - centerGalleryThumb);
//	   if (delta < noScrollZoneSize && delta > - noScrollZoneSize) {
//	   	   delta = 0;
//	   } else if (delta > noScrollZoneSize) { 
//           delta -= noScrollZoneSize;	   	
//	   } else if (delta < - noScrollZoneSize) {
//	   	   delta += noScrollZoneSize;
//	   }
//	   delta *= -15;
//	   delta *= delta *= delta;
//	}
//	if (delta != 0) {
//	   scrollThumbsWithDelta(delta);
//	}
//    scrollThread = setTimeout("beginScrollThumbs()", 100);
//}

/**
 * scrolls the gallery thumb of a delta number of pixel
 */
//scrollThumbsWithDelta = function (delta) {
//	/*
//	 * minOffset e maxOffset non devono essere calcolati rispetto
//	 * ai bordi della pagina ma rispetto al centro delle gallery
//	 */
//	var offset = $('#gallery-thumb').offset();
//    var minOffset = $('#menu').height() * centerGalleryThumb - $('#gallery-thumb').height();
//    var maxOffset = $('#menu').height() * centerGalleryThumb - $('#gallery-thumb img:first').height();
//    // mi assicuro che l'offset rimanga nei vincoli
//    if ( offset.top + delta > maxOffset ) {
//        delta = maxOffset - offset.top;
//    }
//    if ( offset.top + delta < minOffset ) {
//        delta = minOffset - offset.top;
//    }
//    $('#gallery-thumb').css({top: offset.top + delta});
//}

/**
 * remove the big image actually shown
 * cross fading it with the image clicked
 */
//switchBigImageWithThumb = function (thumbid) {
//	var i = indexOfThumbById(thumbid);
//    var bigImg = $('#big-img img');
//    var bigImgDiv = $(bigImg).parent();
//    var newBigImg = loadImage(
//        gallery[i].big,
//        {opacity: 0},
//        function () {
//        	$(newBigImg).fitHeight();
//	        $(bigImg).fadeTo(animationDuration, 0, function(){
//	        	$(newBigImg).css('left', (($(window).width() - 382)/2 - ($(newBigImg).width()/2)) + 'px');
//	        	$(bigImg).remove();
//	        	$(newBigImg).fadeTo(animationDuration, 1);
//	        })
//        }
//    );
//    $(bigImgDiv).appendChild(newBigImg);
//    $(newBigImg).addClass("resizable");
//}

/**
 * Call this function to select a thumb in the gallery
 * Switch the big image with selected one and update the
 * navigation links.
 * Then scroll to center the selected thumb.
 */
selectImage = function(thumb) {
    activeThumb = thumb;
//    scrollToThumb(activeThumb, null, function() {
//        updateGalleryNavigation($(thumb).attr('id'));
//        updateCaption($(thumb).attr('id'));
//    	switchBigImageWithThumb($(thumb).attr('id'));
//    });
}

//scrollToThumb = function(thumb, duration, callback) {
//	if (typeof duration == 'undefined' || duration == null) {
//		duration = animationDuration / 2;
//	}
//	
//	var newOffset = $('#gallery-thumb').offset().top -
////					$('#gender-navigation').offset().top -
//					$(thumb).offset().top;
//	
//    $('#gallery-thumb').animate(
//        {top: newOffset},
//        duration,
//        callback
//    );
//}

/**
 * Update the gallery navigation
 */
//updateGalleryNavigation = function(thumbid) {
//	var strPrev = translate.previous;
//	var strNext = translate.next;
//	
//	var i = indexOfThumbById(thumbid);
//	
//	// if don't find the image, return without doing anything
//	if ( i == -1 ) {
//		return;
//	}
//	
//	// update the image index
//	$('#gallery-actual-index').text(i + 1);
//	
//	// update the links
//	var path = sprintf('/%s/%s/%s/%s/', brand, season, gender, page);
//	$('#previous-link').parent().attr('href', path + i);
//	$('#next-link').parent().attr('href', path + (i+2));
//	bindNavigationLink(i);
//}

positionateCaption = function(caption) {
//	var captionWidth = caption.width();
//	caption.css('width', captionWidth);
//    var imgWidth = $('#big-img img').width();
//    var positionRight = $('#big-img').position().left + imgWidth;
//	caption.css('left', positionRight - captionWidth - 24 + 'px');
}

//updateCaption = function(thumbid) {
//	var i = indexOfThumbById(thumbid);
//    // if don't find the image, return without doing anything
//    if ( i == -1 ) {
//        return;
//    }
//    
//    if (gallery[i].caption != '') {
//    	$('#caption').html(gallery[i].caption);
//    } else {
//    	$('#caption').html(captioncommon);
//    }
//    positionateCaption($('#caption'));
//}

/**
 * find the index in gallery array
 */
indexOfThumbById = function(id) {
	var i = 0;
    while (i < gallery.length) {
        if ( gallery[i].id == id ) {
            break;
        }
        i++;
    }
    if ( i == gallery.length ) {
    	return -1;
    }
    return i;
}

bindNavigationLink = function(thumbindex) {
	$('#previous-link a').click( function(){
		selectImage( $('#' + $(gallery[thumbindex - 1]).attr('id') ) );
		return false;
	});
	$('#next-link a').click( function() {
		 selectImage( $('#' + $(gallery[thumbindex + 1]).attr('id') ) );
		 return false;
	});
}

/**
 * align text with the selected menu item
 */
alignToMenu = function(element) {
	var position = $('.selected').offset().top;
	element.css('top', position-4);
}


/**
 * Loads an image an return a reference to it
 */
loadImage = function(src, cssProperties, callback) {
	var i = new Image();
    i.src = src + '?seed=' + Math.floor(Math.random()*9999999);
    if (typeof callback == 'function') {
        i.onload = callback;
    }
    $(i).css(cssProperties);
    return i;
}


setBackgroundImg = function (src) {
	/*$('body').css({
        backgroundImage: "url('" + src + "')"
    });*/
    var image = loadImage(src, {position:'absolute', top: '0px', left: '0px', height: $(window).height(), width: $(window).width()});
    $(image).addClass('resizable');
    $(image).addClass('resize-stretch');
    $('body').appendChild(image);
}

/**
 * Check if the browser is IE 6 --
 */
isIE6orLess = function() {
	var b = BrowserDetect.browser;
	var v = BrowserDetect.version;
	if (b=="Explorer") {
		return true;
	} else {
		return false;
	}
}
/**
 * Plugin to add an image element to a div
 */
$.fn.appendChild = function(element){
    return this.each(function(){
        this.appendChild(element);
    });
}

$.fn.fitOnResize = function() {
	return this.each(function () {
        if ( $(this).hasClass('resize-width') ) {
        	$(this).fitWidth();
        } else if ( $(this).hasClass('resize-stretch') ) {
        	$(this).stretch();
        } else { // default or on resize-height
        	$(this).fitHeight();
        }
	});
}

/**
 * Resize a div mantaining the actual ratio
 * to fit the height.
 * The #stage can not be narrower than minWidth
 */
$.fn.fitHeight = function(minHeight) {
	return this.each(function(){
		// Le immagini non caricate hanno un'altezza pari alla lineHeight se c'� test nell'attributo alt
		// del lineHeight prendo solo le cifre
		//var reg = /^(\d+)/i;
        //var ar = reg.exec( $(this).css("lineHeight") );
        // alert($(this).css("lineHeight"));
        if ($(this).height() > 50 & $(this).width() != 0) {
        	var finalHeight = $(window).height() - $('#footer').height();
			var scale = finalHeight / $(this).height();
		    if ( $(this).is('#stage') ) {
		    	var height = $(this).height() * scale|0;
		    	$(this).css({
                    height: $(this).height() * scale|0,
                    width: Math.max(height * ratio, minWidth)
                });
		    } else {
	            $(this).css({
	                height: $(this).height() * scale|0,
	                width: $(this).width() * scale|0
	            });
		    }
        } else {
        	$(this).load(function(){
        		$(this).fitHeight();
        	});
        }
	});
}

/**
 * Resize a div to fit the width.
 * The height is the height of the stage.
 * Used mainly for the comingsoon background in deg
 */
$.fn.fitWidth = function(minWidth) {
    return this.each(function(){
        // Le immagini non caricate hanno un'altezza pari alla lineHeight se c'� test nell'attributo alt
        // del lineHeight prendo solo le cifre
        //var reg = /^(\d+)/i;
        //var ar = reg.exec( $(this).css("lineHeight") );
        // alert($(this).css("lineHeight"));
        if ($(this).height() != 0 && $(this).width() > 50) {
            var finalWidth = $(window).width();
            var scale = finalWidth / $(this).width();
            if ( $(this).is('#stage') ) {
                $(this).css({
                    height: $(window).height() - $('#footer').height(),
                    width: $(this).width() * scale|0
                });
            } else {
	            $(this).css({
	                height: $(this).height() * scale|0,
	                width: $(this).width() * scale|0
	            });
            }
        } else {
            $(this).load(function(){
                $(this).fitWidth();
            });
        }
    });
}

$.fn.almostFitHeight = function() {
	return this.each(function(){
		var height = $('#stage').height() - $(this).offset().top - 180;
		$(this).css({
			height: height
		});
	});
}

$.fn.fit = function(element) {
    return this.each(function(){
    	if (typeof element == 'undefined') {
    		element = $(this).parent();
    	}
        if ($(this).height() != 0 && $(this).width() != 0) {
            var scaleY = $(element).height() / $(this).height();
            var scaleX = $(element).width() / $(this).width();
            scale = Math.min(scaleY, scaleX);
            $(this).css({
                height: ($(this).height() * scale)|0,
                width: ($(this).width() * scale)|0
            });
        } else {
        	$(this).load(function(){
                $(this).fit();
            });
        }
    });
}

$.fn.stretch = function(element) {
    return this.each(function(){
        if (typeof element == 'undefined') {
            element = $(this).parent();
        }
        $(this).css({
            height: $(element).height()|0,
            width: $(element).width()|0
        });
    });
}

/**
 * 
 */
$.fn.moveToFront = function() {
	return this.each(function(){
        var cloneElem = $(this).clone();
        cloneElem.addClass('clone-element');
        $(cloneElem).css({
            position: 'absolute',
            top: 0,
            right: '138px'
        });
        $('#stage').append(cloneElem);
    });
}

$.fn.center = function (relativeTo) {
	return this.each(function(){
		if (typeof relativeTo == 'undefined') {
		    var parentNode = $(this).parent();
		} else {
			parentNode = $(relativeTo);
		}
		if ($(this).height() != 0 && $(this).width() != 0) {
			var left = ( $(parentNode).width() - $(this).width() ) / 2;
			var top = ( $(parentNode).height() - $(this).height() ) / 2;
			if ( $(this).hasClass('centered-top') ) {
				top = 0;
			} else if ( $(this).hasClass('centered-bottom') ) {
	            top *= 2;
	        } else if ( $(this).hasClass('centered-left') ) {
	            left = 0;
	        } else if ( $(this).hasClass('centered-right') ) {
	            left *= 2;
	        }
			$(this).css({
		        position: 'absolute',
		        top: top,
		        left: left
			});
		} else {
			 $(this).load(function(){
                $(this).center();
            });
		}
    });
}

/*
 * Plugin Image loaded
 */
/*
observeLoadingSelector = '';

observeLoading = function (selector) {
	if (observeLoadingSelector != '') {
		observeLoadingSelector += ',';
	}
	observeLoadingSelector += selector
	$(document).ready(function(){
	    $(selector).load(function(){
	        $(this).addClass('plugin-loaded');
	    });
	});
}

$.fn.isLoaded = function () {
	return $(this)
}
*/

/**
 * Plugin per il logging
 */
$.fn.log = function (msg) {
    //var now = new Date();
    //console.log("%s: %o - %d:%d:%d", msg, this, now.getHours(), now.getMinutes(), now.getSeconds());
    return this;
};


function stretchBackground() {
	var bg = $('#background img');
	var winWidth = $(window).width();
	var winHeight = $(window).height();
	/*var winRatio = winHeight / winWidth;
	var bgRatio = bg.height() / bg.width();
	
	if (bgRatio < winRatio) {
		bg.height(winHeight);
	} else {
		bg.width(winWidth);
	}*/

	bg.height(winHeight);
	bg.width(winWidth);
}

function positionSplashFigures() {
	$('.splash-image-man').css('left', donnaSize + manPosition.left - 80 + 'px');
}
