/////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////////////////////////
function js_translate_weekdays()
{
	var el = $('#agenda');
	el.html(el.html().replace(/Sunday/ig, "Domingo"));
	el.html(el.html().replace(/Saturday/ig, "S&aacute;bado"));
	el.html(el.html().replace(/Monday/ig, "Segunda"));
	el.html(el.html().replace(/Tuesday/ig, "Ter&ccedil;a"));
	el.html(el.html().replace(/Wednesday/ig, "Quarta"));
	el.html(el.html().replace(/Thursday/ig, "Quinta"));
	el.html(el.html().replace(/Friday/ig, "Sexta"));

}
function get_events(monthnum)
{
	var year = $("#agenda-year").text();
	
	var url = 'agenda/generate/' + year + '/' + monthnum;
    
    $.ajax({
              type:"GET",
              url: url,
              success: function(data){
                 $("#agenda").html(data); 
                 js_translate_weekdays();
              },
              error: function(data){
                 $("#agenda").html(data);
                 
              }        
     });
     

}

function init_events_de()
{  
        
    var today = new Date();
    
    //var monthnum = today.getMonth()+1;

    var jsonyear = $("#agenda-year").text(); 
    
    //get_events(jsonyear, monthnum);
    
    $(".monthheader").click(function () { 
      var monthx = $(this).attr('title');      
      $("#agenda").html('A carregar..');      
      get_events(monthx); 
      $(".monthheader").removeClass('titlesmall');
      $(this).addClass('titlesmall');
      return false;
    });
    
    $("#agenda-menos-ano").click(function () { 
      $("#agenda").html('A carregar..');
      
      var curyear = parseInt($("#agenda-year").text());
      var prevyear = curyear - 1;
      $("#agenda-year").text(prevyear);
      get_events(12);
      $(".monthheader").removeClass('titlesmall');
      $("#month12").addClass('titlesmall');
      
      return false;
    });
    
    $("#agenda-mais-ano").click(function () { 
      $("#agenda").html('A carregar..');
      
      var curyear = parseInt($("#agenda-year").text());
      var nextyear = curyear + 1;
      $("#agenda-year").text(nextyear);
      get_events(01);
      $(".monthheader").removeClass('titlesmall');
      $("#month01").addClass('titlesmall');
      return false;
    });                               
}

/////////////////////////////////////////// \EVENTS //////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////// \VIDEOS //////////////////////////////////////////////////////////////////////////////////
function fillUpPreviews(){
	var container = document.getElementById('previewsContainer');
	var node2Duplicate = document.getElementById('previewVideo');
	node2Duplicate.style.display = "none";
	
	container.innerHTML = "";
	
	for(var i = ((actualPage - 1) * itemsPerPage); dataVideos[i] != undefined && i < (actualPage * itemsPerPage) ; i++){
		var dataTemp = eval(dataVideos[i]);
		
		var toAppend = node2Duplicate.cloneNode(true);
		var toAppendId = "video_" + dataTemp['random_id'];
		toAppend.style.display = "";
		
		toAppend.setAttribute('id', toAppendId);
		toAppend.setAttribute('catId', dataTemp['video_category_id']);
		toAppend.setAttribute('arrayPosition', i);
		
		// alter attributes from anchor
		toAppend.childNodes[0].setAttribute('href', "videos/" + dataTemp['random_id']);
		toAppend.childNodes[0].setAttribute('onClick', "javascript:changeVideo('" + dataTemp['random_id'] + "');return false;");
		
		// alter image
		toAppend.childNodes[0].childNodes[0].setAttribute('src', dataTemp['thumbnail_url']);
		var title = dataTemp['title'];
		if(title.length > 43){
			title = title.substring(0,40) + '...';
		}
		toAppend.childNodes[0].childNodes[0].setAttribute('alt', title);
		
		// alter title
		toAppend.childNodes[2].innerHTML = title;
		
		// alter duration
		toAppend.childNodes[4].innerHTML = dataTemp['duration'];
		
		// alter pubdate
		toAppend.childNodes[6].innerHTML = dataTemp['pubdate_date'];
		
		
		container.appendChild(toAppend);
		
		// add a dummy class to identify categories (easy to apply animations)
		$('#' + toAppendId).addClass('category-class-all');
		$('#' + toAppendId).addClass('category-class-' + dataTemp['video_category_id']);
	}
	
	filterCategory(categorySelected, true);
	
	controlPagination();
}

