/**
 * @author Tobias Fuhlroth - Notch Interactive GmbH
 */

/**
 * Console
 */
 
if (window['console'] === undefined) window.console = { log: function (msg) {} };
if (window['opera']) window.console.log = window.opera.postError;


/**
 * Site
 */
 
var Site = {};

if (Browser.Platform.win) {
	window.addEvent('domready', function () {
		if (document.id('header-content')) document.id('header-content').setStyle('text-align', 'left');
	});
}




/**
 * mainnav
 */
 
 Site.mainnav = {
 	
 	settings: {},
 	
 	initialize: function () {
 		this.container = document.id('main-navigation-container');
 		this.element = document.id('main-navigation');
 		this.arrow = new Element('div', {
 			'class': 'arrow',
 			'tween': {'link': 'cancel', 'transition': 'sine:out'}
 		}).inject(this.container);
 		this.settings.arrow_size = this.arrow.getSize();
 		this.items = this.element.getElements('li').forEach(function (item) {
 			if (item.hasClass('selected')) this.active_item = item;
 			item.addEvents({
 				'mouseover': this.mouseoverListener.pass(item, this),
 				'mouseout': this.mouseoutListener.bind(this)
 			});
 		}, this);
 		this.mouseoutListener();
 	},
 	
 	mouseoverListener: function (item) {
 		this.tweenTo(item);
 	},
 	
 	mouseoutListener: function () {
 		if (this.active_item) {
 			this.tweenTo(this.active_item);
 		} else {
 			this.arrow.tween('left', -this.settings.arrow_size.x);
 		}
 	},
 	
 	tweenTo: function (item) {
 		var position = item.getPosition(this.element);
 		var size = item.getSize();
 		this.arrow.tween('left', (position.x + size.x / 2) - this.settings.arrow_size.x / 2);
 	}
 	
 };
 
 window.addEvent('domready', function () {
 	Site.mainnav.initialize();
 });


/**
 * hiring
 */

/*Site.hiring = {
	
	initialize: function () {
		this.flash_container = $('hiring-chair-flash-container');
		this.button = $('hiring-apply-now');
		this.button.addEvent('click', this.stopPropagation.bindWithEvent(this));
		this.load_flash();
	},
	
	load_flash: function () {
		this.swiff = new Swiff('/media/_assets/flash/hiring-chair.swf', {
			'width': 99,
			'height': 110,
			'container': this.flash_container
		});
	},
	
	stopPropagation: function (event) {
		event.stopPropagation();
	}
	
};

window.addEvent('domready', function () {
	if ($('colorama')) {
		Site.hiring.initialize();
	}
});*/

 
/**
 * colorama
 */

Site.colorama = {
	
	initialize: function () {
		this.settings = new Hash.Cookie('settings', {path: '/', duration: 365});
	}
	
};


