function setupCufon() {		
	Cufon.set('fontFamily', 'Eurostile').replace('h2');	
	Cufon.set('fontFamily', 'Eurostile').replace('h3');	
	//Cufon.set('fontFamily', 'Eurostile').replace('h4');	
	Cufon.now();
}
window.addEvent('domready', function() {	
	document.startTime = new Date().getTime();
	if (!Browser.Engine.trident4) setupCufon();	
	//ie6
	if (Browser.Engine.trident4) {
		document.execCommand("BackgroundImageCache",false,true);				
	}
	//new SmoothScroll({ duration: 900 });
	new SmoothScroll({
		transition:Fx.Transitions.Quint.easeOut,
		duration: 900,
		wait: false
	});

	fixIEPNGs();
	handleSexyAlert();
	setupMenu();	
	setupNewsForm();	
	setupFlashHome();
	setupBoxes();	
	setupLinksExternos();	
	setupBotoes();	
	setupPicFrames();
	setupCarrosseis();
	
	setupGMap();
	setupTooltips();
	setupCenterIcons();	
});		

function fixIEPNGs() {
	if ((Browser.Engine.trident4) && (typeof DD_belatedPNG != "undefined")) {
		DD_belatedPNG.fix('.box_img span, .box_foto .box_img span, .box_media .box_title, .box_media .box_content, .box_metade .box_title, .box_metade .box_content, .box_grande .box_title, .box_grande .box_content, .box_foto ');
		/* .box_pequena .box_title, .box_pequena .box_content, */
	}
}

function getIdNumber(str) {
	return parseInt(str.replace(/[^0-9]/g, ''))
}
function handleSexyAlert() {
	if ((typeof alert_obj == "object") && alert_obj['msg'] != "") {
		Sexy = new SexyAlertBox();
		if (alert_obj['type'] == "info") {
			Sexy.info('<h1>Info</h1><p>'+alert_obj['msg']+'</p>');
		} else {
			Sexy.alert('<h1>Atenção</h1><p>'+alert_obj['msg']+'</p>');
		}
		//alert_msg = alert_msg.replace(/###/, "\r\n");		
		//alert(alert_msg);
	}
}

function setupLinksExternos() {
	var extLinks = $$('a[rel=_blank]');
	//dbug.log("tLINKS");	dbug.log(tLinks);	
	extLinks.each(function(el_a, idx){ 
		var _href = el_a.getProperty("href");
		if (_href && !_href.contains("javascript:"))	{
			el_a.setProperty('target', '_blank');			
		}		
	});
}
function updateLivezilla(livezilla_online) {
	//alert("updateLivezilla " + livezilla_online);
	if (livezilla_online) {
		$('atendimento_off').setStyle('display', 'none');
		if ((Browser.Engine.trident4)) {
			$('atendimento_on').setStyle('display', 'block');
		} else {
			$('atendimento_on').setStyles({'opacity': 0, 'display': 'block'});	
			$('atendimento_on').fade('in');	
		}
	} else {
		if ((Browser.Engine.trident4)) {
			$('atendimento_off').setStyle('display', 'block');
		} else {	
			$('atendimento_on').setStyle('display', 'none');
			$('atendimento_off').setStyle('display', 'inline');
		}
	}
}

