/**
 * @author Mery
*/
function changePassword(){
	
	url = 'form/changePassword.form.php';
	target='popup';
	openOverlay();
	var changeParameter_R = new Request.HTML({	
						url: url, 
						update: target, 
						onComplete: function(tree, elements, html, js){
						//definire i bottoni da attaccare
							if ($$('input.required')) {
								$$('input.required').each(function(element){
									element.addEvent('blur', checkRequest)
								});
								$('cancelButton').addEvent('click', closeOverlay);
				$('saveButton').addEvent('click', savePwd);
							}
						}
						});
	changeParameter_R.post();

	
}
function savePwd(event){
	//verifico che le pass siano uguali
	
var errorList = new Array();
	//controllo campi obbligatori nome e cognome
	if ($$('input.required')) {
			$$('input.required').each(function(reqElement){
				id = reqElement.get("id");
				errorList.push(requestControll(id));
		});
	}
	if($('new1').value != $('new2').value){
		alert('Le nuove password non coincidono');
		errorList.push(1);
	}
	if (arraySum(errorList) == 0) {
		//invio
		url = 'sql/changePassword.sql.php';
		target = 'feedback';
		
		var changeParameter_R = new Request.HTML({
			url: url,
			update: target,
			onComplete: function(tree, elements, html, js){
				closeOverlay();
			}
		});
		changeParameter_R.post($('information'));
	}
	
}
function changeStatus(table, field, value, id_name, id_value){
	url = 'sql/changeStatus.sql.php';
	target='feedback_'+field;
	target.innerHTML = '';
	var changeParameter_R = new Request.HTML({	
						url: url, 
						update: target 
					
						});
	changeParameter_R.post({
		'table': table,
		'field': field,
		'value': value,
		'id_name': id_name,
		'id_value': id_value	});

}
function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}
function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/htmlentities
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function FCKeditor_OnComplete( editorInstance )
{
   // alert( editorInstance.Name ) ;
   	$(editorInstance.Name+'___Frame').setStyles({visibility: 'visible'});
   $(editorInstance.Name+'_loader').setStyles({display: 'none'});
}
function urlDecode(str){
    str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

function initializeFCK(id){
	var oFCKeditor = new FCKeditor( id ) ;
	oFCKeditor.BasePath = "fckeditor/" ;
	//oFCKeditor.ToolbarSet = 'Narrow';
	oFCKeditor.Height = '200' ;
	oFCKeditor.ToolbarSet = 'Default';
	oFCKeditor.ReplaceTextarea() ;
	$(id+'___Frame').setStyles({visibility: 'hidden'});
	$(id+'_loader').setStyles({display: 'block'});
}
function initializeFCKwithHeight(id, height){

	var oFCKeditor = new FCKeditor( id ) ;
	oFCKeditor.BasePath = "fckeditor/" ;
	//oFCKeditor.ToolbarSet = 'Narrow';
	oFCKeditor.Height = height ;
	oFCKeditor.ToolbarSet = 'Default';
	
	oFCKeditor.ReplaceTextarea() ;
	$(id+'___Frame').setStyles({visibility: 'hidden'});
	$(id+'_loader').setStyles({display: 'block'});
}
function findEditorArea(classe){
	
	//	alert('findeditorArea: '+classe);
	$$('textarea.editor_'+classe).each(function(element){ 
		id=element.get("id");
		//alert(id)
		initializeFCK(id);
	});
}
function writeVaule(divid, value){
	var popup = $(divid).set({
		'value': value });
}
function openDiv(divid){
	var popup = $(divid).set({
		'styles': {
			'display': 'block'
		}
	});
}
function closeDiv(divid){
	var popup = $(divid).set({
		'styles': {
			'display': 'none'
		}
	});
}
function openOverlay(){
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var popup = $('popup').set({
		'styles': {
			'top': (arrayPageScroll[1] + ((arrayPageSize[3] - 700 - 35) / 2) + 'px'),
			'left': (((arrayPageSize[2] - 20 - 1000) / 2) + 'px'),
			'display': 'block'
		}
	});
	var overlayS = $('overlayy').set({
		'styles': {
			'height': (arrayPageSize[1] + 'px')
		}
	});
	$('overlayy').fade(1);
	$('popup').fade(1);
}
function closeOverlay(){
	$('overlayy').fade(0);
	$('popup').fade(0);
	$('popup').innerHTML = "";
}
function closeOverlayAndRefresh(){
	closeOverlay();
	initInstruments();
}

function slideDiv(div){
	var mySlide = new Fx.Slide(div);
	mySlide.toggle();
	
}
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;
}

