$.noConflict();
jQuery(document).ready(function($) {

/*Top_Menu Control GTM*/
$('.image').mouseover(function() {
  $(this).css('margin-top', '-17px');
});
$('.image').mouseleave(function() {
  $(this).css('margin-top', '0px');
});

jQuery('#modalWindow object, #modalWindow embed').live('click',function(){
	//return false;
});

masonry();

$('body').delegate('#clienti', 'click', function(){
	$item = $(this);
	$item.data('done', false);
/*	if ($.iShit) {
		$('html, body').scrollTop(0);
		$("#newsletter_slide").hide();
		$("#contacts_slide").toggle();
	} else {*/
	$('html, body').animate({
		scrollTop: 0
		
	}, 300, function() {
		if ($item.data('done') != true) {
			
			if ($("#contacts").is(':visible')) {
				
				$('#contacts').animate({
    				opacity: 0,
    				height: 'toggle'
 				 	}, 300, function(){ $('#contacts').css('opacity',1); $("#customers").slideDown(300); });					
				
			} else {
				
				$("#customers").slideToggle(300);

			}
			
			$item.data('done', true);
		}
	});
//	}
});
$('body').delegate('#contatti', 'click', function(){
	$item = $(this);
	$item.data('done', false);
/*	if ($.iShit) {
		$('html, body').scrollTop(0);
		$("#newsletter_slide").hide();
		$("#contacts_slide").toggle();
	} else {*/
	$('html, body').animate({
		scrollTop: 0
	}, 300, function() {
		if ($item.data('done') != true) {
			if ($("#customers").is(':visible')) {
				$("#customers").slideUp(300, function() {
					$("#contacts").slideDown(300);
				});
			} else {
				$("#contacts").slideToggle(300);
			}
			$item.data('done', true);
		}
	});
//	}
});
/*
$('body').delegate('#facebook', 'mouseenter',$('#facebook').animate(slideUp(300));
$('body').delegate('#facebook', 'mouseleave', $("#facebook").slideDown(300));	
	*/

/*Detail event resize height*/	
jQuery(function(){
 jQuery(window).load(
  function(){
   jQuery("#post-detail-container").height(jQuery("#post-gallery").height()+50)
  }
 )
});

	/*
	 * jQuery Selector Plugin
	 */
	$.expr[':']['nth-of-type'] = function (elem, i, match) {
		var parts = match[3].split("+");
		return (i+1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
	};

	/*
	 * Proxy function which limits multiple executions.
	 */
	function debouncer(func, timeout) {
		var timeoutID;
		timeout = timeout || 200;
		return function () {
			var scope = this , args = arguments;
			clearTimeout( timeoutID );
			timeoutID = setTimeout( function () {
				func.apply( scope , Array.prototype.slice.call( args ) );
			} , timeout );
		}
	}

	/*
	 * Bookmarks management
	 */
	historyLoad = function(hash, scrolldelta){
		if(hash != '') {
			$(".home").css("visibility", "hidden");
			/*$(".home").css("overflow", "hidden");*/
			/*
			$("html,body").stop().animate({
				"scrollTop": 0
			}, 800, 'easeInOutQuad', openModal(hash, scrolldelta));
			*/
			if ($("#customers").is(':visible')){
				$("#customers").slideUp(300);
			}
			if ($("#contacts").is(':visible')){
				$("#contacts").slideUp(300);
			}
			openModal(hash, scrolldelta);
		}
	};
	if(location.hash != '') {
		historyLoad(location.hash.replace('#', ''));
	}

	/*
	 * Tweet box
	 */
	var countTweet = 0;
	var twitterStatuses = new Array();
	var weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
	var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

	function setTwitterEntry() {
		var count = countTweet % twitterStatuses.length;
		$("#twitter-entries span").fadeOut(1000,function(){
			$("#twitter-entries .created_at").html(formatDate(twitterStatuses[count]["created_at"]));
			$("#twitter-entries .text").html(twitterStatuses[count]["text"].replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i, "<a target='_blank' href='$1'>$1</a>"));
			$("#twitter-entries .count").html( (count+1)+"/"+(twitterStatuses.length) );
			$("#twitter-entries p,#twitter-entries span").fadeIn(1000);
		});
		countTweet++;
	}
	function getLatestTweet(username,page,count) {
		$.getJSON("http://twitter.com/statuses/user_timeline/"+username+".json?screen_name="+username+"&count="+count+"&page="+page+"&callback=?", function(data) {
			for(k in data){
				twitterStatuses[k] = new Array();
				twitterStatuses[k]["text"] = data[k]["text"];
				if(navigator.userAgent.match(/MSIE\s([^;]*)/)){
					twitterStatuses[k]["created_at"] = new Date(Date.parse(data[k]["created_at"].replace(/( \+)/, ' UTC$1')));
				}else{
					twitterStatuses[k]["created_at"] = new Date(data[k]["created_at"]);
				}
			}
			setTwitterEntry();
			setInterval(setTwitterEntry,10000);
		});
	}
	function formatDate(date){
		return weekDays[date.getDay()]+"."+months[date.getMonth()]+"."+date.getDate()+"."+(date.getYear()+1900);
	}
	getLatestTweet("dodicitrenta", 1, 5);

	/*
	 * Accordions
	 */
	$('#about-dodicitrenta').accordion({
		'active':false,
		'collapsible': true,
		'autoHeight': false,
		'clearStyle': true
	});

	/*
	 * Post boxes
	 */
	var fitGrid = function(){
		/*
		 * Get the grid
		 */
		$grid = $('.grid');
		/*
		 * Calculate the number of boxes for each row
		 */
		nBoxes = Math.floor($('.grid').width() / 301);
		/*
		 * Cleanup older rows
		 */
		$('.box', $grid).removeClass('rowStart rowEnd');
		$('hr.divider', $grid).remove();
		/*
		 * Apply our new rules
		 */
		$('article.box:nth-of-type('+nBoxes+'n)', $grid)
			.addClass('rowEnd')
				.after('<hr class="divider" />')
			.end()
			.next()
				.addClass('rowStart');
	};
	$(window).resize(debouncer(fitGrid, 100));
	//$(window).resize(fitGrid);
	fitGrid();

	//$('<img src="'+themeRoot+'/images/view.png" />');
	$image = 'http://www.dodicitrenta.com/wp-content/themes/dodicitrenta/images/view.png';
	$('.grid').delegate('.box', 'mouseenter', function(){
		$this = $(this);
		$height = $this.find("img.attachment-post-thumbnail").height();
		
		inject = '<div class="view-container" style="height:' + $height + 'px"><div class="view-background"></div><img class="view" src="'+themeRoot+'/images/view.png" /></div>';
		$this.addClass("active").append(inject);
		/*$(".box-more", $this).css("background", "black");*/
	});
	$('.grid').delegate('.box', 'mouseleave', function(){
		$(this).removeClass("active").children('.view-container').remove();
		$("#"+$this.attr('id')+" .box-more").css("background", "#FFF");
	// $("#"+$this.attr('id')+" .box-more").css("background", "#333333");
	});

	/*
	 * Post link
	 */
	$('.box').live('click', function(){
		work = $("#"+$(this).attr("id")+" a").attr("href").replace(/^.*#/, '');
		historyLoad(work);
	});

	$('.box').each(function(){
		var link = $("#"+$(this).attr("id")+" a");
		if( typeof link.attr('href') != 'undefined' ) {
			link.attr("href",link.attr("href").replace(serverRoot,"#"));
		}
	});
	
	
	$('#page').delegate('#agency', 'click', function(){
		historyLoad($("#"+$(this).attr("id")).attr("href").replace(/^.*#/, ''));
	});
	$('#page').each(function(){
		var link = $("#"+$(this).attr("id"));
		if( typeof link.attr('href') != 'undefined' ) {
			link.attr("href",link.attr("href").replace(serverRoot,"#"));
		}
	});

	/*
	 * Load images on scroll
	 */
	var imgLoad = function(){
		$(".box").each(function(){
			$this = $(this);
			/*
			 * Cache
			 */
			imageTop = $.data($this, 'offTop');
			if (!imageTop) {
				imageTop = $(this).offset().top;
				$.data($this, 'offTop', imageTop);
			}
			/*
			 * Is it visible ?
			 */
			visibleTop = parseInt($(window).scrollTop()) + $(window).height() - 200;
			if (imageTop <= visibleTop) {
				$(".img-ondemand", $this).each(function(){
					$img = $(this);
					$img.attr('src', $img.attr('longdesc')).removeClass("img-ondemand");
				});
			}
		});
	};
	$(window).bind('scroll',function(){
		if($("img.img-ondemand").length) {
			imgLoad();
		} else {
			$(window).unbind('scroll');
		}
	});
	imgLoad();

	/*
	 * Externals
	 */
	$('a[rel="external"]').live('click', function(){
		$(this).attr('target','_blank');
	});
});




/*
 * Modal box
 */

function disableWork()
{
	jQuery('.box').die('click');
	jQuery('.box').live('click', function(){
		return false;	
	});
}


function enableWork()
{
	jQuery('.box').die('click');
	jQuery('.box').live('click', function(){
		work = jQuery("#"+jQuery(this).attr("id")+" a").attr("href").replace(/^.*#/, '');
		historyLoad(work);
		return false;	
	});
}


function closeModal()
{
	jQuery('#post_back').live('click', function(){
		disableWork();
		jQuery(".menu_top_filler").show();
		jQuery("#logo").show();
		jQuery("#twitter-entries").show();
		jQuery(this).fadeOut('slow');
		jQuery("#post-detail-container").css('overflow-y','hidden');
		jQuery("#content").fadeIn('fast');
		$this = jQuery('#modalWindow');
		jQuery('object, embed', $this).hide();
		$this.fadeOut('fast', function(){
				var top = (jQuery(location.hash) && jQuery(location.hash).offset()) ? jQuery(location.hash).offset().top + scrolldelta - 3 : 0;
				location.hash = "";
				$body = (jQuery("html").hasClass("ie7")) ? jQuery("html") : jQuery("html, body");
				$body.stop().animate({
					"scrollTop": top
				}, 400, "easeInOutQuad", function() {
					jQuery("#modalWindow").remove();
					enableWork();
				 //$("#page").css("display", "block");
				});
		});
	});
}
 
function openModal (hash, scrolldelta){
	scrolldelta = parseInt(scrolldelta) || 0;
	if(jQuery("#modalWindow").length == 0){
		jQuery('body').append("<div id='modalWindow'></div>");
	}
	
	jQuery(".menu_top_filler").hide();
	jQuery("#logo").hide();
	jQuery("#twitter-entries").hide();
	jQuery("#content").hide();
	jQuery('#modalWindow').load(serverRoot+""+hash+"?modal=true", function(){
		location.hash = hash;
		jQuery(this).fadeIn();		
		jQuery('#post-detail-container').height( jQuery(document).height());
		jQuery(".home").css("visibility", "visible");
		if(!jQuery(".home"))
		jQuery("#twitter-entries").css("visibility", "hidden");
		setInterval(function(){
			jQuery('#post-detail-container').height( jQuery(document).height());
		}, 1000);
	});

}

window.log = function(){
	log.history = log.history || [];
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};

closeModal();


(function(doc){
	var write = doc.write;
	doc.write = function(q){
		log('document.write(): ',arguments);
		if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);
	};
})(document);


/* MASONRY ************************************************************/

function masonry(){
	var w_w = jQuery(window).width() - 100;
	var n_item = parseInt(w_w/290);
	var w_grid = 300 * n_item;
	jQuery('.grid').width(w_grid);
	jQuery('.grid').masonry({
		itemSelector : '.box',
		 isAnimated: true
	});
}

/* END MASONRY ************************************************************/




jQuery(window).resize(function($) {
	masonry();
});


/*
if (ExternalInterface.available && ExternalInterface.objectID != null)
{
    try {
        ExternalInterface.call('eval', 'true;');
        ExternalInterface.addCallback("scrollEvent", onScrollEvent);
    } catch (e){
        // nope!
    }
}
	
	ExternalInterface.call("eval", SCROLL_SCRIPT);
	ExternalInterface.call("eval", 'setupScrolling( "' + ExternalInterface.objectID + '" );');*/
