var skipValidation = false;
var skipWaitPopup = false;

dojo.addOnLoad(setupMouseEventsOnMenuForIE);
dojo.addOnLoad(addWaitPopupOnAllLinks);
dojo.addOnLoad(removeDisabledAttribute);
dojo.addOnLoad(removeEmptyButtonBars);
dojo.addOnLoad(addCalculators);
dojo.addOnLoad(hideIconImageBroken);
if (window.GLOBAL_JUMP_TO_ID != '') {
	dojo.addOnLoad(jumpTo);
} else {
	dojo.addOnLoad(formFocus);
}

function $n(myid) {
	var normalizedId = "#" + myid.replace( /(:|\.|\[|\])/g, "\\$1" );
	var result = $(normalizedId);
    return result;
}

function hideIconImageBroken() {
	$("img.iconImage").error(function () {
		$(this).attr("src", window.GLOBAL_CONTEXT_PATH + "/resources/img/default_image_icon.png");
	});
	$("img.bannerImage").error(function () {
		$(this).attr("src", window.GLOBAL_CONTEXT_PATH + "/resources/img/default_image_banner.png");
	});
}

if(typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g, ''); 
	}
}

function addCalculators() {
	if ($.calculator) {
		$('div.dijitCurrencyTextBox input').calculator({showOn: 'operator'});
	}
}

function removeDisabledAttribute() { 
	if (dojo.isIE) {
		//dojo.query('input[disabled]').forEach(function(node, index, arr){
		//	dijit.getEnclosingWidget(node).removeAttr("disabled"); 
		//	dijit.getEnclosingWidget(node).removeAttr("disabled"); 
		//});
		//dojo.query('input[disabled]').removeAttr('disabled');
		//dojo.query('input[disabled]').attr('readOnly', 'true');
		//dojo.query('input[disabled]').attr('readonly', 'true');
	}
}

function removeEmptyButtonBars() { 
	if (window.GLOBAL_SKIP_REMOVE_EMPTY_BUTTON_BARS) {
		return;
	}
	$('ul.buttonBar:not(:has(li))').hide();
}

dojo.addOnLoad(function(){
	/*
	 * Disable enter key on not editable fields to prevent form submission.
	 * You can enable form submission with enter key by assigning "default" class to a button.
	 */
	$(document).keypress(function (e) {
	    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			if (e.srcElement.type == "textarea" || e.srcElement.name == "fullTextSearchString") {
				return true;
			}
	    	var elements = $('input[type=submit].default, li a.default');
    		elements.click();
	        return false;
	    };
	});

	/*
	 * This piece of code prevent backspace to return to the previous page.
	 */
	$(document).keydown(function (e) {
	    if ((e.which && e.which == 8) || (e.keyCode && e.keyCode == 8)) {
			if (e.srcElement.type == "textarea" || e.srcElement.type == "text" || e.srcElement.type == "password") {
				if (e.srcElement.readOnly == true) { 
					return false;
				}
				return true;
			}
			return false;
	    }
        return true;
	});
});


function showWaitPopup(checkResult, title) {
	if (window.GLOBAL_LOADING_MSG == undefined) {
		GLOBAL_LOADING_MSG = "Caricamento in corso, attendere prego...";
	}
	if (checkResult == true && !skipWaitPopup) {
		popup = dijit.byId("loading");
		if (popup) {
			popup.hide();
			popup.destroy();
		}
		popup = new dijit.Dialog({
	        title:  title ? title : GLOBAL_LOADING_MSG,
	        content: "<div class='wait'></div>",
	        style: "width: 32em;height: auto;",
	        id: "loading"
	    });
		popup.show();
	}
	return checkResult;
}

function hidePopWin() {
	popup = dijit.byId("loading");
	if (popup) {
		popup.hide();
		popup.destroy();
	}
}

