/// TEMP VARS ////
if(document.domain == 'space.com'){
	var siteloc = "http://a52.g.akamaitech.net/f/52/827/1d/www.space.com/common/community/";
	var img_loc = "http://a52.g.akamaitech.net/f/52/827/1d/www.space.com/template_images/";
	var avatar	= ["http://a52.g.akamaitech.net/f/52/827/1d/www.space.com/common/community/template_images/Avatar_imaginova_gray.jpg",
				  "http://a52.g.akamaitech.net/f/52/827/1d/www.space.com/common/community/template_images/Avatar_imaginova.jpg"];
	
}else{
	var siteloc = "http://images."+domain+".com/common/community/";
	var img_loc = "http://images."+domain+".com/template_images/";
	var avatar	= ["http://images."+domain+".com/common/community/template_images/Avatar_imaginova_gray.jpg",
				  "http://images."+domain+".com/common/community/template_images/Avatar_imaginova.jpg"];
}

var SOloc	= "http://dev.spaceholdings.com/imaginova/communities/";

function captchaKey(){
	switch(document.domain){
		case 'livescience.com': var captcha = "6LcVvwAAAAAAAMRouTmot0uuPtO3DE2a33dTegK1"; break;
		case 'aviation.com': var captcha = "6LcWvwAAAAAAAEOz3E3pY3xJOzJ4u8ML94LMXyVm"; break;
		case 'space.com': var captcha = "6LcUvwAAAAAAAP3sSWHp63FgsfDhtBjX_eGgpes6"; break;
		case 'newsarama.com': var captcha = "6LdCkAEAAAAAAK5BrDaLyUFouO2oo-LZF3MuQpQZ"; break;
	}
	return captcha;
}


//========================================================================================//
// Novaapi 
//========================================================================================//


var novaapi;

Event.observe(window, 'load', function(){ novaapi = new novaclass });

var novaclass = Class.create({
	initialize: function() {
		
		this.FO				= new FlashTag('http://www.space.com/common/community/nomnom.swf', 1, 1); /// Prep Flash Object ///
		this.objBody 		= document.getElementsByTagName("body").item(0);
		this.cover 			= false;
		this.cookieKey		= 'HD';
		this.cookieExpDate  = "2020-11-31";
		this.user 			= this.getCookie('HD');
		this.sortOrder 		= 'TimeStampAscending';
		this.page			= 1;
		
		this.err_txt = new Template("<h4>ATTENTION: We've encountered a problem.</h4><p>Some of the information you have provided is invalid or incomplete. #{err} </p>");
		
		if(domain == 'space' && $('sidebox')){ 
			this.welcome = new Template('<img id="pk_avatar" src="#{avatar}" width="60" height="60"><div class="avatar clearfix"><h3 id="pk_header_title">Welcome, #{user}</h3><h4 id="pk_header_msg">#{msg}</h4></div><div><span id="pk_header_log" style="padding-right:5px;">#{log}</span><span id="pk_header_accnt" style="padding-left:5px; border-left:1px solid #CCC;">#{accnt}</span></div>')
		}else{
			this.welcome = new Template('<img id="pk_avatar" src="#{avatar}" width="60" height="60"><div><h3 id="pk_header_title">Welcome, #{user}</h3><h4 id="pk_header_msg">#{msg}</h4></div><div><span id="pk_header_log">#{log}</span><span id="pk_header_accnt">#{accnt}</span></div>')
		}
		if(this.user == false){
			this.callCookieMonster();
		}else{
			this.setModules();
		}
		setNav();
	},
	action: function(act,doc,arg){
		switch(act){
			case 'login': this.close_window(); this.makeCookies(arg); break;
			case 'logout': this.eatCookies(this.cookieKey); break;
			case 'open': this.open_window(doc,arg); break;
			case 'submit': this.frm_submit(doc); break;
		}
	},
	setModules: function(){
		/// Header Module Update ///
		if($('pk_header') != null){
			
			if(this.user != false){
				this.persona_lnk = '/common/community/profile.php?userid='+this.user[0]+'&plckPersonaPage=PersonaHome&sid=sitelife.'+document.domain;
				
				str = this.welcome.evaluate({avatar: this.user[4], user:'<a href="'+this.persona_lnk+'">'+this.user[1]+'</a>', log: '<a href="javascript:novaapi.action(\'logout\')">Log Out</a>',accnt: '<a href="/common/community/account.php">Account Options</a>',msg:''});
		
			}else{
				str = this.welcome.evaluate({avatar: avatar[0], user:'Guest', log: 'Members: <a href="javascript:novaapi.action(\'open\',\'login\')">Log In</a>',accnt: 'New? Register: <a href="javascript:novaapi.action(\'open\',\'register\')">Join Now!</a>',msg:'Curious?  Join our community!'});
				// Prep Register //
		
				var recapt = new Element('script',{ 
					'type': 'text/javascript','src':'http://api.recaptcha.net/js/recaptcha_ajax.js' });
				this.objBody.appendChild(recapt);
				
			}	
			$('pk_header').innerHTML = str;
		}
			if($('pk_comments')){ this.GetComments(1); }
			else if($('art_toolbar')){ this.RecommendArticle(); }
	},
	frm_submit: function(obj){
		this.form_err= false;
		var act 	 = $(obj).action;
		var form_arg = $(obj).serialize(true);
		$(obj).getElements().each( function(e){ 
			if(e.alt == 'req'){ 
				if( e.value == ''){
					//$(e.name).className = 'error'; 
					novaapi.form_err = "Please fill in the highlighted fields below"; 
				} else {
					$(e.name).className = '';
				}
			} } );
		
		if(act && !this.form_err){
			//$(obj).select('div#pk_note')[0].style.display = 'none';
			$(obj).request({
				onSuccess: function(r){ 
					var re = r.responseText.split("|");
					var code = re.shift();
					if(code == 1) novaapi.process_err(obj, re);
					else if(code == 0) novaapi.action(re[0],re[1],re[2]); 
				}});
		} else if(this.form_err){
			novaapi.process_err(obj, this.form_err);
		}
	},
	process_err: function(frm, error){
		if(typeof(error) == 'object'){
			var str = "<ul>";
			error.each( function(e){
				var r = e.strip().split("=");
				//$(r[0]).className = 'error';
				str += "<li>"+r[1]+"</li>";
			});
			error = str+"</ul>";
		}
		try{
		var w_note = $(frm).select('div#pk_note')[0];
		w_note.className = 'error_msg';
		w_note.innerHTML = this.err_txt.evaluate({err: error});
		}catch(e){ alert(e); }
						
	},
	compare: function(obj){
			var e1 = $(obj);
		var e2 = $(obj+"2");
		this.form_err = (e1.getValue() != e2.getValue());
		var c = (this.form_err)? "error" : "okdokay";
		e1.className = e2.className = c;
	},
	ck_user: function(obj, bol){
		if($(obj).getValue())
		if(bol){
  			var url = "/common/community/check_handle.php";
  			var myRequest = new Ajax.Request(url, {
					 parameters:{un:$(obj).getValue(), mode:'checkavail'}, 
					 onSuccess: function(r) { 
						var re = r.responseText.split("|");
						var code = re.shift();
						if(code == 1) {novaapi.process_err('pk_register', re);}
						else {
							$('user').className = 'okdokay';
							var w_note = $('pk_register').select('div#pk_note')[0];
							w_note.className = '';
							w_note.innerHTML = '<p>To join the community, please complete the registration form below.  After that, we will send a confirmation email containing a validation link to the address you provide.  Check your inbox!</p>';
							}
						}});
		}
	},
	save_password: function(obj, bol){
		if($(obj).getValue())
		if(bol){
  			var url = "/common/community/change_password.php";
  			var myRequest = new Ajax.Request(url, {
					 parameters:{un:$(obj).getValue(), mode:'checkavail'}, 
					 onSuccess: function(r) { 
						if(r.responseText == 0){ 
							$('user').className = 'error';
							alert('User Name is not available'); 
						}else { 
							$('user').className = 'okdokay';
							$('checkname').style.display = "none";
						}} });
		}
	}
});

