/* DOM manipulation for the realtime funcs */
var rt_dom = {};
(function($){
	$(function(){	
		filter_comment_author();
		delete_tooltips(1000, 6000);// every second, delete tooltips visible for more than 6 sec
		set_jGrowl_options();
		enable_live_tv();
		
		// functions 		
		rt_dom.write_news = function(data, show_tooltip){			
			if(undefined==show_tooltip) show_tooltip=true;
			if(!data.id) return;
			if(!data.controller) return;
						
			var alert_mode = data.alert_mode;
			if(alert_mode){
				var hdr = '';
				switch(alert_mode){
					case 'nova_noticia':
						hdr = 'Nova Not&iacute;cia';
						break;
					case 'actualizacao':
						hdr = 'Actualiza&ccedil;&atilde;o';
						break;
					case 'breaking_news':
						hdr = 'Breaking News';
						break;
				}
				get_item_content(
					data.controller,
					data.id,
					function(data){
						data = parse_json(data);
						$.jGrowl(
							'<a href="'+data.url+'" target="_blank">'+data.title+'</a>',
							{'header':hdr}
						);
						if('breaking_news'==alert_mode) play_alert();
					}
				);
			}
			
			if(is_page('live')){
				add_live_latest_news(data.id, data.controller, show_tooltip);
			}else if(is_page('home')){
				/*
				* blocks_id *
				* 0: Nenhum
				* 1: Em Foco Home (fundo preto) 
				* 2: Destaque Home (fundo branco) [#item00]
				* 6: Bloco Ultima Hora Homepage [div#item22]
				* 8: Bloco Colunistas [div#item15]
				*/
				switch(data.blocks_id){
					case 1: //Em Foco Home (fundo preto)
						// Just update. Insert only when ordering
						if($('#column-0 #articles_'+data.id).length>0){// in top section
							get_item_content('articles', data.id, home_top_block_write);
						}
						break; 
					case 2: //Destaque Home (fundo branco) [#item00]
						return false;//tmp: until we can manage cache
						get_item_content(
							data.controller,
							data.id,
							function(data){
								data = parse_json(data);
								var html = '\n\
									<div id="articles_'+ data.id +'" class="highlight-photo">\n\
								';
								if(data.img_small){
									html +=	'<img src="'+ data.img_small +'" alt="'+ data.title +'" />';
								}
								html += '\n\
										<span class="highlight">'+ data.pubdate +'</span><br>\n\
										<a href="'+ data.url +'">'+ data.title + editor_tooltip() +'</a> \n\
										<br class="clear">\n\
									</div>\n\
								';
								var num_items = 10;
								var container_selector = '#item00 .module-content';
								write_block_home(data, html, num_items, container_selector);
							}
						);
						break;
					case 6: //Bloco Ultima Hora Homepage [div#item22]
						return false;//tmp: until we can manage cache
						get_item_content(
							data.controller,
							data.id,
							function(data){
								data = parse_json(data);
								var html = '\n\
									<li id="articles_'+ data.id +'">\n\
										<span class="highlight">'+ data.pubdate +'</span>\n\
										<a href="'+ data.url +'">'+ data.title + editor_tooltip() +'</a>\n\
									</li>\n\
								';
								var num_items = 10;
								var container_selector = '#item22 .module-content ul';
								write_block_home(data, html, num_items, container_selector);
							}
						);
						break;
					case 8: //Bloco Colunistas [div#item15]
						return false;//tmp: until we can manage cache
						get_item_content(
							data.controller,
							data.id,
							function(data){
								data = parse_json(data);
								html = '\n\
									<p id="articles_'+ data.id +'">\n\
								';
								if(data.fields_cache.author.photo){
									html += '<img class="left" alt="'+ data.fields_cache.author.title +'" src="/public/uploads/authors/'+ data.fields_cache.author.photo +'">';
								}
								html += '\n\
										<strong class="highlight">'+ data.fields_cache.author.title + editor_tooltip() +'</strong><br>\n\
										<strong><a href="'+ data.url +'">'+ data.title +'</a></strong><br>'+ data.summary +'\n\
									</p>\n\
								';
								var num_items = 4;
								var container_selector = '#item15 .module-content';
								write_block_home(data, html, num_items, container_selector);
							}
						);
						break;
				}
			}
		}
		
		rt_dom.test_top_block_update = function(new_items){
			for(var i in new_items){
				$.getJSON(
					proxy_server, 
					{'article': new_items[i]},
					function(data){
						//ok
					}
				);
			}
			//rt_dom.home_top_block_update(new_items);
		}
		
		rt_dom.home_top_block_update = function(new_items){
			if(!is_page('home')) return false;
			
			var current_items = [];
			var items_to_delete = [];
			// current items
			$('#feature-index li, .emfoco-caixa', '#column-0').each(function(){
				var id = $(this).attr('id').replace('articles_','');
				current_items.push(id);
			});
			items_to_delete = current_items.slice(0);// temporary... we will strip that down
			// elements to remove
			for(var i in new_items){
				var init = (i>5 ? 6 : 0);
				var max = (i>5 ? current_items.length : 6);
				var elm_exists = false;
				for(var j=init; j<max; j++){
					if(new_items[i] == current_items[j]){
						elm_exists = true;
						break;
					}
				}
				if(elm_exists){
					// remove from elements to delete 
					var idx = $.inArray(new_items[i], items_to_delete); // Find the index
					if(idx!=-1) items_to_delete.splice(idx, 1); // Remove it if really found!
				}
			}
			// delete items
			for(var i in items_to_delete){
				$('#articles_'+items_to_delete[i]).remove();
			}
			//reorder
			for(var i in new_items){
				// fetch?
				var elm = $('#column-0 #articles_'+new_items[i]);
				if(elm.length <= 0){
					var is_new = true;
					for(var j in items_to_delete){
						if(items_to_delete[j]==new_items[i]){
							is_new = false
							break;
						}
					}
					// fetch!
					home_top_block_fetch(new_items[i], i, is_new);
				}else{
					// move
					home_top_block_move(new_items[i], i);
				}
			}
		}
		
		function home_top_block_fetch(id, order, is_new){
			var loading = '<div style="text-align:center;"><img src="public/images/icons/loading.gif" height="15"></div>';
			var index = 0;
			if(order == 0){
				$('#column-0 #feature-index ul')
					.prepend('<li id="articles_'+id+'">'+loading+'</li>');
			}else if(order<=5){
				index = order-1;
				$('#column-0 #feature-index li:eq('+index+')')
					.after('<li id="articles_'+id+'">'+loading+'</li>');
			}else if(order == 6){
				$('#bolsaFlash .inner' )
					.prepend('<div class="emfoco-caixa" id="articles_'+id+'">'+loading+'</div>');
			}else{
				index = order-7;
				$('#column-0 .emfoco-caixa:eq('+index+')')
					.after('<div class="emfoco-caixa" id="articles_'+id+'">'+loading+'</div>');
			}
			if(is_new){
				$('#column-0 #articles_'+id).addClass('new');
			}
			get_item_content('articles', id, home_top_block_write);
		}
		
		function home_top_block_move(id, order){
			var item = $('#column-0 #articles_'+id+':not(.remove)');
			if(item.length<=0)return;
			
			var elm = item.detach();
			var index = 0;
			if(order == 0){
				$('#column-0 #feature-index ul').prepend(elm);
			}else if(order<=5){
				index = order-1;
				$('#column-0 #feature-index li:not(.remove)').eq(index).after(elm);
			}else if(order == 6){
				$('#bolsaFlash .inner' ).prepend(elm);
			}else{
				index = order-7;
				$('#column-0 .emfoco-caixa:not(.remove)').eq(index).after(elm);
			}
		}
		
		function home_top_block_write(data){
			data = parse_json(data);
			var elm = $('#column-0 #articles_'+data.id);
			var is_new = $('#column-0 #articles_'+data.id).hasClass('new');
			if(is_new) $('#column-0 #articles_'+data.id).removeClass('new');
			
			var html = '';
			if(elm.is('li')){
				// black
				html = '\n\
					<li id="articles_'+data.id+'">\n\
						<a href="'+data.url+'">\n\
							<span class="highlight">'+data.tagline+'</span> \n\
							'+data.title+'\n\
				';
				if(is_new) html += editor_tooltip();
				html += '\n\
						</a>\n\
						<div class="dataProvider" style="display:none;">\n\
							<h3><span>Feature</span></h3>\n\
							<div id="feature-pic">\n\
								<h1><a href="'+data.url+'">'+data.title+'</a></h1>\n\
				';
				if(data.stock_chart){
					var filename = '/public/uploads/charts/noticia_'+data.id+'_'+data.stock_chart+'.xml';
					html += '\n\
						<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"\n\
						codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"\n\
						width="397" height="225" id="chart" align="middle">\n\
							<param name="allowScriptAccess" value="always" />\n\
							<param name="allowFullScreen" value="false" />\n\
							<param name="wmode" value="transparent" />\n\
							<param name="flashVars" value="productID='+filename+'"/>\n\
							<param name="movie" value="public/swf/chart-destaque.swf" />\n\
							<param name="quality" value="high" />\n\
							<param name="bgcolor" value="#000000" >\n\
							<embed src="public/swf/chart-destaque.swf" quality="high" bgcolor="#000000" width="397" height="225" name="chart" align="middle" allowScriptAccess="always" allowFullScreen="false" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" flashVars="productID='+filename+'"/>\n\
						</object>\n\
					';
				}else if(data.photo_medium){
					html += '<img alt="'+data.title+'" src="/public/uploads/articles/'+data.photo_medium+'">';
				}
				html +='\n\
								<div id="feature-caption">'+data.summary+'</div>\n\
							</div>\n\
						</div>\n\
					</li>\n\
				';
			}else{
				// white
				html = '\n\
					<div class="emfoco-caixa" id="articles_'+data.id+'">\n\
						<div class="categoria">'+data.tagline+'</div>\n\
						<div class="emfoco-caixa-header">\n\
				';
				if(data.photo_small){
					html += '<img src="/public/uploads/articles/'+data.photo_small+'" alt="'+data.title+'">';
				}
				html +='\n\
							<div class="titulo">\n\
								<a href="'+data.url+'">'+data.title+'</a>\n\
				';
				if(is_new) html += editor_tooltip();
				html += '\n\
							</div>\n\
							<br class="clear">\n\
						</div>\n\
						<div class="corpo">'+data.summary+'</div>\n\
					</div>\n\
				';
			}
			elm.replaceWith(html);
		}
		
		rt_dom.preload_live_news = function(data){
			var container = $('#news');
			if(container.length<=0) return;
			
			if(!container.is(":visible")) container.fadeIn();
			container.find('.module-header h3').append(editor_tooltip());
			// sort
			var elms = []
			for(var i in data) elms.push(data[i]);
			elms.sort(function(a, b) {return b.id - a.id});
			$.each(
				elms, 
				function(id, item){
					rt_dom.write_news(item, false);
				}
			);
		}
		
		rt_dom.write_breaking_news = function(data){
			var element = $('#breaking_news_'+data.id);
			var is_new = (element.length <= 0);
						
			if(is_new){ // new element
				$.jGrowl(
					data.title,
					{'header':"Nova \"Breaking News\""}
				);
				play_alert();
			}
			// home page
			if($('#breaking-news').length<=0) return;
			
			var elm = $('#breaking-news');
			switch(data.ctype){
				case 0:
					elm.attr('class', 'breaking-news');
					break;
				case 1://etv
					elm.attr('class', 'breaking-news etv');
					break;
				case 2://live
					elm.attr('class', 'breaking-news live');
					break;
			}
			var msg = '';
			if(data.url!='') msg += '<a href="'+data.url+'" style="color:#000">';
			msg += data.title
			if(data.url!='') msg += '</a>';
				
			if(is_new){
				elm.html('<p id="breaking_news_'+data.id+'">'+msg+editor_tooltip()+'</p>');
			}else{
				element.html(msg+editor_tooltip());
			}
			elm.fadeIn();
			//getMyDivHeight();// resize breaking news div
			var boxh = elm.height();
			if(boxh>=35){
				elm.removeClass('breaking-news').addClass('breaking-news-big');
			}
		}
		
		function get_item_content(controller, id, callback_function){
			if('articles'==controller){
				$.getJSON(
					proxy_server, 
					{'article': id},
					callback_function
				);
			}
		}
		
		function filter_comment_author(){
			$('#comment-author').change(function(){
				var submited_author = $(this).val();
				$.post(
					'/noticias/cleanup_str/', 
					{'str': submited_author},
					function(data){
						$('#comment-author').val(data);
					}
				);
			});
		}
		
		function is_admin(controller){
			var is_admin_area = $('body').hasClass('admin');
			if(!controller){
				return is_admin_area;
			}else{
				var is_channel = $('body').hasClass(controller);
				return (is_channel && is_admin_area);
			}
		}
		
		function is_page(page){
			if(!page) return false;
			var is_admin_area = $('body').hasClass('admin');
			var is_page = $('body').hasClass(page);
			return (is_page && !is_admin_area);
		}
		
		function page_id(){
			var id = $('body').attr('id');
			return id;
		}
		
		
		function editor_tooltip(id){
			var ts = new Date().getTime(); 
			var editor_tooltip = '\n\
				<span style="position:absolute;" data-ts="'+ts+'" class="editor_tooltip">\n\
					<img style="position:relative;top:-25px;left:5px;z-index:99999;" src="public/images/icons/realtime_ico.png">\n\
				</span>\n\
			';
			return editor_tooltip;
		}
		
		// delete tooltips
		function delete_tooltips(time_check, duration){
			setInterval(
				function(){
					var ts = new Date().getTime(); 
					$('span.editor_tooltip').each(function(){
						if(ts-duration > $(this).attr('data-ts')){
							$(this).fadeOut(function(){
								$(this).remove();
							});
						}
					});
				},
				time_check
			);
		}
		
		function play_alert(){
			//todo: add alternative support to html5
			var audio_elm = $('audio.alert');
			if(audio_elm.length > 0){
				audio_elm[0].play();
			}else{
				//create audio elem
				audio_elm = $('\n\
					<audio autoplay preload="auto" class="alert">\n\
						<source src="/public/audio/chime.ogg" />\n\
					</audio>\n\
				').appendTo($('body'));
			}
		}
		
		function limit_num_items(html_filter, num_items){
			if($(html_filter).length > num_items){
				$(html_filter+':gt('+(num_items-1)+')').fadeOut(
					'slow', 
					function(){
						$(this).remove();
					}
				)
			}
		}
		
		function add_live_latest_news(id, controller, show_tooltip){
			var is_new = ($('#'+controller+'_'+id).length <= 0);
			var loading = '<div style="text-align:center;"><img src="public/images/icons/loading.gif" height="15"></div>';
			html = '<div id="'+controller+'_'+id+'" class="article">'+loading+'</div>';
			if(is_new){
				limit_num_items('#news div.inner div.article', 5);
				$('div#news div.inner').prepend(html);
			}
			get_item_content(
				controller,
				id,
				function(data){
					data = parse_json(data);
					var title = (data.title ? data.title : '');
					var url = (data.url ? data.url : '');
					var tagline = (data.tagline ? data.tagline : '');
					var summary = (data.summary ? data.summary : '');
					var html = '';
					if(data.photo_small){
						html += '<img src="/public/uploads/articles/'+data.photo_small+'" style="float:left;margin-right:10px;">';
					}
					html += '\n\
						<h2>\n\
							<span class="highlight">'+tagline+'</span>\n\
							<a href="'+url+'">'+title+'</a>\n\
					';
					if(show_tooltip) html += editor_tooltip();
					html += '\n\
						</h2>\n\
						<div>'+summary+'</div>\n\
						<br style="clear:both"/>&nbsp;\n\
					';
					$('#'+controller+'_'+id).fadeOut(
						'slow', 
						function(){
							$(this).html(html).fadeIn('slow');
						}
					);
				}
			);
		}
		
		function parse_json(json){
			var data = {};
			if('object'==typeof(json)){
				data = json;
			}else{
				data = $.parseJSON(json);
			}
			return data;
		}
		
		function write_block_home(data, html, num_items, container_selector){
			var elm_selector = '#articles_'+data.id;
			var is_new = ($(elm_selector).length <= 0);
			var is_inside_container = ($(container_selector+' '+elm_selector).length > 0);
			if(!is_new && !is_inside_container){
				// delete element
				$(elm_selector).remove();
				is_new = true;
			}
			
			if(is_new){
				var items = $(container_selector).children();
				if(items.length > num_items){
					items.last().fadeOut(
						'slow',
						function(){
							$(this).parent().prepend(html);
							$(this).remove();
						}
					);
				}else{
					$(container_selector).prepend(html);
				}
			}else{
				$(elm_selector).fadeOut(
					'slow',
					function(){
						$(this).replaceWith(html).fadeIn();
					}
				);
			}
		}
		
		function set_jGrowl_options(){
			// notifications options
			if($.fn.jGrowl){
				$.fn.jGrowl.prototype.defaults.position = 'bottom-right';
				$.fn.jGrowl.prototype.defaults.life = '60000';
				$.fn.jGrowl.prototype.defaults.closerTemplate = '<div>[ Fechar Todos ]</div>';
				$.fn.jGrowl.prototype.defaults.animateOpen = {
					'left': '0'
				};
			}
		}
		
		function enable_live_tv(){
			$('#feature .tv_toggle div').click(function(){
				if($(this).hasClass('show_tv')){
					rt_dom.show_live_tv();
				}else{
					rt_dom.hide_live_tv();
				}
			});
		}
		
		rt_dom.hide_live_tv = function(){
			$('#feature .tv_toggle .show_news').addClass('active').siblings().removeClass('active');
			$('.tv', '#feature').hide().remove();
			$('#feature').animate({'height':260}, 200);
		}
				
		rt_dom.show_live_tv = function(){
			if(!is_page('home')) return false;
			
			var html = '\n\
				<div class="tv">\n\
					<div class="close"></div>\n\
			';
			if(is_ios()){
				html += '\n\
				<video width="520" height="330" controls="controls">\n\
					<source src="http://i.economicotv.pt.edgesuite.net/ipad.m3u8"/>\n\
				</video>';
			}else{
				html += '<embed width="520" height="330" src="AkamaiFlashPlayer2.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" play="true" loop="true" scale="showall" wmode="transparent" devicefont="false" bgcolor="#000" name="myPlayer" menu="true" allowscriptaccess="sameDomain" allowfullscreen="true" flashvars="src=http%3A//tv.economico.pt/economico.smil&amp;autostart=true&amp;themeColor=CCCCCC&amp;mode=sidebyside&amp;scaleMode=native&amp;frameColor=333333&amp;fontColor=cccccc&amp;width=512&amp;link=&amp;embed=" salign="" type="application/x-shockwave-flash">\n';
			}
			html +='\n\
				</div>\n\
			';
			$(html).prependTo('#feature');
			
			$('#feature .tv_toggle .show_tv').addClass('active').siblings().removeClass('active');
			$('.tv', '#feature').show();
			$('#feature').animate({'height':345}, 200);
			$('#feature div.close').click(rt_dom.hide_live_tv);
		}
		
		function is_ios(){
			var deviceAgent = navigator.userAgent.toLowerCase();
			if(deviceAgent.match(/(iphone|ipod|ipad)/)){
				return true;
			}else{
				return false;
			}
		}
	});
})(jQuery162);
