var loadingImage = '/img/loading.gif';		
var closeButton =  '/js/lightbox/close.gif';	

function mytoggle(myobj, toggler) {
	toggler=document.getElementById(toggler);
	if (toggler.className == "open") {
		Effect.BlindUp( myobj, {duration:0.5});
		toggler.className = "close";
	}
	else 
	{
		Effect.BlindDown( myobj, {duration:0.5});
		toggler.className = "open";		
	}
}

function showmenu(myobj) {

	if (myobj != "sort-1" && $('sort-1').style.display== "") { $('sort-1').hide(); }
	if (myobj != "sort-2" && $('sort-2').style.display== "") { $('sort-2').hide(); }
	if (myobj != "sort-3" && $('sort-3').style.display== "") { $('sort-3').hide(); }	 
	if (myobj != "sort-4" && $('sort-4').style.display== "") { $('sort-4').hide(); }
	Effect.Appear(myobj, { duration: 0.5 });

}

function hidemenu(myobj) {
	Effect.Fade(myobj, { duration: 1.0, delay:5 });
}



// constructor ------------------------
function Query () {
  this.ref = document.referrer;
  var qString = document.referrer.replace(/^[^\?]+\??/,'');
  qString = qString.replace(/#[^#]*$/, '');
  if ( qString ) {
     this.queryString = qString;
     this.params = this.parseQuery();
  }
}
Query.prototype.parseQuery = function () {  
  if ( ! this.queryString ) return null;
  var Pairs = this.queryString.split(/[&;]/);

  for ( var i = 0; i < Pairs.length; i++ ) {
	var rx = new RegExp(/^((enc)?q(uery)?|p)=(.*?)$/);
   	if (mt = rx.exec(Pairs[i])) this.q = mt[4];
  }
}


function ShowQuery(){
	var query = new Query();
	var params = query.q;  
	var refSite = ( query.ref.indexOf('google.') > -1 || query.ref.indexOf('yahoo.') > -1 || query.ref.indexOf('msn.') > -1 || query.ref.indexOf('aol.') > -1 || query.ref.indexOf('bing.') > -1);
	var showHint = false;
	
	var hintId = '20091001';
 	var hintText = '<b>Updated:</b> new comment guidelines. <a href="http://www.physorg.com/help/whats-new/" onClick="setCookie(\'physorgHint\',' + hintId +', 30);">Read more</a>';
	var hintOn = false;
	
	if ( params && refSite ) {	
		var hintText = 'Find more articles on <a href="/search/?search='+params+'">'+unescape(params.replace(/[\+]+/g,' '))+'</a>';
		closeBTfunc = function (){Effect.Fade('search-hint', { duration: 0.5 }); return false;}
		showHint = true;
	}
	else if (newPM > 0 ){
		var hintText = 'You have <a href="/profile/pm/">new PM(s)</a> waiting for you';
		closeBTfunc = function (){Effect.Fade('search-hint', { duration: 0.5 }); return false;}
		showHint = true;
	}	
	else if (hintOn){
		ckVal = readCookie('physorgHint');
		if (ckVal != hintId){
				showHint = true;
				closeBTfunc = function (){setCookie('physorgHint',hintId, 30); Effect.Fade('search-hint', { duration: 0.5 }); return false;}
		}
	}
	
	
	if (showHint){
		var hintClose = Builder.node('a', {href: '#', id: 'hintCloseBt'});
		if (hintClose.addEventListener) hintClose.addEventListener('click',closeBTfunc,false);
		else if (hintClose.attachEvent) hintClose.attachEvent('onclick', closeBTfunc);

		var cl = Builder.node('li', {className: 'close'}, hintClose);
		var tx = Builder.node('li');
		tx.innerHTML = hintText;
		var ul = Builder.node('ul', [cl, tx]);
		var div = Builder.node('div', { id: 'search-hint', style: 'display: none' }, ul);
		
		$('mainwrapper').appendChild(div);	
		Effect.Appear('search-hint', { duration: 1 });
	}
	
}

// ajax DEPRECIATED
function makeHttpRequest(url, handler) {
        if (typeof window.ActiveXObject != 'undefined' ) {
          xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
          xmlDoc.onreadystatechange = handler ;
        }
        else {
          xmlDoc = new XMLHttpRequest();
          xmlDoc.onload = handler;
        }
        xmlDoc.open( "GET", url, true );
        xmlDoc.send( null );
      }			
function MakePostRequest(url, strDATA, handler) {
        if (typeof window.ActiveXObject != 'undefined' ) {
          xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
          xmlDoc.onreadystatechange = handler ;
        }
        else {
          xmlDoc = new XMLHttpRequest();
          xmlDoc.onload = handler;
        }
       
	    xmlDoc.open('POST', url, true); 
		xmlDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlDoc.setRequestHeader("Content-length", strDATA.length);
		xmlDoc.setRequestHeader("Connection", "close");

        xmlDoc.send(strDATA);

      }	 
	  
	   
// bookamrk
function CreateBookmark() { 
				title = "PhysOrg.com: science and technology news";   
				url = "http://www.physorg.com/";
				
				if (window.sidebar) { // Mozilla Firefox Bookmark		
						window.sidebar.addPanel(title, url,"");	}
				else if( window.external ) { // IE Favorite		
						window.external.AddFavorite( url, title); }	
				else if(window.opera && window.print) { // Opera Hotlist		
						return true; } 
			} 
			
			
// font size
var min=8;
var max=18;
function increaseFontSize() {
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }
}
function decreaseFontSize() {
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }   
}  