//========================================================================================//
// Magic Cookies - om nom nom nom
//========================================================================================//

novaclass.addMethods({
	autoLog: function(str){
		//// returned from cookie monster ////
		var arg = str.split(",");
		this.setCookie(this.cookieKey, arg[0],arg[1],arg[2],arg[3],arg[4]);
	},
	getCookie: function(ck){ // find standard cookies
		var arrCookies = this.cookieJar(ck);
		var strValue = arrCookies ? arrCookies[1] : false;
		return strValue;
	},
	setCookie: function(){
		var arg 		= $A(arguments);
		var key 		= arg.shift();
		var datearray 	= this.cookieExpDate.split("-");
		if(this.keeplogged){
      		var expdate 	= new Date(datearray[0], datearray[1], datearray[2]);
		document.cookie = key + "=" +arg.join('|') + ";expires="+expdate+";path=/;domain=" + document.domain;
		}else{
			document.cookie = key + "=" +arg.join('|') + ";path=/;domain=" + document.domain;
		}
		if(key == this.cookieKey){
			this.user = arg;
			this.setModules();
		}
	},
	resetCookies: function(){
		var requestBatch = new RequestBatch(); 
			requestBatch.AddToRequest(new UserKey(this.user[0]));
			requestBatch.BeginRequest(daapi, this.resetUserInfo);
				
	},
	resetUserInfo: function(responseBatch){
		try{
		if (responseBatch.Responses.length == 0) {
			var re = avatar[0];
		} else {
			var re = responseBatch.Responses[0].User.AvatarPhotoUrl;
		}
		novaapi.setCookie(novaapi.cookieKey, novaapi.user[0],novaapi.user[1],novaapi.user[2],novaapi.user[3],re);
		}catch(e){ alert(e) };
	},
	makeCookies: function(arg){ // Sets cookie and SO
		this.cookieCrumbs = arg.split(",");
		if (this.cookieCrumbs.length == 0){ return; }
		else{
			var requestBatch = new RequestBatch(); 
				requestBatch.AddToRequest(new UserKey(this.cookieCrumbs[0]));
				requestBatch.BeginRequest(daapi, this.updateUserInfo); 
		}
	},
	updateUserInfo: function(responseBatch){
		if (responseBatch.Responses.length == 0) {
			var re = avatar[0];
		} else {
			var re = responseBatch.Responses[0].User.AvatarPhotoUrl;
		}
		var ts=new Date();
		var arg = novaapi.cookieCrumbs;
		ts = Math.floor(ts.setDate(ts.getDate())/1000);
		
		if(arg[3] == 1){ novaapi.keeplogged = true;}
		novaapi.setCookie(novaapi.cookieKey, arg[0],arg[1],ts,arg[2],re);
		novaapi.callCookieMonster('setSSO',arg[0],arg[1],ts,arg[2],re);
	},
	eatCookies: function(ck){ // no more cookie
		var strValue = this.getCookie(ck);
		if(strValue){
			dtYesterday=new Date();
			dtYesterday.setDate(dtYesterday.getDate()-10);
			document.cookie = ck + "=;" + ";path=/" + ";domain="+document.domain  + ";expires=" + dtYesterday.toGMTString(); 
		}
		this.callCookieMonster('clearSSO',document.domain);
		this.user = false;
		setTimeout( function(){ window.location.href = document.URL; } , 1000);
	},
	cookieJar: function(ck){ // gather cookies
		var cookies = document.cookie.split(";");
		var aCookie = [];
		try{
			cookies.each(function(c){ var t = c.strip().split("=");
				if(t[0]==ck){ var s = unescape(t[1]); t[1] = s.split("|"); aCookie.push(t)}});
		} catch(err) { alert(err) }
		return aCookie.grep(ck)[0];
	},
	callCookieMonster: function(){
		var qs;
		if (arguments.length != 0){
			qs = 'functionName=' + escape(arguments[0]);
			if (arguments.length > 1){
				var justArgs = new Array();
				for (var i = 1; i < arguments.length; ++i) {
					qs += ('&d' + (i-1) + "=" + escape(arguments[i]));
				}
			}
		}
		var divName = $('om_nomnom');
		if(!divName){
			var divName = new Element('div',{ 'id': 'om_nomnom' });
			this.objBody.appendChild(divName);
		} 
		this.FO.setFlashvars(qs);
		divName.innerHTML = this.FO.toString();
		this.setModules();
	}

});