var currentPopupDialogArg;
var gReturnFunc;
function openPopupDialog(popupDialogArg, width, height, retFunc)
{
    //Durante la composizione dell'URL verifica che i parametri siano valorizzati
    tempSrc = popupDialogArg.url ;
    if( popupDialogArg.parameter != null){
        separatorParam = "?" ;
        if( tempSrc.indexOf('?') > 0 )
            separatorParam = "&" ;
        tempSrc = tempSrc + separatorParam + popupDialogArg.parameter;
    }
	popup = dijit.byId("popup");
	if (popup) {
		popup.hide();
		popup.destroy();
	}
	
	var content = "<iframe style=\"width:100%;height:100%;overflow:auto;background-color:transparent;\" id=\"popupFrame\"" + " src='" + tempSrc + "' onload='resizePopupFrame()'/>";
	popup = new dijit.Dialog({
        title: popupDialogArg.title,
        content: content,
        style: "width: " + width + ";height: " + height,
        id: "popup"
    });
    currentPopupDialogArg = popupDialogArg;
	gReturnFunc = retFunc;
	popup.show();
}

function resizePopupFrame() {
	popup = document.getElementById("popup");
	if (popup == null) {
		return;
	}
	popupFrame = document.getElementById("popupFrame");
	if (popupFrame.frameElement) {
		popupFrame.frameElement.style.height = (popup.clientHeight - 44) + "px";
	} else {
		popupFrame.style.height = (popup.clientHeight - 44) + "px";
	}
}

function closePopupDialog(callReturnFunc, pReturnVal) {
	popup = dijit.byId("popup");
	popup.hide();
	popup.destroy();
	
	if (callReturnFunc == true && gReturnFunc != null) {
		gReturnFunc(pReturnVal);
	}
}

var manageDojoAlertDialog = null;
function showDojoAlertDialog(message, highestLevel) {
	var popup = dijit.byId("alert");
	if (popup) {
		popup.hide();
		popup.destroy();
	}
	if (window.GLOBAL_ALERT_TITLE == undefined) {
		GLOBAL_ALERT_TITLE = "Segnalazioni";
	}
	popup = new dijit.Dialog({
        title: GLOBAL_ALERT_TITLE,
        content: message + "<br/><button class='alert' dojoType=\"dijit.form.Button\" type=\"button\" onClick=\"dijit.byId('alert').hide();\">Ok</button>",
        id: "alert"
    });
	
	if (manageDojoAlertDialog != null) {
		manageDojoAlertDialog(popup, highestLevel);
	} else {
		popup.show();
	}
}

function showDojoAlertErrorDialog(message) {
	return showDojoAlertDialog("<div class='message error'><p class='message error'>" + message + "</p></div>", "error")
}

function switchFrameLayout(idFrame, forceSwitch) {
	if (window.GLOBAL_SKIP_SWITCH_FRAME_LAYOUT && !forceSwitch) {
		return;
	}
    frameDiv = document.getElementById('IFB' + idFrame);
    immagine = document.getElementById('IFTI' + idFrame);
    if (frameDiv) {
        if (frameDiv.className == "layerFrameBodyCollapsed") {
            frameDiv.className = "layerFrameBody";
            if (immagine) immagine.className = "trottle expanded";
        }
        else {
            frameDiv.className = "layerFrameBodyCollapsed";
            if (immagine) immagine.className = "trottle collapsed";
        }
    }
}

function isBlank(val) {
    if (val == null) {
        return true;
    }
    for (var i = 0; i < val.length; i++) {
        if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n") && (val.charAt(i) != "\r")) {
            return false;
        }
    }
    return true;
}

//ritorna una data nel formato dd/mm/aaaaa
function getNowDate()
{
    var now = new Date();
    var day = now.getDate();
    var month = now.getMonth();
    var year = now.getYear();
    //year += 1900;
    month += 1;
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }
    strNow = day + "/" + month + "/" + year;
    return strNow;
}

// confronto tra due date
// torna 1 se la data1 > data2
// torna 0 se la data1 < data2
// torna 2 se le date sono uguali;
function CheckDate(strDate1, strDate2)
{
    strDate1 = strDate1.substring(6, 10) + "/" + strDate1.substring(3, 5) + "/" + strDate1.substring(0, 2);
    strDate2 = strDate2.substring(6, 10) + "/" + strDate2.substring(3, 5) + "/" + strDate2.substring(0, 2);

    var gData1 = Date.parse(strDate1);
    var gData2 = Date.parse(strDate2);

    if (gData1 > gData2)
    {
        return 1;
    }
    if (gData1 < gData2)
    {
        return 0;
    }
    else
    {
        return 2;
    }
}