// tabs handling
tabMode = null;

function tabShow(mode,id){ 
 clearTimeout(tabTmId);
 
 url = '/sort/'+mode+'/?ajax=1';
 if (tabShow.arguments[2]) url +='&tmpl='+tabShow.arguments[2];
 if (tabShow.arguments[3]) url +='&cn='+tabShow.arguments[3];
 if (tabShow.arguments[4]) url +='&btSkip=1';
 
 if(document.getElementById(tabMode)) document.getElementById(tabMode).parentNode.className = '';
 tabMode = 'tab-'+mode;
 document.getElementById(tabMode).parentNode.className = 'active';
 new Ajax.Updater('tabs', url, { method: 'get',
 								 onCreate : function(){ $('tabs').innerHTML='<img src="/img/throbber.gif" class="" />';}
								});
 return false;
}

function tabRotate(){
 var tabArray = new Array('editorials', 'video', 'commented', 'popular', 'emailed', 'content', 'physicsforums');
 var rnd = Math.round(Math.random()*tabArray.length);
 
 if (rnd == 0) return false;
 
 if(document.getElementById(tabMode)) document.getElementById(tabMode).parentNode.className = '';
 tabMode = 'tab-'+tabArray[rnd];
 document.getElementById(tabMode).parentNode.className = 'active';
 new Ajax.Updater('tabs','/sort/'+tabArray[rnd]+'/?ajax=1',
 							   { method: 'get',
 								 onCreate : function(){ $('tabs').innerHTML='<img src="/img/throbber.gif" class="" />';}
								});
 return true;
}

function toogleBox(obj, idText){
	if (document.getElementById(obj).style.display == 'none' ) {
			Effect.Appear(obj, { duration: 1.0 });
			document.getElementById(idText).innerHTML = 'hide'; 
	}
	else{
	 		Effect.Fade(obj, { duration: 1.0, delay:0 });
			document.getElementById(idText).innerHTML = 'show'; 
	}
}


// cookie handling
function setCookie(name,value,days) {
   if (days) {
     var date = new Date();
     date.setTime(date.getTime()+(days*24*60*60*1000));
     var expires = ";expires="+date.toGMTString();
   } else {
     expires = "";
   }
   document.cookie = name+"="+value+expires+";path=/";
}
	  
function readCookie(name) {
   var needle = name + "=";
   var cookieArray = document.cookie.split(';');
   for(var i=0;i <cookieArray.length;i++) {
     var pair = cookieArray[i];
     while (pair.charAt(0)==' ') {
       pair = pair.substring(1, pair.length);
     }
     if (pair.indexOf(needle) == 0) {
       return pair.substring(needle.length, pair.length);
     }
   }
   return null;
}

//quick login form
function alertLogin(){

	var lgbox = '<small style="color: black">Enter your PhysOrg account email and password to sign into the system</small>' +
				'<form name="fstlogin" id="fstlogin" method = "POST" action="/profile/login.php" >' +
				'<fieldset id="fieldset-logins">' +
					'<p><label for="email" id="email">Email</label>' +
					'<input type="text" name="email" id="email" size="10" maxlength="128"></p>' +
					'<p><label for="passwd" id="passwd">Password</label>' +
					'<input type="password" name="passwd" id="passwd" size="10" maxlength="128"></p>' +	
					'<input type="hidden" name="status" value="login" /> ' +
					'<input type="hidden" name="redirect" value="1" />' +	
					'<input type="hidden" name="ref" value="' + location.href + '" />' +
					'<p><button type="submit" id="login-submit" name="loginsubmit" value="Sign in" onClick="" >Sign In</button></p>' +		
				'</fieldset>' +
				'</form>';
				
	if (document.getElementById('overlay')){
		 ShowAlert(lgbox);
		 return false;
	}
	else return true;
}

//quick newsletter subscription
function qNwletter(){
		var email = document.nwletter.email.value;
		var queryString = 'status=nwletter' + '&email=' + escape(email);
		submit = new Ajax.Request('/profile/ajax.php', {
								method: 'post',
								parameters: queryString,
								onSuccess: function(respTXT){ ShowAlert(respTXT.responseText); }
								});
}