//========================================================================================//
// Form Window's - lightbox style
//========================================================================================//	
novaclass.addMethods({
	open_window: function(tmp,arg){
		
		if(document.URL.split("/register.php").length < 2){
			//// -----------  Lightbox Cover ------------ ////
			if($('pk_cover') == null){
				var pk_cover = new Element('div',{ 
						'id':'pk_cover', 'style':'display:none; height:'+ document.body.clientHeight +'px; width:'+ document.body.clientWidth +'px;'});
				Element.insert(this.objBody, {top:pk_cover})
				//this.objBody.appendChild(pk_cover);
				window.onresize = function() { novaapi.refit(); }
			}
			
			if($('pk_window')) Element.remove('pk_window');
			var pk_form = this.get_template(tmp,arg);
			pk_form.style.display = "none";
			pk_form.style.visibility = "visible";
			
			if(this.cover == false){
				$('pk_cover').onclick = function() {  novaapi.close_window(); }
				new Effect.Appear('pk_cover', { duration: 0.2, from: 0.0, to: 0.7 });
				this.cover = true;
			}
			
			new Effect.Appear(pk_form, { delay: 0.2,duration: 0.2, from: 0.0, to: 1 });
		}else{
			var pk_form = this.get_template(tmp,arg);
		}
			
		
	},
	close_window: function(){
		if($('pk_cover')){
			$('pk_cover').style.display = "none";
			Element.remove('pk_window');
			this.cover = false;
		}
	},
	get_template: function(tmp,arg){
		var w 		= 431;
		var pk_window, pk_window_hd, pk_window_cnt, pk_window_ft;
		
		pk_window = new Element('div',{ 
			'id':'pk_window', 'style':'visibility:hidden; width:'+ w +'px; top:0px; left:'+ ((document.body.clientWidth - w) / 2) +'px;'});
		
		/// window header
		pk_window_hd = new Element('div',{'id':'pk_window_hd', 'class':'clearfix'}); 
		pk_window_hd.update('<img src="'+siteloc+'template_images/'+domain+'_reg_hd_logo.gif" alt="'+domain+'" /><a href="javascript:novaapi.close_window();"><img src="'+siteloc+'template_images/btn_close_window.gif" width="55" height="18" alt="Close Window" /></a>');
		
		 /// window Content
		pk_window_cnt = new Element('div',{'id':'pk_window_cnt', 'class':'clearfix'});
		
		if(tmp == 'register'){
			this.setCookie('poe',document.URL);
		}
		
		/// window footer
		pk_window_ft = new Element('div',{'id':'pk_window_ft', 'class':'clearfix'});
		pk_window_ft.update('<img src="'+siteloc+'template_images/imagiova_footer_logo.gif" width="108" height="15" alt="imaginova" />');
				
		// Append all 
		pk_window.appendChild(pk_window_hd);
		pk_window.appendChild(pk_window_cnt);
		pk_window.appendChild(pk_window_ft);
		this.objBody.appendChild(pk_window);
		
		var url =  '/common/community/form_'+tmp+'.php?dom='+document.domain+arg;
		new Ajax.Request(url,{ parameters:{key:captchaKey()}, evalJS:false,
				   onSuccess: function(r) { 
						$('pk_window_cnt').innerHTML = r.responseText;
						setTimeout( function(){ 
							if($('recaptcha')) 
							Recaptcha.create(captchaKey(), "recaptcha", { theme: "white", callback: function (r){ Recaptcha.focus_response_field} }) } , 300);
						novaapi.refit();
				   } });
		return pk_window;
	},
	refit: function(){
		var viewport = document.viewport.getScrollOffsets();
		if($('pk_window')){ 
			var top = viewport[1] + ((document.viewport.getDimensions().height - $('pk_window').getDimensions().height) / 2);
			$('pk_window').style.top = (top < 0)? "30px":top+"px";
		}
		if($('pk_cover')){
			$('pk_cover').style.height = document.body.clientHeight +'px';
			$('pk_cover').style.width = document.body.clientWidth +'px';
		}
		if($('pk_login')) $('email').focus(); 
	}
 });


//========================================================================================//
// Flash Loader
//========================================================================================//	