Site.colorama.picker = {
	
	options: {
		duration: 500,
		transition: 'sine:out'
	},
	
	initialize: function () {
		this.container = document.id('colorama');
		if (!this.container) return false;
		this.element = new Element('div', {
			'id': 'colorama-picker',
			'tween': {
				link: 'cancel',
				transition: this.options.transition,
				duration: this.options.duration
			}
		}).inject(this.container);
		
		this.saveInfo = new Element('span', {
			'class': 'save',
			'text': 'click anyware to save color',
			'tween': {
				link: 'cancel',
				transition: 'sine:in'
			},
			'styles': {
				'opacity': 0
			}
		}).inject(this.element);

		if (Site.colorama.settings.get('defaultColor')) {
            this.currentColor = new Color(Site.colorama.settings.get('defaultColor'));
			this.element.tween('background-color', Site.colorama.settings.get('defaultColor'));
		} else {
			var color = this.element.getStyle('background-color');
			this.currentColor = new Color(color);
			Site.colorama.settings.set('defaultColor', color);
		}
		
		this.bound = {
			'mouseenter': this.mouseenter.bind(this),
			'calcValues': function (event) { this.calcValues(event) }.bind(this),
			'setDefaultColor': this.setDefaultColor.bind(this),
			'mouseleave': this.mouseleave.bind(this)
		};
		this.enable();
	},
	
	enable: function () {
		this.attachEvents();
		this.element.tween('background-color', this.currentColor.hex);
	},
	
	disable: function () {
		this.detachEvents();
		if (this.timer) this.timer = clearTimeout(this.timer);
		this.hideSaveInfo();
		this.element.tween('background-color', '#444');
	},
	
	attachEvents: function () {
		this.container.addEvents({
			'mouseenter': this.bound.mouseenter,
			'mousemove': this.bound.calcValues,
			'click': this.bound.setDefaultColor,
			'mouseleave': this.bound.mouseleave
		});
	},
	
	detachEvents: function () {
		this.container.removeEvents({
			'mouseenter': this.bound.mouseenter,
			'mousemove': this.bound.calcValues,
			'click': this.bound.setDefaultColor,
			'mouseleave': this.bound.mouseleave
		});
	},
	
	mouseenter: function () {
		this.timer = this.showSaveInfo.delay(500, this);
	},
	
	mouseleave: function () {
		if (this.timer) this.timer = clearTimeout(this.timer);
		this.hideSaveInfo();
		
		this.element.tween('background-color', Site.colorama.settings.get('defaultColor'));
		Site.colorama.colorize.tweenColor(Site.colorama.settings.get('defaultColor'));
	},
	
	showSaveInfo: function () {
		this.saveInfo.tween('opacity', 1);
	},
	
	hideSaveInfo: function () {
		this.saveInfo.tween('opacity', 0);
	},
	
	calcValues: function (event) {
		var elementCoordinates = this.element.getCoordinates();
		var position = {
			x: event.page.x - elementCoordinates.left,
			y: event.page.y - elementCoordinates.top
		};
		var hue = (position.x / elementCoordinates.width) * 359;
		var saturation = (((position.y / elementCoordinates.height) * 100).round() / 100) * 70 + 30;
		var brightness = ((100 - ((position.y / elementCoordinates.height) * 100).round()) / 100) * 40 + 30;
		
		this.setColor(hue, saturation, brightness);
	},
	
	setColor: function (hue, saturation, brightness) {
		this.element.get('tween').cancel();
		
		this.currentColor = this.currentColor.setHue(hue);
		this.currentColor = this.currentColor.setSaturation(saturation);
		this.currentColor = this.currentColor.setBrightness(brightness);
		
		this.element.setStyle('background-color', this.currentColor);
		Site.colorama.colorize.setColor(this.currentColor);
	},
	
	setDefaultColor: function () {
		Site.colorama.settings.set('defaultColor', this.currentColor.hex);
		this.log(this.currentColor);
		
		var flashColor = this.currentColor.setBrightness(this.currentColor.hsb[2] + 30);
		this.element.set('tween', {'duration': 50, 'transition': 'linear'});
		this.element.get('tween').start('background-color', flashColor.hex).chain(function () {
			this.element.set('tween', {'duration': this.options.duration, 'transition': this.options.transition}).tween('background-color', this.currentColor.hex);
		}.bind(this));
	},
	
	log: function (color) {
		new Request({
			'url': '/colorama/log/',
			'data': {
				'csrfmiddlewaretoken': Site.CSRF_TOKEN,
				'hue': color.hsb[0],
				'saturation': color.hsb[1],
				'brightness': color.hsb[2],
				'browser_engine_name': Browser.name,
				'browser_engine_version': Browser.version,
				'browser_platform_name': Browser.Platform.name
			},
			'onSuccess': function (responseText, responseXML) {
				//console.log(responseText);
			}
		}).send();
	}
	
};


