/**
 * GF Studio - jQuery plugin 2010
 * v 2.2
 *
 * Copyright (c) 2010 GF Studio SRL
 * http://www.gfstudio.com
 *
 * ToDo:
 *	1: aggiungere elementi mancanti alla funzione di validazione
 *	2: inserire un news ticker
 *	3: sistemare la funzione slides per consetire multiple slides in una pagina
 */

var $GF;

(function( $ )
{

	var _$ = $GF = $.sub();

	/**
	 * configuration
	 *
	 * configuration properties
	 */
	_$.config = {
		multilanguage 	: false,
		themedir		: ''
	};
	
	/**
	 * ut
	 */
	_$.ut = {
		arrayClean : function()
		{
			Array.prototype.clean = function( deleteValue )
			{
				for( var i = 0; i < this.length; i++ ){
					if( this[i] == deleteValue ){
						this.splice( i, 1 );
						i--;
					}
				}
				
				return this;
			};
		}
	};
	
	/**
	 * $GF.get
	 *
	 */

	_$.get = {
		
		/**
		 * $GF.get.IEversion
		 *
		 * return the current version of Microsoft Internet Explorer
		 */
		IEversion : $.browser.msie ? $.browser.version : -1,
		
		/**
		 * $GF.get.language
		 *
		 * return the current laguange
		 */
		language : $( 'html' ).attr( 'lang' ).substr( 0, 2 ),
		
		/**
		 * $GF.get.pages()
		 *
		 * return all the pages in address bar
		 */
		pages : function()
		{
			_$.ut.arrayClean();
			
			var pages = location.pathname.split( '/' ).clean( '' );
			
			if( !pages.length )
				return false;
			
			if( pages && _$.config.multilanguage && pages[0].length <= 2 )
				pages.shift();
			
			return pages;
		},

		/**
		 * page
		 *
		 * return the slug of the selected page
		 */
		page : function( index )
		{
			index = index || 0;
			
			var pages = _$.get.pages();
			
			return pages[index];
		}
		
	};

	/**
	 * is
	 *
	 * --------
	 */

	_$.is = {
		
		/**
		 * $GF.is.IE
		 *
		 * check if current browser is Microsoft Internet Explorer
		 */
		IE : $.browser.msie ? true : false,
		
		/**
		 * $GF.is.IE6
		 *
		 * check if current browser is Microsoft Internet Explorer 6.0
		 */
		IE6	: $.browser.msie && $.browser.version == '6.0' ? true : false,
		
		/**
		 * $GF.is.IE7
		 *
		 * check if current browser is Microsoft Internet Explorer 7.0
		 */
		IE7	: $.browser.msie && $.browser.version == '7.0' ? true : false,
		
		/**
		 * $GF.is.mobile
		 *
		 * check if the current agent is android || iphone || ipad
		 */
		mobile : ( /Android|iPhone|iPad/i ).test( navigator.userAgent ),
		

		/**
		 * $GF.is.page( string/array )
		 *
		 * check if the current page is one of the pages 
		 */
		page : function( name, index )
		{
			index = index || 0;
			
			var pages = _$.get.pages();
			
			if( name instanceof Array ){
				
				var nameSize = name.length;
				
				for( i=0; i<nameSize; i++ ) if( pages[index] == name[i] ) return true;
				
				return false;
				
			}
			
			return pages[index] == name
				 ? true
				 : false;
		},

		/**
		 * $GF.is.singlePage( string/array )
		 *
		 * check if we are viewing only the specified page
		 */
		singlePage : function( name, index )
		{
			index = index || 0;
			
			var pages = _$.get.pages();
			
			if( pages[1] )
				return false;
			
			if( name instanceof Array ){
				
				var nameSize = name.length;
				
				for( i=0; i<nameSize; i++ ) if( pages[index] == name[i] ) return true;
				
				return false;
				
			}
			
			return pages[index] == name
				 ? true
				 : false;
		},
		
		
		/**
		 * $GF.is.frontpage( string )
		 *
		 * check if we are viewing the front page
		 */
		frontpage : function( name )
		{
			name = name || 'home';
		
			var pages = _$.get.pages();
			
			if( !pages )
				return true;
			
			return !pages.length || pages[0] == name
				 ? true
				 : false;
		}
	};

	/**
	 * utilities
	 *
	 * --------
	 */
	
	_$.utility = {
		
		/**
		 * $GF.utility.randomNumber( int, int )
		 *
		 * return a random number from min to max
		 */
		randomNumber : function( min, max )
		{
			return Math.floor( min + Math.random() * ( max - min + 1 ) );
		}
	};

	/**
	 * $GF( 'selector' ).imgPreload( object )
	 *
	 * return a random number from min to max
	 */
	_$.fn.imgPreload = function( options )
	{
			/*
			if( $.fn.GF.isIE )
				return false;
			
			$( selector ).hide().each(function()
			{
				var $this	= $( this );
				var src 	= $this.attr( 'src' );
				var $img 	= $( '<img />' );
				
				$img.attr( 'src', src );
				$img.load( function()
				{
					$this.fadeIn();
					
					//$img = null;
				})
			});
			*/	
	};

	/**
	 * $GF.swfWrite( object )
	 *
	 * write swf movie using swf object
	 */

	_$.swfWrite = function( options )
	{

		var swf		   = $.extend(
		{
			'movie'			: 'myMovie.swf',
			'wrapper' 		: 'myWrapperID',
			'width'			: 300,
			'height'		: 300,
			'playerVersion' : '9.0.0',
			'installSwf'	: ''
		}, options.swf );
			
		var flashvars  = $.extend( {}, options.flashvars );	
		var attributes = $.extend( {}, options.attributes );
		var params 	   = $.extend( { 'menu' : false, 'wmode' : 'transparent' }, options.params );	
	
		if( !swfobject ){
			throw Error( 'la libreria swfobject non è stata trovata' );
		}
		
		swfobject.embedSWF( $GF.config.themedir + '/assets/swf/' + swf.movie, swf.wrapper, swf.width, swf.height, swf.playerVersion, swf.installSwf, flashvars, params, attributes );
		
	};

	/**
	 * $GF( 'selector' ).validate( object )
	 *
	 * ...
	 */
	_$.fn.validate = function( options )
	{
		var defaults = {
			errorClass		: 'error',
			requiredClass 	: 'required',
			error 			: '',
			success 		: ''
		};
	
		var opt 	= $.extend( defaults, options );
		var self 	= this;
		
		return this.each(function()
		{
			
			var $form = $( this );

			$form.submit(function()
			{
				
				var error 	= false;
				var filter	= /^[\w](([_\.-]?[\w]+)*)@([\w]+)(([\.-]?[\w]+)*)\.([A-Za-z]{2,})$/;
				var $inputs = $( this ).find( '.' + opt.requiredClass );
				
				$inputs.each(function()
				{
		
					var $input 			= $( this );
					var $prev			= $input.prev();
					var $next			= $input.next();
					var isPrevLabel 	= $prev.is( 'label' );
					var isNextLabel		= $next.is( 'label' );
					var isParentLabel	= $input.parent().is( 'label' );
					var isMail			= $input.attr( 'name' ).toLowerCase().indexOf( 'mail' ) > 0 ? true : false;
					
					if( !$input.val() || ( isMail && !filter.test( $input.val() ) ) || ( $input.is( 'input[type=checkbox]' ) && !$input.is( ':checked' ) ) ){
						$input.addClass( opt.errorClass );
						
						if( isPrevLabel )
							$prev.addClass( opt.errorClass );
						
						if( isNextLabel )
							$next.addClass( opt.errorClass );
						
						if( isParentLabel )
							$input.parent().addClass( opt.errorClass );
						
						if( !isPrevLabel && !isNextLabel && !isParentLabel )
							$input.parent().addClass( opt.errorClass );
						
						error = true;
					}
					else {
						$input.removeClass( opt.errorClass );
		
						if( isPrevLabel )
							$prev.removeClass( opt.errorClass );
						
						if( isNextLabel )
							$next.removeClass( opt.errorClass );
							
						if( isParentLabel )
							$input.parent().removeClass( opt.errorClass );
		
						if( !isPrevLabel && !isNextLabel && !isParentLabel )
							$input.parent().removeClass( opt.errorClass );
					}
		
				});
				
				if( error ){
					if( opt.error instanceof Function ){
						opt.error.form = $form[0];
						opt.error();
					}
					
					return false;
				}
				else {
					if( opt.success instanceof Function ){
						opt.success.form = $form[0];
						return opt.success();
					}
					
					return true;
				}
			});
			
		});

	};

	/**
	 * $GF( 'selector' ).validate( object )
	 *
	 * create a set of slides
	 */
	_$.fn.slides = function()
	{
		var defaults = {
		    menu 		: '#menu',
		    slider 		: '#slider',
		    activeClass : 'current-menu-item',
		    applyClass 	: 'self',
		    width 		: 800,
		    speed 		: 800,
		    easing		: null
		};
		
		var opt 		= $.extend( defaults, options );
		var $scroller	= $( opt.slider );
		
		$( opt.menu ).find( 'a' ).click(function()
		{
		    
		    var $this		= $( this );
		    var href 		= $this.attr( 'href' );
		    var $slide 		= $( href );
		    var range		= $slide.index() * opt.width;
		    
		    if( !$slide ) 
		    	return;
		
		    if( $this.parent().is( 'li' ) ){
		    
		    	if( opt.applyClass == 'self' )
		    		$this.addClass( opt.activeClass ).parent().siblings().children( 'a' ).removeClass( opt.activeClass );
		    	else
		    		$this.parent().addClass( opt.activeClass ).siblings().removeClass( opt.activeClass );
		    		
		    }
		    else {
		    
		    	if( opt.applyClass == 'self' )
		    		$this.addClass( opt.activeClass ).siblings().removeClass( opt.activeClass );
		    	else
		    		$this.parent().addClass( opt.activeClass ).siblings().removeClass( opt.activeClass );
		    
		    }
		
		    var optAnimate = {
		    	duration	: opt.speed,
		    	queue		: false
		    };
		
		    if( null !== opt.easing )
		    	optAnimate.easing = opt.easing;
		
		    $scroller.animate(
		    	{ marginLeft: -range  },
		    	optAnimate
		    );
		
		    
		    return false;
		});
	};

	/**
	 * $GF( 'selector' ).googlemap( object )
	 *
	 * insert google map in matched elements
	 */
	_$.fn.googlemap = function( options )
	{

		var defaults = {
			markers 	: [],
			type 		: 'roadmap',
			zoom		: 10,
			ui			: false,
			scale		: true,
			nav			: true,
			center		: ''
		};
			
		var opt = $.extend( defaults, options );
	
		var mapTypes = {
			hybrid		: 'HYBRID',
			roadmap		: 'ROADMAP',
			satellite	: 'SATELLITE',
			terrain		: 'TERRAIN'
		};
		
		return this.each(function()
		{
				
			var centers = opt.center 
						? opt.center.split( ',' ) 
						: opt.markers[0].coord.split( ',' ); 
	
			var mapOptions = {
				zoom				: opt.zoom,
				center				: new google.maps.LatLng( centers[0], centers[1] ),
				mapTypeId			: google.maps.MapTypeId[mapTypes[opt.type]],
				disableDefaultUI	: opt.ui,
				scaleControl		: opt.scale,
				navigationControl	: opt.nav
			};
	
			var map = new google.maps.Map( this, mapOptions );
			
			// adding markers
			var count = opt.markers.length;
			
			for( var i = 0; i < count; i++ ){
				
				var mark = opt.markers[i];
				
				var coords 			= mark.coord.split( ',' );
				var markerLatLng 	= new google.maps.LatLng( coords[0], coords[1] );
				
				var marker = new google.maps.Marker(
					{ position: markerLatLng, map: map }
				);
	
				if( mark.image )
					marker.icon = mark.image;
	
				if( mark.title )
					marker.title = mark.title;
	
				if( mark.content ){
	
					var infowindow = new google.maps.InfoWindow(
					{
						content: mark.content
					});
	
					if( mark.maxWidth )
						infowindow.maxWidth = mark.maxWidth;
	
					google.maps.event.addListener( marker, 'click', function()
					{
						infowindow.open( map, marker );
					});
				}
	
			}
			
		});
	};

	/**
	 * $GF( 'selector' ).ticker( object )
	 *
	 * create a news ticker
	 */

	_$.fn.ticker = function( options )
	{

		var opt = $.extend( 
		{
			pause 		: 3000,
			duration 	: 800,
			step		: 0,
			direction	: false
		}, options );
		
		return this.each(function()
		{
			var self = this, timer;
			
			var recycling = function()
			{
				$( this ).detach().appendTo( self ).removeAttr( 'style' );
				timer = setTimeout( detachFirst, opt.pause );			
			};
			
			var detachFirst = function()
			{
				var $first = $( self ).children().eq( 0 );
			
				if( !opt.direction ){
					$first.fadeOut( opt.duration, recycling );
				}
				else {
					
					$first.animate(
						opt.direction == 'left' ?
						{ marginLeft : -opt.step } :
						{ marginTop : -opt.step },
						{ queue: false, duration: opt.duration, complete: recycling }
					);
					
				}
				
			};
			
			timer = setTimeout( detachFirst, opt.pause );
			
		});
		
	};

	/**
	 * $GF( 'selector' ).lazy( object )
	 *
	 * create a lazy/fade effect for matched elements
	 */
	
	_$.fn.lazy = function( options )
	{
		
		var opt = $.extend( 
		{
			delay 			: 200,
			fadeDuration 	: 600
		}, options );
		
		var parameters = { opacity : 1 };
		
		return this.each(function( i )
		{
			var time  = opt.delay * i;
			var $this = $( this ).fadeTo( 0, 0 );
				
			setTimeout(function()
			{
				$this.animate(
					parameters,
					{ queue: false, duration: opt.fadeDuration }
				);				
			}, time );
		});
		
	};

	_$.cookie = 
	{ 
		set		: function( name, value, days )
		{
			if( days ){
				var date = new Date();
				date.setTime( date.getTime() + ( days*24*60*60*1000 ) );
				
				var expires = '; expires='+date.toGMTString();
			}
			else var expires = '';
			
			document.cookie = name + '=' + escape( value ) + expires + '; path=/';
		},
	
		get		: function()
		{
			var nameEQ 	= name + '=';
			var ca 		= document.cookie.split( ';' );
			var caSize 	= ca.length;
				
			for( var i=0; i<caSize; i++ ){
				var c = ca[i];
				while( c.charAt( 0 ) == ' ' ) c = c.substring( 1, c.length );
				
				if( c.indexOf( nameEQ ) == 0 ) return unescape( c.substring( nameEQ.length, c.length ) );
			}
			
			return null;
	
		},
		
		unset	: function()
		{
			var date = new Date();
			document.cookie = name+'=;path=/;expires=' + date.toGMTString();
		}
	};

})( jQuery );
