var ajaxObjects = new Array();
//var lingua = ""
var	pageLoadingId = "loading"
var	pageMainId = "main"
var verifymodulesloaded = ""; // moduli caricati

var modulesloaded = false; // moduli caricati
var modulename = ""; // Ultimo modulo caricato
var modulecaller = ""; // modulo chiamante
var moduleToStart = false

var script_regex = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;   

var progress_bar = new Image();
progress_bar.src = 'loading.gif';

// ////////////////////////////////////////////////////////// //
// determina il linguaggio del browser
// ////////////////////////////////////////////////////////// //
//if (navigator.appName == 'Netscape') 
//    var language = navigator.language; 
//else 
//  var language = navigator.browserLanguage;
//if (language.indexOf('en') > -1) setLocation('en'); 
//else if (language.indexOf('de') > -1) setLocation('de'); 
//else if (language.indexOf('fr') > -1) setLocation('fr'); 

//function setLocation(language) {
//	if (language!='it')
//    	var href = '/' + language + '/index.aspx'
//	else
//    	var href = '../index.aspx'
		
//    if (document.location.href.indexOf(href) == -1)
//        document.location.href = href;
//}

//pathArray = window.location.pathname.split( '/' );
//if (pathArray.length >= 2)
//	if (pathArray[1].length == 2)
//		lingua = pathArray[1];

// ///////////////////////////////////////// //
// chioamata alla fine della pagina generata //
// ///////////////////////////////////////// //
function initWebIris()
{
    
	var modulo = getQuerystring('module', 'none')
	if ( modulo != 'none' ) {
		modulo = trim(modulo)
		var params = getQuery() 
		params['module'] = modulo
		if (typeof params['modo'] == 'undefined')
		    params['modo'] = 'default';
		mostra(params)
	} 
}

function LoadScript(url)
{
   	var e = document.createElement("script");
   	e.src = url;
   	e.type="text/javascript";
   	document.getElementsByTagName("head")[0].appendChild(e); 
}

function LoadStyle(url, modulo) {
	var insertCSS = true;
	for (var i=0; i<document.styleSheets.length; i++) {
		if (url==document.styleSheets.href)
			insertCSS = false
	}
	if (insertCSS == true) {
		var cssNode = document.createElement('link');
		cssNode.type = 'text/css';
		cssNode.rel = 'stylesheet';
		cssNode.href = url
		cssNode.media = 'screen';
		// cssNode.title = modulo;
		document.getElementsByTagName("head")[0].appendChild(cssNode);
	}
}

function addStyle(css) {
	if (css=="") { return; }
	var head, style;
	head = document.getElementsByTagName('head')[0];
	if (!head) { return; }
	style = document.createElement('style');
	style.type = 'text/css';
	head.appendChild(style);

	// style.innerText = css;
	if(!!(window.attachEvent && !window.opera)) 
		//this one's for ie
		style.styleSheet.cssText = css;
	else 
		style.appendChild(document.createTextNode(css));
}

function ReloadStyles() {
	var i,a,s;
	a=document.getElementsByTagName('link');
	for(i=0;i<a.length;i++) {
		s=a[i];
		if(s.rel.toLowerCase().indexOf('stylesheet')>=0&&s.href) {
			var h=s.href.replace(/(&|%5C?)forceReload=d+/, ' ');
			s.href=h+(h.indexOf('?')>=0?'&':'?')+'forceReload='+(new Date().valueOf())
		}
	}
}

function replace_html(id, ajaxIndex) {

	try
	{
		var R = document.getElementById(id);
    	R.innerHTML = ajaxObjects[ajaxIndex].response;
		ExecuteScript(ajaxObjects[ajaxIndex].response)
		// hide_progressbar(id)	
		clearAjaxSession(ajaxIndex);
	}
	catch(err)
  	{
  		txt=id + ":\n\n";
  		txt+="There was an error on this page.\n\n";
  		txt+="Error description: " + err.description + "\n\n";
  		// txt+="Click OK to continue.\n\n";
		show_popup("", txt.replace(/\n/g, "<br />"))
  	}
  	hide_progressbar(id)
}

