
var News = {
	
	minImageSize: 25,
	arr:[],
	timers:[],
	
	load: function(blk, url, num, mode, hideVisited){
		// var hideVisited = 1;
		this.arr[blk] = {
			blk: blk,
			url:url, 
			icon: false, 
			num: num, 
			mode: mode,
			title: "", 
			link: "", 
			items:[], 
			page: 0,
			hideVisited: hideVisited
		};
		this.timers[blk] = null;
		waitForLoad(function(){News.fetch(blk);});
	},
	
	newsSizer: function(){
		for(var blk in News.arr){
			News.newsNavSwitch(blk);
		}
	},
	
	newsNavSwitch: function(blk){
		if(!_gel("news_nav_"+blk)){return;}	
		var a = _gel("news_nav_"+blk);
		var b = _gel("news_"+blk);
		a.style.display = parseInt(b.offsetWidth) < (dragSort.getMargin(a)[1] + 35 + 60) ? "none" : "block";
	},
	
	updateAll: function(){
		for(var blk in this.arr){
			this.update(blk);
		}
	},
	
	update: function(blk){
		var d = _gel("news_"+blk);
		if(!d || _getn("EMBED", d).length > 0){return;}
		this.fetch(blk);
	},
	
	fetch: function(blk){
		var g = this.arr[blk];
		call2("proxy.json.php?v=2.5&url="+escape(g.url), false, function(a){
			var a = a.responseText.length ? eval("("+a.responseText+")") : false;
			if(!a){
				News.parseError(blk);
			}else{
				News.store(blk, a);
			}
		});
	},
	
	parseError: function(blk){
		if(_gel("news_"+blk)){
			_gel("news_"+blk).innerHTML = "Kunde inte hitta nyheter för denna källa för tillfället.";
		}
	},
	
	store: function(blk, a){
		var g = this.arr[blk];
		
		g.title = a.title;
		g.link = a.link.match(/^http/i) ? a.link : false;
		
		if(a.link.match(/http/i)){
			var iconUrl = a.link;
		}else if(a.items.length && a.items[0].link.match(/http/i)){
			var iconUrl = a.items[0].link;
		}else{
			var iconUrl = g.url;
		}
		iconUrl = iconUrl.split("/");
		iconUrl = iconUrl.length > 2 ? iconUrl[2] : "";
		// var iconUrl = (a.items.length ? a.items[0].link : (a.link ? a.link : g.url));
		
		g.icon = "favicon.php?"+iconUrl;
		if(_gel("icon"+blk)){
			_gel("icon"+blk).src = g.icon;
		}

		var title = g.title ? (g.title.length < 24 ? g.title : g.title.substring(0,22)+"...") : "Ingen titel";
		
		if(g.link == this.arr[blk].url || (g.link && g.link.match(/\/(rss|feed|atom)/i))){
			var b = g.link.split("/");
			g.link = b[0]+"//"+b[2];
		}
		_gel("title"+blk).innerHTML = g.link ? "<a href='"+g.link+"' title='Länk till "+g.title+"' onclick='if(App.dragging){return false;}App.setDragging(1);App.setDragging(0);'>"+title+"</a>" : "<span title='"+g.title+"'>"+title+"</span>";
		if(a.items.length){
			g.items = [];
		}
		for(var x in a.items){
			var b = a.items[x];
			b.time = this.newsTime(b.pubDate);
			if(b.images){
				for(var y=0;y<b.images.length;y++){
					b.images[y] = this.fixURL(b.images[y], g.link);
				}
			}
			g.items[g.items.length] = b;
		}
		this.render(blk);
	},
	
	popup: function(blk, x){
		var g = this.arr[blk];
		var i = g.items[x];
		
		// i.images && i.images.length ? i.images : false;
		var img = false;
		if(i.images && i.images.length){
			for(var y in i.images){
				var im = loadImage(i.images[y]);
				if(parseInt(im.width) >= this.minImageSize && parseInt(im.height) >= this.minImageSize){
					img = im.cloneNode(true);
					img.align = "right";
					img.style.marginLeft = "4px";
					break;
				}
			}
		}

		if(img || i.description.length){
			var div = _ce("DIV");
			if(img){
				div.appendChild(img);
			}
			var d = _ce("DIV");
			d.style.position = "relative";
			d.innerHTML = i.description;
			div.appendChild(d);
			popup(div.innerHTML, "<img src="+g.icon+" height=16>"+(i.title.length > 30 ? i.title.substring(0,28)+"..." : i.title), 420, [150,400]);
		}
	},
	
	elem: function(blk, x){
		var g = this.arr[blk];
		var i = g.items[x];

		var d = _ce("DIV");
		d.id = "news_"+blk+"_"+x;
		d.className = "entry"; // 
		
		if(i.time){
			var s = _ce("DIV");
			s.className = "newsTime";
			s.innerHTML = i.time;
			d.appendChild(s);
		}

		if(i.embed !== undefined && i.embed.length){
			for(var y=0;y<i.embed.length;y++){
				var e = i.embed[y];
				var img = this.embedder(blk, x, e);
				d.appendChild(img);
			}
		}


		var a = _ce("A");
		a.innerHTML = i.title ? i.title : "Ingen titel...";
		a.href = i.link || "#";
		
		if(a.href.match(/\.mp3$/i)){
			a.target = "_self";
			a.onclick = function(){
				App.playMp3(this.href);
				return false;
			};
		}else if(g.hideVisited){
			a.blk = blk;
			a.onmouseup = News.mouseup;
		}
		
		if(g.mode == 0){
			a.onmouseover = function(){News.popup(blk, x);};
			a.onmouseout = kill;
		}
		d.appendChild(a);
		
		if(g.mode == 1){
			if(i.description.length){
				var desc = _ce("SPAN");
				d.appendChild(desc);
				var maxL = 180;
				var cut = i.description.length < maxL ? -1 : i.description.indexOf(" ", maxL);
				if(cut != -1){
					var str = i.description.substring(0,cut)+"...";
					desc.onmouseover = function(){News.popup(blk, x);};
					desc.onmouseout = kill;
					desc.innerHTML = "<br>"+str.replace(/<br[^>]*>/ig, "");
					desc.style.cursor = "help";
				}else{
					desc.innerHTML = "<br>"+i.description.replace(/<br[^>]*>/ig, "");
				}
			}
		}
		if(i.images != undefined && i.images.length){
			for(var z=0;z<i.images.length;z++){
				this.addImage(d, blk, x, i.images[z]);
			}
		}
		
		return d;
	},
	
	mouseup: function(e){
		var blk = this.blk;
		var e = e != undefined ? e : event;
		var a = e.srcElement != undefined ? e.srcElement : (e.currentTarget != undefined ? e.currentTarget : e.target);
		var button = e.which == null ? ((e.button < 2) ? "LEFT" : ((e.button == 4) ? "MIDDLE" : "RIGHT")) : ((e.which < 2) ? "LEFT" : ((e.which == 2) ? "MIDDLE" : "RIGHT"));
		if(button != "RIGHT"){
			kill();
			setTimeout(function(){
				var pn = a;
				if(pn){
					while(pn = pn.parentNode){
						if(pn && pn.className && pn.className.match(/entry/)){
							var ns = pn.nextSibling;
							if(ns && ns.tagName == "HR"){
								ns.parentNode.removeChild(ns);
							}
							pn.parentNode.removeChild(pn);
							
						}
					}
				}
			},100);
			if(News.timers[blk]){
				clearTimeout(News.timers[blk]);
				News.timers[blk] = null;
			}
			News.timers[blk] = setTimeout(function(){News.render(blk);},6000);
			if(ie && App.target == "_blank" && button == "LEFT"){
				window.open(this.href);
				return false;
			}
		}
	},
	
	addImage: function(d, blk, x, img){
		var i = loadImage(img); // preload for both display modes
		// setTimeout(function(){Debugger.debug(img,0,1);},200);
		if(this.arr[blk].mode){
			// var i = loadImage(img); // preload only for expanded display modes
			if(i.complete){
				this.showImage(d, blk, x, i);
			}else{
				addEvent(i, "onload", function(){
					News.showImage(d, blk, x, this);
				});
			}
		}
	},
	
	showImage: function(d, blk, x, img){
		if(!d || !d.firstChild || !img || img.width < this.minImageSize || img.height < this.minImageSize){
			return;
		}
		
		if(d.firstChild.className != "newsImageDiv"){
			var div = _ce("DIV");
			div.className = "newsImageDiv";
			var size = 62;
			div.style.width = size+"px";
			div.style.height = size+"px";
			d.insertBefore(div, d.firstChild);
		}else{
			// var div = d.firstChild;
			// var i = div.firstChild;
			// Debugger.debug([i.width,i.height],0,1);
			return; // dont show more than one image
		}
		
		var w = parseInt(img.width);
		var h = parseInt(img.height);
		
		var i = img.cloneNode(true);
		
		if(w > h){
			size = size < h ? size : h;
			i.style.height = size+"px";
			var newW = (size / h) * w;
			i.style.width = newW+"px";
			newW -= size;
			i.style.marginLeft = -Math.round(newW / 2)+"px";
		}else{
			size = size < w ? size : w;
			i.style.width = size+"px";
			i.style.height = "auto";
		}
		i.onmouseover = function(){News.popupImages(blk, x, 0);};
		i.onmouseout = kill;
		i.style.cursor = "pointer";
		var a = _ce("A");
		var g = News.arr[blk];
		a.href = g.items[x].link;
		if(g.hideVisited){
			a.blk = blk;
			a.onmouseup = News.mouseup;
		}
		a.appendChild(i);
		div.appendChild(a);
	},
	
	popupImages: function(blk, x, m){
		var div  = _ce("DIV");
		var arr = this.arr[blk];
		var g = arr.items[x];
		
		if(g.images != undefined && g.images.length){
			for(var y=0;y<g.images.length;y++){
				var i = loadImage(g.images[y]);
				if(i.complete){
					if(i.width >= this.minImageSize && i.height >= this.minImageSize){
						div.appendChild(i.cloneNode(true));
						div.innerHTML += " ";
					}
				}
				// html += "<img src='"+i+"'> ";
			}
		}
		if(div.childNodes.length){
			if(!m){
				popup(div.innerHTML, "<img src="+arr.icon+" height=16>"+(g.title.length > 30 ? g.title.substring(0,28)+"..." : g.title), undefined, g.images.length > 1 ? [300,300] : undefined);
			}else{
				App.showBig("<div onclick='App.closeBig()' title='Klicka för att stänga'>"+div.innerHTML+"</div>");
			}
		}
	},
	
	closePlayer: function(blk, x){
		var d = _gel("news_"+blk+"_"+x);
		if(d.lastChild.className == "newsPlayer"){
			var url = _getn("EMBED",d.lastChild)[0].src;
			url = url.replace(/&amp;/ig, "&");
			d.removeChild(d.lastChild);
			return url;
		}
		return false;
	},
	
	playVideo: function(blk, x, url, a){
		url = url.replace(/&amp;/ig, "&");
		if(this.closePlayer(blk, x) == url){return;}
		var d = _gel("news_"+blk+"_"+x);
		var div = _ce("DIV");
		div.className = "newsPlayer";
		switch(a){
			case 'flash':
				if(/youtube\./i.test(url) && !/&(amp;)?fs=1/.test(url)){url += "&fs=1";} // add fullscreen to youtube videos
				var html = "<embed src='"+url+"' height=350 width=100% type=application/x-shockwave-flash wmode='transparent' allowfullscreen='true'></embed>";
				break;
			case 'qt':
				var html = "<embed src='"+url+"' height=350 width=100% type='video/quicktime' pluginspage='http://www.apple.com/quicktime/download/' controller='true' autoplay='true' scale='aspect'></embed>";
				break;
			case 'wm':
				var html = "<embed src='"+url+"' height=350 width=100% type='application/x-mplayer2' pluginspage='http://www.microsoft.com/windows/windowsmedia/download/' controller='true' autoplay='true' scale='aspect'></embed>";
				break;
		}
		div.innerHTML = html+
			"<div class='right'><button onclick='News.closePlayer("+blk+","+x+");showBigVideo(\""+url+"\", \""+a+"\")'>Helskärm</button></div>"+
			"<button onclick='News.closePlayer("+blk+","+x+");'>Stäng video</button>"
		;
		d.appendChild(div);
	},

	
	embedder: function(blk, x, arr){
		
		var a = _ce("A");
		a.href = arr[1];
		a.target = "_self";
		
		switch(arr[0]){
			case 'flash':
			case 'qt':
			case 'wm':
				var img = _ce("IMG");
				img.src = "images/"+arr[0]+".png";
				a.onclick = function(){
					News.playVideo(blk, x, arr[1], arr[0]);
					return false;
				};
				break;
			case 'audio':
				var img = _ce("IMG");
				img.src = "images/mp3.png";
				a.onclick = function(){
					App.playMp3(arr[1]);
					return false;
				};
				break;
		}
		img.className = "newsEmbedImg";
		a.appendChild(img);
		return a;
	},
	
	setPage: function(blk, x){
		this.arr[blk].page = x;
		this.render(blk);
	},

	setMode: function(blk, x){
		this.arr[blk].mode = x;
		this.render(blk);
		call2("blocks/news/news.save.php?action=setMode&blk="+blk+"&mode="+x);
	},

	render: function(blk){
		// Debugger.debug(blk,1,1);
		
		var g = this.arr[blk];
		var div = _gel("news_"+blk);
		if(!div){
			// _gel("title"+blk).parentNode.onclick = function(){App.expandBlock(blk);}; //  =  // no collapse
			return;
		}
		
		div.innerHTML = "";
		div.className = "news_"+g.mode+(g.hideVisited ? " hideVisited" : "");
		var start = g.page * g.num;
		var end = (g.page + 1) * g.num;
		var max = g.items.length;
		var rem = [];
		for(var x=start;x<max;x++){
			if(x == end){break;}
			
			if(g.mode == 1 && x != start){
				div.appendChild(_ce("HR"));
			}
			
			var d = this.elem(blk, x);
			div.appendChild(d);
			
			if(g.hideVisited){
				var a = _getn("A",d);
				a = a[a.length - 1];
				if(a.offsetHeight == 0){
					rem[rem.length] = x;
				}
			}
		}
		
		if(rem.length > 0){
			for(var i=0;i<rem.length;i++){
				var j = rem[i];
				var k = j - i;
				this.arr[blk].items.splice(k,1);
			}
			this.render(blk);
			return;
		}
		
		
		if(1){ // g.mode == 1
			var hasNav = g.page || max > x ? 1 : 0;
			if(hasNav){
				var d = _ce("DIV");
				d.className = "mini_div"; // newsNav
				d.id = "news_nav_"+blk;
				// d.style.marginLeft = "200px";
				d.style.width = "35px";
				d.style.textAlign = "center";
				
				// not needed
				// _gel("title"+blk).parentNode.onclick = function(){}; // no collapse
				
				d.innerHTML = "<div class='left' style='width:10px;'>"+(g.page ? "<a href='javascript:News.setPage("+blk+", "+(g.page - 1)+");undefined;'>&laquo;</a>" : "&nbsp;")+"</div>"+
				"<div class='right' style='width:10px;text-align:right;'>"+(max > x ? "<a href='javascript:News.setPage("+blk+", "+(g.page + 1)+");undefined;'>&raquo;</a>" : "&nbsp;")+"</div>"+
				"<a href='javascript:News.setMode("+blk+", "+(g.mode == 0 ? 1 : 0)+");undefined;'>&nbsp;"+(g.mode == 0 ? "+" : "-")+"</a>";
				div.insertBefore(d,div.firstChild);
			}
			var cl = _ce("DIV");
			cl.className = "clear";
			div.appendChild(cl);
		}
		this.newsNavSwitch(blk);
	},
	
	remove: function(blk){
		this.arr[blk] = false;
	},

	fixURL: function(a,b){
		if(/:\/\//.test(a)){
			 return a;
		}else{
			b = b.split("/");
			return "http://"+b[2]+"/"+a.replace(/^\//, "");
		}
	},

	tz: function(){
		var d = new Date();
		var t = (d.getTimezoneOffset() * 60 * 1000); // + (3600 * 1000)
		return t; // last part for GMT +1
	},

	dls: {2008: ["03-30", "10-26"],2009: ["03-29", "10-25"],2010: ["03-28", "10-31"],2011: ["03-27", "10-30"],2012: ["03-25", "10-28"],2013: ["03-31", "10-27"],2014: ["03-30", "10-26"],2015: ["03-29", "10-25"],2016: ["03-27", "10-30"],2017: ["03-26", "10-29"],2018: ["03-25", "10-28"],2019: ["03-31", "10-27"],2020: ["03-29", "10-25"]},
	isSummer: function(d){
		var t = [d.getFullYear(),d.getMonth()+1,d.getDate()];
		t[1] = t[1] < 10 ? "0"+t[1] : t[1];
		t[2] = t[2] < 10 ? "0"+t[2] : t[2];
		var a = new Date;
		var u = this.dls[t[0]] != undefined ? this.dls[t[0]] : a.getFullYear();
		var v = t[1]+"-"+t[2];
		var summer = v >= u[0] && v <= u[1] ? 1 : 0;
		return summer;
	},
	
	newsTime: function(pubDate){
		var datum = new Date;
		var msNow = datum.getTime();
		if(!pubDate){
			return false;
		}
		pubDate = pubDate.replace(/^må/i, "mo");pubDate = pubDate.replace(/^ti/i, "tu");pubDate = pubDate.replace(/^on/i, "we");pubDate = pubDate.replace(/^to/i, "th");pubDate = pubDate.replace(/^lö/i, "sa");pubDate = pubDate.replace(/^sö/i, "su");
		
		// remove timezone support in parse
		//pubDate = pubDate.replace(/([A-Z]{3,4}|[+-]\d{2}00|N) *(\d{4})?$/, "$2");
		
		var ms = Date.parse(pubDate);
		if(!ms){
			return false;
		}

		// TZ fix
		var swe = 3600 * 1000;
 		var d = new Date(ms);
 		ms += this.tz() + swe + (this.isSummer(d) * 3600 * 1000);
 		
		if(ms.toString().match(/^\d+$/)){
			datum.setTime(ms);
		}else{
			datum.setFullYear(pubDate.substring(0,4));
			datum.setMonth(pubDate.substring(5,7)-1);
			datum.setDate(pubDate.substring(8,10));
			datum.setHours(pubDate.substring(11,13));
			datum.setMinutes(pubDate.substring(14,16));
			datum.setSeconds(pubDate.substring(17,19));
			ms = datum.getTime();
		}
		ms = Math.round(ms/1000);
		msNow = Math.round(msNow/1000);
		if(ms > (msNow - 86400)){
			var h = datum.getHours();
			var m = datum.getMinutes();
			return (h < 10 ? "0"+h : h) +":"+(m < 10 ? "0"+m : m);
		}else{
			var d = datum.getDate();
			var m = datum.getMonth();
			var mArr = ["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"];
			return d+" "+mArr[m];
		}
	}
	
};

App.addResizeEvent(News.newsSizer);

/*
function newsSetMode(blk,page,x){
	newsMode[blk] = x;
	renderNews(blk,page);
	call2("blocks/news/news.save.php?action=setMode&blk="+blk+"&mode="+x);
}

function newsVideo(url,blk, html){
	_gel("video_player_"+blk).style.display = "block";
	if(html != undefined){
		var u = unescape(url).match(/src=["']?([^"' >]+)/)[1];
		_gel("video_player_"+blk).innerHTML = unescape(url)+"<div class='right'><button onclick='showBigVideo("+blk+", \""+u+"\")'>Helskärm</button></div><button onclick='newsVideoClose("+blk+")'>Stäng video</button><hr>";
	}else{
		_gel("video_player_"+blk).innerHTML = "<object height='270' width='100%' classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0'><param name='src' value='"+url+"'><param name='controller' value='true'><param name='autoplay' value='true'><param name='scale' value='aspect'><embed src='"+url+"' width='100%' height='270' pluginspage='http://www.apple.com/quicktime/download/' controller='true' autoplay='true' scale='aspect'> </embed></object><div class='right'><button onclick='showBigVideo("+blk+", \""+url+"\", 0)'>Helskärm</button></div><button onclick='newsVideoClose("+blk+")'>Stäng video</button><hr>";
	}

	var t = 0;
	var n = _gel("video_player_"+blk);
	while(p = n.offsetParent){
		t += n.offsetTop;
		n = p;
	}
	window.scrollTo(0,t-65);
	
}


function newsVideoClose(blk){
	_gel("video_player_"+blk).style.display = "none";
	_gel("video_player_"+blk).innerHTML = "";
}

*/