jQuery.noConflict();
 
 jQuery(document).ready(function(){
	modal();
	externalLinks();
	confirmacao();
	legendas();
	busca_produtos();
	if (get('zoom-increase')) loadZoom();
	if (get('faleconosco')) contato();
	if (get('historico')) empresa_historico();
	if (get('dicas')) aftermarket_dicas();
});

jQuery( function($){
	$("input.date").mask("99/99/9999");
	$("input.phone").mask("(99) 9999-9999");
});


function addEvent(obj, evType, fn){
    if (obj.addEventListener){
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
		return r;
    } else {
		return false;
    }
}


function removeEvent(obj, evType, fn){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, false);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
        return r;
    } else {
		return false;
    }
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
	}
}

function get(el) {
	return document.getElementById(el);
}

function createFlashTitle(el, strTitulo, varEstilo, varWidth) {
	var strFlash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+varWidth+'" height="28"><param name="movie" value="swf/titulo.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="flashvars" value="strTituloPHP='+strTitulo+'&amp;varEstiloPHP='+varEstilo+'" /><embed src="swf/titulo.swf" width="'+varWidth+'" height="28" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent" flashvars="strTituloPHP='+strTitulo+'&amp;varEstiloPHP='+varEstilo+'"></embed></object><span style="display: none">'+strTitulo+'</span>';
	el.innerHTML = strFlash;
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\\\s)"+searchClass+"(\\\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function legendas() {
	jQuery(".image-left, .image-center, .image-right").each( function() {
		var w = getImageSize(jQuery(this).find('img').attr('src'));
		jQuery(this).find('small').css('width',parseInt(w)+'px');
	});
}


function getImageSize(src) {
	var newImg = new Image();
	newImg.src = src;
	var width = newImg.width;
	var height = newImg.height;
	var sizes = new Array(width, height);
	return sizes;
}

function affectedFields(form,el) {
	var classname = 'affected';
	jQuery(form+' *').each( function() {
		if (el!='') {
			if (jQuery(this).attr('id')==el) {
				jQuery(this).focus().addClass(classname);
			} else {
				jQuery(this).removeClass(classname);
			}
		} else {
			jQuery(this).removeClass(classname);
			jQuery(form).resetForm();
		}
	});
	return false;
}

function confirmacao() {
	jQuery('a.confirmacao').bind('click', function() {
		var title = jQuery(this).attr('title');
		if (!confirm(title)) {
			return false;
		}
		return true;
	});
}


/* Zoom */

function loadZoom() {
	addEvent(get('zoom-increase'), 'click', increaseZoom);
	addEvent(get('zoom-decrease'), 'click', decreaseZoom);
	return false;
}

function increaseZoom() { zoom(true); }
function decreaseZoom() { zoom(false); }

function zoom(b) {
	var f = (parseInt(get('conteudo').style.fontSize) || 100) * (b ? 1.1 : 0.9);
	if (f >= 80 && f <= 120) {
		get('topo').style.fontSize = f + "%";
		get('conteudo').style.fontSize = f + "%";
	}
}


/* Contato */

var contatoForm = '#contato';
var contatoMsg = contatoForm+' #mensagem';
var contatoSubmit = contatoForm+' .bt';

function contato() {
	var options = {
		beforeSend: contatoBefore, 
		url: 'ajax.php', 
		dataType: 'xml', 
		type: 'POST', 
		success: contatoResponse 
	};
	jQuery(contatoForm).ajaxForm(options);
	return false;
}


function contatoResponse(response) {
	
	var mensagem = jQuery('mensagem', response).text();
	var incorreto = jQuery('incorreto', response).text();
	
	if (incorreto == '') {
		jQuery(contatoForm+" fieldset").hide();
		jQuery(contatoMsg).hide();
		jQuery("blockquote").html(mensagem);
	}
	
	else {
		jQuery(contatoMsg).css('display','none').html(mensagem).fadeIn('slow');
		affectedFields(contatoForm,incorreto);
		contatoAfter();
	}
	
	return false;
}

function contatoBefore() {
	jQuery(contatoSubmit).attr('disabled','disabled');
}

function contatoAfter() {
	jQuery(contatoSubmit).removeAttr('disabled');
}


/* xModal - v0.1 */

modal_zindex = '100000';

function modal() {
	jQuery(".modal").bind('click', function() {
		if (!get('modal')) { // if the div doesn't exist yet
			
			// you know, it must be on top
			jQuery(this).parent('div').css('z-index',modal_zindex++);
			jQuery(this).parent('li').css('z-index',modal_zindex++);
			
			var src = jQuery(this).attr('href'); // get the image path
			var parent_class = jQuery(this).parent().attr('class'); // for aligment stuff
			
			// legend stuff
			var legenda = jQuery(this).find('small').html();
			if (legenda==null) legenda = jQuery(this).find('img').attr('alt');
			if (legenda==undefined) legenda = '-';
			
			// let's make it's structure
			var code = '<div id="modal" class="'+parent_class+'">';
				code = code+'<img id="large" src="'+src+'" alt="Imagem ampliada" />';
				code = code+'<small>'+legenda+'</small>';
				code = code+'<a id="close" href="javascript:modalClose()" title="Fechar">';
				code = code+'<img src="img/icons/close.gif" alt="Fechar" /></a>';
			code = code+'</div>';
			
			// append and show it!
			jQuery(this).parent().append(code);
			jQuery("#modal").css("display",'none').fadeIn();

		} else {
			modalClose();
		}
		return false;
	});	
}


function modalClose() {
	jQuery("#modal").remove();
}


/* Empresa */

function empresa_historico() {
	blocos('historico',3,'.abas',265);
}

/* After Market - Dicas */


function aftermarket_dicas() {
	
	jQuery("#dicas .registros div.registro").find('div').hide();

	var affected = location.hash.split('-')[1];
	if (affected != undefined) jQuery("#dicas #registro-"+affected).find('div').show();
	
	jQuery("#dicas .registros h3 a").bind('click', function() {
		jQuery("#dicas .registros div.registro div").slideUp();
		
		var display = jQuery(this).parents('div').find('div').css('display');
		if (display == 'block') {
			jQuery(this).parents('div.registro').find('div').slideUp();
		} else {
			jQuery(this).parents('div.registro').find('div').slideDown();
		}
		
		var span = jQuery(this).find('span');
		var simb = (span.html()=='[+]') ? '[-]' : '[+]';
		span.html(simb);
		return false;
	});
}

/*
function aftermarket_dicas() {
	jQuery("#dicas .registros").hide();
	jQuery("#dicas .categoria h3 a").bind('click', function() {
		jQuery("#dicas .registros").slideUp();
		
		var display = jQuery(this).parents('div.categoria').find('div').css('display');
		if (display == 'block') {
			jQuery(this).parents('div.categoria').find('div').slideUp();
		} else {
			jQuery(this).parents('div.categoria').find('div').slideDown();
		}
		
		var span = jQuery(this).find('span');
		var simb = (span.html()=='[+]') ? '[-]' : '[+]';
		span.html(simb);
		return false;
	});
}
*/


/* Blocos */

function blocos(section,level,ul_class,fchild,title) {
		
	var hash = location.hash.split('-')[1];
	var affected = (hash) ? hash : fchild;
	
	jQuery('#'+section+" #blocos div.level-"+level).hide();
	jQuery('#'+section+" #blocos div#registro-"+affected).show();
	if (title==false) jQuery('#'+section+" #blocos div#registro-"+fchild).find('h3').hide();
	jQuery('#'+section+" #blocos ul"+ul_class+" li#aba-"+affected).addClass('ativo');

	jQuery('#'+section+" #blocos ul"+ul_class+" li a").bind('click', function() {
		jQuery(this).parent('li').parents('ul').find('li').siblings().removeClass('ativo');
		jQuery(this).parent('li').addClass('ativo');
		var href = jQuery(this).attr('href');
		var anchor = href.split('-')[1];
		jQuery('#'+section+" #blocos #registro-"+anchor).show().siblings('div').hide().parent('div').show();
		return false;
	});
}


/* Busca de Produtos */

function busca_produtos() {
	fillSuggestInput('input[name=cod]', strCodigoProduto);
	fillSuggestInput('input[name=cod_original]', strMontadora);
}

function fillSuggestInput(selector,msg) {
	
	var inp = jQuery(selector);
	
	fill();
	inp.bind('blur', fill);
	inp.bind('focus', clear);
	inp.parents('form').bind('submit', clear);
	
	function clear() {
		if (inp.val()==msg) {
			inp.attr('value','');
		}
	}

	function fill() {
		if (inp.val()=='') {
			inp.attr('value',msg);
		}
	}
	
}