//var verificarEstudio = false ;

var Site = {
    Init: function() {
		String.prototype.linkar = function( url ){
			return '<a href="' + url + '" target="_blank">' + this + '</a>' ;
		};
		
		String.prototype.zeros = function( qtde ){
			var texto = this ;
			while( texto.length < qtde ) texto = '0' + texto ;
			return texto ;
		};
		
		String.prototype.parseURL = function() {
			return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
				return url.linkar(url);
			});
		};
		
		String.prototype.parseUsername = function() {
			return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
				var username = u.replace("@","")
				return u.linkar("http://twitter.com/"+username);
			});
		};
		
		String.prototype.parseHashtag = function() {
			return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
				var tag = t.replace("#","%23")
				return t.linkar("http://search.twitter.com/search?q="+tag);
			});
		};
		
		$('.external-modal').click(function() {
            var id = $(this).attr('id');
            var source = $(this).attr('href');
            var dimensoes = $(this).attr('rel');
            dimensoes = dimensoes.split('x');
            var w = dimensoes[0];
            var h = dimensoes[1];
            Site.Generics.OpenExternalModal(id, source, w, h);
            return false;
        });
		
		var atualSlide = 0 ;
		var qtdeSlides = $('.patrocinador > div').length ;
		
		var MostrarAtual = function(){
			$('.patrocinador > div').css('display', 'none');
			$('.patrocinador > div').each( function(i){
				if( i == atualSlide ) $(this).css('display', 'block');
			});
			
			atualSlide++ ;
			if( atualSlide >= qtdeSlides ) atualSlide = 0 ;
		};
		
		MostrarAtual();
		$.timer(3000, MostrarAtual);
		
		//$('#site').css('height', $(document).height() );
		
		$('#posts').html('Carregando ...');
			
		var tweetCount = 0;
		var qtdeTweets = 3 ;
		
		var TratarTextoTwitter = function(text) {
			return text.parseURL().parseUsername().parseHashtag();
		}
		
		var tweetsSuccessCallback = function(data){
			var tweetsLi = '';
			for(var i = 0; i < data.results.length; i++){
				var tweet = data.results[i];
				
				tweetsLi += '<li>'
							+ '<p>' + TratarTextoTwitter( '<span>@' + tweet.from_user + '</span>&nbsp;' + tweet.text ) + '</p>'
							+ '</li>' ;
			}
			$('#posts').html( tweetsLi );
			//$('#site').css('height', $(document).height() );
		}
		
		var tweetsErrorCallback = function(errorMessage, tweet){}
		
		var tweets = Twitter.tweets();
		tweets.containing('artriofair').limit(qtdeTweets).all(tweetsSuccessCallback, tweetsErrorCallback);
		
		$('#posts>li:last').css('border', '0') ;
    },
    Generics: {
        OpenExternalModal: function(id, source, w, h, content) {
			var conteudo = '<iframe width=\"' + w + '\" height=\"' + h + '\" frameborder=\"0\" scrolling=\"no\" allowtransparency=\"true\" src=\"' + source + '\"></iframe>';
			if( content != null ) conteudo = content ;
			
            ModalWindow.windowId = id;
            ModalWindow.width = w;
            ModalWindow.height = h;
            ModalWindow.content = conteudo;
            ModalWindow.Open();
        },
        OpenInternalModal: function(id) {
            $(id).jqmShow({ toTop: true });
        },
        FormsEffects: function() {
            $('input[type=text], textarea, select').focus(function() {
                $(this).addClass('on');
            });
            $('input[type=text], textarea, select').blur(function() {
                $(this).removeClass('on');
            });
        },
        ChangeFonts: function() {
            var elements = "#content #main p, #content #main p strong, #content #main p strong span, #content #main li, #content #main a, #content #main h1, #content #main h2, #content #main h3, #content #main h4, #content #main h5, #content #main h6";
            $('.aumentar-fonte').unbind().bind('click', function() {
                var currentFontSize = $(elements).css('font-size');
                var currentFontSizeNum = parseFloat(currentFontSize, 2000);
                var newFontSize = currentFontSizeNum * 1.2;
                $(elements).css('font-size', newFontSize);
                return false;
            });
            $('.diminuir-fonte').unbind().bind('click', function() {
                var currentFontSize = $(elements).css('font-size');
                var currentFontSizeNum = parseFloat(currentFontSize, 2000);
                var newFontSize = currentFontSizeNum * 0.9;
                $(elements).css('font-size', newFontSize);
                return false;
            });
        }
	},
	Intro: function() {
		var fadeIntro = 500 ;
		var bgs = [ { src:'img/common/intro_bg1.jpg', fade:fadeIntro }, { src:'img/common/intro_bg2.jpg', fade:fadeIntro }, { src:'img/common/intro_bg3.jpg', fade:fadeIntro }] ;
		bgs.sort( function(){ return Math.round(Math.random()) - 0.5 ; } );
		$.vegas('slideshow', {backgrounds: bgs})('overlay');
	},
	
	Home: function() {
		$('#ultima_foto').jflickrfeed({
			limit: 1,
			qstrings: { id: '66582694@N06' },
			itemTemplate: 	'<li>'+
								'<img id="flickr_source" src="{{image}}" alt="{{title}}" />' +
						  	'</li>'
		}, function(data) {
			var imgsrc = $('#flickr_source') ;
			
			var img = new Image();
			img.onload = function() {
				$('#box_fotos').css( 'height' , this.height + 'px' );
			}
			img.src = imgsrc.attr('src') ;
			$('#box_fotos').css( 'background-image', 'url(' + imgsrc.attr('src') + ')' ) ;
			
		});
	},
	
	Galerias: function() {
		
		$('a.item_aba').each( function(){
			$(this).click( function(){
				var rel = $(this).attr('rel').substr(1) ;
				
				$('a.item_aba').parent('li').removeClass('selecionado');
				$(this).parent('li').addClass('selecionado');
				
				$('#conteudo_galerias > p').addClass('dn');
				$('#conteudo_galerias > p.' + rel ).removeClass('dn');
				
				$('.lista_galerias > li').slideUp();
				$('.lista_galerias > li.' + rel).slideDown();
			});
		});
		
		//$('.abas > li:first').addClass('selecionado');
		//$(abas[0]).removeClass('dn');
	},
	
	Fotos: function() {
		
		$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=d177d5c36aa6d875e1584ab34d729914&user_id=66582694%40N06&format=json&nojsoncallback=1", 
			function(data){
				var sets_ids = [] ;
				$.each( data.photosets.photoset, function(i,item){
					sets_ids.push( item.id );
				});
				
				$('#fotos_sets').flickrGallery({
					api_key: 'd177d5c36aa6d875e1584ab34d729914',
					photoset_ids: sets_ids,
					thumb_click_hide: true,
					loading_msg:''
				});
			});
		
		
	},
	
	Videos: function(){
		var CarregaLista = function( idLista, container, callback ){
			//$(container).html('Carregando ...') ;
			$.ajax({
				url: "http://gdata.youtube.com/feeds/api/users/" + idLista + "/uploads?alt=json",
				cache: true,
				dataType: 'jsonp',                    
				success: function( data ){
					MontarLista( data.feed.entry, container );
					if( callback != null ){
						callback(data);
					}
				}
			});
		}
		
		var MontarLista = function( lista, container ){
			//$(container).empty();
			
			$.each( lista, function( i, entry ){
				var entrada = TratarEntrada( entry );
				var idVideo = entrada.id ;
				var titleVideo = entrada.titulo ;
				$(container).append('<li title="' + titleVideo + '"><a href="http://www.youtube.com/embed/' + idVideo + '" title="' + titleVideo + '" target="videoframe">'
									+ 	'<img src="http://img.youtube.com/vi/' + idVideo + '/1.jpg" width="130" height="97" class="thumb" /></a>'
									+	'<div class="descricao">'
									+	'<a href="http://www.youtube.com/embed/' + idVideo + '" title="' + titleVideo + '" target="videoframe">'
									+	'<p><strong>' + titleVideo + '</strong></p>'
									+	'</a>'
									+ '</div></li>');
			});
			
			$('#site').css('height', 'auto' );
		};
		
		var MostraPrimeiro = function( data ){
			var primeiro = TratarEntrada( data.feed.entry[0] );
			$('#videoframe').attr( 'src', 'http://www.youtube.com/embed/' + primeiro.id );
		}
		
		var TratarEntrada = function( entry ){
			var obj = {} ;
			obj.titulo = entry.title.$t ;
			
			var spl = entry.id.$t.split('/');
			obj.id = spl[ spl.length -1 ] ;
			
			return obj ;
		}
		
		//CarregaLista( '29B478B8A36CF597','#lista_videos', MostraPrimeiro);
		CarregaLista( 'artriofair','#lista_videos', MostraPrimeiro);
		CarregaLista( 'artrio2011','#lista_videos');
	}
}