function setupCarrosseis() {
	$$('div.car_body').each(function(car_body, idx){ 
		var id_str = car_body.id;
		var id = parseInt(id_str.replace(/[^0-9]/g, ''));
		dbug.log(id);

		var parent_id = car_body.getParent().id;
		
		if ($chk(id)) {;		
			options = {
			  startIndex: 0,
			  slides: $$('#'+ id_str + ' div.car_page'),
			  currentIndexContainer: 'car_atual' + id,
			  maxContainer: 'car_max' + id,
			  prevLink: 'car_ant' + id,
			  nextLink: 'car_prox' + id,
			  //clf
			  wrap: true,
			  dynamicLoad: false,
			  id_carrossel: id
			};
			new CCDCarrossel(car_body, options);				
		}
	});	
}
function setupNewsForm() {
	var form = document.id('form_newsletter');
	if (form) {
		form.getElements('input.input').each(function(el) {
			new OverText(el);
		});
	}		
}
function fix_footer() {	
	if ((Browser.Engine.trident4) && $("footer")) {				
		var alt = (99 + (Math.random()*2)) + "%";
		//alert($("container").getStyle("height") + " -> " + alt);
		$("container").setStyle("height", alt);
	}
}
function setupGMap() {
	if ($("contato") && $("gmap") && (typeof GMap2 != "undefined")) {
		var map = new GMap2(document.getElementById("gmap"));
		//map.addControl(new GSmallMapControl());
		map.setUIToDefault();
		map.setCenter(new GLatLng(-26.988626,-48.637451), 16);
		/*
		var myIcon = new GIcon(G_DEFAULT_ICON);
		myIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";		
		
		*/
		var myIcon = new GIcon();
		myIcon.image = asset_path + "img/balao_hpio.png";
		myIcon.iconSize = new GSize(75,47);
		myIcon.iconAnchor = new GPoint(58,40);
		
		// Set up our GMarkerOptions object
		markerOptions = { icon: myIcon };		
		map.addOverlay(new GMarker(new GLatLng(-26.989226,-48.638451), markerOptions));

	}
}
function setupFlashHome() {	
	var swf_banner_home = 'banner_home_default.swf';
	var flash_vars_home = null;
	if (typeof banner_home_data == "object") {
		swf_banner_home = 'banner_home.swf';
		flash_vars_home = banner_home_data;
	}	
	if ($('banner_home_flash')) {
    	swfobject.embedSWF(
    		asset_path + "swf/"+swf_banner_home, 
    		"banner_home_flash", "940", "284", "8.0.0", 
    		asset_path + "swf/expressInstall.swf", 
    		flash_vars_home, 
    		{wmode: 'opaque', allowFullScreen: true}, 
    		{}
    	);
		//apos wmode: ,base: asset_path + "swf/"
	}
}

function setupMenu() {
	$('nav').getElements('li').each(function(li) {
		//settings
		var link = li.getFirst('a');
		//fix background image
		if(!li.hasClass('current')) {
			link.setStyle('background-image','none');
		}
		//utility div
		var div = new Element('div',{
			'class': 'nav-' + li.get('id'),
			opacity: 0
		}).inject(li);
		//background imagery
		li.addEvents({
			mouseenter: function() {
				div.fade('in');
			},
			mouseleave: function() {
				div.fade('out');
			},
			mousedown: function() {
				div.addClass('nav-' + li.get('id') + '-click');
			},
			mouseup: function() {
				div.removeClass('nav-' + li.get('id') + '-click');
			}
		});
	});
}
function setupCenterIcons() {
	//thumbs com icone
	var img_center = (Browser.Engine.trident)? 'zoom2.gif' : 'zoom.png';
	$$(".center_icon").each( function(el) { 
		dbug.log(el);
		new CCDCenterIcon(el, {
			useFX: true,
		    width: 32,
		    height: 32,	
		    fxOptions: { duration: 400 },
   			forceRelative: true,
		    centerElm: 'child',
			resetPositionOnHover: false,
			hoverStyle: {backgroundImage: 'url(' + asset_path + 'img/' + img_center + ')'}
		}); 
	}) ;
}
function setupTooltips() {
	//tips
	$$('.tipz').each(function(element,index) {
		var title = element.get('title');
		if (!title) return;
		var content = title.split('::');
		var titulo = $chk(content[0])? content[0] : "";
		var texto = $chk(content[1])? content[1] : "";
		element.store('tip:title', titulo);
		element.store('tip:text',  texto);
	});		
	
	//tooltips
	var tipz = new Tips('.tipz',{
		className: 'tipz',
		fixed: false,
		hideDelay: 250,
		showDelay: 50,
		onShow: function(tip) {
			tip.fade('in');
			dbug.log("fade in?");
		},
		onHide: function(tip) {
			tip.fade('out');
		}
	});
}
function setupBotoes() {	
	$$('.botao1').each(function(el) {
		var FXO = {
			transition:Fx.Transitions.Sine.easeInOut,
			duration: 250,
			wait: false
		}
		el.set('morph', FXO);	
		var span = el.getElement('span');
		if (span) span.set('morph', FXO);		
		el.hover(function(e) {		
				el.addClass("hover");
				el.get('morph').start({'background-position': ["0px 0px", "0px -27px"]});				
				if (span) span.get('morph').start({'background-position': ["-2px 0px", "-2px -27px"]});
			}.bind(this), function() {												
				el.removeClass("hover");
				el.get('morph').start({'background-position': ["0px -27px", "0px 0px"]});
				if (span) span.get('morph').start({'background-position': ["-2px -27px", "-2px 0px"]});
			}.bind(this)
		);			
	});
}