function popup_html(id, ajaxIndex) {

	var R = document.getElementById(id);
    show_popup(id, ajaxObjects[ajaxIndex].response);
	clearAjaxSession(ajaxIndex);
}


function show_progressbar(id) {
  var R = document.getElementById(id);
  
  if (!R)
  	  return;

  var progressbar;
  if(!document.getElementById('progressbar_' + id)) {
    progressbar = document.createElement('div');
    progressbar.id = 'progressbar_' + id;
    progressbar.innerHTML = '<img src="loading.gif" border="0" alt="Loading, please wait..." />';
	progressbar.style.position = "absolute"; 
	progressbar.style.zIndex = "200"; 
	document.body.appendChild(progressbar);
  } else {
    progressbar = document.getElementById('progressbar_'+id);
  }
  var height = R.offsetHeight;
  var width = R.offsetWidth;
  var topposition = topPosition(R); 
  var leftposition = leftPosition(R); 

  //var topposition = topPosition(R) + (R.offsetHeight - progress_bar.height) / 2; 
  //var leftposition = leftPosition(R) + (R.offsetWidth - progress_bar.width) / 2; 

  progressbar.style.top = topposition + 'px';
  progressbar.style.left = leftposition + 'px';
  //progressbar.style.width = width + 'px';
  //progressbar.style.height = height + 'px';
  progressbar.style.display ="block";
  progressbar.style.visibility = "visible";
  //progressbar.style.background = "#dddddd";
  //progressbar.style.filter = 'alpha(opacity=50)';
}

function hide_progressbar(id)
{
  var progressbar = document.getElementById('progressbar_' + id)
  if (progressbar) {
  	progressbar.style.display ="none";
  	progressbar.style.visibility = "hidden";
  }
}

function showWaitMessage(id)
{
	//show_progressbar(id)
}


function ExecuteScript(html)
{
	// execute script
    var scripts = html.match(script_regex);
	if (scripts)
		for (var i = 0; i < scripts.length; i++)   
			eval(scripts[i].replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi,'')); 			
}

function getLocale() {
    var locale = 'it';
    pathArray = window.location.pathname.split('/');
    if (pathArray.length >= 2)
        if (pathArray[1].length == 2)
            locale = pathArray[1];
    return locale
}

function newAjaxSession(ajaxIndex, Id, f) {
    var lingua = getLocale()
    show_progressbar(Id);
	var ajax = new sack();
	ajax.onLoading = function(){ show_progressbar(Id)};
	ajax.onLoaded  = function(){ hide_progressbar(Id)};
	ajax.isBookmark = true;

	if (f=='list' || f=='form')
		ajax.isBookmark = true;
	else
		ajax.isBookmark = false;

	ajax.setVar('lingua',(lingua=='')?'it':lingua);
	ajax.setVar('func',f);

	return ajax
}

function clearAjaxSession(ajaxIndex) {
}

// //////////////////////////////////// //
// sperimentale  usato su modulo ordini // 
// //////////////////////////////////// //
function mostra(obj) {

    if (!obj["module"]) return false;

    // //////////////////////////////// //
    // inizializza gestione back button
    // //////////////////////////////// //
    if (!bookmarks.isinit) {
        bookmarks.initialize();
        bookmarks.isinit = true;
    }
    bookmarks.stopcheck()
    
	var name = obj["module"]
	var fn = name + '_initAjax'
	if (typeof fn == 'string' && eval('typeof ' + fn) == 'function') {
        modulename = false;
		fn = fn + '(' + ((typeof obj != 'undefined') ? '{' : '');
		for (var key in obj) {
		    if (key != "hash") {
		        if (obj.hasOwnProperty(key)) {
		            fn = fn.replace(';;', ',')
		            fn = fn + key + ': \'' + obj[key] + '\';;';
		        }
		    }
        }
		fn = fn.replace(';;', '')
		fn = fn + ((typeof obj != 'undefined') ? '}' : '') + ');'; 
		eval(name+'Init=false;')
		eval(fn)
    } else {
		var m = new Modulo(name);
		m.lingua = getLocale();
		m.params = obj;
		m.initAjax();
    }

    if (obj["hash"]) bookmarks.sethash(obj["hash"]);
    bookmarks.startcheck()
    return false;
}