var FlashTag = Class.create({
	initialize: function(src, width, height) {
		this.src       = src;
		this.width     = width;
		this.height    = height;
		this.version   = '7,0,14,0';
		this.id        = null;
		this.bgcolor   = 'ffffff';
		this.flashVars = null;
		this.chkflash();
	},
	setVersion: function(v){ this.version = v },
	setId: function(id){ this.id = id; },
	setBgcolor: function(bgc){ this.bgcolor = bgc; },
	setFlashvars: function(fv){ this.flashVars = fv; },
	toString: function(){
		var flashTag = new String();
		if(ie){
			flashTag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
			if (this.id != null) flashTag += 'id="'+this.id+'" ';
			flashTag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+this.version+'" ';
			flashTag += 'width="'+this.width+'" ';
			flashTag += 'height="'+this.height+'">';
			flashTag += '<param name="movie" value="'+this.src+'"/>'
			flashTag += '<param name="quality" value="high"/>';
			flashTag += '<param name="autoplay" value="true"/>';
			flashTag += '<param name="bgcolor" value="#'+this.bgcolor+'"/>';
			flashTag += '<param name="allowScriptAccess" value="always"/>';
			if (this.flashVars != null) flashTag += '<param name="flashvars" value="'+this.flashVars+'"/>';
        	flashTag += '</object>';
		}else{
			flashTag += '<embed src="'+this.src+'" ';
			flashTag += 'quality="high" '; 
			flashTag += 'bgcolor="#'+this.bgcolor+'" ';
			flashTag += 'width="'+this.width+'" ';
			flashTag += 'height="'+this.height+'" ';
			flashTag += 'autoPlay=true ';
			flashTag += 'allowScriptAccess="always" '; 
			flashTag += 'type="application/x-shockwave-flash" ';
			if (this.flashVars != null) flashTag += 'flashvars="'+this.flashVars+'" ';
			if (this.id != null) flashTag += 'name="'+this.id+'" ';
			flashTag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
			flashTag += '</embed>';
		}
		return flashTag;
	},
	write: function(doc){ doc.write(this.toString()); },
	chkflash: function(){ //// Need to add in plugin check //////
		this.plugin = true;
	}
});

