$(document).ready(function(){
	Utils.init();	
});


var Utils = {
	DEBUG : false,
	
	
	init: function(){
		Utils.placeholder();
		Utils.initTriangles();
		Utils.controlLogin();
		Utils.initSpecialBox();
		Utils.initVideoBox();
		Utils.initTrovaLavoro();
		Utils.initHoverBlue();
                
		/*SLIDERS*/
                if(typeof CarouselData != 'undefined')
                {                
                    $( '#carosello' ).MultiThumb105({ 
                            auto: true,
                            duration: 4000, //milliseconds
                            data: CarouselData, //the array with the items
                            followTriangle: true,//enable little triangle animation
                            followSquareYellow: true,
                            makeNielsen: true,
                            linkDetails: [ //the list of the links to update after transition
                                    '#carosello .title_preview > a', 
                                    '#carosello .desc_preview > a'
                            ]
                    });
                }
                
                if(typeof PhotogalleryData != 'undefined')
                {
                    $( '#photogallery' ).MultiThumb105({ 
                            auto: true,
                            duration: 5000,
                            data: PhotogalleryData,
                            textPreviewBox: '.desc',
                            makeNielsen: true,
                            arrows : '#photogallery .arrow',
                            linkDetails: [ 
                                    '#photogallery .photogallery_button'
                            ]
                    });		
                }
                
                if(typeof NewsData != 'undefined')
                {                
                    $( '#news_box' ).MultiThumb105({ 
                            auto: true,
                            duration: 5000,
                            data: NewsData,
                            makeNielsen: true,
                            textPreviewBox: '.desc',
                            arrows : '#news_box .arrow',
                            linkDetails: [ 
                                    '#news_box .hoverable a',
                                    '#news_box .desc_preview a'
                            ]
                    });
                }
		
		
		/*
$( '#news_box' ).cycle105({
			fx: 'slide'	
		});
*/
		
		
		
		$( '#webtv' ).webtv();
		
		/*END SLIDERS*/
		
		
		
		/*TEMP*/
		$( '#debug_button' ).click(function(){	$( '#debug_screen' ).toggle();	});
		/*TEMP*/
	},
	
	initTriangles: function(){
		$( '.with_triangle' ).each(function(){
			$( this ).append( $( '<div class="triangle"></div>' ) );
		})
	},
	
	placeholder: function(){
		$('.placeholder-compatibility').focus(function() {
			  var input = $(this);
			  if (input.val() == input.attr('placeholder')) {
				input.val('');
				input.removeClass('placeholder');
			  }
			}).blur(function() {
			  var input = $(this);
			  if (input.val() == '' || input.val() == input.attr('placeholder')) {
				input.addClass('placeholder');
				input.val(input.attr('placeholder'));
			  }
			}).blur();
			
			$('.placeholder-compatibility').parents('form').submit(function() {
			  $(this).find('.placeholder-compatibility').each(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
				  input.val('');
				}
			  })
			});
	},
	
	initSpecialBox: function(){
		$( '.specialbox' ).each(function(){
			$( '.title', this).append( $( '<div class="codina"></div>' ) );
		});
		
		//adapt columns height of classifica box to the higher column
		var maxHeight = 0;
		$( '.specialbox#classifica .list_rank > li' ).each(function(){
			if( $(this).height() > maxHeight ){
				maxHeight = $(this).height();
			}
		});
		$( '.specialbox#classifica .list_rank > li' ).height( maxHeight );
		
	},
	
	initVideoBox: function(){
		$( '.specialbox#video li' ).each(function(){

			$(this).append( '<a class="play_video" href="'+ $( '.video_preview_wrapper', $(this) ).attr( 'href' ) +'"></a>' );
		});
	},
	
	initTrovaLavoro: function(){
		$( '#trovolavoro form #trovalavoro_submit p' ).click(function(){
			$( '#trovolavoro form input[type=submit]' ).click();
		});
	},
	
	initHoverBlue: function(){
		$( '.hoverable' ).hover(function(){
			$( '*', $(this) ).each(function(){
				$(this).addClass( 'hover_blue' );
				$( 'a', $(this) ).addClass( 'hover_blue' );
				if( $(this).parent().hasClass( 'bg' ) ){
					$(this).addClass( 'with_bg' );	
				}
				
			});
		},function(){
			$( '*', $(this) ).each(function(){
				$(this).removeClass( 'hover_blue' );
				if( $(this).parent().hasClass( 'bg' ) ){
					$(this).removeClass( 'with_bg' );	
					$( 'a', $(this) ).removeClass( 'hover_blue' );
				}
			});
		});
	},
	
	controlLogin: function(){
		$( '#close_collapse' ).click(function(){
			Utils.closeLogin();
		});
		
		$( '.login_box .login' ).click(function(){
			if( $( '.login_collapse' ).css( 'display' ) == 'block' ){
				Utils.closeLogin();
			}
			else{
				Utils.openLogin();
			}
			
		});
		
	},
	
	openLogin: function(){
		$( '.login_collapse .tohide' ).hide();
			$( '.login_collapse' ).slideDown('fast', 'easeOutQuint', function(){
				$( '.login_collapse .tohide' ).fadeIn('fast');
		});	
	},
	
	closeLogin: function(){
		$( '.login_collapse .tohide' ).fadeOut('fast', function(){
			$( '.login_collapse' ).slideUp('fast', 'easeOutQuint', function(){});
		});
	},
	
		
	log : function(message){
		if( Utils.DEBUG ){
			console.info(message);
		}
	}	
    
}