function mostraStruttura(x) {
	for (var i = 0; i < x.length; i++) {
	    var nome = XmlGet(x, i, "nome");
	    var contenitore = XmlGet(x, i, "contenitore");
	    var tipo = XmlGet(x, i, "tipo");
	    var statico = XmlGet(x, i, "statico");
	    try {
	        if (statico == 'N') {
	            if (tipo == "std") {
	                var m = new Modulo(nome);
	                m.Id = contenitore;
	                m.Init = true
	                m.Child = true;
	                m.params = {};
	                m.params['module'] = nome;
	                m.params['modo'] = 'default';
	                m.initAjax()
	            } else {
	                eval(nome + "Id='" + contenitore + "'")
	                eval(nome + "_initAjax()")
	                verifymodulesloaded += " && " + nome + "Loaded==true"
	            }
	        }
	    }
	    catch (e) { }
	}
}

function Modulo(name){

	this.name = name;
	this.Id = "content"
	this.Init = false;
	this.Child = false;
	this.params;	
	this.Ditta;  
	this.Modo;  
	this.Pagina;
	this.Loaded = false;
	this.Style = false;
	this.ServerPage = "/webiris/AjaxServer/index.aspx";
	this.ajaxObj;
	this.lingua = 'it';

	this.init = function (ajaxIndex)
	{
		var response = this.ajaxObj.responseXML;
		try
		{
		  	this.Ditta=response.getElementsByTagName("ditta")[0].childNodes[0].nodeValue;

			// inizializza il modulo
		  	var moduleStyle=response.getElementsByTagName("style")[0].childNodes[0].nodeValue;
			this.addStyle(moduleStyle); 
		  	var moduleScript=response.getElementsByTagName("script")[0].childNodes[0].nodeValue;
			this.addScript(moduleScript); 

			if (modulename != this.name) {
				modulename = this.name
			  	this.Id=response.getElementsByTagName("contenitore")[0].childNodes[0].nodeValue;

				// inizializza i moduli che compongono la pagina
				var x = response.getElementsByTagName("struttura")
				mostraStruttura(x)
			  	//for (var i=0;i<x.length;i++) {
				//	var nome=XmlGet(x,i,"nome");
				//	var contenitore=XmlGet(x,i,"contenitore");
				//	var tipo=XmlGet(x,i,"tipo");
				//	var statico=XmlGet(x,i,"statico");
				//	try{ 
				//		if (statico == 'N') {
				//			if (tipo == "std") {
				//				var m = new Modulo(nome);
				//				m.Id = contenitore;
				//				m.Init = true
				//				m.Child = true;
				//				m.initAjax()
				//			} else {
				//				eval(nome + "Id='" + contenitore + "'")
				//				eval(nome+"_initAjax()")
				//				verifymodulesloaded += " && " + nome + "Loaded==true"
				//			}
				//		}
				//	}
				//	catch(e){}
				//}
			}		
			
			if (typeof this.params["container"] != 'undefined') {
				hide_progressbar(this.Id)
			 	this.Id = this.params["container"];
				show_progressbar(this.Id)
			 }

			switch(this.Modo)
			{
			case 'form':
				this.formAjax();
			  	break;
			case 'popup':
				this.popupAjax();
				this.ajaxObj.onCompletion = function(){ self.showList(); };	
			  	break;
			default:
				this.listAjax();
			  	break;
			}
		}
		catch (err) {
		    var vDebug = "";
		    for (var prop in err) {
		        vDebug += "property: " + prop + "<br>value: [" + err[prop] + "] <br>";
		    }
		    vDebug += "toString(): " + " value: [" + err.toString() + "]";
		    show_popup("", this.name + ": " + this.ajaxObj.response + "<br>" + vDebug)
		}
    }

	this.showForm = function ()
	{
		this.replace_html()
	}

	this.showList = function ()
	{
		this.replace_html()
	}
	
	this.initAjax = function( )
	{
		this.newAjax('init')
        return false;
	}
	
	this.formAjax = function()
	{
		this.newAjax('form')
        return false;
	}
	
	this.listAjax = function()
	{
		this.newAjax('list')
        return false;
	}

	this.newAjax = function(f) {
	    var isbookmark = true;

	    show_progressbar(this.Id);
	    this.ajaxObj = new sack();
	    this.ajaxObj.requestFile = this.ServerPage;
	    this.ajaxObj.onLoading = show_progressbar(this.Id);

	    for (var key in this.params) {
	        if (key != "hash") {
	            if (this.params.hasOwnProperty(key)) {
	                if (key != 'func' && key != 'lingua')
	                    this.ajaxObj.setVar(key, this.params[key]);
	                if (key == 'modo')
	                    this.Modo = this.params[key];
	                if (key == 'isbookmark')
	                    eval('isbookmark = ' + this.params[key]);
	            }
	        }
	    }

	    if (!this.params["module"]) this.ajaxObj.setVar("module", this.name); ;
	    this.ajaxObj.setVar('lingua', (this.lingua == '') ? 'it' : this.lingua);
	    this.ajaxObj.setVar('func', f);

	    var self = this;
	    switch (f) {
	        case 'init':
	            this.ajaxObj.isBookmark = false;
	            this.ajaxObj.onCompletion = function() { self.init(); };
	            break;
	        case 'list':
	            this.ajaxObj.isBookmark = (!this.Child && isbookmark);
	            this.ajaxObj.onCompletion = function() { self.showList(); self = null; };
	            break;
	        case 'form':
	            this.ajaxObj.isBookmark = (!this.Child && isbookmark);
	            this.ajaxObj.onCompletion = function() { self.showForm(); self = null; };
	            break;
	    }
	    this.ajaxObj.runAJAX(); 	// Execute AJAX function		
	    return false;
	}

 	this.addStyle = function(css) {
		if (css=="") { return; }
		var cssloaded = this.name + 'CSS'	
		if ( eval('typeof window.' + cssloaded) != 'undefined') { return; }

		var head, style;
		head = document.getElementsByTagName('head')[0];
		if (!head) { return; }
		
		style = document.createElement('style');
		style.type = 'text/css';
		head.appendChild(style);
		if(!!(window.attachEvent && !window.opera)) 
			style.styleSheet.cssText = css;
		else 
			style.appendChild(document.createTextNode(css));

		eval('window.' + cssloaded + ' = true;')
	}

	this.script = new Array()

	this.addScript = function(src) {

	    if (src == "") { return; }
	    var jsloaded = this.name + 'JS'
	    if (eval('typeof window.' + jsloaded) != 'undefined') { return; }
	    
	    this.scripts = new Array();
	    p = src.split(/</)
	    for (var i = 0; i < p.length; i++) {
	        if (p[i].indexOf("\/") != 0) {
	            if (p[i].indexOf("src=") != -1 || p[i].indexOf("href=") != -1) {
	                k = p[i].replace(/\"/g, '');
	                k = k.replace(/'/g, "");
	                k = k.replace(/>/g, "");
	                k = k.split(/\s/);
	                if (k[0] == "script") {
	                    var head = document.getElementsByTagName('head')[0];
	                    var script = document.createElement('script');
	                    for (var j = 0; j < k.length; j++) {
	                        z = k[j].split("=")
	                        switch (z[0]) {
	                            case 'type':
	                                script.type = z[1]; break;
	                            case 'src':
	                                script.src = z[1];
	                                // ci sono parametri
	                                for (var ipar = 2; ipar < z.length; ipar++)
	                                    script.src += '=' + z[ipar];
	                                break;
	                        }
	                    }
	                    //head.appendChild(script);
	                    this.scripts.push(script) 
	                }
	                if (k[0] == "link") {
	                    var head = document.getElementsByTagName('head')[0];
	                    var script = document.createElement('link');
	                    for (var j = 0; j < k.length; j++) {
	                        z = k[j].split("=")
	                        switch (z[0]) {
	                            case 'type':
	                                script.type = z[1]; break;
	                            case 'rel':
	                                script.rel = z[1]; break;
	                            case 'href':
	                                script.href = z[1]; break;
	                            case 'title':
	                                script.title = z[1]; break;
	                            case 'media':
	                                script.media = z[1]; break;
	                        }
	                    }
	                    //head.appendChild(script);
	                    this.scripts.push(script) 
	                }
	            } else {
	                var text = p[i].split(">")[1]
	                var head = document.getElementsByTagName('head')[0];
	                var script = document.createElement('script');
	                script.type = 'text/javascript';
	                script.text = text;
	                //head.appendChild(script);
	                this.scripts.push(script)
	            }
	        }
	    }
	    if (this.scripts.length > 0) this.loadScript()
	    
	    eval('window.' + jsloaded + ' = true;')
	}

	this.loadScript = function() {
	    if (this.scripts.length == 0) return;
	    //var callback = function() { WI_scriptloaded = true; }
	    var head = document.getElementsByTagName('head')[0];
	    for (var i = 0; i < this.scripts.length; i++) {
	        var script = this.scripts[i]
	        /*
	        if (script.readyState) {  //IE
	            script.onreadystatechange = function() {
	                if (script.readyState == "loaded" ||
                        script.readyState == "complete") {
	                    script.onreadystatechange = null;
	                    callback();
	                }
	            };
	        } else {  //Others
	            script.onload = function() {
	                callback();
	            };
	        }*/
	        head.appendChild(script);
	    }
	}

	this.replace_html = function() 
	{
		try
		{
			var html = this.ajaxObj.response;
			var R = document.getElementById(this.Id);
   			R.innerHTML = html;
			// hide_progressbar(this.Id)	
			// ExecuteScript(R)
		    var scripts = html.match(script_regex);
			if (scripts)
				for (var i = 0; i < scripts.length; i++)   
					eval(scripts[i].replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi,'')); 			
		}
		catch(err)
  		{
	  		txt=this.Id + ":\n\n";
	  		txt+="There was an error on this page.\n\n";
	  		txt+="Error description: " + err.description + "\n\n";
	  		//txt+="Click OK to continue.\n\n";
	  		//alert(txt);
			show_popup("", txt.replace(/\n/g, "<br />"))
  		}
  		hide_progressbar(this.Id)	
    }
}

// ///////////////////////////////// //
// popup                             // 
// ///////////////////////////////// //

function show_popup(id, content) {
  var R = document.getElementById(id);
  
  var popup;
  var popupclose;
  var popupcontent;
  if(!document.getElementById('popup')) {
    popup = document.createElement('div');
    popup.id = 'popup';
	popup.style.position = "absolute"; 
	popup.style.zIndex = "200"; 
	document.body.appendChild(popup);
 
    popupclose = document.createElement('span');
    popupclose.id = 'popupclose';
    popupclose.innerHTML = '<a href=\"javascript:hide_popup()\" style=\"text-decoration: none\"><strong>X [Close]</strong></a>';
	popup.appendChild(popupclose);
	popupclose.setAttribute("style","float:right");
	popupclose.style.styleFloat = "right";

    popupcontent = document.createElement('div');
    popupcontent.id = 'popupcontent';
    popup.appendChild(popupcontent);
  	popupcontent.style.width = '100%';
  } else {
    popup = document.getElementById('popup');
    popupcontent = document.getElementById('popupcontent');
  }
  
  var height;
  var width;
  var topposition; 
  var leftposition 

  if (!R) {
	height = 200;
	width = 300;
	point = window.center({width:300,height:200})
	topposition = point.y; 
	leftposition = point.x; 
  	popup.style.padding = '20px';
  	popup.style.border = '2px solid red';
	grayOut(true, {'zindex':'50', 'opacity':'50'});  
  } else {
    height = R.offsetHeight;
  	width = R.offsetWidth;
  	topposition = topPosition(R); 
  	leftposition = leftPosition(R); 
  }
  popup.style.top = (topposition) + 'px';
  popup.style.left = (leftposition) + 'px';
  popup.style.width = (width) + 'px';
  // popup.style.height = height + 'px';
  popup.style.display ="block";
  popup.style.visibility = "visible";
  popup.style.background = "#ffffff";

  popupcontent.setAttribute("style","float:none");
  popupcontent.style.styleFloat = "none";
  popupcontent.innerHTML = content;
}

function hide_popup()
{
  var popup = document.getElementById('popup')
  if (popup) {
  	popup.style.display ="none";
  	popup.style.visibility = "hidden";
	grayOut(false);  
  }
}

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':'70'});  
	// 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=document.getElementById('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=document.getElementById('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';  
	}
}