//========================================================================================//
// DAAPI functions
//========================================================================================//	
novaclass.addMethods({
	Request: function(update){
		var articleKey = new ArticleKey(ArticleID); 
		var requestBatch = new RequestBatch(); 
			requestBatch.AddToRequest(this.daapiAction);
			requestBatch.AddToRequest(articleKey); 
		if($('pk_comments')){
		var commentPage  = new CommentPage(articleKey, 10, 1, this.sortOrder); 
			requestBatch.AddToRequest(commentPage);
			requestBatch.BeginRequest(daapi, this.updateComments); 
		}else{
			requestBatch.BeginRequest(daapi, this.getRecommend); 
		}
		
	},
	updateComments: function(responseBatch) {
		
        if (responseBatch.Messages[0].Message == 'ok') {
			novaapi.GetComments(novaapi.page);
        }
	},
	GetComments: function(p) {
		this.page = p;
		var articleKey	 = new ArticleKey(ArticleID); 
		var commentPage  = new CommentPage(articleKey, 10, p, this.sortOrder); 
		var requestBatch = new RequestBatch(); 
			requestBatch.AddToRequest(articleKey); 
			requestBatch.AddToRequest(commentPage);
			requestBatch.BeginRequest(daapi, this.RenderCommentPage); 
		//this.updateCommentForm();
	},
	SubmitComment: function(){
		var text = Clean($('commentText').value);
		if(domain == 'space'){
			title = ArticleTitle;
		}else{ 
			try{
				var title = $('headline').getElementsByTagName('h1')[0].innerHTML;
			}catch(e){ document.body.getElementsByTagName('h1')[0].innerHTML; }
		}
		this.daapiAction = new CommentAction(new ArticleKey(ArticleID), document.location.href, title, text);    
		this.Request(true);
	},
	getKey: function(key){
		var keyType = key.split(':')[0];
        var key = key.split(':')[1];
		switch(keyType){
			case 'CommentKey': var rKey = new CommentKey(key); break;
			case 'ArticleKey': var rKey = new ArticleKey(key); break;
		}
		return rKey;
	},
	ReportAbuse: function(key) {        
        var reason = "Reason for abuse report";
        var description = "Description of abuse report";
        this.daapiAction = new ReportAbuseAction(this.getKey(key), reason, description);   
		this.Request(true);
    },
	Recommend:function(key) { 
		this.daapiAction = new RecommendAction(this.getKey(key));  
		this.Request(true);
	},
	RecommendArticle: function() { 
		try{
		var articleKey	 = new ArticleKey(ArticleID); 
		var requestBatch = new RequestBatch(); 
			requestBatch.AddToRequest(articleKey); 
			requestBatch.BeginRequest(daapi, this.getRecommend); 
		}catch(e){}
	},
	getRecommend: function(responseBatch){
		if (responseBatch.Responses.length == 0) {
			var articleKey	 = new ArticleKey(ArticleID); 
			var str  = '<a class="pk_recommend" href="javascript:novaapi.Recommend(\'ArticleKey:' + articleKey.ArticleKey.Key + '\')">0 Recommend</a>';
		} else {
			var re_article 	 = responseBatch.Responses[0].Article;
			var reccomendNum = re_article.Recommendations.NumberOfRecommendations;
			var has_re = re_article.Recommendations.CurrentUserHasRecommended;
			try{
				if(has_re == "True"){
					str = '<span class="pk_recommend">'+reccomendNum+' Recommended</span>';
				}else{
					str = '<a class="pk_recommend" href="javascript:novaapi.Recommend(\'ArticleKey:' + re_article.ArticleKey.Key + '\')">'+reccomendNum+' Recommend</a>';
				}
			}catch(e){ }
		}
		try{ $('pk_com_rec').innerHTML = str; }catch(e){ }
	},
	RenderCommentPage: function(responseBatch){
		temp = responseBatch;
		if (responseBatch.Responses.length == 0) {
		} else {
			try{
				var commentBlock = $('pk_comments');
				var re_num 		 = responseBatch.Responses.length;
				var re_comments	 = responseBatch.Responses[re_num-1].CommentPage;
				var commentNum 	 = re_comments.NumberOfComments;
				
				if( re_num > 1){
					var re_article 	 = responseBatch.Responses[0].Article;
					var reccomendNum = re_article.Recommendations.NumberOfRecommendations;
					var has_re = re_article.Recommendations.CurrentUserHasRecommended;
					try{
						var str  = '<a class="pk_comments" href="#comments">'+commentNum+' Comments</a>&nbsp;|&nbsp';
						if(has_re == "True"){
							str += '<span class="pk_recommend">'+reccomendNum+' Recommended</span>';
						}else{
							str += '<a class="pk_recommend" href="javascript:novaapi.Recommend(\'ArticleKey:' + re_article.ArticleKey.Key + '\')">'+reccomendNum+' Recommend</a>';
						}
							
						
					}catch(e){ }
				}else{
					try{
					var articleKey	 = new ArticleKey(ArticleID); 
					var str  = '<a class="pk_comments" href="#comments">0 Comments</a>&nbsp;|&nbsp';
					str += '<a class="pk_recommend" href="javascript:novaapi.Recommend(\'ArticleKey:' + articleKey.ArticleKey.Key + '\')">0 Recommend</a>';
					}catch(e){ }
				}
				try{ $('pk_com_rec').innerHTML = str; }catch(e){ }
				
				var commentBlockHtml = "<h3>Comments ("+commentNum+")</h3>";	
				if(novaapi.user != false){
					commentBlockHtml += "<p><span class='right'><a href='javascript:novaapi.action(\"logout\")'>Logout</a></span>You are logged in as: <a href='"+novaapi.persona_lnk+"'>"+novaapi.user[1]+"</a></p>";
				}else{
					commentBlockHtml += "<p>You must be logged in to leave a comment: <a href='javascript:novaapi.action(\"open\",\"login\")'>Log In</a> | <a href='javascript:novaapi.action(\"open\",\"register\")'>Register</a></p>";
				}
				if(novaapi.sortOrder == 'TimeStampAscending'){	
					commentBlockHtml += '<p><span class="right">View: Oldest First | <a href="javascript:novaapi.changeSort(\'desc\');">Newest First</a></span>';
				}else{
					commentBlockHtml += '<p><span class="right">View: <a href="javascript:novaapi.changeSort(\'asc\');">Oldest First</a> | Newest First</span>';
					
				}
				commentBlockHtml += '<a href="#commentForm">Leave a Comment</a></p>';
				
				re_comments.Comments.each( function(i){ commentBlockHtml += novaapi.GetCommentHtml(i) } )
				
				///// PAGINATION //////
				var pn = Math.ceil(commentNum * .1);
				var op = re_comments.OnPage;
				if(pn > 1){
					var html = "<div class='pk_pagination'>Page: ";
					(op == 1)?html += " <span>1</span> " : html += " <a href='#comments' onclick='javascript:novaapi.GetComments(1);'>1</a>";
					for(var i=2; i <= pn; i++){ 
						(op == i)?html += " | <span>"+i+"</span> " : html += " | <a href='#comments' onclick='javascript:novaapi.GetComments("+i+");'>"+i+"</a>";
					}
					commentBlockHtml += html+"</div>";
				}
				commentBlock.innerHTML = commentBlockHtml;
			}catch(e){ }
		}
		 novaapi.updateCommentForm();
	},
	GetCommentHtml: function(comment){
		var uk = '/common/community/profile.php?userid='+comment.Author.UserKey.Key+'&plckPersonaPage=PersonaHome&sid=sitelife.'+document.domain;
		
		var html  = "<div class='comment clearfix'>";
			html += "<img src='" + comment.Author.AvatarPhotoUrl + "' class='commentImg'/>";
			html += "<div class='commentBody clearfix'>";
			html += "<div><strong><a href='"+uk+"'>" +  comment.Author.DisplayName + "</a></strong> wrote: </div><p>" + comment.CommentBody + "</p></div>";
			html += "<div class='commentFooter'><div class='right'>";
			
		if(comment.CurrentUserHasRecommended == "False") {
			html += "<a href='javascript:novaapi.Recommend(\"" + comment.CommentKey.Key + "\")' class='pk_recommend'>"+comment.NumberOfRecommendations+" Recommend</a>";
		} else{
			html += "<span class='pk_recommend'>"+comment.NumberOfRecommendations+" Recommend</span>";
		}	
			 html += "&nbsp;|&nbsp;&nbsp;";
		if(comment.CurrentUserHasReportedAbuse == "False") {
			html += "<a href='javascript:novaapi.ReportAbuse(\"" + comment.CommentKey.Key + "\")' class='pk_abuse'>Report Abuse</a>";
		} else {
		    html += "You have reported abuse on this comment.";
		}
		
			html += "</div><div class='left'>posted " + comment.PostedAtTime + "</div>";
			html += "</div></div>";
			
		return html;
	},
	updateCommentForm: function(){
		var cform = $('pk_commentForm');
		if(!cform){
			var cform = new Element('div',{ 'id': 'pk_commentForm' });
			var html  = '<a name="commentForm"></a><h3>Leave a Comment</h3><form id="pk_comment" name="pk_comment" onsubmit="SubmitComment(); return false">';
				html  +="<div id='SiteLife_Logout'></div>";
				html  +="<div id='SiteLife_Login'><p>You must be logged in to leave a comment: <a href='javascript:novaapi.action(\"open\",\"login\")'>Log In</a> | <a href='javascript:novaapi.action(\"open\",\"register\")'>Register</a></p></div>";
				html  +='<textarea id="commentText" disabled="true"></textarea>';
				html  +='<input type="image" id="btnSubmitCommentDis" name="submit" value="submit" src="'+siteloc+'template_images/btn_submit_comment_inactive.gif" alt="Submit Comment" /><input type="image" id="btnSubmitComment" name="submit" value="submit" src="'+siteloc+'template_images/btn_submit_comment.gif" onclick="novaapi.SubmitComment(); return false" alt="Submit Comment" />';
				html  +='<p><strong>User Comment Guidelines:</strong> Posting of comments requires membership in the Imaginova Community, which is subject to our <a href="http://www.imaginova.com/tos/">Terms of Service</a>. Imaginova reserves the right to remove, without notice, any comment for any reason whatsoever.</p></form></div>';
			cform.update(html);
			$('pk_comments').parentNode.appendChild(cform);
		}
		$('SiteLife_Login').style.display = $('btnSubmitCommentDis').style.display = (this.user) ? 'none' : '';
		$('SiteLife_Logout').style.display = $('btnSubmitComment').style.display = (this.user) ? '' : 'none';
		$('SiteLife_Logout').innerHTML = "<p><span class='right'><a href='javascript:novaapi.action(\"logout\")'>Logout</a></span>You are logged in as: <a href='"+this.persona_lnk+"'>"+this.user[1]+"</a></p>";
		$('commentText').disabled = $('btnSubmitComment').disabled = !this.user;
		$('btnSubmitCommentDis').disabled = this.user;
		$('commentText').value = '';
		$('commentText').style.width = ($('pk_commentForm').offsetWidth - 40)+"px";
	},
	changeSort: function(dir){
		this.sortOrder = (dir == 'desc')? 'TimeStampDescending' : 'TimeStampAscending' ;
		this.GetComments(1);
	}
})

