/* $Rev: 2338 $ $Date: 2008-11-06 19:19:50 -0500 (Thu, 06 Nov 2008) $ $Author: valentin $ */

/**
 *  @todo
 */
function link_to_post(post_id, requester)
{
	requester = typeof(requester) != 'undefined' ? requester : 'viewtopic';
	temp = prompt( L_LINK_TO, "http://" + SERVER_NAME + requester + ".php?p=" + post_id +"#"+post_id );
	return false;
}

/**
 *  @todo
 */
function link_to_topic(topic_id, requester)
{
	requester = typeof(requester) != 'undefined' ? requester : 'viewtopic';
	temp = prompt( L_LINK_TO, "http://" + SERVER_NAME + requester + ".php?t=" + topic_id);
	return false;
}

/**
 *	Mark/unmark checkboxes
 *  @todo
 *  @note id = ID of parent container, name = name prefix, state = state [true/false]
 */
function marklist(id, name, state)
{
	var parent = document.getElementById(id);
	if (!parent)
	{
		eval('parent = document.' + id);
	}

	if (!parent)
	{
		return;
	}

	var rb = parent.getElementsByTagName('input');
	
	for (var r = 0; r < rb.length; r++)
	{
		if (rb[r].name.substr(0, name.length) == name)
		{
			rb[r].checked = state;
		}
	}
}

/**
 *  @todo
 */
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

/**
 *  @todo
 */
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

/**
 *  @todo
 */
function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

/**
 *  @todo
 */
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/**
 *  @todo
 */
function img_popup(image_url, image_width, image_height, popup_rand)
{
    screenwidth = false;
    screenwidth = screen.Width;
    if ( !screenwidth )
    {
        screenwidth = window.outerWidth;
    }
    
    screenheight = false;
    screenheight = screen.Height;
    if ( !screenheight )
    {
        screenheight = window.outerHeight;
    }
    
    if ( screenwidth < ( image_width + 30 ) || screenheight < ( image_height + 30 ) || image_width == null || image_height == null )
    {
        window.open(image_url, 'limit_image_mod_popup_img_' + popup_rand, 'resizable=yes,top=0,left=0,screenX=0,screenY=0,scrollbars=yes', false);
    }
    else
    {
        window.open(image_url, 'limit_image_mod_popup_img_' + popup_rand, 'resizable=yes,top=0,left=0,screenX=0,screenY=0,height=' + ( image_height + 30 ) + ',width=' + ( image_width + 30 ), false);
    }
}

/**
 *  @todo
 */
function _hideBBCode() 
{ 
   this.objs = []; 
   return this; 
} 
_hideBBCode.prototype.IsDisplaySupported = function() 
{ 
   // Opera: Only v7+ supports write access to display attribute ! 
   if( window.opera && !document.childNodes ) return false; 
   // Other DOM browsers and MSIE4+ support it as well. 
   if( document.getElementById || document.all ) return true; 
   // This is where legacy browsers fall. NS4, Hotjava, etc. 
   return false; 
} 
_hideBBCode.prototype.getObj = function(obj) 
{ 
   return ( document.getElementById ? document.getElementById(obj) : 
         ( document.all ? document.all[obj] : 
         ( document.layers ? document.layers[obj] : null ) ) ); 
} 
_hideBBCode.prototype.displayObj = function(obj, status) 
{ 
   var x = this.getObj(obj); 
   if(!x) return; 
   var css = ( document.layers ? x : x.style ); 
   if( this.IsDisplaySupported() ) 
   { 
      css.display = status; 
   } 
   else 
   { 
      css.visibility = ( status == 'none' ? 'hidden' : 'visible' ); 
   } 
} 
_hideBBCode.prototype.open = function(l_hide) 
{ 
   var s='', randomId = 'hide' + Math.floor(Math.random() * 15000); 
   var style = ( this.IsDisplaySupported() ? 'display:none;' : 'visibility:hidden;' ); 
   if( document.layers ) { style = 'position:relative;' + style; } 
   s += '<div class="hidetitle"><a class="postlink" href="javascript:hideBBCode.showHide(\'' + randomId + '\');" onmouseover="top.status=\'\';" onfocus="this.blur();">' + l_hide + '</a></div>'; 
   s += '<div id="' + randomId + '" style="'+style+'" class="hide">'; 
   document.write(s); 
   this.objs[randomId] = 'none'; 
} 
_hideBBCode.prototype.close = function() 
{ 
   document.write('</div>'); 
} 
_hideBBCode.prototype.showHide = function(obj) 
{ 
   if( !this.objs[obj] ) return; 
   this.objs[obj] = ((this.objs[obj]=='none') ? 'block':'none'); 
   this.displayObj(obj, this.objs[obj]); 
} 
var hideBBCode = new _hideBBCode();