// /////////////////////////////////////////////// //
//   function utility
// /////////////////////////////////////////////// //
function getFunction(fn)
{
	if (typeof fn == 'string' && eval('typeof ' + fn) == 'function') {
        var f = eval(fn + ".toString()")
        var p = f.indexOf("{")
        f = f.substr(0, p)
        p = f.indexOf("function")
        f = f.substr(p+8)
        return f
    } else {
		return false;
	}
}
function getArguments(fn)
{
    var p = fn.indexOf("(")
    var e = fn.indexOf(")")
    fn = trim(fn.substr(p, e))
    fn = fn.replace("(","")
    fn = fn.replace(")","")
    return(fn.split(","))
}
function setArguments(fn)
{
    fn = getFunction(fn)
	if (fn) {
	    var arr = getArguments(fn)
	    var len=arr.length;
	    for(var i=0; i<len; i++) {
	        var key = trim(arr[i]);
	        fn = fn.replace(key, '\"' + getQuerystring(key, '') + '\"')
	    }
	    return fn
	} else {
		return false
	}
}

function getQuery() { 
  var result = {}, queryString = location.hash.substring(2), 
      re = /([^&=]+)=([^&]*)/g, m; 
 
  while (m = re.exec(queryString)) {
   	result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 
  } 
 
  return result; 
}

