/**
 * @author 
 */

/**
 * The page state
 */
var state = {	
	homepage : true,
	fragment : null,
	changingFragment : false,
	mainMenuItemClicked : '',
	menuItem : {
		id      : '',
		'class' : '',
		href    : '',
		type    : ''
	},
	pageLoad : {
		request      : null,
		divcontainer : null,
		whereToLoad  : null,
		menuid       : null
	}
};

function getItemObject( jqueryObj, objType ) {
	var newObject = {
		id      : jqueryObj.attr('id'),
		'class' : jqueryObj.attr('class'),
		href    : jqueryObj.attr('href'),
		type    : objType
	};
	return newObject;
}

/**
 * pop-up a new window 
 * 
 * @param mylink
 * @param windowname
 * @param width
 * @param height
 * @returns {Boolean}
 */
function popup(mylink, windowname, width, height)
{
	if (! window.focus)
		return true;
	var href;
	if (typeof(mylink) == 'string')
	   href=mylink;
	else
	   href=mylink.href;
	if( !width  ) width = '400';
	if( !height ) height = '300';
	
	var properties = 'width='+width+',height='+height+',scrollbars=yes,location=no,toolbar=no';
	window.open(href, windowname, properties);
	return false;
}


function removeLoading() {
	$('#loading').animate({opacity : 0} ,0);
}

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

/**
 * 
 */
function startAdGallery() {

	if( typeof $('.ad-gallery').adGallery == 'undefined' ) {
		pausecomp(1500);
	}

	var galleries = $('.ad-gallery').adGallery({
	  loader_image: '/ctw/images/ad-gallery/loader.gif',
	  width: 600, // Width of the image, set to false and it will read the CSS width
	  height: 400, // Height of the image, set to false and it will read the CSS height
	  thumb_opacity: 1, // Opacity that the thumbs fades to/from, (1 removes fade effect)
	                      // Note that this effect combined with other effects might be resource intensive
	                      // and make animations lag
	  start_at_index: 0, // Which image should be displayed at first? 0 is the first image
	  animate_first_image: false, // Should first image just be displayed, or animated in?
	  animation_speed: 400, // Which ever effect is used to switch images, how long should it take?
	  display_next_and_prev: true, // Can you navigate by clicking on the left/right on the image?
	  display_back_and_forward: true, // Are you allowed to scroll the thumb list?
	  scroll_jump: 0, // If 0, it jumps the width of the container
	  slideshow: {
	    enable: true,
	    autostart: false,
	    speed: 5000,
	    start_label: 'Start',
	    stop_label: 'Stop',
	    stop_on_scroll: true, // Should the slideshow stop if the user scrolls the thumb list?
	    countdown_prefix: '(', // Wrap around the countdown
	    countdown_sufix: ')',
	    onStart: function() {
	      // Do something wild when the slideshow starts
	    },
	    onStop: function() {
	      // Do something wild when the slideshow stops
	    }
	  },
	  effect: 'slide-hori', // or 'slide-vert', 'resize', 'fade', 'none' or false
	  enable_keyboard_move: true, // Move to next/previous image with keyboard arrows?
	  cycle: true, // If set to false, you can't go from the last image to the first, and vice versa
	  // All callbacks has the AdGallery objects as 'this' reference
	  callbacks: {
	    // Executes right after the internal init, can be used to choose which images
	    // you want to preload
	    init: function() {
	      // preloadAll uses recursion to preload each image right after one another
	      //this.preloadAll();
	      // Or, just preload the first three
	      this.preloadImage(0);
	      //this.preloadImage(1);
	    },
	    // This gets fired right after the new_image is fully visible
	    afterImageVisible: function() {
	      // For example, preload the next image
	      var context = this;
	      this.loading(true);
	      this.preloadImage(this.current_index + 1,
	        function() {
	          // This function gets executed after the image has been loaded
	          context.loading(false);
	        }
	      );
	
	      this.settings.effect = 'slide-hori';
	    }
	    // This gets fired right before old_image is about to go away, and new_image
	    // is about to come in
	    ,beforeImageVisible: function(new_image, old_image) {
	      // Do something wild!
	    }
	  }
	});

	galleries[0].settings.effect = 'fade';
}

/* **************************************************************************
 *   C a l e n d a r
 * **************************************************************************/

function activateCalendar() {
	// activate behavior on calendar rows
	if( $('#workshops .information').length ) {
		$('#workshops .calendar-info').hide();
		$('#workshops .calendar-row').each( function() {
				$(this)
					.hover( function() { $(this).css({'background-color':'#C7FF8E', 'cursor':'pointer'}); },
							function() { $(this).css('background-color', 'transparent'); })
					.click( function() { $(this).next('.calendar-info').first().toggle();
				});
		});
	}
}

/* **************************************************************************
 *   T o u r
 * **************************************************************************/

