

var _openDialogTitle = "";

function objectInfo(id) {
	var url="/dp/common/object/show.ajax?id="+id;
	openDialog("Info",url);
}

function openDialog(title, url, width, height) {
	_openDialogTitle = title;
	$.ajax({
		url: url,
		cache: false,
		dataType: "html",
		success: function(html){
			_showDialog(title, html, width, height);
		}, error: function( xreq, textStatus, error) {
			alert('Error: ' + textStatus + ': ' + error);
			if(console && console.error)
				console.error('Error: ' + textStatus + ': ' + error);
		}
	});
}

function setContentDialog(url) {
	$.ajax({
		url: url,
		cache: false,
		dataType: "html",
		success: function(html){
			if($('#cisInternalDialog').data("dialog")==undefined)
				_showDialog(_openDialogTitle, html);
			else
				$('#cisInternalDialog').html(html);
		}, error: function( xreq, textStatus, error) {
			alert('Error: ' + textStatus + ': ' + error);
			if(console && console.error)
				console.error('Error: ' + textStatus + ': ' + error);
		}
	});
}

function closeDialog() {
	_onCloseDialog();
}

var _current_dialog;

function _onCloseDialog() {
	$('#cisInternalDialog').data("dialog").destroy();
}

function _showDialog(title, data, width, height) {
	if(typeof(width)=='undefined') width = "auto";
	if(typeof(height)=='undefined') height = "auto";
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.core.css?_=1283439539846");
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.theme.css?_=1283439539846");
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.dialog.css?_=1283439539846");
	cis.loadJs("/cis/lib/jquery-ui-1.7.2/ui.core.min.js?_=1283439539846");
	if(navigator.userAgent.indexOf("MSIE 6")>=0)
		cis.loadJs("/cis/lib/jquery-1.3.2/bgiframe/jquery.bgiframe.min.js?_=1283439539846");
	cis.loadJs("/cis/lib/jquery-ui-1.7.2/ui.dialog.min.js?_=1283439539846", function() {
		$("#cisInternalDialog").dialog({
			bgiframe: true,
			title: title, 
			width: width, 
			height: height, 
			modal: true,
			bgiframe: true, 
			autoOpen: false,
			close: function() {
				_onCloseDialog();
			}
		});

		$('#cisInternalDialog').html(data);
		$('#cisInternalDialog').data("dialog").open();
		
	});
	
}

var __div;
var __functionToRun;

function openLayer(divId, url, functionToRun) {
	__div = document.getElementById(divId);
	__functionToRun = functionToRun;
	
	$.ajax({
		url: url,
		cache: false,
		dataType: "html",
		success: function(html){
			_showLayer(html);
		}, error: function( xreq, textStatus, error) {
			alert('Error: ' + textStatus + ': ' + error);
			if(console && console.error)
				console.error('Error: ' + textStatus + ': ' + error);
		}
	});
}

function _showLayer(data) {
	__div.innerHTML = data;
	__div.style.display = "block";
	
	if(typeof(__functionToRun)=='function')
		__functionToRun();
	else if(typeof(__functionToRun)=='string') 
		eval(__functionToRun);
}

function closeLayer(divId) {
	document.getElementById(divId).style.display = "none";
}


function setContentLayer(divId, url) {
	__div = document.getElementById(divId);
	$.ajax({
		url: url,
		cache: false,
		dataType: "html",
		success: function(html){
			__div.innerHTML = html;
		}, error: function( xreq, textStatus, error) {
			alert('Error: ' + textStatus + ': ' + error);
			if(console && console.error)
				console.error('Error: ' + textStatus + ': ' + error);
		}
	});
}

// alert2 is deprectated
function alert2(msg, title) {
	cisAlert(msg, title);
}

function activateReturnKey(formId) {
	$(jq(formId)+' input').live("keypress", function(e) {
		/* ENTER PRESSED*/
		if (e.keyCode == 13) {
			/* FOCUS ELEMENT */
			var inputs = $(this).parents("form").eq(0).find(":input");
			var idx = inputs.index(this);
			if (idx == inputs.length - 1) {
				$(this).parents("form").submit();
			} else {
				inputs[idx + 1].focus(); // handles submit buttons
//				inputs[idx + 1].select();
			}
			return false;
		}
	});
}

function cisAlert(msg, title, callback, cparam) {
	_cisLoadAlerts(function(){
		var realcallback = callback;
		if(typeof(callback)=='function' && typeof(cparam)!='undefined') {
			realcallback = function() {
				callback(cparam);
			}
		}
		jAlert(msg, title, realcallback);
	});
}
function cisConfirm(msg, title, callback) {
	_cisLoadAlerts(function(){
		jConfirm(msg, title, callback);
	});
}
function cisPrompt(msg, value, title, callback) {
	_cisLoadAlerts(function(){
		jPrompt(msg, value, title, callback);
	});
}
function cisDialog(msg, buttons, title, callback) {
	_cisLoadAlerts(function(){
		jDialog(msg, buttons, title, callback);
	});
}
function _cisLoadAlerts(callback) {
	cis.loadCss('/cis/lib/jquery-1.3.2/themes/conductiva/alerts/jquery.alerts.css?_=1283439539846');
	cis.loadJs("/cis/lib/jquery-1.3.2/alerts/jquery.alerts.min.js?_=1283439539846", function(){
		$.alerts.okButton = '&nbsp;Aceptar&nbsp;';
		$.alerts.cancelButton = '&nbsp;Cancelar&nbsp;';
		callback();
	});
}