// /////////////////////////////////////////////// //
// WINDOW utility
// /////////////////////////////////////////////// //
window.size = function() {
	var w = 0;
	var h = 0;
	//IE
	if(!window.innerWidth) {
	//strict mode
		if(!(document.documentElement.clientWidth == 0)) {
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
	//quirks mode
		else {
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else {
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}
window.center = function() {
	var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
	var _x = 0;
	var _y = 0;
	var offsetX = 0;
	var offsetY = 0;
	//IE
	if(!window.pageYOffset) {
		//strict mode
		if(!(document.documentElement.scrollTop == 0))
		{
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		//quirks mode
		else
		{
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	//w3c
	else
	{
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}
	_x = ((this.size().width-hWnd.width)/2)+offsetX;
	_y = ((this.size().height-hWnd.height)/2)+offsetY;
	return{x:_x,y:_y};
}

function selectOption(el, value){
   	var dd = gid(el)
   	for (var i=0; i < dd.length; i++) {
	  if (dd[i].value == value) {
		dd[i].selected = true;
	  }
	}
}

function setPosition(el, refel, x, y) {
  var R = document.getElementById(refel);
  if (!R) return;
  var o = document.getElementById(el);
  if (!o) return;
  var Y = topPosition(R) + y; 
  var X = leftPosition(R) + x; 
  o.style.top = Y + 'px';
  o.style.left = X + 'px';
}