Site.colorama.colorize = {
	
	options: {
		'className': 'colorize'
	},
	
	initialize: function () {
		this.body = document.id(document.body);
		this.body.set('tween', {'link': 'cancel', 'transition': 'sine:out'});
		this.bodyColor = new Color(this.body.getStyle('background-color'));
		
		this.elements = $$('.{className}, #body-container a'.substitute(this.options));
		this.elements_fx = new Fx.Elements(this.elements, {
			'link': 'cancel',
			'transition': 'sine:out'
		});
		
		this.tweenColor(Site.colorama.settings.get('defaultColor'));
	},
	
	setColor: function (color) {
		this.body.setStyle('background-color', this.bodyColor.mix(color, 7));
		this.elements.forEach(function (element, index) {
			var property = (element.get('tag') == 'a' && !element.hasClass('background')) ? 'color' : 'background-color';
			element.setStyle(property, color);
		}, this);	
	},
	
	tweenColor: function (color) {
		this.body.tween('background-color', this.bodyColor.mix(color, 7).hex);
		var anim_params = {};
		this.elements.forEach(function (element, index) {
			var property = (element.get('tag') == 'a' && !element.hasClass('background')) ? 'color' : 'background-color';
			var value = {};
			value[property] = color;
			anim_params[index] = value;
		}, this);
		this.elements_fx.start(anim_params);
	}
	
};


Site.colorama.stats = {
	
	options: {
		bar_height: 250,
		boost_saturation: 0,
		boost_brightness: 20
	},
		
	initialize: function () {
		this.container = document.id('colorama');
		if (!this.container) return false;
		this.element = new Element('div', {'id': 'colorama-stats'}).inject(this.container);
		this.bar_container = new Element('div', {
			'id': 'colorama-bars',
			'styles': {
				'height': this.options.bar_height
			}
		}).inject(this.element);
		
		this.is_visible = false;
		this.toggle_button = new Element('a', {
			'id': 'colorama-toggle',
			'class': 'show',
			'events': {
				'click': function (event) { this.toggle(event) }.bind(this)
			}
		}).inject(this.element);
		
		this.load();
	},
	
	load: function () {
		// show loader, get data from service
		new Request.JSON({
			'method': 'get',
			'url': '/colorama/stats/',
			'onSuccess': this.build.bind(this) 
		}).send();
	},
	
	build: function (responseJSON, responseText) {
		var response = responseJSON;
		var bar_width = this.element.getSize().x / response.data.length;
		this.bar_elements = [];
		this.bar_fx_show_params = {};
		this.bar_fx_hide_params = {};
		this.section_elements = [];
		var tip_template_title = '<div class="sample" style="background-color : {background-color};"></div>';
		var tip_template_text = '<div class="info"><p class="label">{label}</p><p class="color"><strong>H:</strong>{hue} <strong>S:</strong>{saturation} <strong>B:</strong>{brightness}</p></div><div class="clicks"><span>{count}</span> Clicks</div>';
		
		// loop bars
		response.data.forEach(function (bar, i) {
			var element = new Element('div', {
				'class': 'bar',
				'styles': {
					'left': bar_width * i,
					'width': bar_width,
					'height': bar.height
				}
			});
			
			// loop sections
			var label_color;
			bar.data.forEach(function (section, j) {
				var background_color = new Color([section.hue, section.saturation + this.options.boost_saturation, section.brightness + this.options.boost_brightness], 'hsb');
				if (j == 0) label_color = background_color;
				var section_element = new Element('div', {
					'class': 'section',
					'styles': {
						'height': section.height,
						'background-color': background_color
					}
				}).inject(element);
				
				// Store Data for Tips
				var label = (bar.label.search(/[,&]/) >= 0) ? 'Blend of: ' : 'Similar to: ';
				
				section_element.store('tip:title', tip_template_title.substitute({'background-color': background_color.hex}));
				section_element.store('tip:text', tip_template_text.substitute({
					'label': label + bar.label,
					'hue': section.hue,
					'saturation': section.saturation,
					'brightness': section.brightness,
					'count': section.count
				}));
				
				this.section_elements.push(section_element);
			}, this);
			
			// percentage
			new Element('div', {
				'class': 'percentage',
				'text': bar.percentage,
				'styles': {
					'color': label_color.hex
				}
			}).inject(element);
			
			this.bar_elements.push(element.inject(this.bar_container));
			var element_size = element.getSize();
			element.setStyle('bottom', -element_size.y);
			this.bar_fx_show_params[i] = {'bottom': 0};
			this.bar_fx_hide_params[i] = {'bottom': -element_size.y};
			
		}, this);
		
		this.bar_fx = new Fx.Elements(this.bar_elements, {
			'link': 'cancel',
			'transition': 'sine:out'
		});
		
		this.tips = new Tips(this.section_elements, {
			'className': 'colorama-stats-tip',
			'offset': {'x': 16, 'y': 16}
		});
	},
	
	toggle: function (event) {
		event.stop();
		(this.is_visible) ? this.hide() : this.show();
	},
	
	show: function () {
		Site.colorama.picker.disable();
		this.is_visible = true;
		this.toggle_button.removeClass('show').addClass('hide');
		this.bar_container.setStyle('visibility', 'visible');
		this.bar_fx.start(this.bar_fx_show_params);
		//pageTracker._trackPageview('/colorama/stats/view/');
		if ($('hiring-apply-now')) $('hiring-apply-now').setStyle('display', 'none');
	},
	
	hide: function () {
		Site.colorama.picker.enable();
		this.is_visible = false;
		this.toggle_button.removeClass('hide').addClass('show');
		this.bar_fx.start(this.bar_fx_hide_params).chain(function () {
			this.bar_container.setStyle('visibility', 'hidden');
		}.bind(this));
		if ($('hiring-apply-now')) $('hiring-apply-now').setStyle('display', 'block');
	},
	
	generateColors: function () {
		var numberOfBars = 30;
		var numberOfSections = 5;
		var elementCoordinates = this.element.getCoordinates();
		var barWidth = elementCoordinates.width / numberOfBars;
		var sectionHeight = elementCoordinates.height / numberOfSections;
		
		numberOfBars.times(function (i) {
			numberOfSections.times(function (j) {
				
				var position = {
					x: (barWidth * i) + (barWidth / 2),
					y: (sectionHeight * j) + (sectionHeight / 2)
				};
				var hue = ((position.x / elementCoordinates.width) * 359).round();
				var saturation = (((position.y / elementCoordinates.height) * 100).round() / 100) * 70 + 30;
				var brightness = ((100 - ((position.y / elementCoordinates.height) * 100).round()) / 100) * 40 + 30;
				
				new Element('div', {
					'text': hue + ', ' + saturation + ', ' + brightness,
					'styles': {
						'position': 'absolute',
						'left': barWidth * i,
						'top': sectionHeight * j,
						'width': barWidth,
						'height': sectionHeight,
						'background-color': new Color([hue, saturation, brightness], 'hsb')
					}
				}).inject(this.element);
				
			}, this);
		}, this);
	}
	
};

