/**
 * @namespace Namespace base do TeContei
 */
var TeContei = {};
/**
 * Constante que guarda o hostname padrão
 *IMAGEM_ESTATICO
 * @type String
 */
TeContei.URL = temp.URL;
/**
 * Constante que guarda o hostname do servidor de imagens
 *
 * @type String
 */
TeContei.IMG_SERVER = temp.IMG_SERVER;
/**
 * @namespace Namespace que guarda informações da view atual
 */
TeContei.View = {
	/**
	 * O controller executado
	 *
	 * @type String
	 */
	Controller: temp.controller,
	/**
	 * A ação executada
	 *
	 * @type String
	 */
	Action: temp.action,
	/**
	 * O Id "ativo"
	 *
	 * @type Number
	 */
	Id: temp.id,
	/**
	 * As tags relacionadas
	 *
	 * @type String
	 */
	Tags: temp.tags
};
/**
 * @namespace Namespace que contém funcionalidades gerais úteis
 */
TeContei.Util = {};
/**
 * @function Inclui dinamicamente um Javascript na página
 * @param {String} url A url do script a ser incluído
 */
TeContei.Util.IncludeJS = function (url) {
	var html_doc = document.getElementsByTagName('head')[0];
	var js = document.createElement('script');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', url);
	html_doc.appendChild(js);
	/*js.onreadystatechange = function () {
		if (js.readyState == 'complete') {
			alert('JS onreadystate fired');
		}
	}

	js.onload = function () {
		alert('JS onload fired');
	}*/
	return false;
}
/**
 * @function Acerta a posicao em elementos fixed no IE6
 * @param {Element} elem O elemento que sera reposicionado
 */
TeContei.Util.IE6Fix = {
	/** @private */
	cachedScrollHandler: null,
	Registers: [],
	RegisterElement: function(elem,x,y) {
		if(this.Registers.length == 0) {
			if(this.cachedScrollHandler === null) {
				this.cachedScrollHandler = this.scrollHandler.bindAsEventListener(this);
			}
			Event.observe(window,'scroll',this.cachedScrollHandler);
		}
		this.Registers.push({
			Position: {x:x,y:y},
			Element: elem
		});
		this.scrollHandler();
	},
	UnregisterElement: function(elem) {
		this.Registers.pop(this.Registers.find(function(r){r.Element==elem}));
		if(this.Registers.length == 0) {
			Event.stopObserving(window,'scroll',this.cachedScrollHandler);
		}
	},
	/** @private */
	scrollHandler: function() {
		var scrollOffset = document.viewport.getScrollOffsets();
		for(var i=0,len=this.Registers.length ; i < len ; i++) {
			var style = {}
			style.top = this.Registers[i].Position.y+scrollOffset.top+'px';
			style.left = this.Registers[i].Position.x+scrollOffset.left+'px';
			this.Registers[i].Element.setStyle(style);
		}
	}
}
/**
 * @namespace Namespace que guarda as funções de callback usadas nos workarounds de XDR
 */
TeContei.Callbacks = {};
/**
 * @function Trata a resposta enviada pelo FlickR
 * @param {Object} flickrResponse A resposta enviada pelo FlickR
 */
TeContei.Callbacks.FlickR = function(flickrResponse) {
	var fotos = flickrResponse.items;
	var len = fotos.length > 7 ? 7 : fotos.length;
	TeContei.Containers.Flickr.innerHTML = '';
	for(var i=0 ; i < len ; i++) {
		var html = '<a class="inner_border" href="'+fotos[i].link+'">';
		html += '<img src="'+fotos[i].media.m.replace(/_m\.((?:jpg)|(?:gif)|(?:png))/,"_s.$1")+'" alt="'+fotos[i].title+'"/>';
		html += '</a>';
		TeContei.Containers.Flickr.innerHTML += html;
	}
}
/**
 * @function Trata a resposta enviada pelo YouTube
 * @param {Object} ytResponse A resposta enviada pelo YouTube
 */