function changeVideo(videoId){
	
	if(highlightVideoId == videoId){
		return;
	}
	
	highlightVideoId = videoId;
	window.location.hash = "#" + videoId;
	
	var position = $('#video_' + videoId)[0].getAttribute('arrayPosition');
	var video = eval(dataVideos[position]);
	
	var embed_code = '<embed src="http://www.truetech.com.br/webtvconsole/usuario3.0/embed.swf" quality="high" bgcolor="#ffffff" width="480" height="270" name="AdobeTVPlayer" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" flashVars="console=153&video='+video['random_id']+'"></embed>';
		
	// fill up the hightligthed place!
	$('#feature-pic_big').animate({ opacity: 0.3 }, 10, "linear", function(){
				
		//document.getElementById('feature-pic').innerHTML = '<embed src="http://rd3.videos.sapo.pt/play?file=' + video['video_url'] + '" type="application/x-shockwave-flash" width="400" height="100%"></embed>';
		document.getElementById('feature-pic_big').innerHTML = embed_code;
		
		
	}).animate({ opacity: 1 }, "slow", "linear");
	
	$('#feature-content_big').animate({ opacity: 0.3 }, 100, "linear", function(){
		document.getElementById('feature-category').innerHTML = video['category_name'];
		document.getElementById('feature-title').innerHTML = video['title'];
		document.getElementById('feature-synopse').innerHTML = video['synopse'];
		document.getElementById('feature-pubdate').innerHTML = video['pubdate_date'];
		var str_vid_url = video['video_url'];
				
		document.getElementById('feature-link').value = video['source_reference'];
		document.getElementById('feature-embedCode').value = embed_code;
		
	}).animate({ opacity: 1 }, 500, "linear");
	
}

function filterCategory(catId, force){
	
	var oldCategorySelected = categorySelected;
	
	// do nothing when clicking in the same category!
	if(force == undefined || force != true){
		if(categorySelected == catId){
			return;
		}
	}
	categorySelected = catId;
	
	
	// animate thumbs with desired category
	if(catId == 'all'){
		$('.category-class-all').animate({ opacity: 1 }, "fast", "linear");
	}else{
		if(navigator.appName == "Microsoft Internet Explorer") {
			// buggy IE :(
			for(var i in arrayCategories){
				$('.category-class-' + arrayCategories[i]).animate({ opacity: (catId == arrayCategories[i]) ? 1 : 0.5 }, "fast", "linear");
			}
		}else{
			$('.video-thumb[@catId=' + catId + ']').animate({ opacity: 1 }, "fast", "linear");
			$('.video-thumb[@catId!=' + catId + ']').animate({ opacity: 0.5 }, "fast", "linear");
		}
	}
	
	// select button!
	if(categorySelected != oldCategorySelected){
		$('#category_' + categorySelected).addClass('subactive');
		$('#category_' + oldCategorySelected).removeClass('subactive');
	}
}


// functions to control pagination
function gotoPreviousPage(){
	if(actualPage > 1){
		actualPage = actualPage - 1;
		
		if(pagesPresent >= actualPage){
			fillUpPreviews();
		}else if(hasMorePages){
			getPageFromServer(actualPage);
		}
	}
}

function gotoNextPage(){
	if(hasMorePages || (actualPage * itemsPerPage) < dataVideos.length){
		actualPage = actualPage + 1;
		
		if(pagesPresent >= actualPage){
			fillUpPreviews();
		}else if(hasMorePages){
			getPageFromServer(actualPage);
		}
	}
}

function controlPagination(){
	// hide both buttons if is no more pages
	if(!hasMorePages && pagesPresent == 1){
		$('#pagination-previous-button').hide();
		$('#pagination-next-button').hide();
		return;
	}
	
	$('.pagination-videos-previous-button').animate({ opacity: 0 }, "fast", "linear");
	var disablePrevButton = false;
	var disableNextButton = false;
	if(actualPage == 1){
		disablePrevButton = true;
	}else{
		//$('#pagination-previous-button').animate({ opacity: 1 }, "fast", "linear");
	}
	if(actualPage == pagesPresent && !hasMorePages){
		disableNextButton = true;
	}
	
	$('#pagination-previous-button').animate({ opacity: disablePrevButton ? 0.3 : 1 }, "fast", "linear");
	$('#pagination-previous-button').css("cursor", disablePrevButton ? "default" : "pointer");
	$('#pagination-next-button').animate({ opacity: disableNextButton ? 0.3 : 1 }, "fast", "linear");
	$('#pagination-next-button').css("cursor", disableNextButton ? "default" : "pointer");
}

function getPageFromServer(num) {
	http.open("GET", "videos/page/" + num, true);
	
	http.onreadystatechange=function() {
		if(http.readyState == 4) {
			
			if(http.responseText.substring(0,4) == '[{}]'){
				// no more videos!
				hasMorePages = false;
				actualPage = actualPage - 1;
				controlPagination();
			}else{
				pagesPresent++;
				var response = eval(http.responseText);
				dataVideos = dataVideos.concat(response);
				fillUpPreviews();
			}
		}
	}
	
	http.send(null);
}


/////////////////////////////////////////// \VIDEOS //////////////////////////////////////////////////////////////////////////////////
