function wcmGoToPage(includeId,numPage,maxElementsForPage, initialContext)
{
	//calcolare lo start index
	var startIndex = getStartIndexFromPage(numPage, maxElementsForPage);
	var contentTemplatePreviewURL = applicationContextRoot+'/contentBox/include/view'; // In questo URL dobbiamo chiammare l'includeId che dovrebbe essere già pubblicato,
	wcmAjaxGet( 'get', contentTemplatePreviewURL, 
				{includeId: includeId , firstElementNumber: startIndex},
				'',
				function(response,responseXml){
					if(response){
						wcmGoToPageCallback(initialContext, response);
					}else{
						WCM.processFailureResponse(response);
					}
				}, 
				null,
				WCM.processFailureResponse);
	
} 

function getStartIndexFromPage(numPage, maxElementsForPage)
{
	// Ritorno lo start index
	return maxElementsForPage * (numPage - 1);
}

function wcmGoToPageCallback(initialContext, htmltoInsert)
{
	var containerElement = WCM.searchForElementWithClass(WCM.WCM_EDIT_AREA_CONTAINER_CLASS, initialContext);
	if (containerElement == null) {
		alert ('Edit Area Container not found. Pagination not possible.');
		return null;
	}
	containerElement.innerHTML = htmltoInsert;
	return false;
}

