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

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

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

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

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(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;
};

var ultimeNotizieTimer;

function ultimeNotizieTicker() {
	$('#ultime-notizie li:visible').fadeOut('slow', function() {
		var next = $(this).next('li');
		
		if (next.length) {
			next.fadeIn('slow');
		} else {
			$(this).parent().find('li:first').fadeIn('slow');
		}
		
		ultimeNotizieTimer = setTimeout('ultimeNotizieTicker()', 5000);
	});
};

function startNewsTicker() {
	ultimeNotizieTimer = setTimeout('ultimeNotizieTicker()', 5000);
}

$(document).ready(function () {
	var isMobile = DetectTierIphone();
	
	if (DetectIphoneOrIpod()) {
		if (!pageYOffset) window.scrollTo(0, 1);
	}
	
	startNewsTicker();
	
	$('#bottone-prossima-news').click(function (e) {
		e.preventDefault();
		clearTimeout(ultimeNotizieTimer);
		ultimeNotizieTicker();
	});
	
	/* !POPUP NAVIGAZIONE */
	if (!isMobile) {
		$('#nav-azienda, #rm_menu_azienda > div').hover(
			function () {
				$('#rm_menu_azienda').show();
			},
			function () {
				$('#rm_menu_azienda').hide();
			}
		);
			
		$('#nav-soluzioni, #rm_menu_soluzioni > div').hover(
			function () {
				$('#rm_menu_soluzioni').show();
			},
			function () {
				$('#rm_menu_soluzioni').hide();
			}
		);
		
		$('#nav-consulenza, #rm_menu_consulenza > div').hover(
			function () {
				$('#rm_menu_consulenza').show();
			},
			function () {
				$('#rm_menu_consulenza').hide();
			}
		);
	}
		
	$('.popup-panel > div').click(function (e) {
		e.stopPropagation();
	});
	
	$(document).click(function (e) {
		$('.popup-panel').fadeOut('fast');
	});
	
	$('.carousel').slides({
		preload: true,
		preloadImage: '/images/loading.gif',
		container: 'slide-container',
		next: 'slide-avanti',
		prev: 'slide-indietro',
		pagination: false,
		generatePagination: false,
		autoHeight: true
	});
	
	// play: 5000
	
	if (!isMobile) {
		$('.carousel.image .slide-item a').fancybox({
			cyclic: true
		});
		
		$('.carousel.video .slide-item a').fancybox({
			cyclic: true,
			showNavArrows: false
		});
	} else {
		$('.carousel .slide-item a').attr('target', '_blank');
	}
	
	/* !TODO Questo serve a far funzionare la paginazione delle liste di box blu nei prefooter (finchè non si trova un modo di usare slidejs. */
	$('.slide-list').each(function() {
		var list = $(this);
		var pagination = $('<div class="slide-pagination"/>');
		var paginationElementTpl = $('<a class="slide-pagination-element">a</a>');
		
		if ($(this).find('.list-item').length > 1) {
			for (var i = 0; i < $(this).find('.list-item').length; i++) {
				var paginationElement = paginationElementTpl.clone()
				pagination.append(paginationElement);
				
				paginationElement.click(function(e) {
					e.preventDefault();
					var self = this;
					pagination.find('.slide-pagination-element').removeClass('current');
					$(this).addClass('current');
					list.find('.list-item:visible').fadeOut('fast', function() {
						list.find('.list-item:nth-child(' + ($(self).index() + 1) + ')').fadeIn();
					});
				});
			}
		}
				
		pagination.find('.slide-pagination-element:first-child').addClass('current');
		pagination.width(35 * i);
		
		$(this).append(pagination);
	});
	
	$('.list-item a').not('.std-link').click(function (e) {
		e.preventDefault();
		var href = $(this).attr('href');
		
		if (href && (href != '#')) {
			$(this).closest('.box-prefooter').find('.slide-list-target').find('div').hide().end().find($(this).attr('href')).fadeIn('fast');
			$(this).closest('.box-prefooter').find('.list-item a').removeClass('current');
			$(this).addClass('current');
		}
		
		
	});
	
	$('.link-cartello-stradale').click(function(e) {
		var href = '.' + $(this).attr('href').substr(1);
		var self = this;
		
		$(this).closest('.box-prefooter').find('.link-cartello-stradale').removeClass('current').end().find('.mappa:visible, p.indicazioni:visible').fadeOut('fast', function() {
			$(self).closest('.box-prefooter').find(href).fadeIn('fast');
			$(self).addClass('current');
		});
	});
	
	$('#clienti-categorie a').click(function (e) {
		e.preventDefault();
		$('#client-list-destination').quicksand($($(this).attr('href') + ' li'));
		$('#clienti-categorie a').removeClass('selected');
		$(this).addClass('selected');
	});
		
	$('.client-list img.logo-grigio').live('mouseover', function() {
		$(this).hide().parent().find('.logo-colori').show();
	});
	
	$('.client-list img.logo-colori').live('mouseout', function() {
		$(this).hide().parent().find('.logo-grigio').show();
	});
		
	$('.box-prefooter').find('.archive-list').not(':first').hide();
	
	$('.archive-list-selector a').bind('click.showLists', function(e) {
		e.preventDefault();
		var box = $(this).closest('.box-prefooter');
		var self = this;
		
		box.find('.archive-list-selector a').removeClass('current');
		$(this).addClass('current');
		
		box.find('.archive-list:visible').fadeOut('fast', function() {
			box.find($(self).attr('href')).fadeIn('fast');
		});
	});
	
	$('.archive-list .pulsante-avanti').click(function(e) {
		e.preventDefault();
		var archiveList = $(this).closest('.archive-list').find('ol');
		var firstItem = archiveList.find('li:first-child');
		firstItem.fadeOut('fast', function() {
			archiveList.append(firstItem);
			firstItem.show();
		});
	});
	
	$('.archive-list .pulsante-indietro').click(function(e) {
		e.preventDefault();
		var archiveList = $(this).closest('.archive-list').find('ol');
		var lastItem = archiveList.find('li:last-child');
		lastItem.hide();
		archiveList.prepend(lastItem);
		lastItem.fadeIn('fast');
	});
	
	if ($('#clienti-expo').length) {
		if (window.location.hash && $('#clienti-expo #clienti-categorie a[href=' + window.location.hash + ']').length) {
			$('#clienti-expo #clienti-categorie a[href=' + window.location.hash + ']').click();
		} else {
			$('#clienti-expo #clienti-categorie a[href=#client-list-telco-media]').click();
		}
	}
	
	if ($('#ct_info_privacy').length) {
		$('#ct_privacy').parent().find('a[href=#ct_info_privacy]').toggle(function(e) {
			e.preventDefault();
			$('#ct_info_privacy').fadeIn('fast');
		}, function(e) {
			e.preventDefault();
			$('#ct_info_privacy').fadeOut('fast');
		});
	}
	
	if (isMobile) {
		if (!$.cookie('view_std_version')) {
			var footer_select = $('<select>');
			var home_option = $('<option>').html('Homepage').val('/index.php');
			footer_select.append(home_option);
			
			$('body > footer nav').each(function() {
				if ($(this).children('h2').length) {
					var group = $('<optgroup>').attr('label', $(this).children('h2').text());
					$(this).find('a').each(function() {
						var href = $(this).attr('href');
						var option = $('<option>').html($(this).html()).val(href);
						
						if (window.location.href.substr(window.location.href.lastIndexOf('/')) == href) {
							option.attr('selected', true);
						}
						
						group.append(option);
					});
					
					footer_select.append(group);
				} else {
					$(this).find('div').each(function() {
						var group = $('<optgroup>').attr('label', $(this).children('h2').text());
						
						$(this).find('a').each(function() {
							var href = $(this).attr('href');
							var option = $('<option>').html($(this).html()).val(href);
							
							if (window.location.href.substr(window.location.href.lastIndexOf('/')) == href) {
								option.attr('selected', true);
							}
							
							group.append(option);
						});
						
						footer_select.append(group);
					});
				}
			});
			
			
			
			$('body > footer nav').remove();
			
			var titolo_footer_select = $('<h2>Menu di navigazione</h2>');
			$('body > footer aside').after($('<div id="footer-mobile">').append(titolo_footer_select).append(footer_select));
			
			footer_select.change(function() {
				window.location.replace($(this).val());
			});
		}
		
		if (!$.cookie('view_std_version')) {
			var standard_version_link = $('<a>Versione standard</a>').addClass('change-version-link');
			standard_version_link.click(function() {
				$.cookie('view_std_version', '1');
				window.location.reload();
			});
			
			$('#credits').before(standard_version_link);
		} else {
			var mobile_version_link = $('<a>Versione mobile</a>').addClass('change-version-link');
			mobile_version_link.click(function() {
				$.cookie('view_std_version', null);
				window.location.reload();
			});
			
			$('#credits').before(mobile_version_link);
		}
	}
	
	if (isMobile) {
		$('#clienti-expo #client-list-destination').remove();
		
		$('#clienti-expo #clienti-categorie a').addClass('clienti-accordion-trigger').each(function() {
			var href = $(this).attr('href');
			var panel = $('#clienti-expo').find('.client-list ' + href);
			panel.before($(this));
			$(this).unbind('click').bind('click', function(e) {
				e.preventDefault();
				$('#clienti-expo').find('.client-list ul').slideUp();
				panel.slideDown('fast', function() {
					$(document).scrollTop($('#clienti-expo').position().top);
				});
			});
		});
		
		$('#clienti-expo #clienti-categorie').remove();
		$('#clienti-expo .client-list ul:first').slideDown();
	}
	
	$('.archive-list .list-item').click(function (e) {
		e.preventDefault();
		window.location.replace($(this).find('a.std-link').attr('href'));
	});
});
