// JavaScript Document

	var rands = 0;
	$(function(){
		
		function WindowManager(id)
		{
			this.id;
			this.$id;
			
			this.load = function (page,prevPage)
			{
				$('#container').hide();
				var $s = this.$id;
				var $body = $s.find('.body');
				var vars = page.split("/");
				var docName = vars.shift();
				var query = new Array();
				for(i=0;i<vars.length;i++) query.push('v'+(i+1)+'='+vars[i]);
				
				var urlPage = "inc-"+docName+".php"+(query.length>0?"?"+query.join("&"):"");
								
				$("#loading").fadeIn('slow');
				if ($s.is(':hidden')) { $body.hide(); $s.fadeIn('slow'); $body.load( urlPage , function(){ $body.fadeIn(); $("#loading").fadeOut('slow'); }); }
				else { $body.fadeOut('slow',function(){ $body.load( urlPage , function(){ $body.fadeIn(); $("#loading").fadeOut('slow'); }); }); }
				
			};
			
			this.close = function () { $('#container').show(); this.$id.fadeOut('slow'); };		
			
			this.construct = function (id)
			{
				this.id = id;
				this.$id = $(this.id);
			};
			this.construct(id);
		};
		
		$w = new WindowManager('#window');
		$('#window .buttons>.close').click(function(){ $w.close(); });
		
		// Variável Global $.my
		$.my = {arrItens:{},arrMenus:{}};
			$.my.selPortfolio = 'all';
			$.my.menus = new Object();
			$.my.paginate = new Object();
			$paginate = $.my.paginate;
		
		// Plugin LIGAR LUZES
		$.fn.turnLights = function(options) {
			
			if (typeof(options)=='string') var options = {state:options};
			var defaults = {state:'on',opacityOn:0.4,opacityOff:0.1,duration:'slow',selectIn:'.bginit',selection:$.my.selPortfolio};
			var o = $.extend(defaults,options);
			switch (o.state)
			{
				case 'off': case false: case 0: $(this).each(function(){ var $sel = o.selectIn?$(this).find(o.selectIn):$(this); $sel.fadeTo(o.duration, o.opacityOff); }); break;
				default: case 'on': case true: case 1: $(o.selection=='all'?this:'.'+o.selection).each(function(){ var $sel = o.selectIn?$(this).find(o.selectIn):$(this); $sel.fadeTo(o.duration, o.opacityOn); }); break;
			}
			return $(this);
		};
		
		// Botões LIGAR LUZES
		$('a[rel^=turnon]').click(function(){
			if (this.rel=='turnon-all') {
				$.my.selPortfolio='all';
				$iten = $('.iten');
				$iten.turnLights('off');
				$iten.turnLights('on');
			} else {
				$.my.selPortfolio=String(this.rel).replace("turnon-","");
				switch ($.my.selPortfolio)
				{
					case 'porcliente':
						$w.load('clientes');
						location.href='#!/clientes/';
					break;
					default:
						$('.iten').turnLights('off');
						$('.'+$.my.selPortfolio).turnLights({state:'on',opacityOn:0.5});
					break;
				}
			}
		});	
		
		// MENU - Popular e organizar

		$(".menu")
			.each(function(i){ $.my.menus[$(this).attr('id')] = $(this).offset(); })
			.css({opacity:0})
			.each(function(i){ $(this).delay(Math.floor(0+Math.random()*1500)).animate({opacity:1},'fast') })
			.each(function(){ $(this).append('<div class="bghover">&nbsp;</div><div class="bginit">&nbsp;</div>'); })
			.hover(function(){$(this).find('.bghover').fadeTo(100, 1);},function(){$(this).find('.bghover').fadeTo(400, 0);});	
		
		// Botões para ativar os menus
		$('[id^=botao-],[id^=wmenu-]').click(function(){
			var popupName = String(this.id).split("-").slice(1).join("-");
			switch (popupName)
			{
				case 'home': $w.close(); break;
				case 'portfolio':
					if (this.id=='wmenu-portfolio')
					{
						$w.close();
						setTimeout(function(){
								$.my.selPortfolio='all';
								$iten = $('.iten');
								$iten.turnLights('off');
								$iten.turnLights('on');												
							},500);
					}
						
					
				break;
				default:
					$w.load(popupName);
				break;
			}
		});	
		
		// PORTFÓLIO
		
		// Função para realocar itens verificando a posição dos menus
		$.fn.reallocateItens = function()
		{
			$(this).each(function(i){
				var $iten = $(this);
				$.each($.my.menus,function(i,offset){
					if (
							(
								$iten.offset().left >= offset.left-5 &&
								$iten.offset().left <= offset.left+5
							) &&
							(
								$iten.offset().top >= offset.top-5 &&
								$iten.offset().top <= offset.top+5
							)
						)
					{
						//$iten.before('<div class="square iten void" style="color:#FFF">teste</div>');
						
						if ($iten.offset().left <= 5) $iten.css({marginLeft:(parseFloat($iten.css('margin-left'))+139)});
						else $prevIten.css({marginRight:(parseFloat($prevIten.css('margin-right'))+139)});
						
					}
				});
				$prevIten = $(this);
			});
			return $(this);
		};
		
		$('.iten')
			.css({opacity:0})
			.each(function(i){$(this).delay(Math.floor(1500+Math.random()*1500)).animate({opacity:1},'slow') })
			.hover(function(){$(this).find('.bghover').fadeTo(100, 1);},function(){$(this).find('.bghover').fadeTo(400, 0);})
			.click(function(){
				if ($(this).attr('rel'))
				{
					fancyboxObj = {
								title: '<strong style="float:right;color:#D00;">'+$(this).attr('type')+'/</strong><h2 style="margin:0;padding:0;margin-bottom:5px;">'+$(this).attr('client')+'</h2>'+$(this).attr('title'),
								padding: 0,
								margin: 0,
								autoScale: false,
								titlePosition: 'outside',
								overlayColor: '#000',
								overlayOpacity: 0.8,
								cyclic: false,
								showNavArrows: false
							};
					switch ($(this).attr('type'))
					{
						case 'video': fancyboxObj.content = $(this).attr('code'); break;
						case 'spot': fancyboxObj.content = '<div style="padding: 58px 43px; text-align: center; background: #111;"><object width="330" height="21"><param name="movie" value="player.swf?file=./arcs/'+$(this).attr('code')+'&as=0"></param><param name="wmode" value="transparent"></param><embed src="player.swf?file=./arcs/'+$(this).attr('code')+'&as=0" wmode="transparent" width="330" height="21" type="application/x-shockwave-flash" swLiveConnect="true"></embed></object></div>'; break;
						default: fancyboxObj.href = $(this).attr('code'); break;
					}
					$.fancybox(fancyboxObj);
				}
			});

		$.ajax({
			type: "GET",
			url: "xml.php?s=portfolio",
			dataType: "xml",
			success: function (data) {
					
				$.my.jobs = data;					
					
				// Reallocate itens
				$('#container .iten').reallocateItens();
				$(window).resize(function(){ $('.iten').each(function(){ $(this).css({margin:0}); }).reallocateItens(); });
			}
		});
		
		/*
		$(document).keyup(function(event){
			switch(event.keyCode)
			{
				case 27:
					$.my.popup.portfolio.hide(); $('.iten').turnLights('on'); return false;
				break;
			}
		});
		)*/
				
		// FANCYBOX - LIGHTBOX
		
        $("a[rel=expand]").fancybox({
            padding: 0,
            autoScale: false,
            titlePosition: 'outside',
			overlayColor: '#000',
			overlayOpacity: 0.8
        });
		
		// ANCHOR REFERENCE
		var anchorRef = self.document.location.hash.substring(3);
		if (anchorRef) $w.load(anchorRef);

	});
