/**
* Inicializa as funç&otilde;es assim que os elementos (DOM) são carregados
* @author André Luís Machado <andre.machado@agenciaclick.com.br>
*/
jQuery(function(){Project._init();});

var Project = {
	/**
	* Função de chamada das outras funç&otilde;es que inicializam o site
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_init: function(){
		try{
			Project._pngFix();
			Project._changeValueSearch();
			Project._returnPage();
			Project._externalLink();
			Project._validate();
			Project._galeriaBlueMe();
			Project._carrosComBlueMe();
			Project._galeriaBlueMeNav();
			Project._carrosComBlueMeNav();
		}catch(e){
			alert('Error: ' + e.description);
		}
	},
	
	/**
	* Chama solução pngfix para problemas com o png24 do IE6
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_pngFix: function() {
		$.browser.msie && $.browser.version==6 ? DD_belatedPNG.fix('img, .pngfix, #header h1 a') : '';
	},
	
	/**
	* Muda o value do campo busca no blur e focus
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_changeValueSearch: function() {
		$('#search')
			.focus(function(){$(this).val()=='BUSCAR' ? $(this).val('') : '' ;})
			.blur(function(){$(this).val()=='' ? $(this).val('BUSCAR') : '' ;});
	},
	
	/**
	* Volta a página anterior
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_returnPage: function() {
		$("a[rel='back-page']").unbind().click(function(){
			window.history.back(-1);
		});
	},
	
	/**
	* Implementa target="_blank" para links externos
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_externalLink: function() {
		$("a[rel='external_link']").unbind('click').click(function(){
			$(this).attr('target','_blank')
		});
	},
	
	/**
	* fecha modal
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_closeModal: function() {
		$('.view_modal').fadeTo('fast', 0, function(){
			$(this).remove();
			$('.bg_modal').fadeTo('fast', 0, function(){ $(this).remove(); });
		});
		$(window).unbind();
		$('.bg_modal').unbind();
		$('select').css('visibility', 'visible');
	},

	/**
	* Validação de formulários
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_validate: function() {
		$('#form_chassi').validate({
			errorContainer: $('#msg_errors'),
			errorLabelContainer: $('ol#msg_errors'),
			wrapper: 'li',
			submitHandler: function(form){
				var options = {
					success: function(data){
						var obj = eval(data);
						if(obj.status == '-1'){
							$('#msg_errors').show().html('').append('<li>' +  obj.message +  '</li>');
						}
						else{
							form.action=obj.urlDownload;
							form.submit();
						}
					}
				}
				
				$(form).ajaxSubmit(options);
			},
			rules: {'chassiVO.numChassi': {required: true, minlength: 17}},
			messages: {'chassiVO.numChassi': {required: 'Número do chassi não confere, verifique se foi digitado corretamente. ', minlength: 'O número deve ter no mínimo 17 dígitos.'}}
		})
	},

	/**
	* Pula para o próximo campo ao atingir o maxlenght
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_nextField: function(ele) {
		var target = ele;
		$('#'+target+' input').each(function(i){
			var i=i;
			$(this).keyup(function(){
				var l=$(this).val().length,
					m=$(this).attr('maxlength'),
					e_next=$(''+target+' input:eq('+parseInt(i+1)+')');	
				if(l==m){
					e_next.attr('type')=='radio' || e_next.attr('type')=='checkbox' ? e_next.is(':checked') : e_next.focus();
				};
			});
		});
	},

	/**
	* galeria blue&me nav
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_galeriaBlueMe: function() {
		var content_galeria = new Array();

		//make fewer requests
		if($('#content_galeria_blueme').length == 0){
			return;
		}
		
		$.getJSON("../js/json_galeria.js",
			function(data){
		        $.each(data.galeria, function(i,item){
					content_galeria.push([item.txt,item.src,item.alt]);
				});

				$('#content_galeria_blueme').fadeTo('fast', 0, function(){
					$('#content_galeria_blueme')
						.html('')
						.append(
							$('<img />').attr({
								src: content_galeria[0][1],
								alt: content_galeria[0][2],
								width: '504',
								height: '191'
							})
						).append(content_galeria[0][0])
						.fadeTo('fast', 1, function(){
							jQuery.browser.msie ? this.style.removeAttribute('filter') : '' ;
						});
				});

				$('#options_galeria_blueme li').each(function(i){
					$(this).hasClass('active') ? '' : $(this).css('opacity',0.7) ;
				
					$(this).find('a')
						.click(function(){
							if($(this).parent().hasClass('active')){return false};
							$(this).parent().parent().find('li').removeClass('active').css('opacity',0.7).end().end().addClass('active').css('opacity',1);
							$('#content_galeria_blueme').fadeTo('fast', 0, function(){
								$('#content_galeria_blueme')
									.html('')
									.append(
										$('<img />').attr({
											src: content_galeria[i][1],
											alt: content_galeria[i][2],
											width: '504',
											height: '191'
										})
									)
									.append(content_galeria[i][0])
									.fadeTo('fast', 1, function(){
										jQuery.browser.msie ? this.style.removeAttribute('filter') : '' ;
									});
							});
							return false;
						})
						.mouseover(function(){$(this).parent().not('#options_galeria_blueme li.active').css('opacity',1);})
						.mouseout(function(){$(this).parent().not('#options_galeria_blueme li.active').css('opacity',0.7);});
				});
			}
		);
	},

	/**
	* galeria blue&me nav
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_galeriaBlueMeNav: function() {
		var content_galeria = new Array();
		//make fewer requests
		if($('#content_galeria_blueme_nav').length == 0){
			return;
		}
		
		$.getJSON("../js/json_galeria_nav.js",
			function(data){
		        $.each(data.galeria, function(i,item){
					content_galeria.push([item.txt,item.src,item.alt]);
				});

				$('#content_galeria_blueme_nav').fadeTo('fast', 0, function(){
					$('#content_galeria_blueme_nav')
						.html('')
						.append(
							$('<img />').attr({
								src: content_galeria[0][1],
								alt: content_galeria[0][2],
								width: '504',
								height: '191'
							})
						).append(content_galeria[0][0])
						.fadeTo('fast', 1, function(){
							jQuery.browser.msie ? this.style.removeAttribute('filter') : '' ;
						});
				});

				$('#options_galeria_blueme_nav li').each(function(i){
					$(this).hasClass('active') ? '' : $(this).css('opacity',0.7) ;
				
					$(this).find('a')
						.click(function(){
							if($(this).parent().hasClass('active')){return false};
							$(this).parent().parent().find('li').removeClass('active').css('opacity',0.7).end().end().addClass('active').css('opacity',1);
							$('#content_galeria_blueme_nav').fadeTo('fast', 0, function(){
								$('#content_galeria_blueme_nav')
									.html('')
									.append(
										$('<img />').attr({
											src: content_galeria[i][1],
											alt: content_galeria[i][2],
											width: '504',
											height: '191'
										})
									)
									.append(content_galeria[i][0])
									.fadeTo('fast', 1, function(){
										jQuery.browser.msie ? this.style.removeAttribute('filter') : '' ;
									});
							});
							return false;
						})
						.mouseover(function(){$(this).parent().not('#options_galeria_blueme_nav li.active').css('opacity',1);})
						.mouseout(function(){$(this).parent().not('#options_galeria_blueme_nav li.active').css('opacity',0.7);});
				});
			}
		);
	},

	/**
	* slide de carros com blue&me
	* @author André Luís Machado <andre.machado@agenciaclick.com.br>
	*/
	_carrosComBlueMe: function() {
		var arr_carros = new Array(),
			bt_prev=$('a.bt_prev_info'),
			bt_next=$('a.bt_next_info'),
			cont=0,
			limite='';
		
		//make fewer requests
		if($('#content_galeria_blueme').length == 0){
			return;
		}
		
		//$('#box_blue_me h3').text('Carros com Blue&amp;Me');
		
		$.getJSON("../js/json_carros.js",
			function(data){
		        $.each(data.carros, function(i,item){
					arr_carros.push([item.nome,item.src,item.modelos]);
				});
				
				limite=parseInt(arr_carros.length-(1));
				
				var _html = function(i){
					$('#box_blue_me div').fadeTo('fast', 0, function(){
						$('#box_blue_me div')
							.html('')
							.append(
								$('<img />').attr({
									src: arr_carros[i][1],
									alt: arr_carros[i][0],
									width: '222',
									height: '91'
								})
							)
							.append($('<p></p>').html('<strong>'+arr_carros[i][0]+'</strong>'))
							.append(
								$('<ul></ul>')
								.addClass('opcional_de_serie')
								.addClass('clearfix')
								.html(arr_carros[i][2])
							)
							.fadeTo('fast', 1, function(){
								jQuery.browser.msie ? this.style.removeAttribute('filter') : '' ;
							});
					});
				};
				
				_html(0);

				bt_prev.css('opacity',0.3);
				
				bt_next.click(function(){
					if(cont!=limite){
						cont++;
						$(this).css('opacity')==0.3 ? $(this).css('opacity',1) : bt_prev.css('opacity',0.3);
						_html(cont);
						if(cont>=limite){
							$(this).css('opacity',0.3);
							bt_prev.css('opacity',1)
						};
					}else{
						$(this).css('opacity',0.3);
					};
					return false;
				});
				
				bt_prev.click(function(){
					if(cont!=0){
						cont--;
						$(this).css('opacity')==0.3 ? $(this).css('opacity',1) : bt_next.css('opacity',0.3);
						_html(cont);
						if(cont==0){
							$(this).css('opacity',0.3);
							bt_next.css('opacity',1)
						};
					}else{
						$(this).css('opacity',0.3);
						bt_next.css('opacity',1)
					};
					return false;
				});
			}
		);
	}
	,
	
	_carrosComBlueMeNav: function() {
		var arr_carros = new Array(),
			bt_prev=$('a.bt_prev_info'),
			bt_next=$('a.bt_next_info'),
			cont=0,
			limite='';
		
		
		//make fewer requests
		if($('#content_galeria_blueme_nav').length == 0){
			return;
		}
		
		//$('#box_blue_me h3').text('Carros com Blue&amp;Me Nav');
		
		$.getJSON("../js/json_carros_nav.js",
			function(data){
		        $.each(data.carros, function(i,item){
					arr_carros.push([item.nome,item.src,item.modelos]);
				});
				
				limite=parseInt(arr_carros.length-(1));
				
				var _html = function(i){
					$('#box_blue_me div').fadeTo('fast', 0, function(){
						$('#box_blue_me div')
							.html('')
							.append(
								$('<img />').attr({
									src: arr_carros[i][1],
									alt: arr_carros[i][0],
									width: '222',
									height: '91'
								})
							)
							.append($('<p></p>').html('<strong>'+arr_carros[i][0]+'</strong>'))
							.append(
								$('<ul></ul>')
								.addClass('opcional_de_serie')
								.addClass('clearfix')
								.html(arr_carros[i][2])
							)
							.fadeTo('fast', 1, function(){
								jQuery.browser.msie ? this.style.removeAttribute('filter') : '' ;
							});
					});
				};
				
				_html(0);

				bt_prev.css('opacity',0.3);
				
				bt_next.click(function(){
					if(cont!=limite){
						cont++;
						$(this).css('opacity')==0.3 ? $(this).css('opacity',1) : bt_prev.css('opacity',0.3);
						_html(cont);
						if(cont>=limite){
							$(this).css('opacity',0.3);
							bt_prev.css('opacity',1)
						};
					}else{
						$(this).css('opacity',0.3);
					};
					return false;
				});
				
				bt_prev.click(function(){
					if(cont!=0){
						cont--;
						$(this).css('opacity')==0.3 ? $(this).css('opacity',1) : bt_next.css('opacity',0.3);
						_html(cont);
						if(cont==0){
							$(this).css('opacity',0.3);
							bt_next.css('opacity',1)
						};
					}else{
						$(this).css('opacity',0.3);
						bt_next.css('opacity',1)
					};
					return false;
				});
			}
		);
	},
	
	_call_crvl: function(){
		a = function(){
			var y;
			if ($('#modal_crlv').pageYOffset){
				y = $('#modal_crlv').pageYOffset;
			}else if(document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft){
				y = document.documentElement.scrollTop;
			}else if(document.body){
				y = document.body.scrollTop;
			};
			return y;
		};
		
		$("a[rel='open-crlv']").click(function(){
			$('#modal_crlv').show();

			$('#modal_crlv').css({
				'margin-top': parseInt(a() - ($('#modal_crlv').height()/2)),
				'margin-left': -parseInt($('#modal_crlv').width()/2)
			}).fadeTo('fast', 1);

			return false;
		});

		$("a[rel='close-crlv']").click(function(){
			$('#modal_crlv').fadeTo('fast', 0, function(){ $(this).hide(); });
			return false;
		})
		
	}
};
