/**
 * Após carregamento do site
 */
window.addEvent( 'domready', function() {

	// SearchTabs - Separadores de pesquisa
	/*$$('.searchTab').each( function( element, index ) {
		element.addEvent( 'click', function( event ) {
			if( this.get('rel') != null && this.get('rel').length > 0 ) {
				$('searchForm').set('action', this.get('rel') );
			} else {
				$('searchForm').set('action', '/pesquisa.php' );
			}
			$$('.searchTab').each( function( secElement, j ) {
				if( secElement.hasClass('active') ) secElement.removeClass( 'active' );
			});
			this.addClass( 'active' );
			$('searchsection').set( 'value', this.getElement( 'span' ).get( 'html' ) );
			return false;
		});
	});*/
	
	$$('.searchOption').each( function( element, index ) {
		element.addEvent( 'click', function( event ) {
			if( this.get('rel') != null && this.get('rel').length > 0 ) {
				$('searchForm').set('action', this.get('rel') );
			} else {
				$('searchForm').set('action', '/pesquisa.php' );
			}
			return false;
		});
	});

	// menuAccordion
	var selected = -1;
	if( $$('#menuWrapper .active').get('rel').length > 0 ) selected = $$('#menuWrapper .active')[0].get('rel');
	var menuAccordion = new Accordion( '.menuTogglers', '.menuElements', {
		display: selected,
		alwaysHide: true,
		onActive: function( toggler, element ) {
			toggler.addClass('active');
			toggler.getParent('li').removeClass('collapsed')
			toggler.getParent('li').addClass('expanded');
		},
		onBackground: function( toggler, element ) {
			toggler.removeClass('active');
			toggler.getParent('li').addClass('collapsed')
			toggler.getParent('li').removeClass('expanded');
		}
	});
	
	// contactos uteis
	if( $('contactsTicker').getElements('li').length > 0 )
		var contactsTicker = new Ticker( 'contactsTicker', { 'speed':1000, 'delay':2000, 'direction':'vertical' });
	
	// trânsito
	new Request({
		url: '/widgets/traffic.widget.php',
		method: 'get',
		onSuccess: function( response ) {
			$('traffic').getElement('div').set( 'html', response );
			if( $('traffic').getElements('li').length == 0 ) return false;
			var trafficTicker = new Ticker( 'trafficTicker', { 'speed':1000, 'delay':2000, 'direction':'vertical' });
		return false;
		}
	}).send();
	
	
	// tempo
	var selectedCity = '8';
	if( Cookie.read('weather') != null ) selectedCity = Cookie.read('weather');
	changeCityWeather( selectedCity );
	$('weather').getElement('select').getElements('option').each( function( item, index ) {
		if( item.value == selectedCity ) {
			item.selected = true;
			return true;
		}
		return false;
	});
	$('weather').getElement('select').addEvent( 'change', function() {
		Cookie.write( 'weather', this.options[this.selectedIndex].value );
		changeCityWeather( this.options[this.selectedIndex].value );
	});
	
	loadWidget( 'tagcloud', 'tagcloud' );
	
	$('topBar').getElement('.location').addEvent( 'click', function(e) {
		new Event.stop(e);
		Shadowbox.options.onClose = function() {
			parent.location.reload();
		};
	});
	
	
	// tamanho da letra
	/*PLT-UPADTE
	var resizeText = $$( '#contentWrapper .colLeft p, #contentWrapper .colLeft h3, #contentWrapper .colLeft h4, #contentWrapper .colLeft h5, .topThreads a, .articlesWrapper .itemListWrapper .content, .dirList li a, .listingBlue .mainList .info, .sponsorsList li .info h4 a, .sponsorsList li .info p' );
	$('textSmaller').addEvent( 'click', function(e){
		resizeText.each( function( item, index ){
			var fontsize = item.getStyle( 'font-size' );
			fontsize = fontsize.substring( 0, fontsize.length-2 ).toInt() - 2;
			if( fontsize < 8 ) return false;			
			item.setStyle( 'font-size', fontsize.toString()+'px' );
			item.setStyle( 'line-height', ( fontsize - 2 ).toString()+'px' );
			return true;
		});
		return false;
	});
	$('textBigger').addEvent( 'click', function(e) {
		resizeText.each( function( item, index ){
			var fontsize = item.getStyle( 'font-size' );
			fontsize = fontsize.substring( 0, fontsize.length-2 ).toInt() + 2;
			if( fontsize >= 24 ) return false;			
			item.setStyle( 'font-size', fontsize.toString()+'px' );
			item.setStyle( 'line-height', ( fontsize + 2 ).toString()+'px' );
			return true;
		});
		return false;
	});
	*/
	
	// activar smarthoverboxes (login, registo)
	if( $('register') != null ) smartHoverBox(500, 30, 0, '_smarthbox' );
	if( $('myaccount') != null ) smartHoverBox(500, 30, 0, '_smarthbox' );

	// redireccionar links de email para janela shadowbox
	$$('.mailto').each( function( item, index ) {
		item.addEvent( 'click', function( e ) {
			new Event.stop( e );
			Shadowbox.open({
				content: item.href, 
				player: 'iframe',
                height: 480,
                width: 640
    		});
		});
	});

});


