// 
// -----------------------------------------------------------------------------------------
// *** COMMON.JS ***
// -----------------------------------------------------------------------------------------
// Last Updated: 24/05/2003 by DarkAngel
// 
// Common function (such as open standard-sized popUps or pre-loading images),
// used in other JavaScript and in HTML pages.
// 
// -----------------------------------------------------------------------------------------
// Created for MYST site (http://www.myst.it) in 2003. Free for non-commercial usage.
// 
// 
// 

// PopUp variable, empty if PopUp is not open
// INTERFACE USAGE:
// Open a PopUp: 	PopUp = window.open(...);
// Close a PopUp: 	if (PopUp != "") { PopUp.close(); }
// 
var PopUp = "";


// General PopUp implementations
// Naming conventions: "openPopUp" + width.size (default is 400px)
// 
function openPopUp(path) 
{
	if (PopUp != "") { PopUp.close(); }
	//sinistra=screen.width-larghezza-50; 
	//alto=(screen.height-altezza)/2; 
	sinistra = 320;
	alto = 180;
	PopUp = window.open(path,'PopUp','left='+sinistra+', top='+alto+', status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=auto,resizable=1,width=400,height=300');
	return false;
}

function openPopUp600(path)
{
	if (PopUp != "") { PopUp.close(); }
	//sinistra=screen.width-larghezza-50; 
	//alto=(screen.height-altezza)/2; 
	sinistra = 100;
	alto = 100;
	PopUp = window.open(path,'PopUp','left='+sinistra+', top='+alto+', status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=auto,resizable=1,width=600,height=500');
	return false;
}


function openPopUp400x600(path) {
    if (PopUp != "") { PopUp.close(); }
    //sinistra=screen.width-larghezza-50; 
    //alto=(screen.height-altezza)/2; 
    sinistra = 150;
    alto = 120;
    PopUp = window.open(path, 'PopUp', 'left=' + sinistra + ', top=' + alto + ', status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=yes,resizable=1,width=400,height=600');
    return false;
}

function openPopUp500x650(path) {
    if (PopUp != "") { PopUp.close(); }
    //sinistra=screen.width-larghezza-50; 
    //alto=(screen.height-altezza)/2; 
    sinistra = 150;
    alto = 120;
    PopUp = window.open(path, 'PopUp', 'left=' + sinistra + ', top=' + alto + ', status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=yes,resizable=1,width=500,height=650');
    return false;
}


function openPopUpIRC(path)
{
	//sinistra=screen.width-larghezza-50; 
	//alto=(screen.height-altezza)/2; 
	sinistra = 100;
	alto = 100;
	window.open(path,'IRCChat','left='+sinistra+', top='+alto+', status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=auto,resizable=1,width=730,height=510');
	return false;
}

// General PopUp implementations
// Naming conventions: "openPopUp" + width.size (default is 400px)
// 
function openPopUpPDF(path)
{
	if (PopUp != "") { PopUp.close(); }
	//sinistra=screen.width-larghezza-50; 
	//alto=(screen.height-altezza)/2; 
	//sinistra = 320;
	//alto = 180;
	PopUp = window.open(path,'PopUp');
	return false;
}

// REDIRECT MAIN BROWSER WINDOW FROM A LINK IN A POPUP WINDOW
// INTERFACE USAGE: onClick = "return parentHREF(url to redirect parent window, close popup (true or false), seconds to wait);"
function parentHREF(url,closeIt,delay)
{
    opener.location.href = url;
    if (delay == 0) delay = 1;
	if (closeIt == true) setTimeout('self.close()',delay);
	return false;
}

// COPY CONTENT TO CLIPBOARD
function CopyToClipBoard(text,msg)
{
	if (window.clipboardData) 
	{
	   // IE
	   window.clipboardData.setData("Text", text);
	}
	else if (window.netscape) 
	{ 
	   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
	   var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
	   if (!clip) return;
	   var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
	   if (!trans) return;
	   trans.addDataFlavor('text/unicode');
	   var str = new Object();
	   var len = new Object();
	   var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
	   var copytext=text;
	   str.data=copytext;
	   trans.setTransferData("text/unicode",str,copytext.length*2);
	   var clipid=Components.interfaces.nsIClipboard;
	   if (!clip) return false;
	   clip.setData(trans,null,clipid.kGlobalClipboard);
	}
	alert(msg);
	return false;
}

// Get Screen Width in pixels
function GetScreenWidth()
{
	if( document.body && document.body.scrollWidth ) return document.body.scrollWidth;
	else if( document.body.offsetWidth ) return document.body.offsetWidth;
	else return 0;
	//else return '100%';
}

// Get Screen Height in pixels
function GetScreenHeight()
{
	if( document.body && document.body.scrollHeight) return document.body.scrollHeight;
	else if( document.body.offsetHeight ) return document.body.offsetHeight;
	else return 0;
	//else return '100%';
}

// 
// -----------------------------------------------------------------------------------------
// *** COMMON.JS *** End of File.
// -----------------------------------------------------------------------------------------