/**
 *  Nice pagination
 *  @todo
 *  @version 9 Jan 2005
 */
function page_jump( address, total_posts, ppage )
{
	pages = 1;
	// current location - we get it in the $_GET[''] variable in overall header, otherwize is 0
	cur_st = page_start;
	// current page
	cur_page  = 1;
	
	if ( total_posts % ppage == 0 )
	{
		pages = total_posts / ppage;
	}
	else
	{
		pages = Math.ceil( total_posts / ppage );
	}
	
	// jump_from is set in a language var in overall header = please enter a number between 1 and
	msg = jump_from + " " + pages;
	
	if ( cur_st > 0 )
	{
		cur_page = cur_st / ppage; cur_page = cur_page -1;
	}
	
	show_page = 1;
	
	if ( cur_page < pages )
	{
		show_page = cur_page + 1;
	}
	
	if ( cur_page >= pages )
	{
		show_page = cur_page - 1;
	}
 	else
 	{
 		show_page = cur_page + 1;
 	}
 	
	userPage = prompt( msg, show_page );
	
	if ( userPage > 0  )
	{
		if ( userPage < 1 )     {    userPage = 1;  }
		if ( userPage > pages ) { userPage = pages; }
		if ( userPage == 1 )    {     start = 0;    }
		else { start = (userPage - 1) * ppage; }
	
		window.location = address + "&start=" + start;
	}
}

/**
 *  Sprintf equivalent of the same function in php
 *  @param strings multiple
 *  @return string
 */
function sprintf()
{
	if (!arguments || arguments.length < 1 || !RegExp)
	{
		return;
	}
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str))
	{
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];
		
		//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
				alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
				   if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			  else if (pPad) pad = pPad;
			var justifyRight = true;
				   if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
				   if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
				   if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			var subst = param;
				   if (pType == 'b') subst = parseInt(param).toString(2);
			  else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			  else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			  else if (pType == 'u') subst = Math.abs(param);
			  else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
			  else if (pType == 'o') subst = parseInt(param).toString(8);
			  else if (pType == 's') subst = param;
			  else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			  else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
	return str;
}

/**
 *  Debug function
 *  @todo
 */
function _alert( id, message )
{
	var x = document.getElementById(id);
	x.innerHTML = message;	
}

/**
 *  Set display of page element
 *  s[-1,0,1] = hide,toggle display,show
 *  @todo
 *  @note Borrowed from phpbb3
 */
function dE(n, s)
{
	var e = document.getElementById(n);

	if (!s)
	{
		s = (e.style.display == '' || e.style.display == 'block') ? -1 : 1;
	}
	e.style.display = (s == 1) ? 'block' : 'none';
}

/**
 *	Alternate display of subPanels
 *  @param p
 */