var WCM = {
	version 			: '0.0.1',
	defaultPopupParams 	: 'toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes,width=450,height=450',
	loaderGifURL		: './loading.gif',
	HEAD_AREA_NAME        : '_HEADAREA_',
	//locale 
	locale : 'it',
	
	setLocale : function( n ) {
		this.locale = n;
	},
	
	getLocale : function( ) {
		 return( this.locale );
	},
	  
	utils:
	{
		areEqualsActions: function( left, right ) {
			if ((!left) != (!right)) return false;
			if (!left) return true;
			if (left.contentType != right.contentType) return false;
			if (left.actionMode != right.actionMode) return false;
			if (left.handler != right.handler) return false;
			if (left.destPage != right.destPage) return false;
			if (!WCM.utils.areEqualsParametersMaps(left.handlerParameters,right.handlerParameters )) return false;
			if (!WCM.utils.areEqualsParametersMaps(left.pageParameters,right.pageParameters )) return false;
			return true;
		},

		areEqualsComponents: function( left, right ) {
			if ((!left) != (!right)) return false;
			if (!left) return true;
			if (left.url != right.url) return false;
			if (!WCM.utils.areEqualsParametersMaps(left.parameters,right.parameters )) return false;
			return true;
		},

		equals: function( left, right ) {
			if ((!left) != (!right)) return false;
			if (!left) return true;
			return left == right; 
		},
		
		areEqualMaps: function( left, right, equalFn ) {
			if( !equalFn) equalFn = WCM.utils.equals;

			if ((!left) != (!right)) return false;
			if (!left) return true;

			for( var key in left )
				if( !equalFn( left[ key ], right[ key ]))
					return false;
			for( var key in right )
				if( !equalFn( left[ key ], right[ key ]))
					return false;
			return true;
		},
		
		areEqualsParametersMaps: function( left, right ) {
			return WCM.utils.areEqualMaps( left, right );
		},
		areEqualsActionsMaps: function( left, right ) {
			return WCM.utils.areEqualMaps( left, right, WCM.utils.areEqualsActions );
		},
		
		areEqualsComponentsMaps: function( left, right, equalFn ) {
			return WCM.utils.areEqualMaps( left, right, WCM.utils.areEqualsComponents );
		},
		
		containSameEditAreas : function(json1, json2){
			for(var areaName in json1.definition){
				if(!json2.definition[areaName])
					return false;
			}
			
			for(var areaName in json2.definition){
				if(!json1.definition[areaName])
					return false;
			}
			
			return true;
		},
		
		isTrue : function(value){
			return ("true" == (""+value).toLowerCase());
		}
	},
	
	checkAndLoadEditAreas: function(myJSON, responseJSON, link){
		
		var differentEditAreas = !WCM.utils.containSameEditAreas(myJSON, responseJSON);
		var differentHeadAreaComponents = !WCM.utils.areEqualsComponentsMaps( myJSON.definition[WCM.HEAD_AREA_NAME].components, responseJSON.definition[WCM.HEAD_AREA_NAME].components );
		
		if(differentEditAreas || differentHeadAreaComponents){
			WCM.setLocation(link);
			return;
		}
		
		for(var areaName in myJSON.definition){
			var myEditArea = myJSON.definition[areaName];
			var responseEditArea = responseJSON.definition[areaName];

			var differentActions    = !WCM.utils.areEqualsActionsMaps( myEditArea.actions, responseEditArea.actions );
			var differentComponents = !WCM.utils.areEqualsComponentsMaps( myEditArea.components, responseEditArea.components );
			
			if( differentActions || differentComponents )
				WCM.reloadArea(areaName,link);
		}
		
		pageDefinitionJson = responseJSON;
	},

	reloadArea:function(nomeArea,link){
		//var initialContentArea = $(nomeArea).innerHTML;
		var initialContentArea = document.getElementById(nomeArea).innerHTML;
		wcmAjaxUpdater(initialContentArea,nomeArea,link);
	},
	
	setLocation : function(link){
		document.location = link;
	},
	
	restoreAreaContent:function(areaId, initialAreaContent){
		//$(areaId).update(initialAreaContent);
		document.getElementById(areaId).innerHTML = initialAreaContent;
	},
	
	showLoader:function(nomeArea){
//		$(nomeArea).update('<div style="width: 100%; height:100%; background: url('+WCM.loaderGifURL+') no-repeat center center;">&nbsp;</div>');
//		debugger;
//		var width = document.getElementById(nomeArea).width;
		document.getElementById(nomeArea).innerHTML = '<div align="center"><img src="'+WCM.loaderGifURL+'" border="0" /></div>';
	},
	
	processFailureAjaxResponse:function(response){
			alert("Something went wrong.\n Response code: [ " + response.status + " ] \n Response Message: [ " + response.statusText + " ]");
	},
	processExceptionAjaxResponse:function(header, val){
		alert("Something went wrong.\n Response header failed: [ " + header + " ] \n Header Value: [ " + val + " ]");
		
	},
	
	openLogicLink : function (link, logicLinksParams){
		
		if(typeof WCM.logicLinkPreCall == 'function') 
			WCM.logicLinkPreCall(link, logicLinksParams);
			
		var disableLegacy = logicLinksParams && WCM.utils.isTrue(logicLinksParams.disableLegacy) ;
		if( !disableLegacy && wcmObjectReadAttribute(link,'legacyonclick')) {// $(link).readAttribute('legacyonclick')) {
 			WCM.openLegacyPopUpFromLogicLink(link);
 			
 			if(typeof WCM.logicLinkPostCall == 'function') 
 				WCM.logicLinkPostCall(link, logicLinksParams);
 			return false; /* block anchor loading as we handle it by legacy onclick*/
 		}
		
		var openPopup = logicLinksParams && WCM.utils.isTrue(logicLinksParams.openPopup) ; 
		if ( openPopup ) {
			WCM.openPopUpFromLogicLinkWithParams(link, logicLinksParams.popupParams);
			
			if(typeof WCM.logicLinkPostCall == 'function') 
				WCM.logicLinkPostCall(link, logicLinksParams);
 			return false; /* block anchor loading as we handle it by popup*/
		}

		var sameModel = logicLinksParams && WCM.utils.isTrue(logicLinksParams.sameModel) ;
		if( sameModel ) {
			WCM.handlerAjaxCallLogicLink(link);
			
			if(typeof WCM.logicLinkPostCall == 'function') 
				WCM.logicLinkPostCall(link, logicLinksParams);
 			return false; /* block anchor loading as we handle it by ajax */
		}
		
		
		return true; /* load page through standard browser procedure */
	},
	
	handlerAjaxCallLogicLink : function(link){
		
		wcmAjaxGet( 'post', 
					link.href, 
					{getPageDefinition: true },
					{Accept: 'application/json'},
					function(jsonResponse,responseText){
				    	//var jsonResponse = transport.responseText.evalJSON(true);
				    	WCM.checkAndLoadEditAreas(pageDefinitionJson, jsonResponse, link.href);
					}, 
					function(header, val){ 
				    	WCM.processExceptionAjaxResponse(header, val);
				    },
				    function(transport){ 
				    	WCM.processFailureAjaxResponse(transport);
				    }
				 );
	},
	
	openLegacyPopUpFromLogicLink: function(link)
	{
		var legacyOnClick = wcmObjectReadAttribute(link, 'legacyonclick'); //$(link).readAttribute('legacyonclick');
		legacyOnClick = legacyOnClick.replace('(this','(link');
		legacyOnClick = legacyOnClick.replace('this )','link )');
		
		legacyOnClick = legacyOnClick.replace(/^javascript:/,'');
		
		//if (legacyOnClick.startsWith('window.open') || legacyOnClick.startsWith('WCM.parametricAjax' ))
		if (legacyOnClick.substring(0, 'window.open'.length) == 'window.open' || legacyOnClick.substring(0, 'WCM.parametricAjax'.length) == 'WCM.parametricAjax')
			legacyOnClick = legacyOnClick.replace('return false','');
		else 
			legacyOnClick = legacyOnClick.replace('return ','');
		
		legacyOnClick = legacyOnClick.replace(/;*$/,'');
		
		return eval(""+legacyOnClick) 
	},
	
	openPopUpFromLogicLinkWithParams: function(link, popUpParams)
	{
 		if (!popUpParams) 
 			popUpParams = WCM.defaultPopupParams;
 		return window.open( link.href, 'Popup', popUpParams );
	},
	
	// Porzione per apertura popup su link semplici (creati con tiny con ktal. NON son i link a content box, quelli parametrici.)
	openPopup : function (link, popup){
		if(popup){
	 		var options = WCM.defaultPopupParams;
			var popupProperties = wcmObjectReadAttribute(link , 'popupProperties'); //$(link).readAttribute('popupProperties');
			if (popupProperties && popupProperties!= '') {
				options = popupProperties; 
			}
	 		wcmTestWindow = window.open( link.href, 'Popup', options ) ;  
	 		return false; 
	 	}else{
		 	return true;
	 	}
	},
	
	// Porzione per onclick su link di tipo parametrico (generati da ktal, sono i link parametrici a contentBox)
	WCM_EDIT_AREA_CONTAINER_CLASS		: 'wcm_editarea_container',
	WCM_PARAMETRIC_TARGET_PREFIX_CLASS 	: 'wcm_parametric_target_',

	parametricAjax : function (includeId, contentId, context) 
	{
		var contentTemplatePreviewURL = applicationContextRoot+'/contentBox/include/view'; // In questo URL dobbiamo chiamare l'includeId che dovrebbe essere già pubblicato,
	    contentTemplatePreviewURL = WCM.appendLocaleToQueryString(contentTemplatePreviewURL, window.location.href);
	    
	    if(typeof this.parametricAjax.preCall == 'function') 
	    	this.parametricAjax.preCall({includeId:includeId , contentId:contentId, context:context,contentTemplatePreviewURL:contentTemplatePreviewURL}); 
		
	    wcmAjaxGet( 'get', contentTemplatePreviewURL, 
				{includeId: includeId , contentId: contentId}, 
				'',
				function(response, responseXml){
					if(response){
						WCM.setHtmlResponseIntoTargetElement(context, response);
					}else{
						WCM.processFailureResponse(response);
					}
				}, 
				null,
				WCM.processFailureResponse);
		
	    if(typeof this.parametricAjax.postCall == 'function') 
	    	this.parametricAjax.postCall({includeId:includeId , contentId:contentId, context:context,contentTemplatePreviewURL:contentTemplatePreviewURL});
	},
	
	setHtmlResponseIntoTargetElement : function (context, htmlToInsert)
	{
		var classString = wcmObjectReadAttribute(context, 'class'); //$(context).readAttribute('class');
		// stabilisce se è richiesto un popup o no
			
		var isPopup = WCM.evaluatePopUp(classString);
		// se è richiesto un popup
		if(isPopup == 'true'){ 
			return WCM.createPopUpFromHtml(htmlToInsert, wcmObjectReadAttribute(context, 'popupProperties')); // $(context).readAttribute('popupProperties'));
		}else{
			// se non è richiesto un popup  - recupera l'elemento target e inserire il contenuto
			var targetElement = WCM.searchTargetElement(context); 
			if(targetElement != 'popup'){
				targetElement.innerHTML = htmlToInsert;
				return targetElement;
			}else{
				return WCM.createPopUpFromHtml(htmlToInsert, wcmObjectReadAttribute(context, 'popupProperties')); //$(context).readAttribute('popupProperties'));
			}
		}
		return null;
	},

	evaluatePopUp : function (classString)
	{
		if (classString.indexOf('ParametricPopup_true') >= 0) {
			return 'true';
		}
		else if (classString.indexOf('ParametricPopup_false') >= 0){
			return 'false';
		}
		return null;
	},

    wcm_new_window_popup : null,
    
	createPopUpFromHtml : function (htmlToInsert, popupProperties)
	{
		try {if (WCM.wcm_new_window_popup) {WCM.wcm_new_window_popup.close();} }catch(e) {};
		var defaultPopupProperties = 'location=0,status=0,scrollbars=1,resizable=1,height=250,width=300';
		if (popupProperties && popupProperties!= '')
			defaultPopupProperties = popupProperties; 
		WCM.wcm_new_window_popup = window.open('about:blank','preview',defaultPopupProperties);
		var currentStylesheets = document.styleSheets;
		WCM.wcm_new_window_popup.document.write('<html><head><title>Preview</title>');
		for (var k = 0; k < currentStylesheets.length; k++) {
			WCM.wcm_new_window_popup.document.write('\n<link rel="stylesheet" type="text/css" href="'+currentStylesheets[k].href+'">');
		}
		WCM.wcm_new_window_popup.document.write('\n</head><body>' + htmlToInsert + '</body></html>');
		WCM.wcm_new_window_popup.document.close();
		WCM.wcm_new_window_popup.focus();
		return WCM.wcm_new_window_popup;
	},

	searchForElementWithClass : function (classToSearch, startContext)
	{
		return wcmSearchForElementWithClass(classToSearch, startContext);
		
	},

	searchTargetElement : function (startContext)
	{
		var foundContainer = WCM.searchForElementWithClass(WCM.WCM_EDIT_AREA_CONTAINER_CLASS, startContext);
		if (foundContainer) {
			var classString = wcmObjectReadAttribute(foundContainer, 'class'); //$(foundContainer).readAttribute('class');
			var classValuesList = classString.split(' ');
					
			var tokenNumber = WCM.getTokenNumberWithText(classValuesList, WCM.WCM_PARAMETRIC_TARGET_PREFIX_CLASS);
			if (tokenNumber == -1) {
				alert ('Target not specified. Opening in self container.');
				return foundContainer;
			}else{
				var tokenElement = classValuesList[tokenNumber].substring(22);
				return WCM.getTargetElementFromTargetValue(tokenElement, foundContainer);
			}
		}
		else {
			alert ('Edit area container not found. Opening popup.');
			return 'popup';
		}
	},

	getTokenNumberWithText : function (tokenList, text) 
	{
		for (var i = 0; i < tokenList.length; i++) {
			if (tokenList[i].indexOf(text) > -1) {
				return i;
			}
		}
		return -1;
	},

	getTargetElementFromTargetValue : function (targetValue, editAreaContainer)
	{
		if(!targetValue || targetValue == '' || targetValue == 'popup'){
			return 'popup';
		}
		if(targetValue == 'self') {
			return editAreaContainer;
		}
		var targetElement = document.getElementById(targetValue);
		if (targetElement) {
			return targetElement;
		}
		alert ('Target element with id ['+targetValue+'] not found. Opening popup.');
		return 'popup';
	},

	processFailureResponse : function (response)
	{
		alert("Something went wrong.\n Error code: [" + response.status + ']');
	},

	// Porzione per onchange della combo URL	
	lastOpenedPopupWindow : null,
	
	linkComboChangeHandler : function (oOption) 
	{
		var params = oOption.value.split("|");
	    WCM.comboPopupOpener(params[0],params[2],params[3],params[1]);
	},
	
	comboPopupOpener : function (aUrl, isPopup, somePopupProperties, linkType)
	{
		if(aUrl.indexOf('-') == 0){
			return false;
		}
		
		if ('internal' == linkType) {
			aUrl = WCM.appendLocaleToQueryString(aUrl, window.location.href);
		}
		
		if(isPopup ==  'popup'){
			if (WCM.lastOpenedPopupWindow){
				try { WCM.lastOpenedPopupWindow.close(); } catch(e){/*ignored*/};
			}
			WCM.lastOpenedPopupWindow = window.open(aUrl ,'popWindow',somePopupProperties);
		}
		else
		{
			window.location.href = aUrl;
		}	
	},
	
	appendLocaleToQueryString: function (queryString, ref){
		return wcmAppendLocaleToQueryString(queryString, ref);
	}
};

