/*** jQuery Cookie plugin** Copyright (c) 2010 Klaus Hartl (stilbuero.de)* Dual licensed under the MIT and GPL licenses:* http://www.opensource.org/licenses/mit-license.php* http://www.gnu.org/licenses/gpl.html**/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;};;
/* jquery.imagefit 
 *
 * Version 0.2 by Oliver Boermans <http://www.ollicle.com/eg/jquery/imagefit/>
 *
 * Extends jQuery <http://jquery.com>
 *
 */
(function($) {		
	
	$.fn.imagefit = function(options) {
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
				$(img)
					.width('100%').each(function()
					{
						$(this).height(Math.round(
							$(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
						);
					})
				}
		};
		
		this.each(function(){
				var container = this;
				
				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));
				
				// store initial dimensions on each image 
				imgs.each(function(){
					$(this).attr('startwidth', $(this).width())
						.attr('startheight', $(this).height())
						.css('max-width', $(this).attr('startwidth')+"px");
				
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);;
/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);
;
/* http://yelotofu.com/2008/08/jquery-shuffle-plugin/ */
(function($){  $.fn.shuffle = function() {    return this.each(function(){      var items = $(this).children();      return (items.length)        ? $(this).html($.shuffle(items))        : this;    });  }   $.shuffle = function(arr) {    for(      var j, x, i = arr.length; i;      j = parseInt(Math.random() * i),      x = arr[--i], arr[i] = arr[j], arr[j] = x    );    return arr;  }})(jQuery);


//var loader = new Loader();
var intro = null;

var overlink = new Overlink();


jQuery(document).ready(function(){
		//var $elements = jQuery("body.front .views-row, body.front .region-column-fifth-inner .block");
		//$elements.css("opacity", 0.1);
		
		/*
		$elements.hover(
		function() {
			//jQuery(this).css('opacity', 1);
			//jQuery(this).scrollTop(jQuery(this).top) 
			jQuery(this).fadeTo('fast', 1);			
		},
		function() {
			jQuery(this).stop().css('opacity', 0.2);			
		}		
		);
		*/
		//loader.start();				
		/*
		jQuery('#block-block-8').bind('responsivelayout', function (e, d) { 
			alert("chagne");		
		} );
		*/
			
		
		if(jQuery('body.front').length) {														
			if(!jQuery.cookie('intro2')) {
				//jQuery.cookie('intro', 'played', { expires: 7 });
				jQuery.cookie('intro2', 'played');
				intro = new Intro();
			}															
		} 	
		
		
		if(jQuery('.views-row').length) {														
			jQuery('.views-row').mouseenter(overlink.start);															
		} 																	});



	

jQuery(window).load(function(){
		// http://code.google.com/p/jquery-imagefit-plugin/    //jQuery('.field-content a').imagefit();
    //jQuery('#zone-column').imagefit();    
    jQuery('#section-content').imagefit();
    //loader.finish();   
    if(intro) {    		
			intro.next();    		
    	}
    	
		if(jQuery('body.front').length) {												
			//highlight = new Highlight();								
		} 	    	   
		
		if(jQuery(".fb-share").length) {
			fb_width();			
		}				 	   });


function Overlink() {
	var self = this;
	self.$elem = null;
	self.$ref = null;	
	self.isMobile = false;
		
	this._constructor = function() {														
		self.ini();							  						
	}		
	
	this.ini = function() {
		
		// Check if mobile 
		var deviceAgent = navigator.userAgent.toLowerCase();           var agentID = deviceAgent.match(/(mobile)/);        if (agentID) {    		self.isMobile = true;    		    }		
		
		jQuery(document).ready(function() {	
			self.ready();											
		});							
	}
	
	this.ready = function() {
		if(self.isMobile) {
			return;	
		}
		
		jQuery("body").prepend("<a id='overlink' style='display:none;position:absolute;'><div class='overlink-title'></div><div class='overlink-readon'>" + Drupal.t('read on') + "</div></a>");
		self.$elem = jQuery("#overlink");
		self.$elem.mouseleave(self.end);
		//self.$elem.css('opacity', 0.98);		
		self.$elem.css('opacity', 0.18);
				
		Drupal.behaviors.overlink = {	    attach: function (context, settings) {	    		
				jQuery('.views-row').mouseenter(self.start);					    }	  };												
	}	 		 				
	
	this.start = function() {
		self.$ref = jQuery(this);
		jQuery(document).bind('mousemove', self.move);
		
		var color = '#666';
		/*			
		var colorselectors = ".views-field-field-reference-term-web a, .views-field-field-reference-term-design a, a.term-product";	
		if(newcolor = jQuery(colorselectors, self.$ref).eq(0).css('background-color')) {
			color = newcolor;	
		}	
		*/	
		
		var offset = self.$ref.offset();
		jQuery('.overlink-title').text(jQuery(".views-field-title a", self.$ref).text());		
		self.$elem
			.attr('href', jQuery("a", self.$ref).eq(0).attr('href'))
			.css('left', offset.left + 'px')
			.css('top', offset.top + 'px')
			.css('width', self.$ref.outerWidth() + 'px')
			//.css('cursor', 'default')
			.css('height', self.$ref.outerHeight() + 'px')
			.css('background-color', color)						
			.show()						
			;				
			
			self.position(offset.top, offset.left);
	}										

	this.end = function() {
		jQuery(document).unbind('mousemove', self.move);
		self.$elem.hide();		
	}

	this.move = function(e) {								
		//self.position(e.clientY + jQuery('html, body').scrollTop(), null, true);											
		self.position(e.pageY, null, true);
	}	
	
	this.position = function(top, left, from_move) {
		var offset = self.$ref.offset();	
		
		if(top) {
			
			if(from_move) {				
				var height = self.$elem.outerHeight();		
				var diff = parseInt(height/2) + 2;
				top -= diff;				
			}			
			
			if(top < offset.top) {
				top = offset.top;
			} else {
				//console.log(offset.top + self.$ref.height() + diff);
				if((top) > offset.top + self.$ref.outerHeight() - self.$elem.outerHeight()) {
					top = offset.top + self.$ref.outerHeight() - self.$elem.outerHeight();
				}
			}
			self.$elem.css('top', top + 'px');																		
		}				
		
		if(left) {
			self.$elem.css('left', left + 'px');																		
		}									
	}		
	
	this._constructor();
}


/* CORRECT WIDTH WHEN FB BUTTON IS LOADED - this is crowd, better would be a callback from FB object when it's loaded - facebook is like IE 6 for webdevelopers
	TODO: onresize currently not working due padding changes
*/
var fb_width_count = 0;
function fb_width() {
	fb_width_count++;	
	if(fb_width_count > 50) {		
		return;			
	}
	if(jQuery(".fb-share").outerWidth() != 55) {
		diff = jQuery(".fb-share iframe").outerWidth() - 55;
		diff += 8; // this was a white space inner fb 
		diff2 = parseInt(diff/2);				
		var left = parseInt(jQuery(".google-share").css('padding-left'));
		var right = parseInt(jQuery(".google-share").css('padding-right'));		
		left -= diff2;
		right -= diff2; 		
		jQuery(".google-share").css('padding-left', left);
		jQuery(".google-share").css('padding-right', right);				
	} else {		
		window.setTimeout(fb_width, 250);
	}	
}	


function Loader() {
	var self = this;	
		
	this._constructor = function() {														
		self.start();							  						
	}			
	
	this.start = function() {
		//console.log('loader start');			
		//jQuery('#section-content').css('opacity', '0');																					
		//jQuery('#page').css('opacity', '0');
	}										

	this.finish = function() {
		//console.log('loader finish');
		//jQuery('#section-content').css('opacity', '1');																						
		//jQuery('#page').css('opacity', '1');
	}	

	this._constructor();
}



function Intro() {
	var self = this;	
	
	self.start = 0;
	self.max = 4;
	self.speed = 400;		
	
	self.$menu = null;
	self.$region = null;

	this._constructor = function() {					
		self.ini();
	}	
	
	this.ini = function() {
		self.$menu = jQuery('#zone-menu .menu li');
		self.$region	 = jQuery('#zone-column .region');
		self.max = self.$menu.length - 1;		
		self.$menu.css('opacity', 0.5);		
		self.$region.css('opacity', 0.2);				
	}	 				
													
	this.next = function() {				
		
		if(self.start == 'done') {						
			//jQuery('#zone-column .region').stop();						
			self.$menu.animate({opacity: 1.0}, self.speed*2)
			self.$region.animate({opacity: 1.0}, self.speed*2)
			//console.log(jQuery('#zone-menu .menu li').eq(0).css('opacity'));
			return;
		}
					
		if(self.start > self.max) {
			self.$menu.eq(self.start-1).animate({opacity: 0.5}, self.speed/2);		
			self.$region.eq(self.start-1).animate({opacity: 0.2}, self.speed/2, self.next);					
			self.start = 'done';														
			return;	
		} else {
			if(self.start) {
				self.$menu.eq(self.start-1).animate({opacity: 0.5}, self.speed);		
				self.$region.eq(self.start-1).animate({opacity: 0.2}, self.speed);
			}			
		}			
												
		self.$menu.eq(self.start).animate({opacity: 1}, self.speed);		
		self.$region.eq(self.start).animate({opacity: 1}, self.speed, self.next);
		//jQuery('#zone-column .region').eq(self.start).fadeIn(self.speed, self.next);								
		
		self.start++;						
		//jQuery().eq(self.start).fadeIn(self.speed);																				
	}	

	this._constructor();
}


function Highlight() {
	var self = this;	
		
	self.speed = 300;	
	self.start = 0;

	this._constructor = function() {
		self.ini();	
	}	
	
	this.ini = function() {		
		self.max = jQuery('#zone-column .region').length - 1;
		jQuery('#zone-column .region').addClass('highlighted');		
		self.next();						
	}	 				
													
	this.next = function() {		
		if(self.start) {		
			//jQuery('#zone-menu .menu li').eq(self.start-1).css('background-color', '#fff');		
			jQuery('#zone-column .region').eq(self.start-1).removeClass('highlighted');
		}		
						
		if(self.start > self.max) {
			return;	
		}			
						
		//jQuery('#zone-menu .menu li').eq(self.start).css('background-color', '#FAD160');		
		jQuery('#zone-column .region').eq(self.start).addClass('highlighted');
		
		self.start++;
		window.setTimeout(function() { self.next(); }, self.speed);																														
	}	

	this._constructor();
}

//var screensaver = new Screensaver();

function Screensaver() {
	var self = this;	
	//self.selector = "body.front .views-row, body.front .region-column-fifth-inner .block";	
	self.selector = "body.front .region-column-first-inner .views-row";
	self.selector += ", body.front .region-column-second-inner .views-row";
	self.selector += ", body.front .region-column-third-inner .views-row";
	self.selector += ", body.front .region-column-fourth-inner .views-row";
	self.selector += ", body.front .region-column-fifth-inner .block";
	
	self.start = null;
	self.wait = 3000;
	self.status = false;
	self.index = null;		
	
	
	self.story = [
	{index: 28, text: 'Hello! My name is Nico.'},
	{index: 24, text: 'One of my latest logo is this.'},
	{index: 26, text: 'Contact me if you also want a logo.'},
	];
	self.storyIndex = 0;
	
	
	this._constructor = function() {		
		jQuery(document).ready(function() {	
			self.ready();											
		});											
	}
	
	this.ready = function() {
		self.start = self.timestamp();			
		self.check();		
		
		jQuery(document).mousemove(function() {
			if(self.status) {
				self.shutdown();	
			}	
			self.start = self.timestamp();											
		});																	
	}
	
	this.timestamp = function() {		
		var time = new Date();  		return time.getTime();													
	}	  	
	
	this.begin = function() {		
		self.status = true;
		//jQuery(self.selector).css("opacity", 0.1);
		jQuery(self.selector).fadeTo(1400, 0.2);
		
		jQuery('#section-header').height(jQuery('#section-header').height());						
		
		jQuery("#section-header div").fadeOut(1400);		
		jQuery('body').animate({	    backgroundColor: '#333'	    	  }, 1400, function() {
	  		
			jQuery('#section-header').addClass("story-teller");		
			jQuery('body').css("padding-top", jQuery('#section-header').height() + 6);	 // 6 is section-header padding-bottom	  		
	  		
	  	
	  		jQuery("#section-header").append('<div id="story-teller">At once a story is told ...</div>');
	  		var height = jQuery("#story-teller").height();
	  		jQuery("#story-teller").css("padding-top", (jQuery('#section-header').height()-height)/2 + 4) ;
	  		jQuery("#story-teller").hide();
			jQuery("#story-teller").fadeIn(800);	  			  			  		
	  		jQuery("#section-header").fadeTo(800, 0.8, function() {
	  			window.setTimeout(function() { self.change(0); }, 1000);	
	  		});	  	  	
	    	  });			
	  
	  	  	
	  		
	}
	
	
	this.shutdown = function() {
			
		jQuery(self.selector).stop();
		jQuery("html, body").stop();
		jQuery("body").css("background-color", "#eee");		
		jQuery(self.selector).css("opacity", 1);
		jQuery("#story-teller").remove();
		jQuery("#section-header").show();
		jQuery('html, body').scrollTop(0);		
		self.status = false;
		self.start = self.timestamp();	
		self.check();													
	}	  		
	
	
	this.change = function(step) {
		if(!self.status) {
			return;			
		}
		//console.log(step);		
		
		switch(step) {
			default:	
			case 0:			
				if(self.index) {
					var $elem = jQuery(self.selector).eq(self.index);
					$elem.fadeTo(500, 0.2, function() {																	
						//self.change(1);
					});	
					window.setTimeout(function() { self.change(1); }, 200);
				} else {
					self.change(1);
				}
				break;
									
			case 1:
				var len = jQuery(self.selector).length;
				//self.index = parseInt(Math.random() * len);				
				self.index = self.story[self.storyIndex].index;
				jQuery("#story-teller").text(self.story[self.storyIndex].text);
				self.storyIndex++;
				if(self.storyIndex >= self.story.length) {
					self.storyIndex = 0;	
				}
						
				var $elem = jQuery(self.selector).eq(self.index);
								
				//console.log(self.index + ": " + jQuery(".views-field-title	 .field-content", 	$elem).text());
				var top = $elem.offset().top - jQuery(window).height()/2 + $elem.height()/2;
				
				var current_top = jQuery('html, body').scrollTop();
				
				var duration = 0;
				var diff = Math.abs(current_top - top);
				
				if(diff > 0) {					
					duration = parseInt(diff / 2);
					//console.log(duration);
					duration = Math.max(700, duration);
					//console.log(duration);
					duration = Math.min(2300, duration);
					//console.log(duration);					
					//console.log("---------------");
					
					jQuery('html, body').animate({						scrollTop: top					}, duration, 'swing');
					window.setTimeout(function() { self.change(2); }, (duration-300));					
				}				
				else {					
					self.change(2);	
				}								
				break;		
				
			case 2:											
				jQuery(self.selector).eq(self.index).fadeTo("normal", 1, function(){												
					window.setTimeout(self.change, 3000);	
				});	
				break;		
		}																			
	}	  	
	
			  		
	
	this.check = function() {		
		if(self.timestamp() - self.start > self.wait) {
			self.begin();	
		}
		else {			
			window.setTimeout(self.check, 1000);
		}													
	}	
	
	
		
	this._constructor();
};