//Get a value from a form name, if property is a checkbox, then return
//true or false depending on selected option.
function getReportValue(itemName) {
    var item = document.getElementById(itemName);
    if (item.type == "checkbox") {
        return item.checked;
    }
    return escape(item.value);
}

function AddLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function AddResizeEvent(func) {
    var oldonresize = window.onresize;
    if (typeof window.onresize != 'function') {
        window.onresize = func;
    } else {
        window.onresize = function() {
            oldonresize();
            func();
        }
    }
}

function initInternalFrameField(property, href, name, title, className) {
    var field = document.getElementById(property + "_c");
    if (field) {
        var innerHTML = '|&nbsp;<a id="' + property + '" ';
        if (className) {
            innerHTML = innerHTML + 'class="' + className + '" ';
        }
        if (href) {
            innerHTML = innerHTML + 'href="' + href + '" ';
        }
        if (title) {
            innerHTML = innerHTML + 'title="' + title + '"';
        }
        innerHTML = innerHTML + '>';
        if (name) {
            if(title && title!=name)
        	innerHTML = innerHTML + name + '<span class="hidden">' +title+"</span>";
            else
            innerHTML = innerHTML + name;	
        }
        innerHTML = innerHTML + '</a>&nbsp;';

        field.innerHTML = innerHTML;
    }
}

//TODO - ...
function setupMouseEventsOnMenuForIE(event) {
	/*
    var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
    if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
        var topMenu = document.getElementById("css_main");
        if (topMenu) {
            if (topMenu.setEvent) {
                topMenu.setEvent("onmouseover", hideSelectBoxes);
                topMenu.setEvent("onmouseout", displaySelectBoxes);
            } else {
                topMenu.onmouseover = hideSelectBoxes;
                topMenu.onmouseout = displaySelectBoxes;
            }
        }
    }
*/
}

// Add onclick handlers to 'a' elements excluding of class noWaitPopup,
//for automatic wait poup div.
function addWaitPopupOnAllLinks() {
    var elms = document.getElementsByTagName('a');
    for (i = 0; i < elms.length; i++) {
        //jslog.debug("Processing element: " + i + ". className=" + elms[i].className + ". href=" + elms[i].href + ". onclick=" + elms[i].onclick);
        if (elms[i].className.indexOf("noWaitPopup") == -1 && elms[i].onclick == null) {
            //href with 6578706f7274=1 means that are export links of display tag library.
            if (elms[i].href != undefined && elms[i].href.indexOf("javascript:") == -1 && elms[i].href.indexOf("#") == -1 && elms[i].href.indexOf("6578706f7274=1") == -1) {
                elms[i].onclick = function() {
				    showWaitPopup(true);
                    return true;
			    }
            }
        }
    }
}

//TODO - ...
function focusForPopup() {
	if (document.getElementsByTagName("a")[2]) {
	    document.getElementsByTagName("a")[2].focus(); //in case of IE focus on first active link (No Selection by default).
	}
	if (document.getElementsByTagName("a")[1]) {
	    document.getElementsByTagName("a")[1].focus(); //this focus don't work for IE
	}
}

function getFieldValue(id, isEscape) {
	element = dijit.byId(id);
	if (element) {
		if (element instanceof dijit.form.DateTextBox) {
			retField = formatDate(element.attr("value"));
			if (retField == null) {
				return "";
			} else {
				return escapeValue(retField, isEscape);
			}
		}		
		retField = escapeValue(element.attr("value"), isEscape);
		if (retField == "NaN") {
			retField = "";
		}
		return retField;
	}
	element = document.getElementById(id);
	if (element) {
		return escapeValue(element.value, isEscape);
	}
	return null;
}

function setFieldValue(id, value, isEscape) {
	element = dijit.byId(id);
	if (element) {
		if (element instanceof dijit.form.DateTextBox && value == "") {
			value = null;
		}
		element.attr("value", escapeValue(value, isEscape));
		element._onBlur();
		return;
	}
	element = document.getElementById(id);
	if (element) {
		element.value = escapeValue(value, isEscape);
	}
}