function activateTour() {
	if( $('#tour').length ) {
		$('#tour .tour-old').hide();
		$('#tour  h3.tour-year').each( function() {
			$(this)
				.hover( function() { $(this).css({'background-color':'#C7FF8E', 'cursor':'pointer'}); },
						function() { $(this).css('background-color', 'transparent'); })
				.click( function() { $(this).next('.tour').first().toggle();
			});
		});
	}
}

/* **************************************************************************
 *   R e v i e w s
 * **************************************************************************/

function activateReviews() {
	$('.reviews-doc a').hover(function(e) {
		var href = $(this).attr('href');
		$('<img id="large-review" src="' + href + '" alt="big image" />')
		.prependTo('body');
		setReviewViewerPosition(e, $("#large-review") );
	}, function() {
		$('#large-review').remove();
	})
	.mousemove(function(e) {
		setReviewViewerPosition(e, $("#large-review") );
	})
	.click( function() {
		popup( $(this).attr('href'), $(this).attr('title'), 800, 600 );
		return false;
	});
}

function setReviewViewerPosition( e, imageViewer ) {
	var topMargin = 10;
	var yOffset   = 8;
	var xOffset   = 8;
	
	var mouseY = e.pageY;
	var mouseClientY = e.clientY;
	var imageViewerHeight = imageViewer.height();
	
	var imageViewerY;
	var imageViewerX;
	
	if (mouseClientY > (imageViewerHeight+topMargin+yOffset)) {
		imageViewerY = mouseY - (yOffset + imageViewerHeight); 
	} else {
		imageViewerY = mouseY-mouseClientY+topMargin;
	}
	imageViewerX = e.pageX + xOffset;
	
	imageViewer.css({
		top:  (imageViewerY) + "px",
		left: (imageViewerX) + "px"
	});
}

/* **************************************************************************
 *   N a v i g a t i o n
 * **************************************************************************/

function applyFragment() {

	var fragment = $.deparam.fragment();
	if( typeof fragment.id != 'undefined' ) {
		for( var key in fragment ) {
			state.menuItem[key] = fragment[key];
		}
		state.mainMenuItemClicked = getMainMenuClickedFromId(state.menuItem.href);
	} else {
		// no fragment. I'm in homepage
		state.menuItem.id = null;
		state.menuItem['class'] = null;
		state.menuItem.href = 'index.html';
		state.menuItem.type = '';
		state.homepage = true;
	}
}

function getMainMenuClickedFromId( aLink ) {

	var menuId = '';
	var items = aLink.split( '/' );
	if( items.length == 1 ) {
		menuId = items[0].replace( 'all_content_', '').replace( '.html', '');
	} else {
		menuId = items[0];
	}

	return 'menu-' + menuId;
}

function setStateFromItem( menuItem ) {
	
	var type           = menuItem.type;
	var divcontainer   = $('.container').attr('id');
	var menuid         = menuItem.id;
	var file           = '';
	var whereToLoad; 

	state.fragment = '#' + $.param( 
			{ id     : menuid, 
			  'class': menuItem['class'],
			  href   : menuItem.href,
			  type   : type
			}).replace( /%2F/i, '/');

	if( type == 'first' ) {
	    menuid = menuid.substring(5);
	    whereToLoad = $('#main');

	    // Clicking the same menu. Nothing to do
		if( divcontainer == menuid && $('.content').length == 0 ) {
			return false;
		}
	} else {
		// exception for transgression
		if( 'transgression-1' == menuid ) {
			menuid = 'transgression';
		}
		whereToLoad = $('#'+divcontainer);
	}
	file = menuItem.href;
		
	var request = file + '?ajax=true' +' #' + menuid;

	state.pageLoad.request      = request;
	state.pageLoad.whereToLoad  = whereToLoad;
	state.pageLoad.divcontainer = divcontainer;
	state.pageLoad.menuid       = menuid;
}

function setNavigation( menuItem ) {

	setStateFromItem( menuItem );
	
	// update fragment. The event will fire loading of new content
	location.hash = state.fragment;
}

function setSecondaryMenuAnimations() {
	$('#sec-nav a span').each( function(i) {
		// set behaviour for images
		$(this).siblings().hover( function() { 
									$(this).css('border-color', '#043F03'); },
	  							  function() { 
									$(this).css('border-color', 'transparent');
		});
	
		// set behaviour for span
		$(this).hover( function() {	$(this).siblings().css('border-color', '#043F03'); }, 
					   function() {	$(this).siblings().css('border-color', 'transparent'); }
					 );
	});

	// Exception for transgression
	if( $('#sec-nav #transgression').length ) {
		$('#sec-nav #transgression').hover(
			function() { $('#sec-nav #transgression-1 img').mouseover(); $('#sec-nav #transgression-1').mouseover(); },
			function() { $('#sec-nav #transgression-1 img').mouseout(); $('#sec-nav #transgression-1').mouseout(); } 
		);
	
		$('#sec-nav a#transgression-1 span').hover( 
			function() { $('#sec-nav a[href$=transgression.html] img').css('border-color', '#043F03'); }, 
			function() { $('#sec-nav a[href$=transgression.html] img').css('border-color', 'transparent'); }
		);
	}
}