function cisAjaxJSON(url, settings) {
	settings = $.extend({}, 
			{
				validate : true, 
				beforeSend: function(obj) {return true},
				afterResponse: function(obj) {}, 
				objectResponse: function(js) {}, 
				error: function(e) {}, 
				ajax : {}
			}, settings);

	if(settings.ajax.success) {
		alert("You can not define settings.ajax.success!!!");
		return;
	}
	if(settings.ajax.error) {
		alert("You can not define settings.ajax.error!!!");
		return;
	}
	
	var defAjax = {
			type: "post",
			url: url,
			dataFilter : function( data, type ) {
				if(typeof(data)=='string') {
					return data;
				} else {
					var xml = $(data);
					var json = $("json", xml).text();
					var obj = eval(json);
					var ohtml = $("html", xml);
					var omhtml = $("mhtml", xml);
					if(ohtml.length>0 && omhtml.length>0) {
						if(console && console.error)
							console.error("Invalid mixed response");
						throw "Invalid mixed response";
					}
					if(ohtml.length>0) {
						if(ohtml.length==1) {
							obj.html = ohtml.text();
						} else {
							obj.mhtml = [];
							ohtml.each(function(){
								var html = $(this).text();
								if(!obj.html)
									obj.html = html;
								obj.mhtml.push(html);
							});
						}
					} else if(omhtml.length>0) {
						obj.mhtml = [];
						omhtml.each(function(){
							var html = $(this).text();
							if(!obj.html)
								obj.html = html;
							obj.mhtml.push(html);
						});
					}
					return obj;
				}
			},
			success: function(html) {
				var js = null;
				var settingsError = null;
				try {
					js = typeof(html)=='string' ? eval(html) : html;
				} catch(e) {
					settingsError = {
							type: 'evalObject',
							message: e,
							error: e,
							html: html
							};
				}
				if(settingsError) {
					settings.afterResponse( { html: html, error: settingsError });
					settings.error(settingsError);
				} else {
					settings.afterResponse({obj: js, html: html});
					settings.objectResponse(js);
				}
			}, 
			error: function(xhr, textStatus, e){
				var settingsError = {
						type: 'ajaxCall',
						message: ("error"==textStatus ? ('HTTP ' + xhr.status) : textStatus),
						textStatus: textStatus, 
						error: e, 
						xhr: xhr
					};
				settings.afterResponse( { error: settingsError });
				settings.error(settingsError);
			}
		};

	var ajaxSettings = $.extend({}, defAjax, settings.ajax);
	if(!ajaxSettings.url || ajaxSettings.url.length==0)
		settings.error({
			type: 'local',
			message: 'URL not defined for ajax POST'
			});
	else {
		if(settings.beforeSend({settings : settings}))		
			$.ajax(ajaxSettings);
	}

}

function cisAjaxSubmit(jform, settings) {
	var validSelector = false;
	if( typeof(jform)=="object" && typeof(jform.jquery)=="string" && jform.length>0)
		validSelector = true;
	
	if(!validSelector) {
		cisAlert("Invalid form selector");
		return;
	}
	
	settings = $.extend({}, 
		{
			validate : true, 
			beforeSubmit: function(obj) {return true}, 
			afterResponse: function(obj) {}, 
			objectResponse: function(js) {},
			error: function(e) {alert(e)},
			ajax : {}
		}, settings);

	if(settings.ajax.success) {
		alert("You can not define settings.ajax.success!!!");
		return;
	}
	if(settings.ajax.error) {
		alert("You can not define settings.ajax.error!!!");
		return;
	}

	if(typeof(settings.validate)=='function') {
		if(!settings.validate(jform))
			return;
	} else if(settings.validate) {
		var validationResult = true;
		var firstFocused = false;
		jform.each(function(){
			var validator = $(this).validate();
			var v = validator.form();
			validationResult = validationResult && v;
			if(!v && !firstFocused && validator.settings.focusInvalid) {
				validator.focusInvalid();
				firstFocused = true;
			}
		});
		if(!validationResult)
			return;
	}
	
	
	var sd = '';
	if(typeof(settings.ajax.data)=='string')
		sd = settings.ajax.data;
	else {
		jform.each(function(){
			var isd = $(this).serialize();
			if(isd.length>0)
				sd = sd + (sd.length>0 ? "&" : "") + isd;
		});
	}
	
	var defAjax = {
			type: "post",
			url: (jform.length>0 ? jform[0].action : ''),
			data: sd,
			dataFilter : function( data, type ) {
				if(typeof(data)=='string') {
					return data;
				} else {
					var xml = $(data);
					var json = $("json", xml).text();
					var obj = eval(json);
					var ohtml = $("html", xml);
					var omhtml = $("mhtml", xml);
					if(ohtml.length>0 && omhtml.length>0) {
						if(console && console.error)
							console.error("Invalid mixed response");
						throw "Invalid mixed response";
					}
					if(ohtml.length>0) {
						if(ohtml.length==1) {
							obj.html = ohtml.text();
						} else {
							obj.mhtml = [];
							ohtml.each(function(){
								var html = $(this).text();
								if(!obj.html)
									obj.html = html;
								obj.mhtml.push(html);
							});
						}
					} else if(omhtml.length>0) {
						obj.mhtml = [];
						omhtml.each(function(){
							var html = $(this).text();
							if(!obj.html)
								obj.html = html;
							obj.mhtml.push(html);
						});
					}
					return obj;
				}
			},
			success: function(html) {
				var js = null;
				var settingsError = null;
				try {
					js = typeof(html)=='string' ? eval(html) : html;
				} catch(e) {
					settingsError = {
							type: 'evalObject',
							message: e,
							error: e,
							html: html
							};
				}
				if(settingsError) {
					settings.afterResponse( { error: settingsError });
					settings.error(settingsError);
				} else {
					settings.afterResponse({obj: js, html: html});
					settings.objectResponse(js);
				}
			}, 
			error: function(xhr, textStatus, e){
				var settingsError = {
						type: 'ajaxCall',
						message: ("error"==textStatus ? ('HTTP ' + xhr.status) : textStatus),
						textStatus: textStatus, 
						error: e, 
						xhr: xhr
					};
				settings.afterResponse( { error: settingsError });
				settings.error(settingsError);
			}
		};

	
	var ajaxSettings = $.extend({}, defAjax, settings.ajax);
	if(!ajaxSettings.url || ajaxSettings.url.length==0)
		settings.error({
			type: 'local',
			message: 'URL not defined for ajax POST'
			});
	else {
		if(settings.beforeSubmit({formSelector: jform, settings : settings}))
			$.ajax(ajaxSettings);
	}
}

