/**
 * autor: Marcio Antunes
 * email: cgslivre@cgslivre.com.br
 * para: www.tech&art.com.br
 * data: 18/09/2011
 */
$(document).ready(function(){

	/*$('.sections-menu')
	.css({
		'margin-left': ( ($('.header').innerWidth() - $('.sections-menu').outerWidth()) / 2 )+'px'
	});*/
	
	if(window.location.pathname == '/' || window.location.pathname == '/home'){
		
		
		var img = $('<img style="width: 100%; float: left;" src="/web-files/img/feriado.png" alt="Aviso de feriado" />');
		var aviso = $('<div style="z-index: 10000; display: none; position: absolute; width: 466px; height: 304px; top: 35%; left: 70%; margin-left: -233px; margin-top: -152px;"></div>');	
		//var close = $('<a href="#" title="Fechar este aviso" style="background: transparent url();z-index: 10001; position: absolute; right: 29px; top: 4px; width: 42px; height: 42px;"></a>');
		aviso
		.click(function(){
			$(this).fadeOut(500).remove();
			return false;
		});
		
		img.load(function(){
			aviso.append($(this));//.append(close);
			$('body').prepend(aviso);
			aviso.fadeIn(500);
		});
		
	}
	
	$('.slider ul.itens').roundabout({
        duration: 800,
        btnNext: '.slider a.next',
        btnPrev: '.slider a.prev'
	})
	.hover(function(){
		clearInterval(slider_timer);
	}, function(){
		start_slider();
	});
	
	start_slider();

	var footer_is_visible = false;	
	
	$('.header, .main, .slider')
	.live({
		click: function(){
			if(footer_is_visible){
				footer_is_visible = false;
				$('.footer-state-hide').click();
				return false;
			}
			return true;
		}
	});
	
	$('a[href="#sobre"]')
	.live({
		click: function(){
			$('.footer-state-show').click();
			return false;
		}
	})

	$('.footer-state-hide')
	.live({
		click: function(){
			var self = $(this);
			$('.footer').slideUp(function(){				
				self
				.hide()
				.insertAfter('.footer')
				.removeClass('footer-state-hide')
				.addClass('footer-state-show')
				.fadeIn('fast');
			});
			return false;
		}
	});

	$('.footer-state-show')
	.live({
		click: function(){
			footer_is_visible = true;
			var self = $(this);
			$('.footer').slideDown(function(){				
				self
				.hide()
				.insertBefore('.footer-content')
				.removeClass('footer-state-show')
				.addClass('footer-state-hide')
				.fadeIn('fast');
				content_scroller_cmd();
			});
			return false;
		}
	});
	
	/**
	 * Validate Settings
	 */
	$('#contact-form')
	.validate({
		/*
		 * required fields
		 */
		rules: {
			nome: 'required',
			assunto: 'required',
			mensagem: 'required',
			email: {
				required: true,
				cgs_email: true
			}
		},
		/*
		 * required fields messages
		 */
		messages:{
			nome: 'Informe seu nome por favor!',
			assunto: 'O assunto é um campo requerido!',
			mensagem: 'Digite sua mensagem, por favor!',
			email: {
				required: 'Informe seu endereço de email!',
				cgs_email: 'Por favor, informe um enderelo de email válido!'
			}
		},
		errorPlacement: function(){
			
		},
		/*
		 * callback for submit event
		 * execute a ajax request and print return
		 */
		submitHandler: function(form){
			/*var data = doPost($(form).attr('action'), $(form).serialize());
			$(form).reset();
			$(form).prepend('<p class="padding image text-center '+(data == "Mensagem enviada com sucesso!" ? ' highlight' : ' error' )+'">'+data+'</p>');
			return false;*/
			
			$(form)
			.animate({'margin-left': '300px'}, 300);
			
			$('.send-loader')
			.animate({'right': 0}, 300, function(){
				//
				$.ajax({
					url: $(form).attr('action'),
					type: 'POST',
					data: $(form).serialize(),
					success: function(data){
						if(data == 'Mensagem enviada com sucesso!'){
							setTimeout(function(){
								$('.send-loader .loader').hide();
							}, 1000);
							
							setTimeout(function(){
								$('.send-loader .success').fadeIn(200);
							}, 1000);
							
							setTimeout(function(){
								$(form).reset();
								$('.close-contact-form').click();
							}, 3000);
						}else{
							$('.send-loader').html(data);
							setTimeout(function(){
								$(form).reset();
								$('.close-contact-form').click();
							}, 3000);
							//alert(data);
						}
					}
				});
			});
			
			return false;
		
		}
	});
	
	/**
	 * (X)HTML Validation hack
	 */
	$('a')
	.each(function(){
		if($(this).attr('title').toLowerCase() == 'abre externamente' && $(this).attr('href') != '#'){
			$(this).attr('target', '_blank');
		};
	});
	
	/**
	 * Aplica efeito de opacidade nos links que levam ao cardápio
	 */
	$('.main-list li').fadeTo(50, 0.8);
	
	/**
	 * Aplica efeito ao passar do mouse
	 */
	$('.main-list li')
	.hover(function(){
		$(this).fadeTo(300, 1);
	}, function(){
		$(this).fadeTo(500, 0.8);
	});
	
	/*
	 * 
	 */
	
	$('.portfolio ul a, .slider ul a')
	.each(function(index) {
		if(!$(this).parent().hasClass('grafico')){
			$(this)
			.attr('target', '_black')
			.hover(function(){
				$('.info', this).fadeTo(500, '0.8');
			}, function(){
				$('.info', this).fadeOut();
			});
		}else{
			$(this)
			.attr({
				href: $('img', this).eq(0).attr('src'),
				rel: 'colorbox'
			})
			.hover(function(){
				$('.max', this).fadeTo(500, '0.8');
			}, function(){
				$('.max', this).fadeOut();
			})
			.colorbox({
				maxWidth: '800',
				maxHeight: '600',
				scalePhotos: true
			});
		}
	});
	
	$('.clients-list a')
	.each(function(index) {
		$(this)
		.attr('target', 'blank')
		.hover(function(){
			var img = $('img', this);
			img.attr('src', img.attr('src').replace('.png', '-hover.png'));
		}, function(){
			var img = $('img', this);
			img.attr('src', img.attr('src').replace('-hover.png', '.png'));
		});
	});
	
	var contact_form_is_visible = false;
	
	$('a[href="#contato"]')
	.live({
		click: function(){
			if(contact_form_is_visible){
				$('.close-contact-form').click();
				contact_form_is_visible = false;
				return false;
			}
			$('html, body').animate({scrollTop:0}, 200, function(){
				$('.contact-form-overlay, .contact-form').stop().animate({right: '0'}, 500);
			});
			setTimeout(function(){
				contact_default_values();
			}, 700);
			contact_form_is_visible = true;
			return false;
		}
	});
	
	$('.close-contact-form')
	.live({
		click: function(){
			
			contact_form_is_visible = false;
			
			$('.contact-form-overlay, .contact-form').animate({right: '-300px'}, 500);
			
			$('#contact-form').animate({'margin-left': 0}, 500);
			
			$('.send-loader').animate({'right': '-300px'}, 500);
			
			$('span', '#contact-form').remove();
			
			return false;
		}
	})
	.fadeTo(50, 0.7)
	.hover(function(){
		$(this).fadeTo(50, 1);
	}, function(){
		$(this).fadeTo(50, 0.7);
	});
	
	content_accordion();
	
	portfolio();
	
	portfolio_filters();
			
});