/***************************************
 * 
 * Funzioni Per Prototype
 * 
 ***************************************/
function __wcmAppendLocaleToQueryString(queryString, ref)
{
	var localeFromRequest = (ref.toQueryParams()).locale;
    if (localeFromRequest) {
    	if (queryString.indexOf('?') == -1) {
    		queryString = queryString + '?locale=' + localeFromRequest; 
    	} else {
    		queryString = queryString + '&locale=' + localeFromRequest; 
    	}
    }
    return queryString;
}


function __wcmAjaxGet( requestType, requestURL, requestParametes, requestHeaders, successCallBack, exceptionCallBack)
{
	new Ajax.Request(requestURL,
	{
		method			: requestType,
	    parameters		: requestParametes,
	    requestHeaders 	: requestHeaders,
	    options			: { asynchronous: true },
	    onSuccess		: function(transport){ successCallBack(transport);},
	    onException		: (exceptionCallBack!=null)?function(transport){ exceptionCallBack(transport);}:null,
	    onFailure		: function(transport){ failureCallBack(transport); }
	});
}

function __wcmAjaxUpdater(initialContentArea,nomeArea,link)
{
		new Ajax.Updater(nomeArea,link,
		{
			method		: 'post',
			evalScripts	: true,
			evalJSON  	: false,
		    parameters	: {	getOnlyAreaContent: nomeArea },
		    onCreate	: WCM.showLoader(nomeArea),
		    onException : function(transport, ex){ 
		    	WCM.processFailureAndExceptionAjaxResponse(transport.transport, ex); 
		    	WCM.restoreAreaContent(nomeArea, initialContentArea);
		    },
			onFailure	: function(transport){ 
		    	WCM.processFailureAndExceptionAjaxResponse(transport.transport, null); 
		    	WCM.restoreAreaContent(nomeArea, initialContentArea);
		    }
		});
}

