function populateConcelhos(transport) {
    
    $('mun').update();
    
    $('mun').insert({ bottom: new Element('option', { value: 0 }).update('Seleccione..') });
    
    transport.responseJSON.each(function(elem) {
                                    $('mun').insert({ bottom: new Element('option', { value: elem.id }).update(elem.name) }); 
                                });
    
    $('mun').enable();
}

function updateConcelhos(event) {	
	if ($$('body').first().readAttribute('id') == 'agenda-lista') {
	    dis_id = $F(event.target);
	    
	    $('mun').update(new Element('option', { value: 0 }).update('A carregar...'));
	    $('mun').disable();
	    new Ajax.Request('/agenda/concelhos/'+dis_id, { method: 'get', onSuccess: populateConcelhos });
	    
	} else { // Mapa
		dis_id = $F(event.target);
		if (dis_id == 0) {
		    $('mun').update(new Element('option', { value: 0 }).update('Concelho'));
		    return;
		}
		
	    $('mun').update(new Element('option', { value: 0 }).update('A carregar...'));
	    $('mun').disable();	
		$(event.target).up('form').submit();
	}
}

/**
 *
 * Inline calendar
 *
 */ 

/* Inline calendar */
var inlinecal = null;
var today     = null;
var selected_date = null;

function initInlineCalendar() {
    
    if($('calendario')) {
        
        today = new Date();
        
        // date selected
        if( (day = $F('date-filter')).length > 0) {
            selected_date = new Date();
            day_p = day.split('-');
            
            selected_date.setFullYear(parseInt(day_p[2], 10));
            selected_date.setMonth(parseInt(day_p[1], 10)-1);
            selected_date.setDate(parseInt(day_p[0], 10));
            
        }
        else
            selected_date = today;
        
        inlinecal = new Calendar('calendario', inlineCalDateChoosed);
        inlinecal.drawDate(selected_date.getMonth()+1, selected_date.getFullYear());
    }
    
}

function inlineCalDateChoosed(year, month, day) {
    
    if(month < 10)
        month = '0'+month;
    
    if(day < 10)
        day = '0'+day;
    
    $('date-filter').value = day + '-' + month + '-' + year;
    
    $('map-filter').submit();
}
 
function increaseFont() {
    $$('.resizable p').each(function(elem) {
                          fontsize = parseInt(elem.getStyle('fontSize'), 10);
                          elem.setStyle({ 'fontSize': (fontsize+1)+'px' }); 
                          });
}

function decreaseFont() {
    $$('.resizable p').each(function(elem) {
                          fontsize = parseInt(elem.getStyle('fontSize'), 10);
                          elem.setStyle({ 'fontSize': (fontsize-1)+'px' });
                          });
}


function agendaPagination(anchor) {
	if (typeof window._agenda_pagination == 'undefined') 
		window._agenda_pagination = false;

	if (window._agenda_pagination == true)
		return;
	window._agenda_pagination = true;
	
	
	$$('div.paginacao-agenda').first().insert ({
	  'bottom' : '<img class="agenda-wait" src="http://imgs.sapo.pt/sapovideo/imgs/indicator_medium.gif" />	'
	});
	
	try {
	
	    new Ajax.Request('/agenda' + anchor.readAttribute('href'), {
	  	  onSuccess: function(response) {	    
	    	if (response.responseJSON == null) 
	    		throw "Null response";
	    	
	    	if (typeof response.responseJSON != 'object') 
	    		throw "Unexpected response";
	    	
	    	if(! (typeof response.responseJSON.events == 'object' && response.responseJSON.events instanceof Array))
	    		throw "Unexpected response";
	    	
	    	if (typeof response.responseJSON.pagination != 'string') 
	    		throw "Unexpected response";
	    	
	    	$$('ul.list-figure3').first().update();
	    	$$('div.paginacao-agenda img.agenda-wait').first().remove();
	    		
	    	response.responseJSON.events.each(function(event, index) {
    			var css_class = '';
    			if (index == 0) {
    				css_class = 'first-child'
    			} else if (index == 2) {
    				css_class = 'last-child';
    			}
    			
    			var html = '<li class="' + css_class + '">' +
    			           '<a class="figure" title="' + event.name + '" href="/agenda/' + event.id + '"><img alt="" src="' + event.image  + '" onerror="this.src=\'' + event.image_error + '\'"></a>' +
    			           '<div class="detail1">' +
    			           '<a class="title" title="' + event.name + '" href="/agenda/' + event.id + '"><strong>' + event.name + '</strong></a>' +
    			           '<div class="resume">' +
    			           '<strong>' + event.venue + '</strong><br />' +
    			           event.date + '<br />' +
    			           'Género: ' + event.type +
    			           '</div>' +
    			           '</div>' +
    			           '<div class="fb_like">' +
    			           '<fb:like href="' + event.fe_url + 'agenda/' + event.id + '" layout="button_count" show_faces="false" width="90"></fb:like>';
    			
    			$$('ul.list-figure3').first().insert ({
    			  'bottom' : html
    			});
    			
    		}); 
	    	
	    	$$('div.paginacao1 div.inline-block').first().update(response.responseJSON.pagination);
	    	$$('div.paginacao-agenda a').each(function(s) {
	            s.observe('click', function(evt) {
	            	Event.stop(evt);        	
	            	agendaPagination(this);
	            }.bind(s));
	    	});
	    	
	    	FB.init({xfbml:true});
	    	
	    	window._agenda_pagination = false;
	      },
	      
	      onError: function() {
	    	  throw "Server Error";
	      }
	    });
	} catch(err) {
		// Failed request
		$$('ul.list-figure3').first().update('<p>Não há eventos para esta data com os filtros seleccionados.</p>');
		$$('div.paginacao1').first().remove();
		
		window._agenda_pagination = false;
	}
}