;(function($) {
	
	var isEnlarged = function(area) {
		return "1"==area.attr('alreadyEnlarged');
	};
	
	var doConstraint = function(area) {
		area.width(parseInt(area.attr('originalWidth'))).height(parseInt(area.attr('originalHeight'))).removeAttr('originalWidth').removeAttr('originalHeight').removeAttr('alreadyEnlarged');
	};

	$.fn.areaEnlarger = function( opts ) {
		
		var options = $.extend({}, $.fn.areaEnlarger.defaults, opts);
		
		return this.each(function(){
			var link = $(this);
			if(typeof(link.attr('areaId'))=='string') {
				var area = $(jq(link.attr('areaId')));
				if(area.length==1) {
					link.show().click(function(){
						if(isEnlarged(area))
							doConstraint(area);
						else {
							var position=area.position();
							var wwidth=$(window).width();
							area.attr('originalWidth', area.width()).attr('originalHeight', area.height()).width(wwidth-position.left-options.horizontalMargin).height(options.height).attr('alreadyEnlarged','1');
						}
					});
					
					if(options.constraintOnBlur)
						area.blur(function(){
							if(isEnlarged(area))
								doConstraint(area);
						});
				}
			}
		});
	};

	$.fn.areaEnlarger.defaults = {
		height: 400, 
		horizontalMargin: 50,
		constraintOnBlur: true
	};

})(jQuery);


function handleSubmit(formId,mustHandle) {
	if (mustHandle) {
		if (document.forms[formId].validate.value=="false") {
			$("#"+formId).validate({ onsubmit: false });
			$("#"+formId).unbind('submit').submit();
		} else {
			$("#"+formId).submit();
		}
	}
	
	return false; 
}


var _cis_CONTEXT_PATH="";
var _cis_CURRENT_LANG="es";

var	_editor_url = "/cis/lib/flasharea/";// path to FlashArea 
var	_textarearich_url = "/cis/lib/textarearich/";// path to FlashArea 

var __cisAppVersionId = "1283439539846";

var onrefreshes = new Array();
function doRefresh() {
	for (var i = 0; i<onrefreshes.length;i++) {
		onrefreshes[i]();
	}
}

var onloads = new Array();
window.onload=function() {
	for ( var i = 0 ; i < onloads.length ; i++ ) {
		onloads[i]();
	}
	
	doRefresh();
};

function submitForm(formName,validate) {
	var execSubmit=true;
	if (validate) {
		execSubmit=validateForm(formName);
	}
	
	if (execSubmit) {
		var form=document.forms[formName];
		if (form.onsubmit) {
			if (form.onsubmit()) {
				form.submit();
			}
		} else {
			form.submit();
		}
	}
}

function resetSearchForm(formName, prefix) {
	var f = document.forms[formName];
	for(var i=0;i<f.elements.length;i++) {
		var e = f.elements[i];
		if(e.name && e.name.startsWith(prefix)) {
			if(e.type.equals('text'))
				e.value = '';
			else if(e.type.equals('select-one'))
				e.selectedIndex = 0;
		}
	}
}