function __wcmObjectReadAttribute(object, attributeName)
{
	return $(object).readAttribute(attributeName);
}

function __wcmSearchForElementWithClass(classToSearch, startContext)
{
	var continueLoop = true; 
	var parentElement = startContext.parentNode;
	while (continueLoop) {
		if (!parentElement || parentElement.nodeName == 'BODY') {
			continueLoop = false;
		}else{
			var classString = $(parentElement).readAttribute('class');
			if (classString && classString != '') {
				var classValuesList = classString.split(' ');
				if (WCM.getTokenNumberWithText(classValuesList, classToSearch) != -1)
					return parentElement;
			}
			parentElement =  parentElement.parentNode;
		}
	}
	return null;
}
/***************************************
 * 
 * Funzioni Per Mootools
 * 
 ***************************************/
function wcmAppendLocaleToQueryString(queryString, ref)
{
	var localeFromRequest = getUrlVar(ref, 'locale');
    if (localeFromRequest) {
    	if (queryString.indexOf('?') == -1) {
    		queryString = queryString + '?locale=' + localeFromRequest; 
    	} else {
    		queryString = queryString + '&locale=' + localeFromRequest; 
    	}
    }
    return queryString;
}

function wcmAjaxGet( requestType, requestURL, requestParametes, requestHeaders, successCallBack, exceptionCallBack, failureCallBack)
{
	if (requestType=='get'){
		var req = new Request({
			//evalScripts : true, //legge ed esegue gli script nella responseText
			//evalResponse : true, // commentato per evitare errore 80021... su IE 6
			method: requestType, 
			link : 'cancel',
			data: requestParametes,
		    onSuccess		: function(response, responseXml){ successCallBack(response, responseXml);},
		    onException		: (exceptionCallBack!=null)?function(header, val){ exceptionCallBack(header, val);}:null,
		    onFailure		: (failureCallBack != null)?function(transport){ failureCallBack(transport); }:null
		}).get(requestURL);	
	} else {
		var req = new Request.JSON({
			//evalScripts : true, //legge ed esegue gli script nella responseText
			//evalResponse : true, // commentato per evitare errore 80021... su IE 6
			method: requestType, 
			link : 'cancel',
			data: requestParametes,
		    onSuccess		: function(responseJSON, responseText){ successCallBack(responseJSON, responseText);},
		    onException		: (exceptionCallBack!=null)?function(header, val){ exceptionCallBack(header, val);}:null,
		    onFailure		: (failureCallBack != null)?function(transport){ failureCallBack(transport); }:null
		}).get(requestURL);	
	}
}