var CCDAnimatedElement = new Class({
	Implements: [Options, Events],	
	options: {							
		animElSelector: 'span',		
		FXO: {
			transition:Fx.Transitions.Sine.easeInOut,
			duration: 550,
			wait: false
		},
		configEnter: {			
			//'opacity': [1,0]
		},
		configLeave: {			
			//'opacity': [0, 1]
		}
	},
	initialize: function(container, options){
		dbug.log("initialize CCDAnimatedElement");
		this.setOptions(options);
		this.container = document.id(container);
		dbug.log(this.container)
		
		//cursor
		this.container.setStyle("cursor", "pointer");
				
		this.animEl = this.container.getElement(this.options.animElSelector);
		if (this.animEl) {
			this.animEl.set('morph', this.options.FXO);			
		} else {			
			return false;
		}
	
		//background imagery
		this.container.hover(function(e) {		
				dbug.log("anim hover in")
				if (this.animEl) this.animEl.get('morph').start(this.options.configEnter);
			}.bind(this), function() {	
				dbug.log("anim hover out")			
				if (this.animEl) this.animEl.get('morph').start(this.options.configLeave);
			}.bind(this)
		);		
	}
});

function setupPicFrames() {	
	dbug.log("setupPicFrames");	
	$$('.box_foto').each(function(div_item) {
		dbug.log(div_item);		
		
		var _reflexMorphConfigIn = (Browser.Engine.trident)
									? {'background-position': ["0px 0px", "0px -180px"]}
									: {'background-position': "0px -120px", 'opacity': [1,0.3] };
									
		var _reflexMorphConfigOut = (Browser.Engine.trident)
									? {'background-position': ["0px -180px", "0px 0px"]}
									: {'background-position': "0px 0px", 'opacity': [0.3,1] };	 					
		
		/*
		_reflexMorphConfigIn  = {'background-position': "0% -100%"};
		_reflexMorphConfigOut = {'background-position': "0% 0%"};
		*/
		
		new CCDAnimatedElement(div_item, {				
				animElSelector:	'.box_img span',			
				FXO:	{ duration: 400 },
				configEnter:  _reflexMorphConfigIn,
				configLeave: _reflexMorphConfigOut
			}
		);		
	});
	
}
 var CCDBoxReflexo = new Class({
	Implements: [Options, Events],	
	options: {					
		maxHeight: 150,		
		reflexSelector: 'span',
		haltWithoutLink: true,
		reflexFX: {
			transition:Fx.Transitions.Sine.easeInOut,
			duration: 550,
			wait: false
		},
		reflexMorphConfigIn: {			
			//'opacity': [1,0]
		},
		reflexMorphConfigOut: {			
			//'opacity': [0, 1]
		}
	},
	initialize: function(container, options){
		dbug.log("initialize");
		this.setOptions(options);
		this.container = document.id(container);
		dbug.log(this.container)
		
		//setup link
		var links = this.container.getElements('a');
		var link = $pick(links[0], null);
		dbug.log(link);
		
		if (!link && this.options.haltWithoutLink) return;

		//click
		this.container.addEvent('click', function(el) {
			if (link) {
				var href = link.getProperty("href");
				if (!href) return;
				window.location = href;
			}
		});
			
		//reflex
		this.reflexElement = this.container.getElement(this.options.reflexSelector);
		if (this.reflexElement) {
			this.reflexElement.set('morph', this.options.reflexFX);			
		}
				
		//title attr propagation
		var title = link.getProperty("title");
		if (title) this.container.setProperty("title", title);

		//cursor
		this.container.setStyle("cursor", "pointer");
		
		//get the size again AFTER the image is loaded - for webkit and other browsers
		var event = (Browser.Engine.trident4)? "onload" : "load";		
		this.img = this.container.getElement('img');		
		if (this.img) {
			this.img.addEvent(event, function() { 			
				var larg = this.img.getWidth();
				var alt  = this.img.getHeight();			
				if (!alt) return;
				dbug.log("mH = " + this.options.maxHeight);
				_top = Math.round(Math.abs(this.options.maxHeight - alt ) / 2);			
				dbug.log("_____top");
				dbug.log(_top);
				this.img.setStyle('marginTop', _top+"px");			
			}.bind(this));	
		}
	
		//background imagery
		this.container.hover(function(e) {						
				if (this.reflexElement) this.reflexElement.get('morph').start(this.options.reflexMorphConfigIn);
			}.bind(this), function() {								
				if (this.reflexElement) this.reflexElement.get('morph').start(this.options.reflexMorphConfigOut);
			}.bind(this)
		);			
	}
});