function grayOut(vis, options)
{
	// Pass true to gray out screen, false to ungray
	// options are optional. This is a JSON object with the following (optional) properties
	// opacity:0-100 // Lower number = less grayout higher = more of a blackout 
	// zindex: # // HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx) // Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'50'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order. Pass only the properties you need to set.
	var options = options || {}; 
	var zindex = options.zindex || 50;
	var opacity = options.opacity || 70;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#000000';
	var dark=$('darkenScreenObject');
	if (!dark) 
	{
		// The dark layer doesn't exist, it's never been created. So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div'); // Create the layer.
		tnode.style.position='absolute'; // Position absolutely
		tnode.style.top='0px'; // In the top
		tnode.style.left='0px'; // Left corner of the page
		tnode.style.overflow='hidden'; // Try to avoid making scroll bars 
		tnode.style.display='none'; // Start out Hidden
		tnode.id='darkenScreenObject'; // Name it so we can find it later
		tbody.appendChild(tnode); // Add it to the web page
		dark=$('darkenScreenObject'); // Get the object.
	}
	if (vis) 
	{
		// Calculate the page width and height 
		if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
		{
			var pageWidth = document.body.scrollWidth+'px';
			var pageHeight = document.body.scrollHeight+'px';
		} 
		else if( document.body.offsetWidth ) 
		{
			var pageWidth = document.body.offsetWidth+'px';
			var pageHeight = document.body.offsetHeight+'px';
		} 
		else 
		{
			var pageWidth='100%';
			var pageHeight='100%';
		}
		//set the shader to cover the entire page and make it visible.
		dark.style.opacity=opaque; 
		dark.style.MozOpacity=opaque; 
		dark.style.filter='alpha(opacity='+opacity+')'; 
		dark.style.zIndex=zindex; 
		dark.style.backgroundColor=bgcolor; 
		dark.style.width= pageWidth;
		dark.style.height= pageHeight;
		dark.style.display='block'; 
	} 
	else dark.style.display='none';
}

// MooTools updates
Element.extend( {
setValue: function(value)
{ 
    if(value) 
    { 
        value = value.toString(); 
        value = value.replace(/%25/g,"%"); 
        value = value.replace(/%26/g,"&"); 
        value = value.replace(/%2b/g,"+"); 
    } 
    switch(this.getTag())
    { 
        case 'select': 
        case 'select-one': 
            this.value = value; 
                break;
        case 'hidden': 
        case 'text': 
        case 'textarea': 
        case 'input': 
            if(['checkbox', 'radio'].test(this.type))
            { 
                if(['1', 'checked', 'on', 'true', 'yes'].test(value)) this.checked = true;
                else this.checked = false; 
            } 
            else
            {
                if(append) this.value += value; 
                else this.value = value; 
            }
            break;
        case 'img':
            this.src = value;
            break;
        default: 
            if(append) this.innerHTML += value; 
            else this.innerHTML = value; 
            if(append && this.scrollHeight) this.scrollTop = this.scrollHeight; 
            break; 
    } 
    return this;
}
});

function Pager(tableName, itemsPerPage, prev, next)
{
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.prev = prev;
    this.next = next;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;
    
    this.showRecords = function(from, to) {        
        var rows = $(tableName).rows;
        for (var i = 0; i < rows.length; i++) {
            if (i < from || i > to)  rows[i].style.display = 'none';
            else rows[i].style.display = '';
        }
    }
    
    this.showPage = function(pageNumber) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}

        var oldPageAnchor = $(this.tableName+'pg'+this.currentPage);
        oldPageAnchor.className = 'pg-normal';
        
        this.currentPage = pageNumber;
        var newPageAnchor = $(this.tableName+'pg'+this.currentPage);
        newPageAnchor.className = 'pg-selected';
        
        var from = (pageNumber - 1) * itemsPerPage;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
    }   
    
    this.prev = function() {
        if (this.currentPage > 1) { this.showPage(this.currentPage - 1); }
    }
    
    this.next = function() {
        if (this.currentPage < this.pages) { this.showPage(this.currentPage + 1); }
    }                        
    
    this.init = function() {
        var rows = $(tableName).rows;
        var records = (rows.length-1); 
        this.pages = Math.ceil(records / itemsPerPage);
        this.inited = true;
    }

    this.showPageNav = function(pagerName, positionId) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}
    	if (this.pages<2) { return; }
    	var element = $(positionId);
    	var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-nextprev"> '+prev+' </span> &middot; ';
    	this.pages.each(function(e,i){
    	    var p = Math.round(parseInt(e)+1);
            pagerHtml += '<span id="'+this.tableName+'pg' + p + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + p + ');">' + p + '</span> &middot; ';
    	    },this);
        pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-nextprev"> '+next+' </span>';            
        element.innerHTML = pagerHtml;
    }
};

// Initialize Tooltips
function InitTooltips() {
    var myTips = new Tips($$('.tooltip'),
		{
		    onShow: function(el) { el.setStyle("opacity", 0); el.fade('0.95'); },
		    onHide: function(el) { el.fade('out'); },
		    className: "tooltip-panel", maxTitleChars: 50,
		    offsets: { 'x': 20, 'y': 20 },
		    fixed: true
		});
}

window.addEvent('domready', function() { InitTooltips() });