$.fn.cycle105 = function(options){
	// default configuration properties
	var defaults = {			
		firstImageShowed: 0,
		auto: false,
		duration: 500,
		fx: 'fade',
		width: 262
	}; 
	
	var options = $.extend(defaults, options);  
			
	this.each(function() {  
		var obj = $(this);
		var lis = $( 'li', obj );
		var size = lis.length;
		var actualIndex = options.firstImageShowed;
		var firstTime = true;
		initEventListeners();
		if( options.fx == 'slide' ){
			buildSlider();
		}
			
		show( actualIndex );
		
		
		
		function initEventListeners(){
			$( '.arrow.next', obj ).click(function(){ next(); });
			$( '.arrow.prev', obj ).click(function(){ prev(); });
		}
		
		function buildSlider(){
			$( 'ul', obj ).width( size * options.width ).wrap( $( '<div />' ).addClass( 'slider_wrapper' ) );
			$( '.slider_wrapper' ).append( '<div class="clear"></div>' );
		}
		
		function show( index ){
			if( options.fx == 'slide' ){
				$( 'ul', obj ).animate( { left: -options.width * index }, 400, 'easeOutQuad' );
			}
			else{
				if(firstTime){
					firstTime = false;
					$( lis ).hide();
					$( lis[ index ] ).show();	
				}
				$( lis ).fadeOut( options.duration );
				$( lis[ index ] ).fadeIn( options.duration );
			}
		
			
			actualIndex = index;
			
		}
		
		function next(){
			var _index = actualIndex + 1;
			if( _index >= size ){
				_index = 0;
			}
			show( _index );
		}
		
		function prev(){
			var _index = actualIndex - 1;
			if( _index < 0 ){
				_index = size - 1;
			}
			show( _index );
		}
	});
};
	