TeContei.Callbacks.YT = function(ytResponse) {
	var videos = ytResponse.feed.entry;
	TeContei.Containers.YouTube.innerHTML = '';
	if (videos != null)
		for(var i=0,len = videos.length ; i < len ; i++) {
			var videoUrl = videos[i].link[0].href;
			var videoThumbUrl = videos[i].media$group.media$thumbnail[0].url;
			var html = '<a class="inner_border" href="'+videoUrl+'">';
			html += '<img src="'+videoThumbUrl+'" alt="'+videos[i].title+'" height="75px" width="75px" />';
			html += '</a>';
			TeContei.Containers.YouTube.innerHTML += html;
		}
}
/**
 * @function Trata a resposta enviada pelo Bolsa para popular o Fã-Clube
 * @param {Object} bolsaResponse A resposta enviada pelo Bolsa
 */
TeContei.Callbacks.FaClube = function(bolsaResponse) {
	var usuarias = bolsaResponse.usuarias;
	var len = usuarias.length;
	var cor;
	if(len == 0) {
		TeContei.Containers.FaClube.down('div.faclube_loading').innerHTML = TeContei.Dicionario.FaClube.Vazio;
	}
	else {
		TeContei.Containers.FaClube.down('div.faclube_loading').hide();

		for(var i=0 ; i < len ; i++) {

			var imgSrc = usuarias[i].avatar_url.replace(/com\/\//, 'com/');

			var cor = 'cor'+parseInt((i%4+1));
            var a = new Element('a', {
					href: usuarias[i].minha_url,
					id: 'faclube-user-avatar-'+usuarias[i].login
				})
				.addClassName('inner_border')
				.addClassName('right_margin_10')
				.addClassName('cor'+cor);

			img = new Element("img", {
					// src: usuarias[i].avatar_url,
					src: imgSrc,
					alt: usuarias[i].login
				})
				.addClassName('avatar_small_h')
				.setStyle({ display: 'block'});

			TeContei.Containers.FaClube.appendChild(a);
			a.appendChild(img);

			delete a; delete img;
		}

	}
}
/** @namespace */
TeContei.Favorito = {
	/** @private */
	isBusy: false,
	/** @private */
	url: TeContei.URL+'proxy/favoritos/',
	/**
	 * O possíveis tipos para um favorito
	 *
	 * @type Object
	 */
	Tipos: {
		'noticia': 'TNOT',
		'celebridade': 'TC',
		'video': 'TV',
		'novela': 'TNOV',
		'dieta': 'TD'
	},
	/**
	 * @function
	 * @param favorito Informacoes sobre o conteudo a ser adicionado aos favoritos do usuario
	 * @param {Number} favorito.Id O id do conteudo
	 * @param {String} favorito.Tipo O tipo de conteudo
	 */
	Add: function(favorito) {
		if (!this.isBusy) {
			this.isBusy = true;
			new Ajax.Request(this.url+'addVinculo',{
				method: 'post',
				parameters: {
					obj_id: favorito.Id,
					obj_tipo: favorito.Tipo
				},
				onSuccess: function() {
					document.fire('favoritos:added', favorito);
				},
				onComplete: function() {
					this.isBusy = false;
				}.bind(this)
			});
		}
	},
	/**
	 * @function
	 * @param favorito Informacoes sobre o conteudo a ser removido dos favoritos do usuario
	 * @param {Number} favorito.Id O id do conteudo
	 * @param {String} favorito.Tipo O tipo de conteudo
	 */
	Remove: function(favorito) {
		if (!this.isBusy) {
			this.isBusy = true;
			new Ajax.Request(this.url+'removeVinculo',{
				method: 'post',
				parameters: {
					obj_id: favorito.Id,
					obj_tipo: favorito.Tipo
				},
				onSuccess: function() {
					document.fire('favoritos:removed', favorito);
				},
				onComplete: function() {
					this.isBusy = false;
				}.bind(this)
			});
		}
	}
};
/** @namespace */
TeContei.Avaliacao = {
	/** @private */
	isBusy: false,
	/** @private */
	url: TeContei.URL+'proxy/avaliacao/',
	/**
	 * O possíveis tipos para uma avaliacao
	 *
	 * @type Object
	 */
	Tipos: {
		'celebridade': 1,
		'novela': 2,
		'video': 3
	},
	/**
	 * @function
	 * @param favorito Informacoes sobre a avaliacao feita pelo usuario
	 * @param {Number} favorito.Id O id da avaliacao
	 * @param {String} favorito.Tipo O tipo de conteudo
	 */
	Make: function(avaliacao) {
		if (!this.isBusy) {
			this.isBusy = true;
			new Ajax.Request(this.url,{
				method: 'post',
				parameters: avaliacao,
				onSuccess: function() {
					document.fire('avaliacao:made', avaliacao);
				},
				onComplete: function() {
					this.isBusy = false;
				}.bind(this)
			});
		}
	}
}
/** @namespace */
TeContei.Quiz = {
	/** @private */
	isBusy: false,
	/**
	 * @function
	 * @param id Id do quiz a ser carregado
	 */
	Load: function(id) {
		new Ajax.Request(TeContei.URL+'proxy/quiz/',{
			method: 'post',
			parameters: {
				quiz_id: id
			},
			onSuccess: function(response) {
				var quizObj = response.responseJSON;
				if(quizObj == null) {
					document.fire('quiz:loadError');
				}
				else {
					document.fire('quiz:loaded', quizObj);
				}
			}.bind(this)
		});
	},
	/**
	 * @function
	 * @param quiz Informacoes sobre o quiz
	 * @param {Number} quiz.Id O id do quiz
	 */
	Submit: function(quiz) {
		if (!this.isBusy) {
			this.isBusy = true;
			new Ajax.Request(TeContei.URL+'diversao/resultado/',{
				method: 'post',
				parameters: quiz,
				onSuccess: function() {
					document.fire('quiz:submitted', quiz);
				},
				onComplete: function() {
					this.isBusy = false;
				}.bind(this)
			});
		}
	}
}
/** @namespace */
TeContei.Containers = {};
/** @ignore */
Event.observe(window, 'load', function() {
	var faclube = $('faclube_container');
	if(faclube != null) {
		TeContei.Containers.FaClube = faclube;
		var url = 'http://www.bolsademulher.com/AJAX/favoritos.php?mode=json';
		url += '&obj_id='+faclube.down('input[name="obj_id"]').value;
		url += '&obj_tipo='+faclube.down('input[name="obj_tipo"]').value;
		url += '&limit='+faclube.down('input[name="limit"]').value;
		url += '&action=getUsuarias&page=1&callback=TeContei.Callbacks.FaClube';
		TeContei.Util.IncludeJS(url);
	}
	var yt = $('youtube_container');
	if(yt != null) {
		TeContei.Containers.YouTube = yt;
		var url = 'http://gdata.youtube.com/feeds/api/videos?';
		url += 'category='+yt.down('input[name="yt_tags"]').value;
		url += '&max-results=7&alt=json-in-script&callback=TeContei.Callbacks.YT';
		TeContei.Util.IncludeJS(url);
	}
	var flickr = $('flickr_container');
	if(flickr != null) {
		TeContei.Containers.Flickr = flickr;
		var tag_mode = flickr.down('input[name="flickr_tagmode"]').value;
		var url = 'http://api.flickr.com/services/feeds/photos_public.gne?';
		url += 'tags='+flickr.down('input[name="flickr_tags"]').value;
		url += '&tagmode='+flickr.down('input[name="flickr_tags"]').value;
		url += '&format=json&lang=pt-br&jsoncallback=TeContei.Callbacks.FlickR';
		TeContei.Util.IncludeJS(url);
	}
});