function printSwf(id,url,width,height,bgcolor) {
	widthStr="";
	heightStr="";
	if (width) widthStr=' width="'+width+'"';
	if (height) heightStr=' height="'+height+'"';
	if (!bgcolor) bgcolor="#ffffff";
	document.write('<div style="z-index:2;">');
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" '+widthStr+' '+heightStr+' id="'+id+'" align="middle">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="movie" value="'+url+'" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="bgcolor" value="'+bgcolor+'" />');
	document.write('<embed swLiveConnect="true" src="'+url+'" quality="high" '+widthStr+' '+heightStr+' bgcolor="'+bgcolor+'" name="'+id+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
	document.write('</div>');
};

function jq(myid,prefix) {
	if (!prefix) prefix="#";
	return prefix+myid.replace(/:/g,"\\:").replace(/\./g,"\\.").replace(/\@/g,"\\@");
};

function Cis() {
	this._externalFilesLoadeds_ = new Array();
	this._loadJsLoadedFiles_ = new Array();
	this._loadJsLoadingFiles_ = new Array();
	
	this.fileWasLoaded = function (filename) {
		return this._loadJsLoadedFiles_[filename];
	};
	this.processLoadCallbacks = function(filename) {
		var callbacksArray = this._loadJsLoadingFiles_[filename];
		for(var i=0;i<callbacksArray.length;i++)
			callbacksArray[i]();
		this._loadJsLoadedFiles_[filename] = true;
	};
	this.addLoadCallback = function (filename, callback) {
		if( (typeof this._loadJsLoadingFiles_[filename])=='undefined')
			this._loadJsLoadingFiles_[filename] = new Array();
		var callbacksArray = this._loadJsLoadingFiles_[filename];
		callbacksArray[callbacksArray.length++] = callback;
		return callbacksArray.length==1;
	};
};

Cis.prototype.require = function(filename) {
	this.loadjscssfile(filename,"js");
};

Cis.prototype.loadjscssfile = function(filename, filetype){
	if(!this._externalFilesLoadeds_[filename]) {
		if (filetype=="js"){ //if filename is a external JavaScript file
			var fileref=document.createElement('script')
			fileref.setAttribute("type","text/javascript")
			fileref.setAttribute("src", filename)
		}
		else if (filetype=="css"){ //if filename is an external CSS file
			var fileref=document.createElement("link")
			fileref.setAttribute("rel", "stylesheet")
			fileref.setAttribute("type", "text/css")
			fileref.setAttribute("href", filename)
		}
		if (typeof fileref!="undefined") {
			document.getElementsByTagName("head")[0].appendChild(fileref)
			this._externalFilesLoadeds_[filename] = true;
		}
	}
};

Cis.prototype.loadCss = function(filename) {
	this.loadjscssfile(filename, "css");
};

Cis.prototype.setCssLoaded = function(filename) {
	this._externalFilesLoadeds_[filename] = true;
};

(function() {
	if(typeof(__cisAppVersionId)=='undefined')
		__cisAppVersionId = "";
})();

Cis.prototype.setJsLoaded = function(filename) {
	this._loadJsLoadedFiles_[filename] = true;
}

Cis.prototype.loadJs = function(filename, callback) {
	var localCallback = ((typeof callback)=='function') ? callback : function(){};
	var cis = this;
	if(this.fileWasLoaded(filename))
		localCallback();
	else if(this.addLoadCallback(filename, localCallback)) {
		if(__cisAppVersionId!="") {
			var data = (filename.indexOf("?_=")!=-1) ? null : "_=" + __cisAppVersionId;  
			$.ajax({
				type: "GET",
				url: filename,
				cache: true, 
				data: data,
				success: function(){
					cis.processLoadCallbacks(filename);
				},
				dataType: "script"
			});
		}
		else { 
			$.getScript(filename, function(){
				cis.processLoadCallbacks(filename);
			});
		}
	}
};

Cis.prototype.setHidden = function(form, name, value) {
	var f;
	if(typeof(form)=='object') f = form;
	else if(typeof(form)=='string'){
		f = document.getElementById(form);
		if( typeof(form)!='object')
			f = document.forms[form];
	}
	
	if(typeof(f)=='object') {
		if(typeof(f.elements[name])=='undefined') {
			var h = document.createElement('input');
			h.setAttribute("type", "hidden");
			h.setAttribute("name", name);
			h.setAttribute("value", value);
			f.appendChild(h);
		} else {
			f.elements[name].value = value;
		}
	} else {
		console.error("Form " + form + " not found");
	}
};

Cis.prototype.runWhenReady = function(config) {
	var opts = $.extend({iterationTimeout : 100, maxIterations: 30, timeout : function(){} }, config);

	if(typeof(opts.callback)!='function') {
		alert('runWhenReady: Error callback is not a function');
		return;
	}
	if(typeof(opts.isReady)!='function') {
		alert('runWhenReady: Error test is not a function');
		return;
	}
	if(typeof(opts.timeout)!='function') {
		alert('runWhenReady: Error timeout is not a function');
		return;
	}

	var waitForInitialization = function(innerOpts) {
		innerOpts = $.extend({__counter: 0}, innerOpts);
		innerOpts.__counter++;
		var isReady = opts.isReady();
		if(!isReady && innerOpts.__counter<innerOpts.maxIterations) {
			setTimeout(function(){
				waitForInitialization(innerOpts);
			}, innerOpts.iterationTimeout);
		}

		if(isReady)
			innerOpts.callback();
		else
			innerOpts.timeout();
	};

	if(opts.isReady())
		opts.callback();
	else
		waitForInitialization(opts);

}

var cis = new Cis();


function getRadioValue(formId,elId) {
	var radio=document.getElementById(formId)[elId];
	var val;
	for (i=0;i<radio.length;i++){
		if (radio[i].checked==true){
			val=radio[i].value;
			break; //exist for loop, as target acquired.
		}
	}
	return val;
}

function randomPassword(length)
{
  var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  var pass = "";
  for(var x=0;x<length;x++)
  {
    var i = Math.floor(Math.random() * 62);
    pass += chars.charAt(i);
  }
  return pass;
}

function isValidEmail(x) {
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(x);
}

function isVoid(x) {
	if (x==undefined) return true;

	return x=='';
}

function isValidPhone(x) {
	var filter  = /^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/;
	return filter.test(x);
}

function isValidNumber(x) {
	var filter  = /^[0-9]*$/;
	return filter.test(x);
}

function isValidDate(x) {
	var filter = /^\d{1,2}\-\d{1,2}\-\d{4}$/;
	return filter.test(x);
}

function isValidNie(x) {
	var startsWithX = (x.substring(0,1)=='X');
	if(startsWithX) {
		var dni = x.substring(1, x.length);
		return isValidDni(dni);
	}
	return false;
}

function isValidDni(x) {
	if (x.length!=9) return false;
	
	var dni=x.substring(0,x.length-1);
	var let=x.charAt(x.length-1);
	if (!isNaN(let))
	 {
	  return false;
	 }
	else
	 {
	  var cadena="TRWAGMYFPDXBNJZSQVHLCKET";
	  var posicion = dni % 23;
	  var letra = cadena.substring(posicion,posicion+1);
	  if (letra!=let.toUpperCase())
	   {
	    return false;
	   }
	 }
 	 return true;
}

function isValidPassword(x) {
	var filter = /^[a-zA-Z0-9]{4,15}$/;
	return filter.test(x);
}

function changeLanguage(lang) {
    var url = document.location.toString();
    if( url.indexOf("?") > -1 ) {
        if( url.indexOf("&lang") > -1 ) {
            var tmp1 = url.substring(0, url.indexOf("&lang="));
            var tmp2 = url.substring(url.indexOf("&lang=")+9);
            url = tmp1 + tmp2;
            document.location = url + "&lang=" + lang;
        } else {
            document.location = url + "&lang=" + lang;
        }
        if( url.indexOf("lang") > -1 ) {
            var tmp1 = url.substring(0, url.indexOf("lang="));
            var tmp2 = url.substring(url.indexOf("lang=")+9);
            url = tmp1 + tmp2;
            document.location = url + "lang=" + lang;
        } else {
            document.location = url + "&lang=" + lang;
        }
    } else {
        document.location = url + "?&lang=" + lang;
    }
}

/*
 * ERROR CONTROL
 */
function showErrorMessage(elId,msg) {
	el=document.getElementById(elId);
	el.innerHTML=msg;
}

function clearErrorMessage(elId) {
	el=document.getElementById(elId);
	el.innerHTML="";
}

/*
 * VALIDATOR METHODS
 */
function validate_nonVoid(elId,formId) {
	if (isVoid(document.getElementById(formId)[elId].value))
	{
		showErrorMessage(elId+"_errMsg",error_nonVoid);
		return false;
	}
	
	return true;
}

function validate_nonVoidSelect(elId,formId) {
	if (isVoid(document.getElementById(formId)[elId].value)) 
	{
		showErrorMessage(elId+"_errMsg",error_nonVoid);
		return false;
	}
	
	return true;
}

function validate_nonVoidRadio(elId,formId) {

	if (isVoid(getRadioValue(formId,elId))) 
	{
		showErrorMessage(elId+"_errMsg",error_nonVoid);
		return false;
	}
	
	return true;
}

function validate_number(elId,formId) {
	if (isVoid(document.getElementById(formId)[elId].value)) {  // we assume number is valid if void (by default)
		return true;
	}
	
	if (!isValidNumber(document.getElementById(formId)[elId].value))
	{
		showErrorMessage(elId+"_errMsg",error_number);
		return false;
	}
	
	return true;
}

function validate_email(elId,formId) {
	if (isVoid(document.getElementById(formId)[elId].value)) {  // we assume email is valid if void (by default)
		return true;
	}
	
	if (!isValidEmail(document.getElementById(formId)[elId].value))
	{
		showErrorMessage(elId+"_errMsg",error_email);
		return false;
	}
	
	return true;
}

function validate_date(elId,formId) {
	if (isVoid(document.getElementById(formId)[elId].value)) {  // we assume email is valid if void (by default)
		return true;
	}
	
	if (!isValidDate(document.getElementById(formId)[elId].value))
	{
		showErrorMessage(elId+"_errMsg",error_date);
		return false;
	}
	
	return true;
}

function validate_uppercase(elId,formId) {
	document.getElementById(formId)[elId].value=document.getElementById(formId)[elId].value.toUpperCase();
	return true;
}

function validate_password(elId,formId) {
	var newPwdId=elId+"_new";
	var newrepeatPwdId=elId+"_newrepeat";
	
	var newpwd=document.getElementById(formId)[newPwdId].value;
	var newrepeatpwd=document.getElementById(formId)[newrepeatPwdId].value;
	
	if (newpwd!=newrepeatpwd) {
		showErrorMessage(elId+"_errMsg",error_passwordsNoMatch);
		return false;
	}
	
	if (!isVoid(newpwd)) {
		if (!isValidPassword(newpwd)) {
			showErrorMessage(elId+"_errMsg",error_passwordIncorrectFormat);
			return false;
		}
		
		document.getElementById(formId)[elId].value=newpwd;
	}
	
	return true;
}

function validate_passwordMatch(elId,formId) {
	var newPwdId=elId+"_new";
	var newrepeatPwdId=elId+"_newrepeat";
	
	var newpwd=document.getElementById(formId)[newPwdId].value;
	var newrepeatpwd=document.getElementById(formId)[newrepeatPwdId].value;
	
	if (newpwd!=newrepeatpwd) {
		showErrorMessage(elId+"_errMsg",error_passwordsNoMatch);
		return false;
	}
	
	return true;
}

function validate_passwordFormat(elId,formId) {
	var newPwdId=elId+"_new";
	var newpwd=document.getElementById(formId)[newPwdId].value;
	
	if (!isVoid(newpwd)) {
		if (!isValidPassword(newpwd)) {
			showErrorMessage(elId+"_errMsg",error_passwordIncorrectFormat);
			return false;
		}
		
		document.getElementById(formId)[elId].value=newpwd;
	}
	
	return true;
}

var validators = new Array();

function validateForm(formName) {
	var success=true;

	// clearing fields first	
	for (var i=0; i<validators.length;i++) {
		if (validators[i].form==formName) {
			clearErrorMessage(validators[i].id+"_errMsg");
		}
	}
	
	var invalidFields=new Object();
	
	// executing validators
	for (var i = 0; i<validators.length;i++) {
		var vform=validators[i].form;
		var vtype=validators[i].type;
		var vid=validators[i].id;
		if (vform==formName && typeof(invalidFields[vid])=='undefined') {
			if (!eval("validate_"+vtype+"('"+vid+"','"+vform+"')")) {
				invalidFields[vid]='invalid';
				success=false;
			}
		}
	}
	
	return success;
}

function Validator(id,type,form) {
	this.id=id;
	this.type=type;
	this.form=form;
	return this;
}



var error_nonVoid="El campo no puede estar vacío.";
var error_email="El correo electrónico no es válido.";
var error_date="El formato de la fecha no es correcto (ej. 12-07-1975)";
var error_passwordsNoMatch="Las contraseñas introducidas no están coincidiendo.";
var error_passwordIncorrectFormat="La contraseña solo puede contener letras o números y ha de tener una longitud entre 4 y 15 carácteres.";
var error_number="El campo solo puede contener números.";

var confirm_imageRemove="La imagen seleccionada será eliminada. ¿Continuar?";
		
function changeStyle(obj,style) {
	obj.className=style;
}		

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}
  
