/*
---



...
*/

Nerocreativo = {
	'version': '0.0.1',
	'url': ''
};

Nerocreativo.Core = new Class({

	Implements: Events,

	initialize: function(params){

		this.verbose = params.verbose ? Boolean(params.verbose) : document.location.href.indexOf('') != -1;
		this.baseUrl = params.baseUrl;

		window.addEvent('domready', this._onDomReady.bind(this));
		window.addEvent('load', this._onPageLoad.bind(this));

	},

	_onDomReady: function(){

		if(Nerocreativo._isDomReady) return;
		Nerocreativo._isDomReady = true;
		console.info('Nerocreativo.core: Fireing event: "domready"');
		this.fireEvent("domready");

	},

	_onPageLoad: function(){

		this._onDomReady();
		Nerocreativo._isPageLoaded = true;
		console.info('Nerocreativo.core: Fireing event: "load"');
		this.fireEvent("load");

	},

	isPageLoaded: function() { return this._isPageLoaded; },
	isDomReady: function() { return this._isDomReady; },
	isAppFreezed: function() { return this._freezeApp; },

	socialShare: function(type){

		var windowprops = 'width=600,height=400,top=0,left=0,toolbar=no,location=no,directories=no,status=no,scrollbars=no,menubar=no';
		var popup;

		if(type == 'facebook')
			popup = window.open('http://www.facebook.com/sharer.php?u='+document.location.href.replace('#/', '')+'&t='+document.title, 'remote', windowprops);
		else
			popup = window.open('http://twitter.com/home?status=Take a look at ' + document.title + ' ' + document.location.href.replace('#/', ''), 'remote', windowprops);

		popup.moveTo(0, 0);
		popup.resizeTo(600, 400);
		popup.focus();

	}

});

if(typeof console == "undefined" || typeof console.debug == "undefined")
	console = { log: function(){}, warn: function(){}, info: function(){}, trace: function(){} };

Nerocreativo.pngfix = function(img){

	var src = img.get('src');
	img.set('src', 'spacer.gif');
	img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + src + ')';
};

/*
---

script: Nerocreativo.Analytics.js

description: Google Analytics wrapper

authors:
- Chilian Ciuffolo

requires:
- core:1.2.4/MooTools
- core:0.0.1/Nerocreativo

provides: [Nerocreativo.Analytics]

...
*/

var _gaq = _gaq || [];;

Nerocreativo.Analytics = new Class({

	Implements: Events,

	initialize: function(nerocreativo, accounts, verbose){

		this.verbose = nerocreativo.verbose;
		this.nerocreativo = nerocreativo;

		this.accounts = accounts instanceof Array ? accounts : new Array(accounts);

		for(var i=0; i < this.accounts.length; ++i)
		{
			_gaq.push([this.accounts[i].name + '._setAccount', this.accounts[i].code]);
			_gaq.push([this.accounts[i].name + '._setDomainName', this.accounts[i].domain ]);
			if(this.verbose) console.info('Nerocreativo.Analytics: Successfull initialized account "' + this.accounts[i].name + ':' + this.accounts[i].code + '"');
		}

		new Element('script', { 'type': 'text/javascript', 'async': true, 'src': 'http://www.google-analytics.com/ga.js' }).inject($(document.head), 'bottom');

	},

	trackPage: function(value){

		if(!this.nerocreativo.isPageLoaded()) {
			if(this.verbose) console.warn('Nerocreativo.Analytics: You cannt use Nerocreativo.Analytics.trackPage before the page load');
			return this;
		}

		for(var i=0; i < this.accounts.length; ++i)
		{
			try{
				_gaq.push([this.accounts[i].name + '._trackPageview', value]);
				if(this.verbose) console.info('Nerocreativo.Analytics: Successfull tracked page "' + value + '" for "' + this.accounts[i].name + ':' + this.accounts[i].code + '"');
			} catch(error){
				if(this.verbose) console.warn('Nerocreativo.Analytics: Cannot track page "' + value + '" for "' + this.accounts[i].name + ':' + this.accounts[i].code + '"');
			}
		}

		return this;

	},

	trackEvent: function(data){

		if(!this.nerocreativo.isPageLoaded()) {
			if(this.verbose) console.warn('Nerocreativo.Analytics: You cannt use Nerocreativo.Analytics.trackEvent before the page load');
			return this;
		}

		for(var i=0; i < this.accounts.length; ++i)
		{
			try{
				_gaq.push([this.accounts[i].name + '._trackEvent', data.category, data.action, data.label, data.value ]);
				if(this.verbose) console.info('Nerocreativo.Analytics: Successfull tracked event "' + data + '" for "' + this.accounts[i].name + ':' + this.accounts[i].name + '"');
			} catch(error){
				if(this.verbose) console.warn('Nerocreativo.Analytics: Cannot track event "' + value + '" for "' + this.accounts[i].name + ':' + this.accounts[i].name + '"');
			}
		}

		return this;

	}

});