$.fn.MultiThumb105 = function(options){
  
	// default configuration properties
	var defaults = {			
		firstImageShowed: 0,
		auto: false,
		duration: 10000,
		speedTransition: 600,
		data: [],
		previewBox: '.preview',
		imgPreviewBox: '.img_preview',
		textPreviewBox: '.preview .text_preview',
		thumbsBox: '.carousel_thumbs',
		arrows: '',
		linkDetails: [],
		makeNielsen: false,
		followTriangle: false,
		followSquareYellow: false,
		followHeight: false,
		startCodina: -516,
		offsetCodina: 103
	}; 
	var options = $.extend(defaults, options);  
			
	this.each(function() {  

		var obj = $(this); 	
		var lock = false;
		//var info = readInfo();
		var thumbsContainer, thumbs, preview, textPreview, actualIndex, theInterval, size;
		var lastInterval = -1;
		buildStructure();
		initEventListeners();
		show( options.firstImageShowed );
		if( options.auto ){
			startTimer();	
		}

		function buildStructure(){
			//build preview div
			size = options.data.length;
			preview = $( options.previewBox, obj);
			textPreview = $( options.textPreviewBox, obj);
			
			$( options.imgPreviewBox, obj).append( $( '<ul />' ) );
			
			//build thumbs
			thumbsContainer = $( options.thumbsBox, obj);
			
			if( options.followTriangle ){
				preview.append( '<div class="codina"><div class="codina_mobile"></div></div>' );
				
			}
			if( options.followSquareYellow ){
				preview.append( '<div class="square_selected"></div>' );
			}
			var img = '', a = '', li = '' ;
			for(var i = 0; i < options.data.length; i++ ){
				//append thumbs
				thumbsContainer.append( '<li id="li_'+ i +'"><a class="link_preview" href="javascript:;" ><img src="'+ options.data[ i ].thumb +'" /></a></li>' );
				
				//append preview
				img = $('<img />').attr( 'id', 'image_preview' ).attr( 'src', options.data[ i ].image );
				_a = $('<a />').attr('href', options.data[ i ].link ).append(img);
				li = $( '<li />' ).attr( 'id', 'img_preview_' + i ).append( _a );
				$( options.imgPreviewBox + ' > ul', obj).append( li );
				
			}
			$( 'li:last-child', thumbsContainer ).addClass( 'last' );
			$( '.codina li:last-child', obj ).addClass( 'last' );
			thumbs = $( 'li', thumbsContainer );
		}
		
		
		function initEventListeners(){
			$( thumbs ).click(function(){	

				var temp = $(this).attr( 'id' ).split( '_' );
				stopTimer();
				show( temp[ 1 ] );

				if( options.makeNielsen ){
					$( '#imrworldwide' ).remove();
					
					_img = $('<img />')
							.attr( 'src', '//secure-it.imrworldwide.com/cgi-bin/m?ci=105-it&cg=0&si=http%3A//www.105.net/imrworldwide-' + temp[ 1 ] + '&rnd=' + Math.random() )
							.attr( 'alt', '').attr( 'border', '0').attr( 'height', '1').attr( 'width', '1').attr( 'style', 'display:none;');
					div = $( '<div />' ).attr( 'id', 'imrworldwide' ).append( _img );
					$( '.square_selected').append( div );
				}				
			
			});
			
			if( options.arrows != '' ){
				$( options.arrows + '.prev' ).click(function(){ prev(); });
				$( options.arrows + '.next' ).click(function(){ next(); });
			}
			
			if( options.auto ){
				$( obj ).hover(function() {
			    	stopTimer();
				}, function() {
					startTimer();
				});
			}
			
			

		}
		
		function next(){
			if(obj.attr( 'id' ) == 'carosello' ){
				
			}
			
			if(lastInterval == theInterval){
				return;
			}
			
			lastInterval = theInterval;
			var _index = actualIndex + 1;
			if( _index >= size ){
				_index = 0;
			}
			show( _index );
		}
		
		function prev(){
			var _index = actualIndex - 1;
			if( _index < 0 ){
				_index = size - 1;
			}
			show( _index );
		}

		
		function show( index ){	
			if( index == actualIndex ){	return;	}
			
			stopTimer();
			
			
			//update thumbs
			thumbs.removeClass( 'selected' );
			if( !options.followSquareYellow ){
				$( '.square_selected', thumbsContainer ).remove();
				$(thumbs[ index ]).addClass( 'selected' ).append( '<div class="square_selected"></div>' );
			}
			
			$( 'li#img_preview_' + actualIndex, preview ).css( 'z-index', 1 );
			$( 'li#img_preview_' + index, preview ).show();
			
			//fix ie
			$( 'img', preview ).removeAttr( 'width' ).removeAttr( 'height' );
			
			
			//manage label new
			if (typeof options.data[ index ].is_new !== "undefined" && options.data[ index ].is_new === true){
				$( '.label_new', preview ).show();
			}
			else{
				$( '.label_new', preview ).hide();
			}
			
			
			$( 'li#img_preview_' + actualIndex, preview ).fadeOut( 'slow', function(){
				$( 'li', preview ).css( 'z-index', 0 );
				$( 'li:not(#img_preview_' + index+')', preview ).hide();
				$( 'li#img_preview_' + index, preview ).show();	
				
				
				updateLinks( index );
				startTimer();
			});
			
			
			if( options.followHeight ){
				var _height = $( 'li#img_preview_' + index + ' #image_preview', preview ).height();
				
				$(preview).animate({
					height: _height
					}, 500, function() {
				});		
			}
			
			if (typeof options.data[ index ].title !== "undefined"){
				$( '.title_preview a', textPreview ).html( options.data[ index ].title ).attr( 'href', options.data[ index ].link );
			}
			if (typeof options.data[ index ].desc !== "undefined"){
				$( '.desc_preview a', textPreview ).html( options.data[ index ].desc ).attr( 'href', options.data[ index ].link );
			}
			
			//animation triangle
			if( options.followTriangle ){
				var offsetToMove = parseInt(options.offsetCodina * index)
				var newLeft = parseInt(options.startCodina) + offsetToMove;
				$( '.codina .codina_mobile', obj ).animate({ left: newLeft + 'px' }, options.speedTransition, 'easeOutQuint');
				
			}
			if( options.followSquareYellow ){
				$( '.square_selected', obj ).animate({ left: offsetToMove + 'px' }, options.speedTransition, 'easeOutQuint');
			}
			actualIndex = parseInt(index); 
			
		}
		function updateLinks( index ){
			for( var i = 0; i < options.linkDetails.length; i++ ){
				$( options.linkDetails[ i ] ).attr( 'href', options.data[ index ].link );
			}
		}
		
		function startTimer(){
			stopTimer();
			theInterval = setTimeout(function(){
				next();
			}, options.duration );
			Utils.log('***startTimer: ' + theInterval);
		}
		
		function stopTimer(){
			Utils.log('***stopTimer: ' + theInterval);
			clearTimeout(theInterval);
		}
	});
};