// tooltip funcs
function showTooltip(objLink){

   if(objLink.getAttribute('href')){
	   var objTooltip = document.getElementById("JT");	  
   	   var objTooltipCont = document.getElementById("JT_cont");	
	   
	   var offY = getOffsetY(objLink) - 160;
	   
	   objTooltip.style.top = offY + 'px';

	   var patNews = new RegExp('news([0-9]+)');
	   var idEl = patNews.exec(objLink.getAttribute('href'));
	   if (idEl) objTooltipCont.innerHTML = document.getElementById(idEl[0]).innerHTML; 
	   else {
	   		patNews = new RegExp('([0-9]{5,10})');
	   		var idEl = patNews.exec(objLink.getAttribute('href'));
			if (idEl) {
				var idCont = 'tpN'+idEl[0];
				objTooltipCont.innerHTML = document.getElementById(idCont).innerHTML; 
	   	   }
	   }
	   Effect.Appear(objTooltip, { duration: 0.4 });
//	   setTimeout(dispTip, 200);	
   }		   
}				


function  hideTooltip(){
 Effect.Fade('JT', { duration: 0.1 });
}
  		 
function getOffsetY(obj){
 var curtop = 0;
 if (obj.offsetParent) {
 	 do {
			curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
}									 
	return 	curtop;
}

function iniToolTip()
{
	
	if (!document.getElementsByTagName){return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "tooltip")){
			anchor.onmouseover = function () {showTooltip(this); }
			anchor.onmouseout = function () {hideTooltip(this); }			
		}
	}	   
	
	var objBody = document.getElementById("content");

	var objTooltip = document.createElement("div");
	objTooltip.setAttribute('id','JT');
	objTooltip.style.display = 'none';	   

	objBody.appendChild(objTooltip);

	var objTooltipCont = document.createElement("div");
	objTooltipCont.setAttribute('id','JT_cont'); 
	objTooltip.appendChild(objTooltipCont);	 
	
}

// lighbox IMAGE
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



// Returns array with page width, height and window width, height

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
// pause(numberMillis)

function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}
//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');

	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	// preload image
	imgPreload = new Image();

	imgPreload.onload=function(){
		objImage.src = objLink.href;

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
		objLightbox.style.width = imgPreload.width + 'px';

		objLightboxDetails.style.width = imgPreload.width + 'px';
		
		if(objLink.getAttribute('title')){
			objCaption.style.display = 'block';
			//objCaption.style.width = imgPreload.width + 'px';
			objCaption.innerHTML = objLink.getAttribute('title');
		} else {
			objCaption.style.display = 'none';
		}
		
		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		} 

		if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }
		objLightbox.style.display = 'block';

		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		
		// Check for 'x' keypress
		Event.observe(document, 'keypress', function(event){ if(event.keyCode == Event.KEY_ESC) hideLightbox();});

		return false;
	}

	imgPreload.src = objLink.href;
	
}

function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';
	
	// disable keypress listener
	document.onkeypress = '';
}


function initLightbox()
{
	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {showLightbox(this); return false;}
		}
	}

	// the rest of this code inserts html at the top of the page that looks like this:
	//
	// <div id="overlay">
	//		<a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
	//	</div>
	// <div id="lightbox">
	//		<a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
	//			<img id="closeButton" />		
	//			<img id="lightboxImage" />
	//		</a>
	//		<div id="lightboxDetails">
	//			<div id="lightboxCaption"></div>
	//			<div id="keyboardMsg"></div>
	//		</div>
	// </div>
	
	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found, 
	imgPreloadCloseButton.onload=function(){

		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;

	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	
	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);

	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);

	// create keyboard message
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
	objKeyboardMsg.innerHTML = 'press <kbd>esc</kbd> to close';
	objLightboxDetails.appendChild(objKeyboardMsg);


}

//  show msg text
function ShowAlert(msg){

	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	if (objOverlay)	 {
		// set height of Overlay to take up whole page and show
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		objOverlay.style.display = 'block';	

		// hide any previously loaded images
		//objImage.src = '/img/warning.png';
		objImage.src = '/img/dotted.gif';

		// center lightbox and make sure that the top and left values are not negative
		var lightboxTop = arrayPageScroll[1] + ( arrayPageSize[3]/2 - 100 );
		var lightboxLeft = (arrayPageSize[0]/2 - 250);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
		
		objLightbox.style.width = '500px';
		objCaption.innerHTML = '<div class="centered" style="color: maroon; width: 490px; padding: 10px 0;">' + msg + '</div>';
		
		objLightbox.style.display = 'block';
		objCaption.style.display = 'block';
		pause(500);
		new Effect.Highlight('lightbox', { startcolor: '#FFFF66', endcolor: '#FFFFFF', restorecolor: '#FFFFFF' });
	
		// Check for 'x' keypress
		Event.observe(document, 'keypress', function(event){ if(event.keyCode == Event.KEY_ESC) hideLightbox();});

	}
	else {
		if (ShowAlert.arguments[1]) alert(ShowAlert.arguments[1]);
		else alert(msg);
	}
	return;
}	 
	 
	 
	 
function addLoadEvent_v2(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}	

addLoadEvent_v2(iniToolTip);	// run iniToolTip onLoad
addLoadEvent_v2(initLightbox); 	// lighbox