/**
 * Define o site como homepage do browser
 */
function setHomePage() {
	if( document.all ) {
		document.body.style.behavior = "url(#default#homepage)";
		document.body.setHomePage('http://www.buzina.pt/');
	} else if( document.getElementById ) {
		alert( 'Arraste o logótipo do Buzina para o ícone "Home" do seu browser para tornar como página inicial o portal Buzina.' );
		return false;
	}
    return true;
}

/**
 * Favoritos
 */
function bookmark(){
    var title = "BUZINA.PT - O SEU PORTAL AUTOMÓVEL";
    var url = "http://www.buzina.pt/";
	if ( document.all ) { //  para o ie
		window.external.AddFavorite( url, title );
	} else if( window.sidebar ) { // ff
		window.sidebar.addPanel( title, url, "" );
	} else { // others browsers
		alert( "Para adicionar o Buzina aos seus Favoritos, pressione CTRL+D." );
	}
}


/**
 * Contabiliza os clicks de um banner
 * @param int $bid
 */
function refreshClicks( bid, key ) {
	new Request({
		url: 'ajax/refreshclicks.ajax.php',
		method: 'post',
		onSuccess: function( response ) {
		}
	}).send( 'bid='+bid );
	if( key.length > 0 ) window.open( $(key).get('href') );
	return false;
}


/**
 * Carrega um registo para um elemento
 */
function loadWidget( elementId, widget ) {
	new Request.JSON({
		url: '/widgets/'+widget+'.widget.php',
		method: 'get',
		onRequest: function( response ) {
			$(elementId).set( 'html', '<p class="widgetLoading">Loading...</p>' );
		},
		onSuccess: function( response ) {
			$(elementId).addClass( 'hidden' );
			$(elementId).set( 'html', response.html );
			$exec( response.js );
			$(elementId).removeClass( 'hidden' );
		}
	}).send();
}


/**
 * Actualiza a informação do tempo
 */
function changeCityWeather( city ) {
	new Request({
		url: '/widgets/weather.widget.php',
		method: 'get',
		onRequest: function() {
			$('weather').getElement('.weatherStatus').empty();
			$('weather').getElement('.weatherStatus').set( 'html', '<p>A carregar...</p>' );
		},
		onSuccess: function( response ) {
			$('weather').getElement('.weatherStatus').empty();
			$('weather').getElement('.weatherStatus').set( 'html', response );
		}
	}).send( 'city='+city );
}

function viewLocation( elementName, latitude, longitude, zoom, text, baseIconPath ) {
	if( GBrowserIsCompatible() ) {
		var map = new GMap2( document.getElementById(elementName) );
		map.setUIToDefault();                
		var point = new GLatLng( latitude, longitude );
		map.setCenter( point, zoom );
		map.clearOverlays();

		// se receber o path do icon
		if( $chk( baseIconPath ) ){
			var baseIcon = new GIcon();
			baseIcon.image = baseIconPath;
			baseIcon.iconSize = new GSize( 48, 48 );
			baseIcon.iconAnchor = new GPoint( 0, 0 );
			baseIcon.infoWindowAnchor = new GPoint( 24, 24 );
			var marker = createMarker( point, text, baseIconPath, baseIcon );
		} else {
			var marker = new GMarker( point );
		}

		// click
		GEvent.addListener( marker, "click", function() {
			marker.openInfoWindowHtml( text );
		});
		map.addOverlay( marker );
	}
}

// Inicialização shadowbox
Shadowbox.init({
	language: "pt-PT",
	players: [ 'img', 'iframe', 'flv' ]
});