window.addEvent('domready', function () {
	if (document.id('colorama')) {
        Site.colorama.initialize();
        Site.colorama.picker.initialize();
        Site.colorama.colorize.initialize();
        Site.colorama.stats.initialize();
    }
	//Site.colorama.stats.generateColors();
});




/**
 * Slideshow
 */
 
var Slideshow = new Class({
	
	Implements: [Options],
	
	options: {
		clear_container: true,
		transition_duration: 1000,
		slide_display_time: 4000,
		delay_after_reset: 8000
	},
	
	initialize: function (container, images, options) {
		this.container = $(container);
		this.images = images;
		this.ubound = this.images.length - 1;
		this.setOptions(options);
		
		if (this.options.clear_container) this.container.empty();
		
		new Asset.images(this.images, {
			'onComplete': function () {
				this.build();
				this.show_image(0);
				this.start_timer($random(30, 60) * 100);
			}.bind(this)
		});
	},
	
	build: function () {
		// Image-Container
		this.image_container_1 = new Element('div', {
			'styles': {
				'opacity': 0
			}
		});
		this.image_1 = new Element('img').inject(this.image_container_1);
		this.image_container_1.inject(this.container);
		
		this.image_container_2 = new Element('div', {
			'styles': {
				'opacity': 0
			}
		});
		this.image_2 = new Element('img').inject(this.image_container_2);
		this.image_container_2.inject(this.container);
		
		this.current_image = this.image_2;
		
		// Effect
		this.fx = new Fx.Elements([this.image_container_1, this.image_container_2], {
			'link': 'cancel',
			'transition': Fx.Transitions.Sine.easeInOut,
			'duration': this.options.transition_duration
		});
		this.fx_params = {
			'0': {'opacity': 0},
			'1': {'opacity': 1}
		};
		
		// Navigation
		this.navigation_container = new Element('div', {
			'class': 'slideshow-navigation'
		});
		this.navigation_items = [];
		this.images.forEach(function (src, index) {
			this.navigation_items.push(new Element('a', {
				'events': {
					'click': this.set_image.pass(index, this)
				}
			}).inject(this.navigation_container));
		}, this);
		this.navigation_container.inject(this.container);
	},
	
	show_image: function (index) {
		if ((index >= 0 && index <= this.ubound) && (index != this.current_image_index)) {
			if (this.current_image_index >= 0) this.navigation_items[this.current_image_index].removeClass('active');
			
			this.current_image_index = index;
			this.navigation_items[this.current_image_index].addClass('active');
			
			this.current_image = (this.current_image == this.image_1) ? this.image_2 : this.image_1; 
			this.current_image.set('src', this.images[this.current_image_index]);
			
			this.fx_params[0].opacity = (this.fx_params[0].opacity) ? 0 : 1; 
			this.fx_params[1].opacity = (this.fx_params[0].opacity) ? 0 : 1; 
			this.fx.start(this.fx_params);
		}	
	},
	
	set_image: function (index) {
		this.reset_timer();
		this.show_image(index);
	},
	
	next_image: function () {
		this.show_image((this.current_image_index < this.ubound) ? this.current_image_index + 1 : 0);
	},
	
	start_timer: function (timer_value) {
		var periodical = timer_value || this.options.slide_display_time;
		this.timer_periodical = this.next_image.periodical(periodical, this);
	},
	
	reset_timer: function () {
		if (this.timer_periodical) this.timer_periodical = clearInterval(this.timer_periodical);
		if (this.timer_delay) this.timer_delay = clearTimeout(this.timer_delay);
		this.timer_delay = this.start_timer.delay(this.options.delay_after_reset, this);
	}

});




