;(function($) {
	
	var BEHAVIOUR_PREFIX = "js";
	var BEHAVIOUR = {};
	
	BEHAVIOUR.homecycle = function()
	{
		var _this = $(this);
		if (_this.data("__homecycle"))
			return this;
		_this.data("__homecycle", "true");
		
		function init() 
		{
			_this.cycle({fx: 'fade'});
		}
		
		init();
		
		return this;
	}
	
	BEHAVIOUR.studio = function()
	{
		var _this = $(this);
		if (_this.data("__studio"))
			return this;
		_this.data("__studio", "true");
		
		function init() 
		{
			$('#studioTeam .cardHeader').hover(function() {
					$(this).parents('.box').addClass('rollover');
				},function() {
					$(this).parents('.box').removeClass('rollover');
				}
			);
			$('#studioTeam .cardHeader').click(function(ev) {
				ev.stopPropagation();
				var $box = $(this).parents('.box');
				if(!$box.hasClass('open')) {
					$('#studioTeam .open').removeClass('open').find('.cardDetails').slideUp('fast');
					$box.addClass('open').find('.cardDetails').slideDown('fast');
				} else {
					$box.removeClass('open').find('.cardDetails').slideUp('fast');
				}
			});
			var leftCol = $('#studioTeam').append('<div class="left"></div>');
			var rightCol = $('#studioTeam').append('<div class="right"></div>');
			var cards = $('#studioTeam .box');
			cards.removeClass('left').removeClass('right');
			cards.each(function(i,e){
				if(i%2==1) {
					$(e).appendTo('#studioTeam .right');
				} else {
					$(e).appendTo('#studioTeam .left');
				}
			});	
		}
		
		init();
		
		return this;
	}
	
	BEHAVIOUR.worksNavigation = function()
	{
		var _this = $(this);
		if (_this.data("__worksNavigation"))
			return this;
		_this.data("__worksNavigation", "true");
		
		function init() 
		{
			_this.find('a').click(function(ev) {
				ev.preventDefault();
				worksPager($(this));
			});
		}
		
		function worksPager($button)
		{
			$('#worksNav a').removeClass('active');
			$button.addClass('active');
			$('#worksPages').animate({'left':-(640*($button.text()-1))+'px'},600);
		}
		
		init();
		
		return this;
	}
	
	BEHAVIOUR.projectGallery = function()
	{
		var _this = $(this);
		if (_this.data("__projectGallery"))
			return this;
		_this.data("__projectGallery", "true");
		
		function init() 
		{
			_this.find('div').each(function(i,el){
				$(el).attr('data',i);
			});
			
			_this.find('div').crossBrowserClick(function(ev){
				clickThumbnail($(this));
			});
		}
		
		function clickThumbnail($e)
		{
			var $g = $('#projectGallery'),
				$d = $('#projectGallery div'),
				a = 'active',
				l = 'loading',
				i = $e.attr('data');
			if(!$e.hasClass(a) && !$g.hasClass(l))
			{
				$d.removeClass(a);
				$g.addClass(l);
				$e.addClass(a);

				$g.find('.active span').append('<img src="/res/img/loading.gif" />');
				
				var img = galleryData[i].s;
				$.cacheImage(img, {
				    load : function (e) {
						var $img = $(this);
						//find height
						$('body').append('<div id="temp"></div>');
						$('#temp').append($img);
						var h = $('#temp img').height();
						var maxh = $('#projectZoom img').css('max-height');
						maxh = maxh.substr(0,maxh.length-2);
						if(h>maxh) h = maxh;
						$('#temp').remove();
						
						$('#projectZoom a').attr('data',i);
						$('#projectZoom').css('height',$('#projectZoom img').height());
						$('#projectZoom img').remove();
						$('#projectZoom a').append($img);
						$('#projectZoom img').css('display','none').fadeIn();
						$('#projectZoom').animate({height:h});
						$g.removeClass(l);
						$g.find('.active span img').remove();
						$('#projectGallery .marker').css('top',$e.position().top+'px');
						$('#projectGallery .marker').css('left',$e.position().left+'px');
					},
				    error: function (e) { $g.removeClass(l); },
				    abort: function (e) { $g.removeClass(l); }
				  });
				
			}
		}
		
		init();
		
		return this;
	}
	
	BEHAVIOUR.projectZoom = function()
	{
		var _this = $(this);
		if (_this.data("__projectZoom"))
			return this;
		_this.data("__projectZoom", "true");
		
		function init() 
		{
			_this.find('a').click(function(ev){
				if(!$('html').hasClass('mobile') || $(this).hasClass('forced')) {
					ev.preventDefault();
					clickZoom($(this));
				}
			})
		}
		
		function clickZoom ($e)
		{
			if($('html').hasClass('mobile') && $(window).scrollTop()==0) {
				window.scrollTo(0, 1);
			}

			_this.data('currentImage',$e.attr('data'));
			_this.data('galleryData',galleryData);
			
			var viewHeight = window.innerHeight ? window.innerHeight : $(window).height(),
				bodyHeight = Math.max($('body').height(), viewHeight),
				scrollTop = $(window).scrollTop();
				
				
			
			$('body').append('<div id="lightbox" style="height:'+bodyHeight+'px;"><div id="lightboxStage" style="top:'+scrollTop+'px;height:'+viewHeight+'px"><div id="lightboxImage"></div><div id="lightboxLoading"><img src="/res/img/loading.gif" /></div><div id="lightboxFooter"><div class="title">'+$('h1').text()+'</div><div class="nav"><div class="prev button"></div><div class="next button"></div></div><div class="close button"></div></div></div></div>');
			//$('html').css('overflow','auto');
			if ($.browser.msie  && parseInt($.browser.version) == 7) {
			  $('html').css('overflow-y','hidden');
			}
			
			$('body').css('overflow','hidden');
			
			
			$('#lightboxFooter').click(function(ev){
				ev.stopPropagation();
			});
			$('#lightbox .next').click(function(ev){
				gotoNext();
			});
			$('#lightbox .prev').click(function(ev){
				gotoPrev();
			});
			if(!$('html').hasClass('mobile')) {
				$('#lightbox .close').click(function(ev){
					closeZoom();
				});
				$('#lightboxStage').click(function(ev){
					closeZoom();
				});
			}
			
			
			$(window).resize(resize);
			window.onorientationchange = function(){
				resize();
			}
			
			loadImage(_this.data('galleryData')[_this.data('currentImage')].b);
			
		}
		
		function AllowZoom(flag) {
		  if (flag == true) {
		    $('head meta[name=viewport]').remove();
		    $('head').prepend('<meta name="viewport" content="width=960, user-scalable=1, maximum-scale=1.6, minimum-scale=.25" />');
		  } else {
		    $('head meta[name=viewport]').remove();
			$('head').prepend('<meta name="viewport" content="width=960, user-scalable=0, initial-scale=1, maximum-scale=1, minimum-scale=1" />');
		    //$('head').prepend('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=0" />');              
		  }
		}
		
		
		
		function resize()
		{
			var h = window.innerHeight ? window.innerHeight : $(window).height();
			$('#lightboxStage').css('height',h+'px').css('top',$(window).scrollTop()+'px');
			$('#lightbox').css('height',Math.max($('body').height(), h)+'px')
			h-=$('#lightboxFooter').height();
			$('#lightboxImage').css('height',h+'px');
			var w = $('body').width();
			$('#lightboxImage img').resizeImage({'height':h,'width':w,'center':true})
			
		}
		
		function loadImage(img)
		{
			
			showLoading();
			$('#lightboxImage img').remove();
			$.cacheImage(img, {
			    load : function (e) {
					hideLoading();
					$('#lightboxImage').append($(this));
					resize();
					$('#lightboxImage img').css('display','none').fadeIn();
				},
			    error: function (e) { },
			    abort: function (e) { }
			  });
			
		}
		
		function closeZoom()
		{
			$('#lightbox').remove();
			$('body').css('overflow','auto');
			if ($.browser.msie  && parseInt($.browser.version) == 7) {
			  $('html').css('overflow-y','auto');
			}
			
		}
		
		function showLoading()
		{
			$('#lightboxLoading').show();
		}
		
		function hideLoading()
		{
			$('#lightboxLoading').hide();
		}
		
		function gotoNext()
		{
			var i = _this.data('currentImage'),
				g = _this.data('galleryData');
				
			i++;
			if(i==g.length) i=0;
			_this.data('currentImage',i),
			loadImage(g[i].b);
		}
		
		function gotoPrev()
		{
			var i = _this.data('currentImage'),
				g = _this.data('galleryData');
				
			i--;
			if(i<0) i=g.length-1;
			_this.data('currentImage',i),
			loadImage(g[i].b);
		}
		
		init();
		
		return this;
	}
	
	/**
	 * common
	 */
	
	$.fn.resizeImage = function(params) {
		
		if(!params.width && !params.height)
			return this;
		
		this.removeAttr('height').removeAttr('width');
		this.css('height','auto').css('width','auto').css('top',0).css('left',0);
		
		this.each(function(i,k){
			_this = $(k)
			var h = _this.height();
			var w = _this.width();
			var ratio = w / h;
			if(params.width) 
			{
				_this.width(params.width);
				_this.height(Math.round(params.width / ratio))
				if(params.height && params.height<_this.height()) 
				{
					_this.height(params.height);
					_this.width(Math.round(params.height * ratio))
				}
			} else {
				_this.height(params.height);
				_this.width(Math.round(params.height * ratio))
			}

			//needs parent with css position absolute or relative
			if(params.center)
				_this.css('position','absolute').css('left',-Math.round((_this.width()-_this.parent().width())/2)+'px').css('top',-Math.round((_this.height() - _this.parent().height())/2)+'px');
		})
		
		return this;
	}
	
	$.fn.crossBrowserClick = function(func) {
		if(window.Touch)
		{
			this.bind('touchend',func);
		} else {
			this.click(func);
		}
	}
	
	$.fn.__crossBrowserClick = function(func){
		if( window.Touch ){
			this.bind('touchstart', function(e){
				e.preventDefault();
				this.moved = false;
				$(this).bind('touchmove', function(){
					this.moved = true;
				});
				$(this).bind('touchend', function(){
					$(this).unbind('touchmove');
					$(this).unbind('touchend');
					if( !this.moved ) {
						$.proxy(func,$(this));
						func();
					}
				});
			});
		} else{
			this.click(func);
		}
	}
	
	$.getUrlVars = function()
	{
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	}
	
	$.getUrlVar = function(name)
	{
		return $.getUrlVars()[name];
	}
	
	$.getResourceBaseUri = function()
	{
		if (!$.cmResourceBaseUri)
		{
			var s = $("head>link").attr("href");
			$.cmResourceBaseUri = s.substring(0,s.lastIndexOf("/res/")+5);
		}
		return $.cmResourceBaseUri;
	}

	$.require = function(scr)
	{
		if (!$.require[scr])
		{
			$.require[scr] = true;
			//var scriptBase = $.getResourceBaseUri() + "js/lib/";
			var scriptBase = "js/lib/"
			$("head").append("<scr" + "ipt type=\"text/javascript\" src=\"" + scriptBase + scr + "\"></script>");
		}
	}
	
	$.resetZoom
	
	if (!window.console)
		window.console = {log:function(){}}
	
	$.fn.GUI = function()
	{
	
		// setup plugins	
		for (var p in BEHAVIOUR)
		{
			$.fn[BEHAVIOUR_PREFIX + p] = BEHAVIOUR[p];
			$(this).find("." + BEHAVIOUR_PREFIX + "-" + p).each(function()
			{
				$(this)[BEHAVIOUR_PREFIX + p]();
			})
		}
	}
	
	$(document).ready(function()
	{
		$('html').GUI();
	})
	
	$(window).load(function()
	{
		$.windowLoaded = true;
	})
	
	
})(jQuery);