Nerocreativo.Fx = {
	
};

Nerocreativo.Fx.Rotate = new Class({

	Extends: Fx,
	Implements: Options,

	options: {
		offset: { x: 0, y: 0 }
	},

	initialize: function(element, options) {

		this.element = document.id(element);
		this.parent(options);
	},

	set: function(current) {

		if(Browser.Engine.trident){

			this.element.style['filter'] = null;

			var costheta = Math.cos(current);
			var sintheta = Math.sin(current);
			var size = this.element.getSize();
			var center = { x: size.x * .5 , y: size.y * .5 };
			var origin = { x: -center.x, y: -center.y };

			origin.tx = origin.x * costheta - origin.y * sintheta + center.x;
			origin.ty = origin.x * sintheta + origin.y * costheta + center.y;

			var a  =  costheta;
			var b  =  sintheta;
			var c  = -sintheta;
			var d  =  costheta;
			var tx =  Math.abs(c) * center.y + (Math.abs(a) - 1) * center.x + origin.tx;
			var ty =  Math.abs(b) * center.x + (Math.abs(d) - 1) * center.y + origin.ty;

			this.element.style['filter'] = 'progid:DXImageTransform.Microsoft.Matrix(M11=' + a + ', M21=' + b + ', M12=' + c + ', M22=' + d + ', SizingMethod="auto expand")';
			this.element.style.left = Math.round(-tx + this.options.offset.x);
			this.element.style.top  = Math.round(-ty + this.options.offset.y);
			return;
		}

		if(Browser.Engine.gecko){

			this.element.style.MozTransform = 'rotate(' + current + 'rad)';
			/*
				TODO cache origin
			*/
			this.element.style.MozTransformOrigin = '0px 0px';
			return;
		}

		if(Browser.Engine.webkit){

			this.element.style.webkitTransform = 'rotate(' + current + 'rad)';
			/*
				TODO cache origin
			*/
			this.element.style.webkitTransformOrigin = '0px 0px';
			return;
		}

		if(Browser.Engine.presto){

			this.element.style.OTransform = 'rotate(' + current + 'rad)';
			/*
				TODO cache origin
			*/
			this.element.style.OTransformOrigin = '0px 0px';
			return;
		}
	}
});

// elements
//var logo;
var logoLink;
var menuItems;
var menu;
var scroller;

// routing
var lastAddressValue;
var pathArray;

// various
var baseStrokeColor = $HSB(0, 0, 60);
var positionsList = ['TL', 'TR', 'BL', 'BR'];
var defaultRadians = { TL: 7.26, TR: 12.34, BL: 3, BR: .5 };
var ncc = new Nerocreativo.Core({ 'baseUrl': '' });
var nca = new Nerocreativo.Analytics(ncc, { 'name': 'awd', 'code': 'UA-11382876-1', 'domain': 'none' });

ncc.addEvent('domready', function(){

	menu = $('menu');
	menuItems = $$('#menu a');
	//logo = $('logo');
	//logoLink = logo.getFirst();

	showLogo();
	showGrid($$('#main div#menu, #main div.gridItems'));
	showGrid($$('#main div#menu, #main div.gridItems2'));
	showGrid($$('#main div#menu, #main div.gridItems5'));
	showGrid($$('#main div#menu, #main div.gridStatic'));
	showGrid($$('#main div#menu, #main div.unitsdesc'));
	showGrid($$('#main div#menu, #main div.units'));
	
	
	configureMenu();

	
	
	$$('img.work-arrow').addEvent('click', function(e){ scrollToImage(this); });

	scroller = new Fx.SmoothScroll({ duration: 1000, transition: Fx.Transitions.Expo.easeInOut });

	configureGallery();

	if($('itemInfoBox') || $('newsItemInfoBox'))
		configureShareLinks($$('.shareLink'));

	if($$('.staff'))
		configureStaff($$('.staff'));

	nca.trackPage(document.location.href);

	if($(window).getScrollSize().y != $(window).getSize().y)
		$(document.body).setStyle("height", $("main").getSize().y + 50);
	else
		$(document.body).setStyle("height", $(window).getSize().y);

}).addEvent("load", function(){

	if($(window).getScrollSize().y != $(window).getSize().y)
		$(document.body).setStyle("height", $("main").getSize().y + 50);
	else
		$(document.body).setStyle("height", $(window).getSize().y);
});