/**
 * FlashHeader
 */

var FlashHeader = new Class({
	
	initialize: function (url) {
		if (Browser.Plugins.Flash.version >= 9) {
			this.url = url;
			this.loadFlash();
		}
	},
	
	loadFlash: function () {
		this.swiff = new Swiff(this.url, {
			'width': 960,
			'height': 365,
			'container': 'header-media',
			'vars': {
				'videoPath': '/media/_assets/video/'
			}
		});
	}
		
});




/**
 * CustomTracking
 */
 
 var CustomTracking = new Class({
 	
 	Implements: Options, 	
 	
 	options: {
 		'prefix': '/outbound/'
 	},
 	
 	initialize: function (elements, options) {
 		this.elements = $$(elements);
 		this.setOptions(options);
 		this.elements.forEach(function (element, index, array) {
 			 element.addEvent('click', this.track_view.pass(element.get('href'), this));
 		}, this);
 	},
 	
 	track_view: function (key) {
 		_gaq.push(['_trackPageview', this.options.prefix + key]);
 	}
 	
 });
 
 
 
 
/**
 * MailtoRewrite
 */
 
var MailtoRewrite = new Class({
	
	Implements: Options,
	
	options: {
		className: 'msg',
		domain: 'notch-interactive.com'
	},
	
	initialize: function (options) {
		this.setOptions(options);
		$$('.{className}'.substitute(this.options)).forEach(function (item) {
			if (item.get('href')) {
				var account = item.get('href').match(/^mailto:(.*)$/)[1];
				var email = account + '@' + this.options.domain;
			} else {
				var email = item.get('text') + '@' + this.options.domain;
				item.set('text', email);
			}
			
			item.set('href', 'mailto:' + email);
		}, this);
	}
	
});

window.addEvent('domready', function () {
	new MailtoRewrite();
});




/**
 * TargetModifier
 */

var TargetModifier = new Class({

    Implements: Options,

    options: {
        target: '_blank',
        className: 'target:blank'
    },

    initialize: function(options) {
        this.setOptions(options);
        $$('a').forEach(function(item) {
            if (item.hasClass(this.options.className)) {
                item.set('target', this.options.target);
            }
        }, this);
    }

});

window.addEvent('domready', function() {
    new TargetModifier();
});