function escapeValue(value, isEscape) {
	if (isEscape) {
		return escape(value);
	}
	return value;
}

function safeEval(value) {
	try {
		return eval("return " + value);
	} catch (e) {
		return "";
	}
}
/*
function clearFiltersStandard(divName) {
	if (divName == undefined) {
		divName = "IFBSearch";
	}

	dojo.query('input[id]', divName).forEach(function (dom) { 
		widget = dijit.byId(dom.id);
		if (widget && widget.attr("type") != "hidden" && widget.attr("readOnly") != true) {
			if (widget.attr("type") == "select-one" || widget.attr("type") == "select-multi") {
				//TODO - cercare un metodo per selezionare il primo elemento della lista.
				widget.attr('value', null);
			} else if (widget.attr("type") == "checkbox" || widget.attr("type") == "radio") {
				widget.attr('checked', false);
			} else {
				widget.attr('value', null);
			}
		}
	})
	return;
}
*/
function clearFiltersStandard(divName) {
	if (divName == undefined) {
		divName = "IFBSearch";
	}

	dojo.query('input[id]', divName).forEach(function (dom) { 
		widget = dijit.byId(dom.id);
		
		if ((widget && widget.attr("type") != "hidden" && widget.attr("readOnly") != true) || (widget && widget["class"] && widget["class"].indexOf("cleanable")>-1)) {
			if (widget.attr("type") == "select-one" || widget.attr("type") == "select-multi") {
				setFieldValue(widget.id, "");
			} else if (widget.attr("type") == "checkbox" || widget.attr("type") == "radio") {
				widget.attr('checked', false);
			} else {
				setFieldValue(widget.id, "");
			}
		}else{//nel caso degli hidden
			if (!widget){
				widget = document.getElementById(dom.id);
				if (widget.className && widget.className.indexOf("cleanable")>-1){
					setFieldValue(widget.id, ""); //metodo usato anche nel "Nessuna selezione" delle popup
				}
			}
		}
	})
	return;
}

function disableFields(divName, disable) {
	dojo.query('input', divName).forEach(
	  function(inputElem){
	    inputElem.disabled = disable ? 'disabled' : '';
	  }
	);
}

function handleSwapTab(link) {
	if (document.getElementById("pageStatus") == undefined || document.getElementById("pageStatus").value == "READ") {
		showWaitPopup(true);
		window.location = link.href;
	} else {
		var lastForm = document.forms.length - 1;
		document.forms[lastForm].action = link.href;
		if (document.forms[lastForm].onsubmit()) {
			document.forms[lastForm].submit();
		}
	}
	return false;
}

function getCheckedByName(name) {
	var checkedElements = dojo.query('[name=' + name + ']').filter(function(elm){return elm.checked;});
	return checkedElements;
}

function getCheckedRadioByName(name) {
	var checkedElements = getCheckedByName(name);
	if (checkedElements.length > 0) {
		return checkedElements[0];
	}
	return null;
}

function formatDate(data) {
	if (data == null) {
		return null;
	}
	return dojo.date.locale.format(data, {datePattern: "dd/MM/yyyy", selector: "date"});
}

function formatTime(data) {
	if (data == null) {
		return null;
	}
	return dojo.date.locale.format(data, {datePattern: "HH:mm", selector: "time"});
}

function formatDateTime(data) { 
	if (data == null) {
		return null;
	}
	return dojo.date.locale.format(data, {datePattern: "dd/MM/yyyy HH:mm"});
}

function parseDate(data) {
	if (data == null) {
		return null;
	}
	return dojo.date.locale.parse(data, {datePattern: "dd/MM/yyyy", selector: "date"});
}

function validateDialogForm(formId) {
	var form = dijit.byId(formId);
	var result = form.validate();
	if (!result) {
		form.attr("state", "Error");
	} else {
		form.attr("state", "");
	}
	return form.isValid();
}