$.fn.webtv = function(options){
  
	// default configuration properties
	var defaults = {			
		firstImageShowed: 0
	}; 
	
	var options = $.extend(defaults, options);  
			
	this.each(function() {  
		
		var obj = $(this); 	
		var channelList = $( '.channel_list li', obj );
                var channelView = $( '.channel_view li', obj );
                
		var channelDesc = $( '.channel_description li', obj );
		
		
		initEventListeners();
		
		
		show( options.firstImageShowed );
		
		function show( index ){
			selectChannelList( index );
			selectChannelView( index );
			selectChannelDescription( index );
		}
		
		function selectChannelList( index ){
			channelList.removeClass( 'selected' );
			$( channelList[ index ] ).addClass( 'selected' );
		}
		
		function selectChannelView( index ){
			channelView.hide();
			$( channelView[ index ]	).show();
		}
		
		function selectChannelDescription( index ){
			channelDesc.css( 'position', 'absolute' ).hide();
			$( channelDesc[ index ]	).css( 'position', 'relative' ).show();
		}
		
		function initEventListeners(){
			channelList.click(function(){
				var temp = $(this).attr( 'id' ).split( '_' );
				show( temp[ 1 ] );
			});
		}
	});
};


var GallerySlider = (function( doc ){
	
	//private var
	var WRAPPER 	= {},
		LIST 		= {},
		ARROW_R 	= {},
		ARROW_L 	= {},
		ITEMS		= 0,
		THUMB_W		= 90, //width of the el when are hidden
		MAIN_W		= 255, //width of the el when are visible	
		MARGIN		= 75,
		EVENT		= '',
		OPACITY		= .7,
		TIME		= 600,
		DELTA_W		= MAIN_W - THUMB_W,
		SAFE		= 2, //n of aux slides append on top and bottom	
		SUPPORT		= false,
		index 		= 1,
		last		= 3,
		lastText	= 2,
		DELTA_X		= 0,
		TEXT		= {},
		CONTROLS	= true,
		overlay;
	
	//private methods
	function _bindEvents(){
		
		ARROW_R.bind( EVENT , next );
		ARROW_L.bind( EVENT, prev );
		
	}
	
	function _supportCSS3(){
		
		div = doc.createElement('div');
		if( 'WebkitTransform' in div.style ){
			return '-webkit';
		}
		else{
			return false;
		}
		
	}
	
	
	function _animateSlider( direction ){
		if( direction === 'left' ){
			DELTA_X += THUMB_W;
			if( !SUPPORT ){
				//animate slider
				left = parseInt(LIST.css('left'));
				LIST.stop().animate({'left': left + THUMB_W},{duration:600,queue:false});			
			}
			else{
				//animate with css3 transform3d
				LIST.css( SUPPORT + '-transition-duration','700ms' );
				LIST.css( SUPPORT + '-transition-easing' , 'ease-in-out;' );
				LIST.css( SUPPORT + '-transform' , 'translate3d( '+ DELTA_X +'px, 0px , 0px )' );
			}
			
		}
		else if( direction === 'rigth' ){
			DELTA_X -= THUMB_W;
			if( !SUPPORT ){
				//animate slider
				left = parseInt(LIST.css('left'));
				LIST.animate({'left': left - THUMB_W},{duration:600,queue:false});
			}
			else{
				//animate with css3 transform3d
				LIST.css( SUPPORT + '-transition-duration','700ms' );
				LIST.css( SUPPORT + '-transition-easing' , 'ease-in-out;' );
				LIST.css( SUPPORT + '-transform' , 'translate3d( '+ DELTA_X +'px, 0px , 0px )' );
			}
	
		}
	
	}
	
	function _animateText( index , prevIndex, phase , fx ){

		var el 		 = TEXT.find('li[data-index=' + index + ']'),
			lastItem = TEXT.find('li[data-index=' + prevIndex + ']');
	
		
		//fade text
		if( phase === "show" ){
			el.fadeIn(_enableControl);
			
		}else{
			lastItem.fadeOut();
		}
		
		lastText = index;
				
	}	
	
	
	function _enableControl(){
		CONTROLS = true;
	}
	
	function _disableControl(){
		CONTROLS = false;
	}

		
	function init( el , overlay ){
		
		WRAPPER = $(el);
		LIST 	= WRAPPER.find('ul.img');
		LI 		= LIST.find('li'),
		ITEMS	= LI.length;	
		
		TEXT	= WRAPPER.find('ul.text');
		
		//arrow
		ARROW_R = WRAPPER.find('.arrowRight');
		ARROW_L = WRAPPER.find('.arrowLeft');
		
		//setup list length
		var w 		= ( (ITEMS-1) * THUMB_W ) + MAIN_W + 10,
			left 	= -THUMB_W;	
		LIST.width(w);
		
		//setup index
		first 	= 0;
		last  	= ITEMS-1;
		current = 3; 
			
		//setup li position
		LI.each(function(index){
			var el = $(this);
			
			if( index != 4 ){
				left += THUMB_W;
			}
			else{
				left += MAIN_W;
			}
			
			el.css('left',left);
			el.attr('data-index',index);
				
		});
		
		TEXT.find('li').each(function(index){
			$(this).attr('data-index',index);
		});
		
		//setup selected class on first item
		$(LI[3]).width(MAIN_W);

		TEXT.find('li[data-index=3]').fadeIn();

		
		//check css3 support
		SUPPORT = _supportCSS3();
		
		//check option
		overlay = (overlay == false)? overlay : true;
		
		//append span overlay or set opacity
		if( overlay ){
			WRAPPER.append('<span class="overlay overlayLeft"></span><span class="overlay overlayRight"></span>');
		}
		else{
			WRAPPER.append('<span class="overlayBlack overlayLeft"></span><span class="overlayBlack overlayRight"></span>');
		}
			
		
		EVENT = ( 'ontouchstart' in window )? 'touchstart' : 'click';
		
		_bindEvents();
	};
	
	function getItems(){
		return ITEMS;
	}
	
		
	function next(){		
		var left, aux, index , el, prevIndex;
		
		if( !CONTROLS )
			return false;
		
		index     = $(LI[current]).attr('data-index'); 
		el 	      = $(LI[current]),
		next  	  = $(LI[current+1]);
		prevIndex = next.attr('data-index'); 	
			
		//update classes current item
		
		//update classes next item
		left = parseInt(next.css('left'));
		

		el.animate({'width':THUMB_W},490);
		_disableControl();
		
		_animateText(prevIndex,index,'hide','fade');
		next.delay(0).animate({'left':left-DELTA_W,'width':MAIN_W},480, function(){ _animateText(prevIndex,index,'show','fade');} );
					
		//move first item to the end
		left = parseInt($(LI[last]).css('left'));
		$(LI[first]).css('left', left + THUMB_W);
			
		LI.push(LI[first]);
		LI.splice(0,1);
				
		_animateSlider('rigth');	
                
                // === CASGIN: se impostato imposto su campo hidden quale elemento visualizzato
                if($('#selctedCounter').length!=0)
                {
                    $('#selctedCounter').val(index);
                }                
		
	}
	
	function prev(){
		var left, aux, index, 
			el = $(LI[current]),prevIndex;
		
		if( !CONTROLS )
			return false;
		
		index 	  = el.attr('data-index');
		prevIndex = $(LI[current-1]).attr('data-index'); 	
		
		//update classes current item
		el.removeClass('selected');
		
		//update classes next item
		left = parseInt($(LI[current]).css('left'));
		_disableControl();
		
		 
		$(LI[current-1]).animate({'width':MAIN_W},490);
		_animateText(prevIndex,index,'hide','fade');
		el.delay(0).animate({'left':left+DELTA_W,'width':THUMB_W},500 , function(){ _animateText(prevIndex,index,'show','fade');} );
				
		//move first item to the end
		left = parseInt($(LI[first]).css('left'));
		$(LI[last]).css('left', left - THUMB_W);
			
		LI.splice(0,0,LI[last]);
		Array.prototype.pop.call(LI);
		
		_animateSlider('left');
                
                // === CASGIN: se impostato imposto su campo hidden quale elemento visualizzato
                if($('#selctedCounter').length!=0)
                {
                    $('#selctedCounter').val(index);
                }                
                

	}
	
	//public api
	return {
		init	: init,
		next 	: next,
		prev 	: prev,
		items	: getItems
	
	};	
		 
		
	
})(document);