function agendaReloadHighlights() {
	$('events_highlights').update();
	$('events_highlights').insert ({
		  'bottom' : '<img class="agenda-wait" src="http://imgs.sapo.pt/sapovideo/imgs/indicator_medium.gif" />	'
	});
	
	try {
		var dis_id = $F('dis');
		var mun_id = $F('mun');
		var date   = $F('date-filter');
		
	    new Ajax.Request('/agenda/highlights/', {
	     parameters: {'dis_id': $F('dis'), 'mun_id': $F('mun'), 'date': $F('date-filter')},
	  	  onSuccess: function(response) {
	    	if (response.responseJSON == null) 
	    		throw "Null response";	    	 
	    	 
	    	if (typeof response.responseJSON != 'object') 
	    		throw "Unexpected response";
	    	
	    	$('events_highlights').update();	    		    		
	    	response.responseJSON.each(function(event, index) {
    			var css_class = '';
    			if (index == 0) {
    				css_class = 'first-child'
    			} else if (index == 4) {
    				css_class = 'last-child';
    			}
    			
    			var html = '<li class="' + css_class + '">' +
    			           '<a class="figure" title="' + event.name + '" href="/agenda/' + event.id + '"><img alt="" src="' + event.thumb  + '" onerror="this.src=\'' + event.thumb_error + '\'"></a>' +
    			           '<div class="detail1">' +
    			           '<a class="title" title="' + event.name + '" href="/agenda/' + event.id + '"><strong>' + event.name + '</strong></a>' +
    			           '<div class="resume">' +
    			           '<strong>' + event.venue + '</strong><br />' +
    			           event.date + '<br />' +
    			           'Género: ' + event.type +
    			           '</div>' +
    			           '</div>' +
    			           '<div class="fb_like">' +
    			           '<fb:like href="' + event.fe_url + 'agenda/' + event.id + '" layout="button_count" show_faces="false" width="90"></fb:like>';
    			
    			$('events_highlights').insert ({
    			  'bottom' : html
    			});
    			
    		}); 
	    		    	
	    	FB.init({xfbml:true});

	      },
	      
	      onError: function() {
	    	  throw "Server Error";
	      }
	    });
	    
	} catch(err) {
		// Failed request
		$('events_highlights').update();
	}
	
	return false;
}



function sendTAF(e) {
    
    e.stop();
    
    $('message').show();
    $('message').update('A enviar...');
    
    $('tafform').select('.brd').invoke('removeClassName', 'inErro');
    
    $('tafform').request({
                         onComplete: function(transport) {
                            response = transport.responseJSON;
                            
                            if(response.state == 0) {
                                
                                response.fields.each(function(elem) {
                                                        $(elem+'-input').addClassName('inErro');
                                                     });
                                
                                $('message').addClassName('msgErro');
                                $('message').removeClassName('msgNotify');
                            }
                            else {
                                
                                $('tafform').select('input.brd').each(function(elem) {
                                                                    elem.value = '';
                                                                  });
                                
                                $('tafform').select('textarea').each(function(elem) {
                                                                    elem.value = '';
                                                                  });
                                
                                $('message').removeClassName('msgErro');
                                $('message').addClassName('msgNotify');
                            }
                            
                            $('message').update('<strong>'+response.msg+'</strong>');
                         }
                         });
    
}

function reloadAds() {
    
    if($('mrecIframe') != null) 
        $('mrecIframe').contentWindow.location.reload(true);
    
    if (typeof w_counter != 'undefined')
    	if(w_counter != null)
    		w_counter.count();
}


function datePT(date) {
	var months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
	parts = date.split('-');
	parts[1] = (parseInt(parts[1], 10)) - 1;
	
	return parts[0] + ' ' + months[parts[1]];
}