function setupBoxes() {		

	$$('.boxes').each(function(div_boxes) {
		dbug.log(div_boxes);	
		var is_home = ($("home"));
		var _seletor = (is_home)? 'div.box' : 'div.boxp';
		var _maxHeight =  (is_home)? 156 : 139; 	
		
		var _reflexMorphConfigIn = {
			'background-position': (is_home)? ["0 0", "0 -180"] : ["-20px -20px", "-20px -180px"]
			,'opacity': [1, 0.3]
		}		
		var _reflexMorphConfigOut =	{
			'background-position': (is_home)? ["0 -180", "0 0"] : ["-20px -180px", "-20px -20px"]
			,'opacity': [0.3, 1]
		}
		
		if(Browser.Engine.trident) {
			delete _reflexMorphConfigIn.opacity;			
			delete _reflexMorphConfigOut.opacity;
		}
		
		div_boxes.getElements(_seletor).each(function(div_item) {			
			new CCDBoxReflexo(div_item, {				
					reflexSelector:	'.box_img span',				
					maxHeight: _maxHeight,
					reflexMorphConfigIn:  _reflexMorphConfigIn,
					reflexMorphConfigOut: _reflexMorphConfigOut
				}
			);		
		});		
	});	
}

/* tips */
(function(){

var read = function(option, element){
	return (option) ? ($type(option) == 'function' ? option(element) : element.get(option)) : '';
};

this.Tips = new Class({

	Implements: [Events, Options],

	options: {
		/*
		onAttach: $empty(element),
		onDetach: $empty(element),
		*/
		onShow: function(){
			dbug.log("on show padrao");
			this.tip.setStyle('display', 'block');
		},
		onHide: function(){
			dbug.log("on hide padrao");
			this.tip.setStyle('display', 'none');
		},
		title: 'title',
		text: function(element){
			return element.get('rel') || element.get('href');
		},
		showDelay: 100,
		hideDelay: 100,
		className: 'tip-wrap',
		offset: {x: 16, y: 16},
		windowPadding: {x:0, y:0},
		fixed: false
	},

	initialize: function(){
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options);
		if (params.elements) this.attach(params.elements);
		this.container = new Element('div', {'class': 'tip'});
	},
	toElement: function(){
		if (this.tip) return this.tip;

		return this.tip = new Element('div', {
			'class': this.options.className,
			styles: {
				position: 'absolute',
				top: 0,
				left: 0
			}
		}).adopt(
			new Element('div', {'class': 'tip-top'}),
			this.container,
			new Element('div', {'class': 'tip-bottom'})
		).inject(document.body);
	},

	attach: function(elements){
		$$(elements).each(function(element){
			var title = read(this.options.title, element),
				text = read(this.options.text, element);
			
			element.erase('title').store('tip:native', title).retrieve('tip:title', title);
			element.retrieve('tip:text', text);
			this.fireEvent('attach', [element]);
			
			var events = ['enter', 'leave'];
			if (!this.options.fixed) events.push('move');
			
			events.each(function(value){
				var event = element.retrieve('tip:' + value);
				if (!event) event = this['element' + value.capitalize()].bindWithEvent(this, element);
				
				element.store('tip:' + value, event).addEvent('mouse' + value, event);
			}, this);
		}, this);
		
		return this;
	},

	detach: function(elements){
		$$(elements).each(function(element){
			['enter', 'leave', 'move'].each(function(value){
				element.removeEvent('mouse' + value, element.retrieve('tip:' + value)).eliminate('tip:' + value);
			});
			
			this.fireEvent('detach', [element]);
			
			if (this.options.title == 'title'){ // This is necessary to check if we can revert the title
				var original = element.retrieve('tip:native');
				if (original) element.set('title', original);
			}
		}, this);
		
		return this;
	},

	elementEnter: function(event, element){
		this.container.empty();
		
		['title', 'text'].each(function(value){
			var content = element.retrieve('tip:' + value);
			if (content) this.fill(new Element('div', {'class': 'tip-' + value}).inject(this.container), content);
		}, this);
		
		$clear(this.timer);
		this.timer = (function(){
			this.show(this, element);
			this.position((this.options.fixed) ? {page: element.getPosition()} : event);
		}).delay(this.options.showDelay, this);
	},

	elementLeave: function(event, element){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this, element);
		this.fireForParent(event, element);
	},

	fireForParent: function(event, element){
		element = element.getParent();
		if (!element || element == document.body) return;
		if (element.retrieve('tip:enter')) element.fireEvent('mouseenter', event);
		else this.fireForParent(event, element);
	},

	elementMove: function(event, element){
		this.position(event);
	},

	position: function(event){
		if (!this.tip) document.id(this);

		var size = window.getSize(), scroll = window.getScroll(),
			tip = {x: this.tip.offsetWidth, y: this.tip.offsetHeight},
			props = {x: 'left', y: 'top'},
			obj = {};
		
		for (var z in props){
			obj[props[z]] = event.page[z] + this.options.offset[z];
			if ((obj[props[z]] + tip[z] - scroll[z]) > size[z] - this.options.windowPadding[z]) obj[props[z]] = event.page[z] - this.options.offset[z] - tip[z];
		}
		
		this.tip.setStyles(obj);
	},

	fill: function(element, contents){
		if(typeof contents == 'string') element.set('html', contents);
		else element.adopt(contents);
	},

	show: function(element){
		if (!this.tip) document.id(this);
		this.fireEvent('show', [this.tip, element]);
	},

	hide: function(element){
		if (!this.tip) document.id(this);
		this.fireEvent('hide', [this.tip, element]);
	}

});

})();