function Clean(cmt) {
	var clean="";
	if(cmt.length>0){
			var clean=cmt.replace(/</g,"&lt;");
			clean=clean.replace(/>/g,"&gt;");
			clean=clean.replace(/\u2019/g,"&#8217;");
			clean=clean.replace(/\u201C/g,"&#8220;");
			clean=clean.replace(/\u201D/g,"&#8221;");
			clean=clean.replace(/\r\n/g,"\n");
			clean=clean.replace(/\n/g,"<br />\n");
	}
	return (clean);
 }

	
var tab_group = Class.create({
	initialize: function(nav, win, pos) {
		this.cur_tab = pos;
		this.tabs = new Array($(nav).childElements(), $(win).childElements());
		
		this.tabs[0][pos].addClassName('active');
		this.tabs[1][pos].addClassName('active');
		for(var i=0; i<this.tabs[0].length; i++){
			 Event.observe(this.tabs[0][i], 'click', this.action.bindAsEventListener(this,i));
		}
	},
	action: function(event, n){
		this.tabs[0][this.cur_tab].removeClassName('active');
		this.tabs[1][this.cur_tab].removeClassName('active');
		this.tabs[0][n].addClassName('active');
		this.tabs[1][n].addClassName('active');
		this.cur_tab = n;
	}
 })


//========================================================================================//
//  Discovery Widgets
//========================================================================================//
var disc_widget = Class.create({
	initialize: function(id) {		
		this.cur_tab = 0;
		this.id 	 = $(id);
		this.tabs	 = $(id).getElementsByTagName('dt');
		this.views	 = $(id).getElementsByTagName('dd');
		
		if(!this.tabs[0]) return;
		if(!this.views[0]) return;
		
		try{
			var w = ($(id).hasClassName('disc_mod'))? (($(id).offsetWidth - (this.tabs.length-1)*5) / this.tabs.length)-2 : Math.floor(($(id).offsetWidth - 2) / this.tabs.length);
			
			for(var i=0; i < this.tabs.length; i++){
				if(id != 'top-list') this.tabs[i].style.width = w+"px";
				
				if( this.tabs.length == 1) this.tabs[i].style.margin = 0;
				Event.observe(this.tabs[i], 'click', this.action.bindAsEventListener(this,i));
			}
			try{
				if($(this.id.parentNode).hasClassName('col4')){
					var list = this.id.getElementsByTagName('dl').item(0);
					for(var i=0; i < this.tabs.length; i++){
						list.appendChild(this.tabs[0]);
						list.appendChild(this.views[0]);
					}
				}
			}catch(e){  }
			this.tabs[0].addClassName('active');
			this.views[0].style.display = "block";
		}catch(e){ return; }
	},
	action: function(event, n){
		this.tabs[this.cur_tab].removeClassName('active');
		this.views[this.cur_tab].style.display = 'none';
		this.tabs[n].addClassName('active');
		this.views[n].style.display = 'block';
		this.cur_tab = n;
	}
});

//========================================================================================//
//  Carousel [ Spotlight ]
//========================================================================================//
var carousel = Class.create({
	initialize: function(items) {	
		this.main_obj 	= $('carousel');
		this.objwrapper = $('carouselwrapper');
		if(!this.main_obj) return;
		
		this.pos		 = 0;
		this.moduleLimit = items;
		this.moveby 	 = items-1;
		this.duration	 = 1; // seconds
		this.disabled	 = false;
		this.elements	 = this.main_obj.getElementsByTagName("li").length;
		this.objwidth 	 = this.main_obj.getElementsByTagName("li").item(0).offsetWidth;
		
		if(this.elements <= this.moduleLimit){
			$('carousel_next').style.display = "none";
			$('carousel_prev').style.display = "none";
			return;
		}
		
		if(this.elements <= this.moduleLimit + this.moveby ){
			this.moveby = this.elements - this.moduleLimit;
			this.duration = (this.elements - 3)*.1;
		}
		
		this.shiftBy = this.moveby * this.objwidth;
		
		this.content_obj = this.main_obj.getElementsByTagName("ul").item(0);
		this.content_obj.style.width = this.elements * this.objwidth+"px";
		

		/* PRIME EFFECTS */
		new Effect.MoveBy(this.objwrapper, 0, 0, {duration: 0.0, transition: Effect.Transitions.sinoidal});
		
		this.setControls($('carousel_next'), "-16px", this.next_item.bindAsEventListener(this));
		this.setControls($('carousel_prev'), "0px", this.prev_item.bindAsEventListener(this));

	},
	next_item: function(event){
		if(this.disabled) return;
		this.disabled = true;
		this.shift = this.shiftBy*-1;
		if(this.pos < 0 ){
			for(var i= 0; i < this.moveby; i++){
				this.content_obj.appendChild(this.content_obj.firstDescendant());
			}
			this.pos = 0;
			this.objwrapper.style.left = "0px";
		}
		this.action();
	},
	prev_item: function(event){
		if(this.disabled) return;
		this.disabled = true;
		this.shift = this.shiftBy;
		if(this.pos >= 0 ){
			for(var i= 1; i <= this.moveby; i++){
				Element.insert(this.content_obj, {top: this.content_obj.getElementsByTagName("li").item(this.elements-1)} )
				
			}
			this.pos = this.shiftBy * -1;
			this.objwrapper.style.left = this.pos+"px";
		}
		this.action();
	},
	action: function() {
		this.pos += this.shift;
		new Effect.MoveBy(this.objwrapper, 0, this.shift, {duration: this.duration, transition: Effect.Transitions.sinoidal, afterFinish: this.disabled = false })
	},
	end: function(event) {
		//updateItems(mycarousel);
		this.disabled = false;
	},
	setControls: function(obj, left, f) {
		Event.observe(obj, 'mouseover', function(e){ obj.style.backgroundPosition = left +" top"; });
		Event.observe(obj, 'mouseout', function(e){ obj.style.backgroundPosition = left +" bottom"; });
		Event.observe(obj, 'click', f);
	}
})