var slider_timer = false;
function start_slider(){
	
	slider_timer = setInterval(function(){
		$('.slider ul.itens').roundabout_animateToPreviousChild();
	}, 5000);
	
	$('.slider a.next, .slider a.prev')
	.live({
		click: function(){
			clearInterval(slider_timer);
			start_slider();
		}
	})
};

var contact_default_values = function( ){
	$('#contact-form input, #contact-form textarea')
	.each(function(index) {
		var self = $(this);
		var txt = self.attr('title');
		var span = $('<span>'+txt+'</span>');
		span.css({
			display: 'block',
			padding: '8px 10px 5px',
			width: '230px',
			position: 'absolute',
			top: (self.offset().top)+'px',
			right: '25px'
		});
		
		span
		.insertBefore(self)
		.click(function(){
			$(this).hide().next().focus();
		});
		
		self
		.blur(function() {
			if( $(this).val() == '' ){
				$(this).prev().show();
			}
		})
		.focus(function() {
			$(this).prev().hide();
		});
	});
}

var itens_per_page 	= 6;
var lines_per_page 	= 2;
var current_page	= 0;
var pages = 0;
var scroll_width = 0;

var update_portfolio = function(){
	
	$('.paginator').hide();
	
	current_page = 0;
	
	var container = $('.portfolio ul');
	
	var itens = $('li:visible', container);
	
	var dim_item = {
		width: itens.outerWidth(),
		height: itens.outerHeight()
	};
	
	pages = (Math.ceil(itens.length / itens_per_page));
	
	scroll_width = dim_item.width * ( itens_per_page / lines_per_page );
	
	container.css({width: (dim_item.width *(Math.ceil(itens.length / lines_per_page)))+'px'});
	
	if(pages > 1){
		$('.paginator').show();
		$('.paginator span').text((current_page+1)+'/'+pages);
	}else{
		container.css({width: '960px'});
	}
	
	animate_scroll(container, 0);

	//return {pages: pages, scroll_width: scroll_width};

};