function setSecondaryNavBehaviour(){

	// Secondary Menu animation
	setSecondaryMenuAnimations();
	
	// activate behaviour on tour rows
	activateTour();

	$('#sec-nav a').click( function() {
		state.menuItem = getItemObject( $(this), '' );
		setNavigation( state.menuItem );

		return false;
	} );
}

function turnHomePageStyle( onOrOff ) {

	$('#main_nav a.active').removeClass('active');

	if( onOrOff == 'on' ) {
		$('#masthead').addClass('home');
		$('#mood').removeClass('filled');
		$('#background-container img').show();
		$('#main .container').html('');
		$('#main').css('opacity', 0);
	} else if( state.homepage ){
		$('#masthead').removeClass('home');
		$('#mood').addClass('filled');
		$('#background-container img').hide();	
	}
}

$(document).ready(function() {

	// perform a Search Engine Friendly redirect:
	// 1. Serves the real content to the bots, but
	// 2. Do a javascript redirect to the dynamically built page	
	var URLData1 = /all_content_(.+)\.html$/g.exec(window.location.pathname);
	if( URLData1 && URLData1.length ) {
		$('#main').hide();
		var item = URLData1[1];
		window.location = '/index.html#id=menu-' + item + '&class=active&href=all_content_' + item  + '.html&type=first';
		return false;
	}

	var URLData2 = /^\/(.+)\/(.+)\.html$/g.exec(window.location.pathname);
	if( URLData2 && URLData2.length ) {
		$('#main').hide();
		var item = URLData2[1];
		var page = URLData2[2];
		window.location = '/index.html#id=' + page + '&class=&href=' + item + '/'+ page +'.html&type=';
		return false;
	}
	
	// switch off effects for old browsers
	var isIE6_7 = /MSIE (6|7)/i.test(navigator.userAgent);
	
	if( isIE6_7 ) {
		jQuery.fx.off = true;

		var ieCookie = jQuery.cookie("ctw_ie_6_7");
		if( ieCookie == null ) {
			var sorry_en  = 'Sorry, you\'re using an unsopported browser.\nPlease install one of these :\n';
			var sorry_it  = 'Stai usando un browser non supportato.\nPer favore, utilizza uno di questi :\n';
			var userLang  = navigator.userLanguage;
			var sorry     = ((userLang == 'it') ? sorry_it : sorry_en);
			var sorryList = '\nGoogle Chrome  (ww.google.com/chrome)\nFirefox  (www.mozilla.com)\nInternet Explorer 8 (http://www.microsoft.com/windows/internet-explorer/default.aspx)';

			$.cookie("ctw_ie_6_7", "y", { expires: 7 });
			var alertString = sorry + sorryList;
			alert(alertString);
		}
	}

	$('#main_nav a, #branding a#menu-spazio').click( function() {

		state.menuItem = getItemObject( $(this), 'first' );
		setNavigation( state.menuItem );

		return false;
	} );

	// apply state : go to last viewed page
	if( location.hash ) {
		$(window).trigger('hashchange');
	}
});

// listen to hash changes (back button of browser)
$(window).bind('hashchange', function (e) {
	
	applyFragment();
	setStateFromItem( state.menuItem );
	
	// change style : only the first time
	if( state.menuItem.href == 'index.html' ) {
		turnHomePageStyle( 'on' );
		return;
	} else {
		turnHomePageStyle( 'off' );
		state.homepage = false;
		try {
			$( '#'+state.mainMenuItemClicked ).addClass('active');
		} catch(e) {}
	}
	
	// Load new content
	$('#main').animate({opacity : 0}, 300, "", function() {

		var divcontainer = state.pageLoad.divcontainer;
		
		$('#mood').addClass('loading-link');
		state.pageLoad.whereToLoad.load( state.pageLoad.request, function() {

			// show all content (and possible scrollbar!)
			$('#'+divcontainer).removeClass('fixed');

			// Loads additional behaviour for secondary navigation
			if( $('#tabs').length )
				$("#tabs").tabs();
			
			if( $('#gallery-container div.ad-gallery').length ) {
				try{ 
					startAdGallery();
				} catch(e) {}
			}

			activateCalendar();
			activateReviews();
			
			// exception for labo, which is a div nested one level more 
			if( $('#education div#labo').length ) {
				setSecondaryNavBehaviour();
			}
			
			// change behavior of back to top buttons
			$('.gotop a').each( function(){
				$(this).click( function() {
					$( 'html, body' ).animate( { scrollTop: 0 }, 0 );
					return false;
				});
			});

			if( state.menuItem.type == 'first' ) {
				setSecondaryNavBehaviour();
			}

			$('#mood').removeClass('loading-link');
			$('#main').animate({opacity : 1} ,300);
		});
	});
});	

jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