function getX(obj){
    return obj.offsetLeft + (obj.offsetParent ? getX(obj.offsetParent) : obj.x ? obj.x : 0);
}

function getY(obj){
    return (obj.offsetParent ? obj.offsetTop + getY(obj.offsetParent) : obj.y ? obj.y : 0);
}
  

function openUrl(url) {
	if (url.indexOf('popup:')==0) {
		openPopupWindow(_cis_CONTEXT_PATH+url.substring(6,url.length));
	} else if (url.indexOf('javascript:')==0) {
		eval(url.substring(11,url.length));
	} else if (url.indexOf('http://')!=0 && url.indexOf('https://')!=0) {
		document.location.href=_cis_CONTEXT_PATH+url;
	} else {
		// it's an external url (let's open it in a new window)
		openWindow(url);
	}
}

function URLencode(sStr) {
    return escape(sStr)
       .replace(/\+/g, '%2B')
          .replace(/\"/g,'%22')
             .replace(/\'/g, '%27');
  }


function openWindow(url) {
	  var name="window_popup";
		var wtmp=window.open(url,name,'status=yes,scrollbars=yes,toolbar=yes,location=yes,resizable=yes');
		if (wtmp) {
			wtmp.focus();
		}
}

function openPopupWindow(url,winname,width,height) {
	  var name="window_popup2";
	  if (winname) name=winname;
	  
	  var dimension="";
	  if (width && height) dimension="width="+width+",height="+height+",";
	  
		var wtmp=window.open(url,name,dimension+'status=no,scrollbars=yes,toolbar=no,location=no,resizable=yes');
		
		if (wtmp) {
			wtmp.focus();
		}
		
		return wtmp;
}

function openFullscreenWindow(url) {
	  var name="window_popup3";
		var wtmp=window.open(url,name,'status=no,scrollbars=no,toolbar=no,location=no,resizable=no,fullscreen=yes');
		if (wtmp) {
			wtmp.focus();
		}
}

function openUniquePopupWindow(url) {
	  var name="win_"+new Date().getTime();
		var wtmp=window.open(url,name,'status=no,scrollbars=yes,toolbar=no,location=no,resizable=yes');
		if (wtmp) {
			wtmp.focus();
		}
}

function openWindowVideo(url) {
	  var name="video_popup";
	  var w=640, h=480;
	  var t=(screen.height/2 - 240);
	  var l=(screen.width/2 - 320);
	  
		var wtmp=window.open(url,name,'top='+t+',left='+l+',width='+w+',height='+h+',status=no,scrollbars=no,toolbar=no,location=no,resizable=no');
		if (wtmp) {
			wtmp.focus();
		}
		
		return wtmp;
}

function openVideo(video) {

}

function notaLegal() {
	  var url="nota_legal.html";
	  legalNote(url);
}

function legalNote(url) {
	  var name="legal";
	  var w=750, h=225;
	  var t=(screen.height/2 - 115);
	  var l=(screen.width/2 - 375);
	  
		var wtmp=window.open(url,name,'top='+t+',left='+l+',width='+w+',height='+h+',status=no,scrollbars=yes,toolbar=no,location=no,resizable=no');
		if (wtmp) {
			wtmp.focus();
		}
}

function alert1(x) { alert(acentos(x)); }

function confirm1(x) { confirm(acentos(x)); }

function acentos(x) {
	return x;
}


function swinttyWidgetDoLogin(formId, result) {
	document.getElementById(formId).submit();
	return result;
}

function swinttyShowLegal(result) {
	var width = 800, winWidth = $(window).width();
	var height = 600, winHeight = $(window).height();

	if(winWidth<width) width = winWidth-50;
	if(winHeight<height) height = winHeight-50;

	openDialog('Aviso legal','/dp/module/swintty/public/legal.void', width, height);
	if(result!='undefined')
		return result;
}


/*
 * DO NOT REMOVE THIS NOTICE
 *
 * PROJECT:   MyGosuMenu
 * VERSION:   1.5.5
 * COPYRIGHT: (c) 2003-2009 Cezary Tomczak
 * LINK:      http://www.gosu.pl/MyGosuMenu/
 * LICENSE:   BSD revised (free for any use)
 */

/*
  Todo, bugs to fix:
  - delay.show = 400 , delay.hide = 400
    go Product Three -> Live Demo -> Test Drive -> Test Three , go fast to Product Four.
    Result: 2 elements highlighted in the same section
  - delay.show = 0 , delay.hide = 400
    go Product Three -> Live Demo , section out , section over, seciont out.
    Result: Live Demo is not highlighted
  - active className changing, unnecessary blink
  - opera: hideSection() exceptions are throwed
*/

// 20090622 RST(conductiva): Added onResize
function DropMenuX(id) {

    /* Type of the menu: "horizontal" or "vertical" */
    this.type = "horizontal";

    /* Delay (in miliseconds >= 0): show-hide menu
     * Hide must be > 0 */
    this.delay = {
        "show": 0,
        "hide": 400
    }
    /* Change the default position of sub-menu by Y pixels from top and X pixels from left
     * Negative values are allowed */
    this.position = {
        "level1": { "top": 0, "left": 0},
        "levelX": { "top": 0, "left": 0}
    }

    /* fix ie selectbox bug ? */
    this.fixIeSelectBoxBug = true;

    /* Z-index property for .section */
    this.zIndex = {
        "visible": 500,
        "hidden": -1
    };

    // Browser detection
    this.browser = {
        "ie": Boolean(document.body.currentStyle),
        "ie5": (navigator.appVersion.indexOf("MSIE 5.5") != -1 || navigator.appVersion.indexOf("MSIE 5.0") != -1),
        "ie6": (navigator.appVersion.indexOf("MSIE 6.0") != -1)
    };

    if (!this.browser.ie) {
        this.browser.ie5 = false;
        this.browser.ie6 = false;
    }

    /* Initialize the menu */
    this.init = function() {
        if (!document.getElementById(this.id)) { return alert("DropMenuX.init() failed. Element '"+ this.id +"' does not exist."); }
        if (this.type != "horizontal" && this.type != "vertical") { return alert("DropMenuX.init() failed. Unknown menu type: '"+this.type+"'"); }
        if (this.browser.ie && this.browser.ie5) { fixWrap(); }
        fixSections();
        parse(document.getElementById(this.id).childNodes, this.tree, this.id);
    }
    
    this.onResize = function() {
    	parse(document.getElementById(this.id).childNodes, this.tree, this.id);
    }

    /* Search for .section elements and set width for them */
    function fixSections() {
        var arr = document.getElementById(self.id).getElementsByTagName("div");
        var sections = new Array();
        var widths = new Array();

        for (var i = 0; i < arr.length; i++) {
            if (arr[i].className == "section") {
                sections.push(arr[i]);
            }
        }
        for (var i = 0; i < sections.length; i++) {
            widths.push(getMaxWidth(sections[i].childNodes));
        }
        for (var i = 0; i < sections.length; i++) {
            sections[i].style.width = (widths[i]) + "px";
        }
        if (self.browser.ie) {
            for (var i = 0; i < sections.length; i++) {
                setMaxWidth(sections[i].childNodes, widths[i]);
            }
        }
    }

    function fixWrap() {
        var elements = document.getElementById(self.id).getElementsByTagName("a");
        for (var i = 0; i < elements.length; i++) {
            if (/item2/.test(elements[i].className)) {
                elements[i].innerHTML = '<div nowrap="nowrap">'+elements[i].innerHTML+'</div>';
            }
        }
    }

    /* Search for an element with highest width among given nodes, return that width */
    function getMaxWidth(nodes) {
        var maxWidth = 0;
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].nodeType != 1 || /section/.test(nodes[i].className)) { continue; }
            if (nodes[i].offsetWidth > maxWidth) { maxWidth = nodes[i].offsetWidth; }
        }
        return maxWidth;
    }

    /* Set width for item2 elements */
    function setMaxWidth(nodes, maxWidth) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].nodeType == 1 && /item2/.test(nodes[i].className) && nodes[i].currentStyle) {
                if (self.browser.ie5) {
                    nodes[i].style.width = (maxWidth) + "px";
                } else {
                    nodes[i].style.width = (maxWidth - parseInt(nodes[i].currentStyle.paddingLeft) - parseInt(nodes[i].currentStyle.paddingRight)) + "px";
                }
            }
        }
    }

    /* Parse nodes, create events, position elements */
    function parse(nodes, tree, id) {
        for (var i = 0; i < nodes.length; i++) {
            if (1 != nodes[i].nodeType) {
                continue;
            }
            switch (true) {
                // .item1
                case /\bitem1\b/.test(nodes[i].className):
                    nodes[i].id = id + "-" + tree.length;
                    tree.push(new Array());
                    nodes[i].onmouseover = itemOver;
                    nodes[i].onmouseout = itemOut;
                    break;
                // .item2
                case /\bitem2\b/.test(nodes[i].className):
                    nodes[i].id = id + "-" + tree.length;
                    tree.push(new Array());
                    nodes[i].onmouseover = itemOver;
                    nodes[i].onmouseout = itemOut;
                    break;
                // .section
                case /\bsection\b/.test(nodes[i].className):
                    // id, events
                    nodes[i].id = id + "-" + (tree.length - 1) + "-section";
                    nodes[i].onmouseover = sectionOver;
                    nodes[i].onmouseout = sectionOut;
                    // position
                    var box1 = document.getElementById(id + "-" + (tree.length - 1));
                    var box2 = document.getElementById(nodes[i].id);
                    var el = new Element(box1.id);
                    if (1 == el.level) {
                        if ("horizontal" == self.type) {
                            box2.style.top = box1.offsetTop + box1.offsetHeight + self.position.level1.top + "px";
                            if (self.browser.ie5) {
                                box2.style.left = self.position.level1.left + "px";
                            } else {
                                box2.style.left = box1.offsetLeft + self.position.level1.left + "px";
                            }
                        } else if ("vertical" == self.type) {
                            box2.style.top = box1.offsetTop + self.position.level1.top + "px";
                            if (self.browser.ie5) {
                                box2.style.left = box1.offsetWidth + self.position.level1.left + "px";
                            } else {
                                box2.style.left = box1.offsetLeft + box1.offsetWidth + self.position.level1.left + "px";
                            }
                        }
                    } else {
                        box2.style.top = box1.offsetTop + self.position.levelX.top + "px";
                        box2.style.left = box1.offsetLeft + box1.offsetWidth + self.position.levelX.left + "px";
                    }
                    // sections, sectionsShowCnt, sectionsHideCnt
                    self.sections.push(nodes[i].id);
                    self.sectionsShowCnt.push(0);
                    self.sectionsHideCnt.push(0);
                    if (self.fixIeSelectBoxBug && self.browser.ie6) {
                        nodes[i].innerHTML = nodes[i].innerHTML + '<iframe id="'+nodes[i].id+'-iframe" src="javascript:false;" scrolling="no" frameborder="0" style="position: absolute; top: 0px; left: 0px; display: none; filter:alpha(opacity=0);"></iframe>';
                    }
                    break;
            }
            if (nodes[i].childNodes) {
                if (/\bsection\b/.test(nodes[i].className)) {
                    parse(nodes[i].childNodes, tree[tree.length - 1], id + "-" + (tree.length - 1));
                } else {
                    parse(nodes[i].childNodes, tree, id);
                }
            }
        }
    }

    /* event, item:onmouseover */
    function itemOver() {
        //debug("itemOver("+this.id+") , visible = " + self.visible);
        self.itemShowCnt++;
        var id_section = this.id + "-section";
        if (self.visible.length) {
            var el = new Element(self.visible.getLast());
            el = document.getElementById(el.getParent().id);
            if (/item\d-active/.test(el.className)) {
                el.className = el.className.replace(/(item\d)-active/, "$1");
            }
        }
        if (self.sections.contains(id_section)) {
            clearTimers();
            self.sectionsHideCnt[self.sections.indexOf(id_section)]++;
            var cnt = self.sectionsShowCnt[self.sections.indexOf(id_section)];
            var timerId = setTimeout(function(a, b) { return function() { self.showSection(a, b); } } (id_section, cnt), self.delay.show);
            self.timers.push(timerId);
        } else {
            if (self.visible.length) {
                clearTimers();
                var timerId = setTimeout(function(a, b) { return function() { self.showItem(a, b); } } (this.id, self.itemShowCnt), self.delay.show);
                self.timers.push(timerId);
            }
        }
    }

    /* event, item:onmouseout */
    function itemOut() {
        //debug("itemOut("+this.id+") , visible = " + self.visible);
        self.itemShowCnt++;
        var id_section = this.id + "-section";
        if (self.sections.contains(id_section)) {
            self.sectionsShowCnt[self.sections.indexOf(id_section)]++;
            if (self.visible.contains(id_section)) {
                var cnt = self.sectionsHideCnt[self.sections.indexOf(id_section)];
                var timerId = setTimeout(function(a, b) { return function() { self.hideSection(a, b); } }(id_section, cnt), self.delay.hide);
                self.timers.push(timerId);
            }
        }
    }

    /* event, section:onmouseover */
    function sectionOver() {
        //debug("sectionOver("+this.id+") , visible = " + self.visible);
        self.sectionsHideCnt[self.sections.indexOf(this.id)]++;
        var el = new Element(this.id);
        var parent = document.getElementById(el.getParent().id);
        if (!/item\d-active/.test(parent.className)) {
            parent.className = parent.className.replace(/(item\d)/, "$1-active");
        }
    }

    /* event, section:onmouseout */
    function sectionOut() {
        //debug("sectionOut("+this.id+") , visible = " + self.visible);
        self.sectionsShowCnt[self.sections.indexOf(this.id)]++;
        var cnt = self.sectionsHideCnt[self.sections.indexOf(this.id)];
        var timerId = setTimeout(function(a, b) { return function() { self.hideSection(a, b); } }(this.id, cnt), self.delay.hide);
        self.timers.push(timerId);
    }

    /* Show section (1 argument passed)
     * Try to show section (2 arguments passed) - check cnt with sectionShowCnt */
    this.showSection = function(id, cnt) {
        if (typeof cnt != "undefined") {
            if (cnt != this.sectionsShowCnt[this.sections.indexOf(id)]) { return; }
        }
        //debug("showSection("+id+", "+cnt+") , visible = " + this.visible);
        this.sectionsShowCnt[this.sections.indexOf(id)]++;
        if (this.visible.length) {
            if (id == this.visible.getLast()) { return; }
            var el = new Element(id);
            var parents = el.getParentSections();
            //debug("getParentSections("+el.id+") = " + parents);
            for (var i = this.visible.length - 1; i >= 0; i--) {
                if (parents.contains(this.visible[i])) {
                    break;
                } else {
                    this.hideSection(this.visible[i]);
                }
            }
        }
        var el = new Element(id);
        var parent = document.getElementById(el.getParent().id);
        if (!/item\d-active/.test(parent.className)) {
            parent.className = parent.className.replace(/(item\d)/, "$1-active");
        }
        if (document.all) { document.getElementById(id).style.display = "block"; }
        document.getElementById(id).style.visibility = "visible";
        document.getElementById(id).style.zIndex = this.zIndex.visible;
        if (this.fixIeSelectBoxBug && this.browser.ie6) {
            var div = document.getElementById(id);
            var iframe = document.getElementById(id+"-iframe");
            iframe.style.width = div.offsetWidth + parseInt(div.currentStyle.borderLeftWidth) + parseInt(div.currentStyle.borderRightWidth);
            iframe.style.height = div.offsetHeight + parseInt(div.currentStyle.borderTopWidth) + parseInt(div.currentStyle.borderBottomWidth);
            iframe.style.top = -parseInt(div.currentStyle.borderTopWidth);
            iframe.style.left = -parseInt(div.currentStyle.borderLeftWidth);
            iframe.style.zIndex = div.style.zIndex - 1;
            iframe.style.display = "block";
        }
        this.visible.push(id);
    }

    /* Emulating an empty non-existent section, we have to hide elements, works like showSection() */
    this.showItem = function(id, cnt) {
        if (typeof cnt != "undefined") {
            if (cnt != this.itemShowCnt) { return; }
        }
        this.itemShowCnt++;
        if (this.visible.length) {
            var el = new Element(id + "-section");
            var parents = el.getParentSections();
            //debug("showItem() getParentSections("+el.id+") = " + parents);
            for (var i = this.visible.length - 1; i >= 0; i--) {
                if (parents.contains(this.visible[i])) {
                    break;
                } else {
                    this.hideSection(this.visible[i]);
                }
            }
        }
    }

    /* Hide section (1 argument passed)
     * Try to hide section (2 arguments passed) - check cnt with sectionHideCnt */
    this.hideSection = function(id, cnt) {
        if (typeof cnt != "undefined") {
            if (cnt != this.sectionsHideCnt[this.sections.indexOf(id)]) { return; }
            if (id == this.visible.getLast()) {
                //debug("hideSectionAll("+id+", "+cnt+") , visible = " + this.visible);
                for (var i = this.visible.length - 1; i >= 0; i--) {
                    this.hideSection(this.visible[i]);
                }
                return;
            }
        }
        //debug("hideSection("+id+", "+cnt+") , visible = " + this.visible);
        var el = new Element(id);
        var parent = document.getElementById(el.getParent().id);
        if (/item\d-active/.test(parent.className)) {
            parent.className = parent.className.replace(/(item\d)-active/, "$1");
        }
        document.getElementById(id).style.zIndex = this.zIndex.hidden;
        document.getElementById(id).style.visibility = "hidden";
        if (document.all) { document.getElementById(id).style.display = "none"; }
        if (this.fixIeSelectBoxBug && this.browser.ie6) {
            var iframe = document.getElementById(id+"-iframe");
            iframe.style.display = "none";
        }
        if (this.visible.contains(id)) {
            if (id == this.visible.getLast()) {
                this.visible.pop();
            } else {
                //throw "DropMenuX.hideSection('"+id+"', "+cnt+") failed, trying to hide a section that is not the deepest visible section";
                return;
            }
        } else {
            //throw "DropMenuX.hideSection('"+id+"', "+cnt+") failed, cannot hide element that is not visible";
            return;
        }
        this.sectionsHideCnt[this.sections.indexOf(id)]++;
    }

    /* Element (.section, .item2 etc) */
    function Element(id) {

        this.menu = self;
        this.id = id;

        /* Get Level of given id
         * Examples: menu-1 (1 level), menu-1-4 (2 level) */
        this.getLevel = function() {
            var s = this.id.substr(this.menu.id.length);
            return s.substrCount("-");
        }

        /* Get parent Element */
        this.getParent = function() {
            var s = this.id.substr(this.menu.id.length);
            var a = s.split("-");
            a.pop();
            return new Element(this.menu.id + a.join("-"));
        }

        /* Check whether an element has a parent element */
        this.hasParent = function() {
            var s = this.id.substr(this.menu.id.length);
            var a = s.split("-");
            return a.length > 2;
        }

        /* Check whether an element has a sub-section */
        this.hasChilds = function() {
            return Boolean(document.getElementById(this.id + "-section"));
        }

        /* Get parent section elements for current section */
        this.getParentSections = function() {
            var s = this.id.substr(this.menu.id.length);
            s = s.substr(0, s.length - "-section".length);
            var a = s.split("-");
            a.shift();
            a.pop();
            var s = this.menu.id;
            var parents = [];
            for (var i = 0; i < a.length; i++) {
                s += ("-" + a[i]);
                parents.push(s + "-section");
            }
            return parents;
        }

        this.level = this.getLevel();
    }

    /* Clear all timers set with setTimeout() */
    function clearTimers() {
        for (var i = self.timers.length - 1; i >= 0; i--) {
            clearTimeout(self.timers[i]);
            self.timers.pop();
        }
    }

    var self = this;
    this.id = id; /* menu id */
    this.tree = []; /* tree structure of menu */
    this.sections = []; /* all sections, required for timeout */
    this.sectionsShowCnt = [];
    this.sectionsHideCnt = [];
    this.itemShowCnt = 0;
    this.timers = []; // timeout ids
    this.visible = []; /* visible section, ex. Array("menu-0-section", ..) , succession is important: top to bottom */
}

/* Finds the index of the first occurence of item in the array, or -1 if not found */
if (typeof Array.prototype.indexOf == "undefined") {
    Array.prototype.indexOf = function(item) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === item) {
                return i;
            }
        }
        return -1;
    }
}

/* Check whether array contains given string */
if (typeof Array.prototype.contains == "undefined") {
    Array.prototype.contains = function(s) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === s) {
                return true;
            }
        }
        return false;
    }
}

/* Counts the number of substring occurrences */
if (typeof String.prototype.substrCount == "undefined") {
    String.prototype.substrCount = function(s) {
        return this.split(s).length - 1;
    }
}

/* Get the last element from the array */
if (typeof Array.prototype.getLast == "undefined") {
    Array.prototype.getLast = function() {
        return this[this.length-1];
    }
}