function wcmAjaxUpdater(initialContentArea,nomeArea,link)
{
	var req = new Request.HTML({
		evalScripts : true, //legge ed esegue gli script nella responseText
		//evalResponse : true, // commentato per evitare errore 80021... su IE 6
		update: nomeArea,
		method: 'post', 
//		link : 'cancel',
		data: {	getOnlyAreaContent: nomeArea },
		onCreate	: WCM.showLoader(nomeArea),
	    onException : function(header, val){ 
	    	WCM.processExceptionAjaxResponse(header, val); 
	    	WCM.restoreAreaContent(nomeArea, initialContentArea);
	    },
		onFailure	: function(transport){ 
	    	WCM.processFailureAjaxResponse(transport); 
	    	WCM.restoreAreaContent(nomeArea, initialContentArea);
	    }
  }).get(link);	
}

function wcmObjectReadAttribute(object, attributeName)
{
	if (typeof object == 'undefined' || object == null) return '';
	return $(object).getProperty(attributeName);

}

function getUrlVar(url, name) {
	    var vars = {};
	    var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
	        vars[key] = value;
	    });
	    return vars[name];
}

function wcmSearchForElementWithClass(classToSearch, startContext)
{
	return $(startContext).getParent(classToSearch.indexOf('.') == 0 ? classToSearch : '.'+classToSearch);
	
}