function initAccordion(){
	alert('initi accordion');
	//create our Accordion instance
	var myAccordion = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
		opacity: false,
		onActive: function(toggler, element){
			//toggler.setStyle('color', '#41464D');
			
		},
		onBackground: function(toggler, element){
			toggler.setStyle('color', '#528CE0');
		}
	});
}
function initAccordionWidthProp(divName, toggler, totoggle){
//	alert(divName+'-'+toggler+'-'+totoggle);
	//create our Accordion instance
	var myAccordion = new Accordion($(divName), toggler, totoggle, {
		opacity: false,
		onActive: function(toggler, element){
		
			//toggler.setStyle('color', '#41464D');
			
		},
		onBackground: function(toggler, element){
			//toggler.setStyle('color', '#528CE0');
		},initialDisplayFx:false
		
	});
}

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;
}

function refreshTable( target, url, sortables, button, accordion, language, pa, page){
	
	var refreshTable_R = new Request.HTML({	
						url: url, 
						update: target, 
						onComplete: function(tree, elements, html, js) {
								if(sortables == 1){ initSortables('myTable');		}
								if(button == 1){	addButtonEvent();	}
								if(accordion == 1){ initAccordion(); }
								}
						});
	refreshTable_R.post({
		'lang': language,
		'pa': pa, 
		'page': page	});
}

function initSortables(Tid){

	var myTable = {};
	myTable = new sortableTable(Tid, {
		overCls: 'over',
		/*onClick: function(){
			alert(this.id)
		}*/
	});
}
function handerlMatch(event){	
	var id_split= event.target.get("id").split("_");
	openOverlay();
	var fModify_R = new Request.HTML({	
		url: this[1], 
		update: 'popup', 
			onComplete: function(tree, elements, html, js){
				//definire i bottoni da attaccare
				var mySortables = new Sortables('#correlated, #uncorrelated', {
					revert: {
						duration: 500,
						transition: 'elastic:out'
					},
					constrain: false,
					clone: true,
					revert: true
				});
				$('cancelButton').addEvent('click', closeOverlay);
				$('saveButton').addEvent('click', saveMatch);
			}
	});
	fModify_R.post({ 'id': id_split[0], 'action': this[0], 'table':this[2]});
}

function saveMatch(event){
	var correlated = new Array();
	$$('#correlatedDiv li.sortListElement').each(function(element){
		var spliId= element.get("id").split("_");
		correlated.push(spliId[0]);
	})
	var fModify_R = new Request.HTML({	
		url: 'sql/match.sql.php', 
		update: 'popup', 
			onComplete: function(tree, elements, html, js){
				//definire i bottoni da attaccare
				 //closeOverlay();
			}
	});
	fModify_R.post({ 'rid': $('id').value, 'pages': correlated, 'table':$('table').value });
}
function handerlAction(event){	
	var id = event.target.get("id"); 
	var url = this[0];
	var target = 'popup';
	var formButton = this [1]; 
	var editor = this[2];
	var accordion = this[3];
	var action = this[4];
	var name=this[5];
	openOverlay();
	var fModify_R = new Request.HTML({	
						url: url, 
						update: 'popup', 
						onComplete: function(tree, elements, html, js) {
								if(editor == 1){	
									findEditorArea(name);	
								}
								if(accordion == 1){
									initAccordionWidthProp('accordion_'+name, 'h3.toggler_'+name, 'div.element_'+name);
								}
								if(formButton == 1){ addButtonFormEvent(name);		}
								}
						});
	fModify_R.post({ 'button_id': id, 'action': action});
}


function handerlVisible(event){
	var id = event.target.get("id");
	var id_split = id.split("_");
	target = id_split[0] + '_container';
	if ($(id_split[0] + '_visible').hasClass('vis1')) {
		status = 0;
	}
	else {
		status = 1;
	}
	$(target).innerHTML = '<img src="css/img/loading-small.gif" alt="carico" />';
	
	var status;
	url = 'sql/changeVisibleStatus.sql.php';
	var chageVisibleStauts_R = new Request.HTML({
		url: url,
		update: target,
		onComplete: function(tree, elements, html, js){
			initInstruments()
		}
	});
	chageVisibleStauts_R.post({
		'id': id_split[0],
		'status': status,
		'table': this
	});
}