function showLogo(){

	return;
	// logoLink.set('href', '#/' + logoLink.get('href')).addEvent('click', onMenuItemClick.bind(logoLink));
	logoLink.fade('hide').setStyle('margin-left', -15).set('morph', { duration: 500, transition: Fx.Transitions.Elastic.easeOut });
	
	(function(){
		logoLink.morph({ 'opacity': 1, 'margin-left': 0 });
	}).delay(500);
};

function configureMenu(){

	menuItems.set('morph', { duration: 1000, transition: Fx.Transitions.Elastic.easeOut });

	fixLinks(menuItems);

	menuItems.each(function(item){
		// item.fade('hide');

		item.addEvent('mouseenter', onMenuItemMouseOver.bind(item));
		item.addEvent('mouseleave', onMenuItemMouseOut.bind(item));
		item.addEvent('click', onMenuItemClick.bind(item));
	});
};

function onMenuItemMouseOver(e){ this.morph('#main #menu a.over'); };
function onMenuItemMouseOut(e){ this.morph('#main #menu a'); };
function onMenuItemClick(e){
	// SWFAddress.setValue(this.get('href'));
};

function configureGallery(){

	$$('.galleryPrevNext').each(function(item, index){

		item.fade('hide').fade(.5);
		item.addEvent('mouseenter', function(){
			this.fade(.8);
		});
		item.addEvent('mouseleave', function(){
			this.fade(.3);
		});

		(function(){ (function(){ new Fx.Tween(item, { property: 'opacity', duration: 500 }).start(.8).chain(function(){ this.start(.3); }); }).delay(index * 1000); }).periodical(5000);
	});
};

function configureStaff(elements){

	var classes = new Object();
	var className;

	elements.each(function(item){

		className = (item.get('class').split(' ').pop());
		classes[className] = $$('.' + className);
	});

	$$('.staff p').fade('hide');

	if(classes.staff)
		delete classes.staff;

	for(var k in classes){

		(function(){
			var els = classes[k];
			els.addEvent('mouseenter', function(){ els.getFirst().fade(.8); });
			els.addEvent('mouseleave', function(){ els.getFirst().fade(0); });
		})();
	}
};

function showGrid(elements){

	elements.each(function(item, index){

		if(document.location.pathname.indexOf("/gallery-") != -1){

			if(index > 2)
				item.fade("hide").fade.delay(100 * index, item, 1);

			return;
		}

		var cornerPosition = positionsList[index ? parseInt(Math.random() * 3) : 2];

		if(index % 3 == 0) {

			var radians = (Math.PI * .5 * Math.random() - Math.PI * .25) + Math.PI;
		}
		else if(index % 3 == 1) {
		
			var radians = (Math.PI * .5 * Math.random() - Math.PI * .25) + Math.PI * Number(Math.random() < .5);
		}
		else if(index % 3 == 2) {
		
			var radians = (Math.PI * .5 * Math.random() - Math.PI * .25);
		}

		var className = item.get('class').split(' ').pop();

		if(positionsList.contains(className)){

			cornerPosition = className;
			radians = defaultRadians[cornerPosition];
		}

		var point = getPointFromAngleAndDistance(radians, 2300);
		var color = baseStrokeColor.setBrightness(Math.random() * 50 +30);
		var strokeData = createStroke(cornerPosition, color);

		item.setStyles({ 'left': point.x, 'top': point.y });
		item.store('point', point);


		new Nerocreativo.Fx.Rotate(strokeData.stroke, { offset: { x: 18, y: 18 } }).set(radians);

		(function(){
			new Fx.Morph(item, { duration: 707, transition: Fx.Transitions.Quint.easeOut }).start({ 'left': 0, 'top': 0 });
		}).delay(253 * index + 1000);

	});
};

function createStroke(cornerPosition, color){

	var stroke = new Element('div', {
		'class': 'stroke',
		'styles': { 'background-color': color }
	});

	var hole = new Element('div', { 'class': 'hole' });
	var corner = new Element('div', { 'class': 'corner corner' + cornerPosition });

	corner.grab(stroke, 'bottom').grab(hole);

	return { corner: corner, stroke: stroke };
}

function hideGrid(elements) {

	elements.each(function(item, index){

		(function(){
			var point = item.retrieve('point');
			new Fx.Morph(item, { duration: 5000, transition: Fx.Transitions.Expo.easeOut }).start({ 'left':  point.x, 'top': point.y });
		}).delay(20 * index);
	});
};