var portfolio = function(){
	
	if($('.portfolio').get().length){
		
		update_portfolio();
	
		var container = $('.portfolio ul');
	
		$('.paginator a.prev')
		.live({
			click: function(){
				
				current_page = (current_page -1) > 1 ? current_page -1 : 0 ;
				
				animate_scroll(container, (scroll_width * current_page));
				
				$('.paginator span').text((current_page+1)+'/'+pages);
				
				return false;	
			}
		});
		
		$('.paginator a.next')
		.live({
			click: function(){
				current_page = (current_page +1) < pages ? current_page +1 : 0 ;
				
				animate_scroll(container, (scroll_width * current_page));
				
				$('.paginator span').text((current_page+1)+'/'+pages);
				
				return false;	
			}
		});
		
	};
	
};

var animate_scroll = function(container, scroll_width){
	container.stop().animate({'margin-left': '-'+(scroll_width)+'px'}, 300);
};
		
var portfolio_filters = function(){
	$('.apply-filters a')
	.live({
		click: function(){
			
			$('.paginator').hide();
			
			var filter = $(this).attr('id');
			
			$('.apply-filters a').removeClass('active');
			
			if(filter == 'all'){
				$('.apply-filters .display-all').hide();
				$('.portfolio ul li.'+filter).show('300', function(){
					setTimeout("update_portfolio()", 100);
				});
				return false;
			}else{
				$('.apply-filters .display-all').show();
			}
			
			$(this).addClass('active');
			
			$('.portfolio ul li').hide('100');
			$('.portfolio ul li.'+filter).show('300', function(){
				setTimeout("update_portfolio()", 100);
			});
			
			return false;
			
		}
	});
}

var content_accordion = function(){
	
	if($('.accordion').get().length){
		
		var container = $('.accordion');
		
		$('.show-hide')
		.live({
			click: function(){
				var self = $(this);
				var content = $('.description', self.parent());
				var all_content = $('.description', container);
				
				if(content.is(':visible')){
					
					content.slideUp();
					self.text('+').css('right', '5px');
					return false;
					
				}else{
				
					$('.show-hide', container).text('+').css('right', '5px');
					
					all_content.slideUp(500);
					
					setTimeout(function(){
						content.slideDown();
						self.text('-').css('right', '13px');
					}, 50)				
					
					return false;
				}
				
			}
		});
		
		var open_hash = window.location.hash.replace('#', '');
		
		if(open_hash == ''){
			
			$('#_web_design').click();
		
			}else{
			
			var link = $('#_'+open_hash);
			
			if(link.length){
			
				link.click();
				
				$('html, body').delay(300).animate({scrollTop:link.parent().offset().top}, 'slow');
			
			}
		
		}
		
		
		
	}
	
};

/**
 * executa uma requisição assincrona via POST, enviando 
 * o parameto objectData para a url urlToPost retornando
 * um responseText (html, json, text/plain)
 * 
 * @param urlToPost
 * @param objectData
 * @return string
 */
var doPost = function (urlToPost, objectData){
	return $.ajax({
		async: false,
		type: 'POST',
		url: urlToPost,
		data: objectData
	}).responseText;		
};

/**
 * jQuery reset form plugin
 */
$.fn.reset = function (){
   $(this).each (function(){
      this.reset();
   });
};

var timer_down = false;
var timer_up = false;
var multiple = 15;
var scroller_status = 0;
var scroller_height = 0;

var content_scroller_cmd = function(){
	
	setTimeout(function(){
		
		scroll_content(0);
		
		scroller_height = parseInt( $('.scrollable-content').outerHeight() - $('.scrollable-content-base').outerHeight() ) + 20;
		var scroller_cmd	= $('.scroll-content');
		var scroller_up 	= $('.scroll-up');
		var scroller_down 	= $('.scroll-down');
		
		if(scroller_height > 0){
			
			/*if($.browser.mozilla){
				scroller_up
				.css('right', '3px')
				.css('top', '-1px')
				.hover(function(){
					$(this).css('background-position', '-13px -62px');
				}, function(){
					$(this).css('background-position', 'center top');
				});
			}*/
			
			scroller_cmd.show();
			
			scroller_up
			.click(function(){
				return false;
			})
			.mousedown(function(){
				clearInterval(timer_up);
				timer_up = setInterval(function(){
					if(scroller_status > 0){
						scroll_content( '-'+(scroller_status - multiple));
						scroller_status-= multiple;
					}
				}, 25);
				return false;
			})
			.mouseup(function(){
				clearInterval(timer_up);
				return false;
			});
			
			
			scroller_down
			.click(function(){
				return false;
			})
			.mousedown(function(){
				clearInterval(timer_down);
				timer_down = setInterval(function(){				
					if(scroller_height > ( scroller_status)){
						scroll_content( '-'+scroller_status);
						scroller_status+= multiple;
					}				
				}, 25);			
				return false;
			})
			.mouseup(function(){
				clearInterval(timer_down);
				return false;
			});
		}else{
			scroller_up
			.click(function(){
				return false;
			});
			
			scroller_down
			.click(function(){
				return false;
			});
		};
		
	}, 50);
	
};

var scroll_content = function( pixels ){
	$('.scrollable-content')
	.css({
		top: pixels+'px'
	});
};