//========================================================================================//
//   Related Image Module [article pages]
//========================================================================================//
var related_module = Class.create({
	initialize: function() {
		this.cur_img = 0;
		this.images  = $('related_images_module').getElementsByTagName("dt");
		this.caption = $('related_images_module').getElementsByTagName("dd");
		this.cnt	 = this.images.length
		if(this.cnt > 1){
			var next = new set_control($('ri_next'), img_loc+'buttons/btn_nextsm.gif', img_loc+'buttons/btn_nextsm_inactive.gif', function(e){  related_images.next_img(this) });
			var prev = new set_control($('ri_prev'), img_loc+'buttons/btn_prevsm.gif', img_loc+'buttons/btn_prevsm_inactive.gif', function(e){  related_images.prev_img(this) });
		}else{
			$('ri_next').style.display = "none";
			$('ri_prev').style.display = "none";
		}
		Event.observe('ri_enlarge', 'click', this.navigate);
		this.populate(this.cur_img);
	},
	populate: function(n){
		var lnk = this.images[n].getElementsByTagName("a")[0].href;
		$('ri_imgHolder').innerHTML = this.images[n].innerHTML;
		$('ri_caption').innerHTML = this.caption[n].innerHTML;
		$('ri_count').innerHTML = (this.cur_img+1) + " of " + this.cnt;
		$('ri_enlarge').innerHTML = '<a href="'+lnk+'">Full Size</a>';
	},
	next_img:function(event){
		this.cur_img = (this.cur_img >= this.cnt)? 0 : this.cur_img+1;
		this.populate(this.cur_img);
	},
	prev_img:function(event ){
		this.cur_img = (this.cur_img <= 0)? this.cnt : this.cur_img-1;
		this.populate(this.cur_img);
	},
	navigate:function(){
		//window.location = myrelated.obj_dat[myrelated.cid].href;
	}
});

//========================================================================================//
//  ImageGallery - print page | share toolbar etc
//========================================================================================//
var init_Galleries = Class.create({
	initialize: function(id) {
		this.current = 0;
		this.id 	 = $(id);
		this.img	 = $(id).getElementsByTagName('dt');
		this.desc	 = $(id).getElementsByTagName('dd');
		this.type 	 = ($('topten'))? 'topten' : 'gallery'; 
		
		if($('img_progress')){
			this.bar 	 = $('img_progress').getElementsByTagName('input').item(0);
			this.bar_txt = $('img_progress').getElementsByTagName('h5').item(0);
		}else if($('ri_count')){
			this.bar 	 = false;
			this.bar_txt = $('ri_count');
		}else if($('topten')){
			var count = $('countdown').getElementsByTagName("li");
			for(var i=0; i < count.length; i++){
				count[i].setAttribute('value', i);
				count[i].setAttribute('id', 'num_'+i);
				Event.observe(count[i], 'click', this.update.bindAsEventListener(count[i],this));
			}
		}
		this.set_progress();
	},
	next: function(){
		if(this.current+1 <	  this.img.length){
			this.desc[this.current].style.display = "none";
			this.img[this.current].style.display = "none";
			if(this.type == 'topten') $('num_'+this.current).removeClassName('selected');
			this.current++;
			this.set_progress();
		}
	},
	prev: function(){
		if(this.current-1 >= 0){
			this.desc[this.current].style.display = "none";
			this.img[this.current].style.display = "none";
			if(this.type == 'topten') $('num_'+this.current).removeClassName('selected');
			this.current--;
			this.set_progress();
		}
	},
	update: function(obj,f){
		f.desc[f.current].style.display = "none";
		f.img[f.current].style.display = "none";
		$('num_'+f.current).removeClassName('selected');
		f.current = this.getAttribute('value');
		f.set_progress();
	},
	link: function(){
		var goto = this.img[this.current].getElementsByTagName('a').item(0);
		window.location = goto.href;
	},
	set_progress: function(){
		if(this.type == 'gallery'){
			if(this.bar){
				var output = "IMAGE "+(this.current+1)+" of "+this.img.length;
				this.bar.style.backgroundPosition = (((this.current+1)/this.img.length)*150)-150+"px 0px";
			}else{
				var output = (this.current+1)+" of "+this.img.length;
			}
			this.bar_txt.innerHTML = output;
				
			$('next').style.backgroundPosition = (this.current+1 < this.img.length)?'bottom':'top';
			$('prev').style.backgroundPosition = (this.current > 0)?'bottom':'top';
		}
		if(this.type == 'topten'){
			$('num_'+this.current).addClassName('selected');
		}
		this.desc[this.current].style.display = "block";
		this.img[this.current].style.display = "block";
		
	}
 });