function get_sitespath() {
	var pos = base_url.indexOf("index.php");
	if (pos > 0) {
		return base_url.substr(0, pos);
	}
}

/*
*/
if(typeof Shadowbox == 'undefined'){
	throw 'Shadowbox não pôde carregar';
}


function SBCloseHandler() {
	dbug.log("SB HAS CLOSED");
}

function setupShadowBox() {
	//alert("settinng up SB");
	
	var strClose = (Browser.Engine.trident4)? "X" : "";
	
	Shadowbox.skin.markup = ''+
	'<div id="sb-container">'+
		'<div id="sb-overlay"></div>' + 
		'<div id="sb-wrapper">' + 
			'<div id="sb-title">' + 
				'<div id="sb-title-inner"></div>' + 			
			'</div>' + 			
			'<div id="sb-body">' + 
				'<div id="sb-loading">' + 
	                '<span><a onclick="Shadowbox.close();">{cancel}</a></span>' +
				'</div>' + 
				'<div id="sb-body-inner"></div>' + 
			'</div>' + 
			'<div id="sb-info">'+
				'<div id="sb-info-inner">'+			
					'<div id="sb-counter"></div>' + 
					'<div id="sb-nav">' +
						'<a id="sb-nav-close" title="{close}" onclick="Shadowbox.close()">'+strClose+'</a>' + 
						'<a id="sb-nav-next" title="{next}" onclick="Shadowbox.next()"></a>' + 
						'<a id="sb-nav-play" title="{play}" onclick="Shadowbox.play()"></a>' + 
						'<a id="sb-nav-pause" title="{pause}" onclick="Shadowbox.pause()"></a>' + 
						'<a id="sb-nav-previous" title="{previous}" onclick="Shadowbox.previous()"></a>' + 
					'</div>' + 
				'	<div style="clear:both"></div>' + 
				'</div>' + 
			'</div>' + 
		'</div>' + 
	'</div>';
	
	Shadowbox.init({animate: true, overlayColor: "#333", language: "pt-BR", handleOversize: "drag", players: ["img","iframe"], onClose: SBCloseHandler});
}

setupShadowBox();

var dbug = {
	log: function(str) {	
		if (typeof console != "undefined") {
			console.log(str);
		} else {			
			return;
			if (Browser.Engine.trident) {
				if (!$('ie-console')) {
					new Element('div',	
						{"id":"ie-console", "html":"<h1>IE Console</h1><br/>"}
					).inject(document.body, "bottom");
				}
				$('ie-console').set("html", $('ie-console').innerHTML + str + "<br/>"); 
			}			
		}		
	}
};