function onGetItemZoomComplete(responseTree) {

	var infoBox = responseTree[0];
	var navigation = responseTree[2];
	var zoomContainer = responseTree[4].fade('hide');
	var images = zoomContainer.getElements('img');

	images.each(function(item, index){

		item.getParent().setStyle('height', 0);
		item.store('next', images[index + 1]);
	});

	configureShareLinks(infoBox.getElements('.shareLink'));

	var radians1 = (Math.PI * .5 * Math.random() + Math.PI * .75);
	var radians2 = (Math.PI * .5 * Math.random() + Math.PI * .75);

	var point1 = getPointFromAngleAndDistance(radians1, 2300);
	var point2 = getPointFromAngleAndDistance(radians2, 2300);

	infoBox.setStyles({ 'left': point1.x, 'top': point1.y });
	navigation.setStyles({ 'left': point1.x, 'top': point2.y });

	// infoBox.grab(createStroke(radians1, 'BL', baseStrokeColor.setHue(Math.random() * 360)), 'bottom').inject(logo, 'after');
	// navigation.grab(createStroke(radians2, 'Navigation', '#555'), 'bottom').inject(infoBox, 'after');

	new Fx.Morph(infoBox, { duration: 707, transition: Fx.Transitions.Quint.easeOut }).start({ 'left': 0, 'top': 389 });
	new Fx.Morph(navigation, { duration: 1207, transition: Fx.Transitions.Quint.easeOut }).start({ 'left': 0, 'top': 718 });

	zoomContainer.inject(navigation, 'after').fade(1);

	loadNextImage(images[0]);
};

function showImg(){
	var parent = this.getParent();
	new Fx.Tween(parent, { duration: 1000, transition: Fx.Transitions.Expo.easeInOut }).start('height', parseInt(this.get('height')));
};

function loadNextImage(firstImg){

	this.removeEvent('load', showImg);
	this.removeEvent('load', loadNextImage);

	var imgToLoad = firstImg ? firstImg : this.retrieve('next');

	if(!imgToLoad) return;

	imgToLoad.addEvent('load', showImg);
	imgToLoad.addEvent('load', loadNextImage);
	imgToLoad.set('src', imgToLoad.get('ajaxsrc'));

};

function fixLinks(elementsList){

	// elementsList.each(function(item){
	// 	item.set('href', '#/' + item.get('href'));
	// });
};

function handleChange(e){

	freezeApp = true;

	if(e.value == lastAddressValue)
		return;

	pathArray = e.value.split("/");
	pathArray.shift();

	//memorizzo ultimo indirizzo valido
	lastAddressValue = e.value;

	//se nn ho il secondo livello, seleziono il primo modulo
	if(!pathArray[1])
	{
		// SWFAddress.setValue(defaultCategory.url);
		return;
	}

	loadPage(pathArray[1]);

	hideGrid($$('#main div.gridItems'));

	// SWFAddress.setTitle(pathArray[1]);
};

function loadPage(pageName){

	(function(){ new Request.HTML({ url: ncc.baseUrl + '/ajax/get' + pageName + '.php', onSuccess: onLoadPageComplete }).get(); }).delay(500);
};

function onLoadPageComplete(responseTree){

	var elements = responseTree[0].getChildren();
	
	console.log(elements);

	elements.each(function(item){

		item.inject(menu, 'after');
	});
	showGrid(elements);
	// (function(){ new Request.HTML({ url: ncc.baseUrl + '/ajax/showItem.php', onSuccess: onGetItemZoomComplete }).get(); }).delay(500);
}

function configureShareLinks(links){

	links.each(function(item){

		item.setStyle('opacity', .5);
		item.set('tween', { duration: 1201, transition: Fx.Transitions.Expo.easeOut });
		item.addEvent('mouseover', function(){ this.fade(1); });
		item.addEvent('mouseout', function(){ this.fade(.5); });
		item.addEvent('click', function(e){ e.preventDefault(); });
	});

	$('shareFacebook').addEvent('click', ncc.socialShare.bind(this, 'facebook'));
	$('shareTwitter').addEvent('click', ncc.socialShare.bind(this, 'twitter'));
};

function getPointFromAngleAndDistance(angle, distance) {

	return { x: Math.cos(angle) * distance , y: Math.sin(angle) * distance - 1500 };
};

function scrollToImage(theBadge){ var myFx = new Fx.Scroll(window, {offset:{'y': + 30},duration:1500,transition:Fx.Transitions.Expo.easeInOut}).toElement(theBadge); }