//========================================================================================//
//  Random functions - print page | share toolbar etc
//========================================================================================//

function ts_size(s, id){
	if(!$(id).style.fontSize){ var size=1; }
	else{
		var size = $(id).style.fontSize.split("em");
			size = size.shift();
	}
	if(s == 'min'){
		$(id).style.fontSize = size-0.1+"em";
	}else{
		$(id).style.fontSize = Math.abs(size)+0.1+"em";
	}
}

var set_control = Class.create({
	initialize: function(obj, active, inactive, f) {
		
		Event.observe(obj, 'mouseover', function(e){ obj.src = active; });
		Event.observe(obj, 'mouseout', function(e){ obj.src = inactive; });
		Event.observe(obj, 'click', f);
	}
});

var sect = document.URL.split("/");

function setNav(){
	try{
		nav_obj = $('navigation').getElementsByTagName('a');
		if(nav_obj.length > 1){
			for(n=0; n < nav_obj.length; n++)
				if('/'+sect[3]+'/' == nav_obj[n].getAttribute('href') || document.URL == nav_obj[n].getAttribute('href')) 
					nav_obj[n].className = "selected";
		}
	}catch(e){}
}



var showPrint = Class.create({
	initialize: function() {
		var obj		= document.body;
		this.copy   = Object.clone(obj);
		this.text = $('article_text').innerHTML;
		this.image = $('related_images_module');
		$('main').style.display = 'none';
		$('ibar').style.display = 'none';
		obj.addClassName('print_art');
		
		var	str  = '<div class="right"><a href="javascript:window.location.reload( false )"><img src="'+img_loc+'buttons/btn_backto.gif"></a><br><br><a href="javascript:window.print()"><img src="'+img_loc+'buttons/btn_send2print.gif"></a></div>';
			
			str += '<img src="'+siteloc+'template_images/'+domain+'_reg_hd_logo.gif" alt="'+domain+'" />';
			str += '<div class="divider"></div>';
			str += '<div id="headline" class="clearfix">' + $('headline').innerHTML + '</div>'+this.text;
			str += '<div class="clearfix" id="footer">'+ $('footer').innerHTML + '</div>';
		obj.innerHTML = str;
		if(this.image){ $('related_images_module').style.display = 'none'; }
	}
});


function show_share(pos){
	$('share_items').style.display = ($('share_items').style.display == "none")?"block":"none";
	if(pos == 'left'){
		var w = ($('tb_share').offsetLeft + $('tb_share').offsetWidth) - $('share_items').offsetWidth;
		$('share_items').style.left = w+"px";
	}else{
		$('share_items').style.right = "0px";	
	}
	
}

//========================================================================================//
//  Advertisment functions
//========================================================================================//

var adTile 	= 0;
var adId	= 0;
var ord 	= Math.random() * 1000000000000000000;


function changeAd(target,pos,w,h) {
	ad_obj = $(target);
	if($('adId_0') != null){
		var leader = $('adId_0');
		leader.src = leader.src;
	}
	h += 16;
	w += 16;
	var str = '<iframe id="ad_grab" src="/common/inc/mod_adblock_b.php?sitepage='+sitepage+'&pos='+pos+'" width="'+w+'" height="'+h+'" frameborder="0" scrolling="no"></iframe>';
	ad_obj.innerHTML = str;
}

// ------- / DART / Double Click / --------- //
function DartAd(pos){
	
	adTile++;
	
	var p = (sect[3] != '')? sect[3] : 'homepage';
	var s = (section != '' )? section : 'home'; 
	switch(document.domain){
		case 'livescience.com': var key = "imn.ls."+p+"/"+s; break;
		case 'aviation.com': var key = "imn.av."+p+"/"+s; break;
		case 'space.com': var key = "imn.sp."+p+"/"+s; break;
		case 'newsarama.com': var key = "imn.nr."+p+"/"+s; break;
	}
		
		if ((!document.images && navigator.userAgent.indexOf("Mozilla/2.") >= 0)  || navigator.userAgent.indexOf("WebTV")>= 0) {
			document.write('<A href="http://ad.doubleclick.net/jump/'+ key +';pos=1;tile='+ adTile +';sz='+ pos +';ord=' + ord + '?" TARGET="_blank">');
			document.write('<IMG src="http://ad.doubleclick.net/ad/'+ key +';pos=1;tile='+ adTile +';sz='+ pos +';ord=' + ord + '?"></A>');
		}else{
			document.write('<SCR'+'IPT LANGUAGE="JavaScript1.1" src="http://ad.doubleclick.net/adj/'+ key +';pos=1;dcopt=ist;tile='+ adTile +';sz='+ pos +';ord=' + ord + '?" ><\/SCRIPT>');
		}
		
}
		

// ------- / OAS / --------- //	
function DisplayAds(position, width, height){
	if(window.location.search && window.location.search.match(/\?.*ybf1=([0-9]*)/) && width == 728){
			
		document.write('<iframe src="http://pn1.adserver.yahoo.com/a?f=2023135827&pn=PARTNERNAME&p=buzznet&l=N&c=sh" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0" allowtransparency="true" width="728" height="90"></iframe>');
	}else{
		if(!sitepage && sitepage != '') sitepage = "www."+document.domain;
		
		switch(sitepage){
			case "www.livescience.com/animals": sitepage="www.livescience.com/animalworld"; break;
			case "www.livescience.com/strangenews": sitepage="www.livescience.com/news"; break;
		}
		if(!width || !height){
			document.write('<div id="ad_square"></div>');
			changeAd('ad_square',position);
		}else{
			str = "/common/inc/mod_adblock.php?sitepage="+sitepage+"&pos="+position+"&w="+width+"&h="+height;		
			document.write('<iframe id="adId_'+adId+'" src="'+str+'" width="'+width+'" height="'+height+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no></iframe>');
			ad_obj = $('adId_'+adId);
		}
		adId++;
	}
}