function subPanels(p)
{
	var i, e, t;

	if (typeof(p) == 'string')
	{
		show_panel = p;
	}

	for (i = 0; i < panels.length; i++)
	{
		e = document.getElementById(panels[i]);
		t = document.getElementById(panels[i] + '-tab');

		if (e)
		{
			if (panels[i] == show_panel)
			{
				e.style.display = 'block';
				if (t)
				{
					t.className = 'activetab';
				}
			}
			else
			{
				e.style.display = 'none';
				if (t)
				{
					t.className = '';
				}
			}
		}
	}
}

/**
 *  Show/hide groups of blocks
 *  @param string c CSS style name
 *  @param string e checkbox element
 *  @param string t toggle dispay state (used to show 'grip-show' image in the profile block when hiding the profiles)
 */
function displayBlocks(c, e, t)
{
	var s = (e.checked == true) ?  1 : -1;

	if (t)
	{
		s *= -1;
	}

	var divs = document.getElementsByTagName("DIV");

	for (var d = 0; d < divs.length; d++)
	{
		if (divs[d].className.indexOf(c) == 0)
		{
			divs[d].style.display = (s == 1) ? 'none' : 'block';
		}
	}
}

/**
 *  @todo
 */
function selectCode(a)
{
	// Get ID of code block
	var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];

	if (document.selection)
	{
		var r = document.body.createTextRange();
		r.moveToElementText(e);
		r.select();
	}
	else
	{
		var s = window.getSelection();
		var r = document.createRange();
		r.setStartBefore(e);
		r.setEndAfter(e);
		s.addRange(r);
	}
}

/**
 *  @todo
 */
function leq(a, b)
{
	if ( a < b ) return true
	else return false;
}

/**
 *  @todo
 */
function jumpto(url, per_page, on_page)
{
	var page = prompt(JUMP_PAGE, on_page);

	if (page !== null && !isNaN(page) && page > 0)
	{
        param = url.indexOf('?') != -1 ? '&' : '?';
  		document.location.href = url.replace(/&amp;/g, '&') + param + 'start=' + ((page - 1) * per_page);
	}
}

/**
 *  Poplatex
 *  @param string formula
 *  @param integer wd
 *  @param integer ht
 *
 *  Creates the popup showing the associated latex code. Styling is mostly defined inside.
 */
function poplatex(formula, wd, ht)
{
	/* set some default vars */
	if ( !wd ) { wd = 500; }
	if ( !ht ) { ht = 200; }
	
	/* make sure L_LATEX_POPUP_TITLE doesn't have spaces in it - will crash on IE */
	if ( ie ) { L_LATEX_POPUP_TITLE = L_CODE; }
	
	var w = window.open('', L_LATEX_POPUP_TITLE, 'width=' + wd + ', height=' + ht + ', resizable=yes, scrollbars=yes, menubar=no, toolbar=no, location=no, status=yes');
	
	w.document.write(
		'<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
		'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>' + L_LATEX_POPUP_TITLE + '</title>' +
		'<link rel="stylesheet" href="' + STYLESHEET + '" />' +
		'<link rel="stylesheet" href="' + CODEBOX_STYLESHEET + '" />' +
		'<script type="text/javascript" src="http://' + SERVER_NAME + 'js/latex_code.js" ></script>' +
		'</head><body>' +
		'<div style="width: 95%; padding: 5px; text-align: left;"><dl class="codebox" style="width: 95%;"><dt>' + L_CODE + ': <a href="#" onclick="selectCode(this); return false;">' + L_SELECT_ALL + '</a></dt><dd><code>' + formula + '</code></dd></dl></div>' +
	//	w.document.write('<div style="padding-top: 10px; text-align: center; margin: 0px auto; width: 95%;"><form><button onclick="window.close();" class="liteoption">' + L_CLOSE_WINDOW + '</button></form></div></div>');
		'</body></html>');
	w.document.close();

	w.focus();
}

/**
 *  Latexcenter
 */
function latexHand()
{
	$jq('img.latexcenter').each(function() {
	    $jq(this).css({'cursor': 'pointer'});
	});
}

$jq(function() { latexHand(); });