function formFocus() {
	if (window.GLOBAL_SKIP_FORM_FOCUS) {
		return;
	}
	if (document.forms.length > 0 && document.getElementById("header") != null) {
		var formElements = ["text", "checkbox", "radio", "select-one", "select-multiple", "textarea"];
		var form = document.forms[document.forms.length-1];
		
		var elements = dojo.query('input[id], textarea[id]', form);
		for (var j = 0; j < elements.length; j++) {
			field = dijit.byId(elements[j].id);
			if (field && field.attr("type") != "hidden" && field.attr("readOnly") != true) {
				for (var x = 0; x < formElements.length; x++) {
					if (field.attr("type") == formElements[x]) {
						field.focus();
						return false;
					}
				}
			}
		}
	}
}

function applyComplexRequired(elements, msg, min, max, minOrMax) {
	for (var field in elements) {
		elements[field].invalidMessage = elements[field].missingMessage = msg;
		elements[field].prev_validator = elements[field].validator;
		elements[field]._fields = elements;
		elements[field].validator = function(value, constraints) {
			var result = this.prev_validator(value, constraints);
			if (result == false) {
				return false;
			}
			var activeId = dijit.byId(document.activeElement).id;
			var ctr = 0;
			for (var field in this._fields) {
				if (this._fields[field].attr("value") != null && this._fields[field].attr("value") != "" && (this._fields[field].attr("value") + "") != "NaN") {
					ctr = ctr + 1;
				}
			}
			if (ctr < min || ctr > max) {
				result = false;
			}
			if (minOrMax == true && ctr != min && ctr != max) {
				result = false;
			}
			if (result == true && activeId == this.attr("id")) {
				for (var field2 in this._fields) {
					if (this._fields[field2].attr("id") != activeId) {
						this._fields[field2].validate();
					}
				}
			}

			return result;
		};
		elements[field].filterValidator = function(value, constraints) {
			var result = true;
			var activeId = dijit.byId(document.activeElement).id;
			var ctr = 0;
			for (var field in this._fields) {
				if (this._fields[field].attr("value") != null && this._fields[field].attr("value") != "" && (this._fields[field].attr("value") + "") != "NaN") {
					ctr = ctr + 1;
				}
			}
			if (ctr < min || ctr > max) {
				result = false;
			}
			if (minOrMax == true && ctr != min && ctr != max) {
				result = false;
			}
			if (result == true && activeId == this.attr("id")) {
				for (var field2 in this._fields) {
					if (this._fields[field2].attr("id") != activeId) {
						this._fields[field2].validate();
					}
				}
			}

			return result;
		};
	}
}

var jfSubmitChecks = new Array();
function performChecksSubmit(){
	var checkResult = true;
	if (skipValidation == false) {
		for (var id in jfSubmitChecks) {
			checkResult = checkResult && jfSubmitChecks[id]();
		}
	}
	return showWaitPopup(checkResult);
}

function jumpTo() {
    var divid = document.getElementById(window.GLOBAL_JUMP_TO_ID);
    if (divid) {
        divid.scrollIntoView(true);
    }
    return false;
}

function addCodeMirrorFor(id) {
    var textarea = document.getElementById(id);
    var defaultOptions = {
  		  lineNumbers: true,
		  matchBrackets: true,
		  readOnly: textarea.readOnly,
		  theme: 'default' + (textarea.readOnly ? ' readonly' : '') ,
		  mode: "text/x-java"
    };
    if (typeof window.customizeCodeMirrorOptions == 'function') {
    	customizeCodeMirrorOptions(defaultOptions);
    }
	var editor = CodeMirror.fromTextArea(textarea, defaultOptions);
    if (typeof window.postProcessCodeMirrorEditor == 'function') {
    	postProcessCodeMirrorEditor(id, editor, defaultOptions);
    }
	textarea.codeMirrorEditor = editor;
}

function initMapForDetail(latitude, longitude, canvas) {
  var myLatLng = new google.maps.LatLng(latitude, longitude);
  var mapCanvas = document.getElementById(canvas);
  var mapOptions = {
    center: myLatLng,
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(mapCanvas, mapOptions)
  var iconBase = 'https://maps.google.com/mapfiles/kml/pushpin/';
  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    animation: google.maps.Animation.DROP,
    icon: {
        size: new google.maps.Size(32, 32),
        scaledSize: new google.maps.Size(32, 32),
        url: iconBase + 'red-pushpin.png'
    },
  });
}
//fine 
//-->