function domLoaded() {
    
    // init tabs
    new Tabs({ ctrl_class: 'tab-btn', target_class: 'tab' });
    new Tabs({ ctrl_class: 'right-tab-btn', target_class: 'tabcontent', active_class: 'selected' });
    new Tabs({ ctrl_class: 'search-tab-btn', target_class: 'search-results', active_class: 'selected' });
    
    // right area - Tops
    $$('.tabcontent').invoke('select', 'a.toggler').each(function(list) {
                                                 list.invoke('observe', 'click', function(e) {
                                                                e.target.up('div').down('.info').toggle();
                                                                e.stop();
                                                             });
                                                 });
    
    // Agenda - ajax pagination
    if ($$('body[id="agenda"] div.paginacao-agenda a'))
	$$('body[id="agenda"] div.paginacao-agenda a').each(function(s) {
        s.observe('click', function(evt) {
        	Event.stop(evt);        	
        	agendaPagination(this);
        }.bind(s));
	});

    	
                     
    // Agenda - Districts and muni
    if($('dis'))
        $('dis').observe('change', updateConcelhos);

    if ($$('body').first().readAttribute('id') == 'agenda') {
        $('mun').observe('change', function(event) {
        	        	
        	$(event.target).up('form').insert({ top:  new Element('input', {'type' : 'hidden', 
											   			                    'name' : 'dis',
																            'value': $F('dis')})}); 
        	$(event.target).up('form').insert({ top:  new Element('input', {'type' : 'hidden', 
															                'name' : 'mun',
																            'value': $F('mun')})});         	
        	$('dis').disable();	
        	$('mun').disable();	
    		$(event.target).up('form').submit();
        });
    }
    
    // Agenda - Inline calendar
    initInlineCalendar();
    
    // Agenda - Filters
    if($('agenda-lista-form')) {
    	$('Quem').observe('focus', function() {
    		                           if (this.value == 'Banda ou artista')
    		                               this.value = '';
    	                           }.bind($('Quem')));
    	$('Quem').observe('blur', function() {
						              if (this.value == '')
						           	      this.value = 'Banda ou artista';
          						  }.bind($('Quem')));
    	
    	$('Onde').observe('focus', function() {
						               if (this.value == 'Ex.: Coliseu')
						                   this.value = '';
        						   }.bind($('Onde')));
    	$('Onde').observe('blur', function() {
                                      if (this.value == '')
        	                              this.value = 'Ex.: Coliseu';
		                          }.bind($('Onde')));
    }
    
    // Agenda - Genres Filter
    if($('agenda-toggle-genres'))
        $('agenda-toggle-genres').observe('click', function(evt) {
        	                                         Event.stop(evt);
        	                                         if (typeof $('agenda-genres-filter')._motion == 'undefined')
        	                                        	 $('agenda-genres-filter')._motion = false;
        	                                         if ($('agenda-genres-filter')._motion == true)
        	                                        	 return;
        	                                         $('agenda-genres-filter')._motion = true;
        	                                         
        	                                         if ($('agenda-genres-filter').visible()) {
        	                                        	 new Effect.BlindUp('agenda-genres-filter', { duration: 0.5 ,
        	                                        		                                       afterFinish: function() {
        	                                        		                                                      $('agenda-genres-filter')._motion = false;
        	                                        	                                                        }
        	                                        	                                            });
        	                                         } else {
        	                                        	 new Effect.BlindDown('agenda-genres-filter', { duration: 0.5, 
										              		                                         afterFinish: function() {
												                                                                    $('agenda-genres-filter')._motion = false;
											                                                                      }
        	                                        	 });
        	                                         }
                                                   });
    
    // toggle taf
    $$('.toggletaf').invoke('observe', 'click', function() { $('enviarPorEmailForm').toggle(); });
    
    // taf send
    if($('tafform'))
        $('tafform').observe('submit', sendTAF);
    
    // init selectAll 
    $$('.selectAll').each(function(elem) {
                          elem.observe('click', function(e) {
                                        e.target.focus();
                                        e.target.select();
                                       });
                          });
    
    // init artist and genre filter - Concertos
    if($('artist'))
        $('artist').observe('change', function(e) {
                                window.location = '/concertos?artist='+$F('artist');
                            });
        
    if($('genre'))
        $('genre').observe('change', function(e) {
                                window.location = '/concertos?genre='+$F('genre');
                            });
        
    // Increase/Decrease font
    $$('.increase-font').invoke('observe', 'click', increaseFont);    
    $$('.decrease-font').invoke('observe', 'click', decreaseFont);
    
    // Init ticker
    $$('.ticker').each(function(elem) { new Ticker(elem); });
    
    // Search
    $('searchform').observe('submit', function(event) {
        window.location = '/pesquisa/?q='+$F($('searchform').select('.pesquisa-campo')[0]);
        event.stop();
    });
    
    // Print
    $$('.print-activate').each(function(elem) { 
    	                         elem.observe('click', function(e) {
      	                           e.stop();
    	                           print();
						         });
                               });
}

Event.observe(document, 'dom:loaded', domLoaded);

