document.observe("dom:loaded", function(){
	$$('dl.decade').each(function(elm){
		elm.hide();
	});
	
	$$(".only_number").each(function(elm){
		Event.observe(elm,'keyup',function(){
			elm.value = elm.value.replace(/\D/g,"")
		});
	});
	
	var heightBox = $($$(".downBox")[0]).getHeight();
	$$(".downBox").each(function(elm){
		elm.style.height = heightBox + "px";
	});
	
});

Event.observe(window, "load", function(){
	if(navigator.appVersion.search('MSIE 6') != -1 || navigator.appVersion.search('MSIE 5') != -1){
		var li_group = $('products_main_menu').childElements();
		li_group.each(function(li){
			var submenu = li.down(3);
			if(submenu != undefined)
			{
				li.down(2).setStyle({ height:Number(submenu.getHeight() - 18) + "px" });
			}
		});
	}
	
	// função para hablitar a navegação nos submenus através da tecla "tab"
	var lis = document.getElementsByTagName('li');
	for (var i = 0, li; li = lis[i]; i++){
		var link = li.getElementsByTagName('a')[0];
		if (link){
			link.onfocus = function(){
				var div = this.parentNode.getElementsByTagName('div')[0];
				var iframe = this.parentNode.getElementsByTagName('iframe')[0]; //ie6 
				if (div){
					div.style.visibility = 'visible';
				}
				if (iframe) //ie6
					iframe.style.display = 'block';
			}
			
			var div = link.parentNode.getElementsByTagName('div')[0];
			if (div){
				var ullinks = div.getElementsByTagName('a');
				
				var ullinksqty = ullinks.length;
				if( ullinksqty > 0){
					var lastItem = ullinks[ullinksqty - 1];
					if (lastItem){
						lastItem.onblur = function(){
							this.parentNode.parentNode.parentNode.style.visibility = 'hidden';
						}
						lastItem.parentNode.onblur = function(){
							this.parentNode.parentNode.style.visibility = 'hidden';
						}
					}
				}
			}
			
			/* IE6 -- */
			var iframe = link.parentNode.getElementsByTagName('iframe')[0]; 
			if (iframe){ 
				
				var ullinksqty = ullinks.length;
				var lastItem = ullinks[ullinksqty - 1];
				if (lastItem){
					lastItem.onblur = function(){
						this.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('iframe')[0].style.display = "none";
						this.parentNode.parentNode.parentNode.style.visibility = 'hidden';
					}
					lastItem.parentNode.onblur = function(){
						this.parentNode.parentNode.parentNode.getElementsByTagName('iframe')[0].style.display = "none";
						this.parentNode.parentNode.style.visibility = 'hidden';
					}
				}
			}
		}
	}
	
	function scroll(){
		var current_url = document.location.href;
		current_url = ((current_url.match(/\/page\//)) ? current_url : current_url+'/page/1');

		$('.list-products').scrollPagination({	
				'contentPage': current_url, // the page where you are searching for results
				'scrollTarget': $(window), // who gonna scroll? in this example, the full window
				'heightOffset': 10, // how many pixels before reaching end of the page would loading start? positives numbers only please
				'beforeLoad': function(){ // before load, some function, maybe display a preloader div
					$('#page').val(parseInt($('#page').val()) + 1);
					var product_url = document.location.href;
					product_url = ((product_url.match(/\/page\//)) ? product_url.split('/page/', 2)[0] : product_url);
					$('.list-products').scrollPagination.defaults.contentPage = product_url+'/page/'+$('#page').val();
					$('#loading').fadeIn();	
				},
				'afterLoad': function(elementsLoaded){ // after loading, some function to animate results and hide a preloader div
					$(elementsLoaded).fadeInWithDelay();
					$('#loading').fadeOut();
					if ($('.list-products .productPage').size() >= $('#limit').val()){ // if more than 100 results loaded stop pagination (only for test)
						$('.list-products').stopScrollPagination();
					 }
				}
			});
			
			// code for fade in element by element with delay
			$.fn.fadeInWithDelay = function(){
				var delay = 0;
				return this.each(function(){
					$(this).delay(delay).fadeIn(200);
					delay += 100;
				});
			};  
};
	
	$$('#products_main_menu a.parent_menu').each(function(elm){
		if (elm.readAttribute('href') == "#" ) {
			elm.writeAttribute("href","javascript:void(0)");
		}
		
		elm.onmouseover = function(){
			$$('#products_main_menu a').each(function(elm){
				if(elm.focus)
					elm.blur();
			})
			$$('#products_main_menu a.parent_menu').each(function(elm){
				if(elm.next("div").style.visibility == "visible")
					elm.next("div").style.visibility = "hidden";
				if(elm.next("iframe") && elm.next("iframe").style.display =="block")	
					elm.next("iframe").style.display = "none";
			})
		}
	})
	
})

function init() {
	createExternalLinks();
}

function createExternalLinks() {
    if(document.getElementsByTagName) {
        var anchors = document.getElementsByTagName('a');
        for(var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if(anchor.getAttribute("href") && anchor.getAttribute('rel')=='externo') { // <-- É necessário inserir rel="externo" no link
                anchor.target = '_blank';
                var title = anchor.title + ' (Este link abre uma nova janela)'; // <-- Insere este texto no final do Title do link
                anchor.title = title;
            }
        }
    }
}

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;
    }
}

addEvent(window, "load", init);

function clearField(field, default_value){
	if($(field).value == default_value)
	{
		$(field).value = '';
	}
}

function defaultFieldValue(field, default_value){
	if($(field).value == '')
	{	
		$(field).value = default_value;
	}
}

function typePassword(obj){
	if (obj.type != "password") {
		$('field_password').down("input").remove();
		new Insertion.Bottom( $('field_password'), '<input id="'+obj.id+'" name="'+obj.name+'" type="password" />');
		$('field_password').down("input").focus();
	}
}

function showElement(element){
	$(element).setStyle({ display:"block" });
}

function hideElement(element){
	$(element).setStyle({ display:"none" });
}

function visibleElement(element,top,left){
	$(element).setStyle({ top:top+"px", left:left+"px" })
}

function invisibleElement(element){
	$(element).setStyle({ top:"-9999%", left:"-9999%" })
}

function upValue(element){
	if($(element).up('div').down("input").value == ""){
		$(element).up('div').down("input").value = 1;
		$(element).up('tr').down("input").checked= true; 
	}
	else{
		$(element).up('div').down("input").value = Number($(element).up('div').down("input").value) + 1;
		$(element).up('tr').down("input").checked= true;
	}
}

function downValue(element){
	if($(element).up('div').down("input").value == ""){
		$(element).up('div').down("input").value = "";
	}
	if($(element).up('div').down("input").value == 1){
		$(element).up('div').down("input").value = "";
		$(element).up('tr').down("input").checked = false;
	}
	if($(element).up('div').down("input").value >= 1){
		$(element).up('div').down("input").value = Number($(element).up('div').down("input").value) - 1;
	}
}

function changeDozen(element){
	if($(element).value == ""){		
		$(element).up('tr').down("input").checked = false;
	} else {
		$(element).up('tr').down("input").checked = true;
	}
}

function includeElement(element){
	if($(element).checked == true){
		if($(element).up('tr').down('input', 1) != null) {
			if($(element).up('tr').down('input', 1).value == ""){
				$(element).up('tr').down('input',1).value = 1;
			}
		} else {
			if($(element).up('tr').down('select', 0).value == ""){
				$(element).up('tr').down('select',0).value = 12;
			}
		}
	}
}

function viewDecade(element_toggle, element_style ){
	if($(element_toggle).getStyle("display") == "none"){
		$(element_toggle).setStyle({ display:"block" });
		$(element_style).setStyle({ backgroundPosition:"left -24px" });
	}
	else{
		$(element_toggle).setStyle({ display:"none" });
		$(element_style).setStyle({ backgroundPosition:"left 1px" });
	}
}

function pageSize(){
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ 
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { 
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { 
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { 
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	if(xScroll < windowWidth){	
		pageWidth = windowWidth - 18;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function enlargedImage(url){
	var total_height = pageSize();

	if(navigator.appVersion.search('MSIE 6') != -1 || navigator.appVersion.search('MSIE 5') != -1){
		new Insertion.Top(document.body, '<iframe id="ie_overlay" frameborder="0" noresize="noresize" scrolling="no" src="about:blank"></iframe><div id="overlay"></div><div id="ajax_container"></div>');
		$('ie_overlay').setStyle({ height:total_height[1]+"px", opacity:"0.3" });
	}
	else{
		new Insertion.Top(document.body, '<div id="overlay"></div><div id="ajax_container"></div>');
	}

	$('overlay').setStyle({ height:total_height[1]+"px", opacity:"0.3" });
	
	new Ajax.Updater('ajax_container',url);
	
	var enlarged_image_height = $('ajax_container').getHeight();
	var top_distance = document.viewport.getScrollOffsets().top;
	
	if( enlarged_image_height + top_distance > total_height[1] ){
		var new_posY = top_distance - ((enlarged_image_height + top_distance) - total_height[1]);
		$('ajax_container').setStyle({ top:new_posY+"px" });
	}
	else{
		$('ajax_container').setStyle({ top:top_distance+"px" });
	}
}

function removeEnlargedImage(){
	if($('ie_overlay'))
		$('ie_overlay').remove();
	if($('overlay'))
		$('overlay').remove();
	if($('ajax_container'))
		$('ajax_container').remove()
}

function deleteItens(element, rootUrl){
	if($('ajax_container'))
		$('ajax_container').remove();
	new Insertion.Top(element, '<div id="ajax_container"></div>');
	new Ajax.Updater('ajax_container',rootUrl + 'cote/clean/type/2');
}

function sendToCote(element, rootUrl, redirect) {
	new Ajax.Request(rootUrl + 'cote/ajax/', {
	  method: 'post',
	  parameters: $('cote_addItem_form').serialize(), 
	  onSuccess: function(transport) {
		if($('ajax_container')) 
			$('ajax_container').remove();
		if (redirect.length != 0) {
			new Insertion.Top(element, '<div id="ajax_container"></div>');
			new Ajax.Updater('ajax_container',rootUrl + 'product/msgBox/type/1');
		}
	  },
	  onComplete: function(transport) {
	    if (200 == transport.status) {
	    	if (element.href) {
	    		location.href = element.href;
	    	}
	    }
	  }
	});
}

function sendCote(element, rootUrl) {
	new Ajax.Request(rootUrl + 'cote/edit/type/1', {
	  method: 'post',
	  parameters: $('cote_edit_form').serialize(), 
	  onComplete: function(transport) {
	    if (200 == transport.status) {
	    	location.href = element.href;
	    }
	  }
	});
}

function deleteIten(element, rootUrl, id){
	if($('ajax_container'))
		$('ajax_container').remove();
	new Insertion.Top(element, '<div id="ajax_container"></div>');
	new Ajax.Updater('ajax_container',rootUrl + 'cote/clean/type/3/id/'+id);
}

function formatPhone(v){
    v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1)$2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2") //Coloca hífen entre o quarto e o quinto dígitos
    v=v.substr(0,13);
    return v
}

//ADD THIS
function add_This(){
	var addthis_config;
	return (addthis_config = {
        "data_track_clickback" : true
    });
}

var $j = jQuery.noConflict();
$j('html').removeClass('nojs');
var current_url = document.location.href;
current_url = current_url.split('/index/', 2)[0]+'/page/'+current_url.split('/index/', 2)[1]+'page/2';
$j(document).ready(function() {
	$j(function(){
		if($j('#product_limit').val() > 9) {		
		$j('.list_products').scrollPagination({	
				'contentPage': current_url, // the page where you are searching for results
				'scrollTarget': $j(window), // who gonna scroll? in this example, the full window
				'heightOffset': 10, // how many pixels before reaching end of the page would loading start? positives numbers only please
				'beforeLoad': function(){ // before load, some function, maybe display a preloader div
					$j('#product_page').val(parseInt($j('#product_page').val()) + 1);
					$j('.list_products').scrollPagination.defaults.contentPage = current_url.split('/2', 2)[0]+'/'+$j('#product_page').val();
					$j('#loading').fadeIn();	
				},
				'afterLoad': function(elementsLoaded){ // after loading, some function to animate results and hide a preloader div
					$j(elementsLoaded).fadeInWithDelay();
					$j('#loading').fadeOut();
					if ($j('.list_products .box-prod').size() >= $j('#product_limit').val()){ // if more than 100 results loaded stop pagination (only for test)
						$j('.list_products').stopScrollPagination();
					 }
				}
		});	
		// code for fade in element by element with delay
		$j.fn.fadeInWithDelay = function(){
			var delay = 0;
			return this.each(function(){
				$(this).delay(delay).fadeIn(200);
				delay += 100;
			});
		};
		}
	});
});

