

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?_=1283310338599");
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.theme.css?_=1283310338599");
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.dialog.css?_=1283310338599");
	cis.loadJs("/cis/lib/jquery-ui-1.7.2/ui.core.min.js?_=1283310338599");
	if(navigator.userAgent.indexOf("MSIE 6")>=0)
		cis.loadJs("/cis/lib/jquery-1.3.2/bgiframe/jquery.bgiframe.min.js?_=1283310338599");
	cis.loadJs("/cis/lib/jquery-ui-1.7.2/ui.dialog.min.js?_=1283310338599", 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 _cisLoadAlerts(callback) {
	cis.loadCss('/cis/lib/jquery-1.3.2/themes/conductiva/alerts/jquery.alerts.css?_=1283310338599');
	cis.loadJs("/cis/lib/jquery-1.3.2/alerts/jquery.alerts.min.js?_=1283310338599", 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 = "1283310338599";

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;
}




/*
 * jQuery validation plug-in 1.6
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}var validator=$.data(this[0],'validator');if(validator){return validator;}validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});if(validator.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){validator.submitButton=this;});}this.submit(function(event){if(validator.settings.debug)event.preventDefault();function handle(){if(validator.settings.submitHandler){if(validator.submitButton){var hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);}validator.settings.submitHandler.call(validator,validator.currentForm);if(validator.submitButton){hidden.remove();}return false;}return true;}if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}return handle();}else{validator.focusInvalid();return false;}});}return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=true;var validator=$(this[0].form).validate();this.each(function(){valid&=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}return data;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(""+a.value);},filled:function(a){return!!$.trim(""+a.value);},unchecked:function(a){return!a.checked;}});$.validator=function(options,form){this.settings=$.extend({},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length==1)return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.format.apply(this,args);};if(arguments.length>2&&params.constructor!=Array){params=$.makeArray(arguments).slice(1);}if(params.constructor!=Array){params=[params];}$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass,this.settings.validClass);this.errorsFor(element).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)this.element(element);else if(element.parentNode.name in this.submitted)this.element(element.parentNode)},highlight:function(element,errorClass,validClass){$(element).addClass(errorClass).removeClass(validClass);},unhighlight:function(element,errorClass,validClass){$(element).removeClass(errorClass).addClass(validClass);}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator");validator.settings["on"+event.type]&&validator.settings["on"+event.type].call(validator,this[0]);}$(this.currentForm).delegate("focusin focusout keyup",":text, :password, :file, select, textarea",delegate).delegate("click",":radio, :checkbox, select, option",delegate);if(this.settings.invalidHandler)$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())$(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);}this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus();}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name)[0];}var rules=$(element).rules();var dependencyMismatch=false;for(method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,element.value.replace(/\r/g,""),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method",e);throw e;}}if(dependencyMismatch)return;if(this.objectLength(rules))this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta&&meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)return arguments[i];}return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method),theregex=/\$?\{(\d+)\}/g;if(typeof message=="function"){message=message.call(this,rule.parameters,element);}else if(theregex.test(message)){message=jQuery.format(message.replace(theregex,'{$1}'),rule.parameters);}this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)toToggle=toToggle.add(toToggle.parent(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass,this.settings.validClass);this.showLabel(error.element,error.message);}if(this.errorList.length){this.toShow=this.toShow.add(this.containers);}if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,this.settings.validClass);}}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();}if(!this.labelContainer.append(label).length)this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}this.toShow=this.toShow.add(label);},errorsFor:function(element){var name=this.idOrName(element);return this.errors().filter(function(){return $(this).attr('for')==name});},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return/radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))return this.findByName(element.name).filter(':checked').length;}return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();this.formSubmitted=false;}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false;}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",{old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}if(rules.messages){delete rules.messages}return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message!=undefined?message:$.validator.messages[name];if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var val=$(element).val();return val&&val.length>0;case'input':if(this.checkable(element))return this.getLength(value,element)>0;default:return $.trim(value).length>0;}},remote:function(value,element,param){if(this.optional(element))return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])this.settings.messages[element.name]={};previous.originalMessage=this.settings.messages[element.name].remote;this.settings.messages[element.name].remote=previous.message;param=typeof param=="string"&&{url:param}||param;if(previous.old!==value){previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){validator.settings.messages[element.name].remote=previous.originalMessage;var valid=response===true;if(valid){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};var message=(previous.message=response||validator.defaultMessage(element,"remote"));errors[element.name]=$.isFunction(message)?message(value):message;validator.showErrors(errors);}previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";}else if(this.pending[element.name]){return"pending";}return previous.valid;},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(value),element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))return"dependency-mismatch";if(/[^0-9-]+/.test(value))return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(var n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)nDigit-=9;}nCheck+=nDigit;bEven=!bEven;}return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param.replace(/,/g,'|'):"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){var target=$(param).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){$(element).valid();});return value==target.val();}}});$.format=$.validator.format;})(jQuery);;(function($){var ajax=$.ajax;var pendingRequests={};$.ajax=function(settings){settings=$.extend(settings,$.extend({},$.ajaxSettings,settings));var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}return(pendingRequests[port]=ajax.apply(this,arguments));}return ajax.apply(this,arguments);};})(jQuery);;(function($){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){if($.browser.msie)return false;this.addEventListener(original,$.event.special[fix].handler,true);},teardown:function(){if($.browser.msie)return false;this.removeEventListener(original,$.event.special[fix].handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};});$.extend($.fn,{delegate:function(type,delegate,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});},triggerEvent:function(type,target){return this.triggerHandler(type,[$.event.fix({type:type,target:target})]);}})})(jQuery);
cis.setJsLoaded('/cis/lib/jquery-1.3.2/validate/jquery.validate.min.js?_=1283310338599');
// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;OK&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;Cancel&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);
cis.setJsLoaded('/cis/lib/jquery-1.3.2/alerts/jquery.alerts.min.js?_=1283310338599');
/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);
cis.setJsLoaded('/cis/lib/jquery-1.3.2/tooltip/jquery.tooltip.min.js?_=1283310338599');





function lsAjaxJSON(url, settings) {
	settings = $.extend({},
			{
				lsDialogTitle : 'Conductiva',
				lsDialogOkMessage : '',
				lsOnSuccessHandler : function(obj) {},
				lsOnBeforeSend : function() {return true},
				lsOnAfterResponse : function(obj) {}, 
				error: function(e) {
					var message = "";
					message = message + "<b>Tipo</b>: " + e.type + "<br>";
					message = message + "<b>Mensaje</b>: " + e.message + "<br>";
					if(e.error)
						message = message + "<b>Error</b>: " + e.error + "<br>";
					cisAlert(message, this.lsDialogTitle);
				},
				objectResponse: function(obj) {
					if(obj.error) {
						cisAlert(obj.error, this.lsDialogTitle);
					} else if(obj.result==true){
						if(this.lsDialogOkMessage && this.lsDialogOkMessage!='')
							cisAlert(this.lsDialogOkMessage, this.lsDialogTitle, this.lsOnSuccessHandler, obj);
						else
							this.lsOnSuccessHandler(obj);
					} else {
						cisAlert('No se pudo completar la operación por un error indeterminado', this.lsDialogTitle);
					}
				}
			}, settings);

	settings.beforeSend = settings.lsOnBeforeSend;
	settings.afterResponse = settings.lsOnAfterResponse;
	cisAjaxJSON(url, settings);
}
function lsAjaxSubmit(jform, settings) {
	
	settings = $.extend({},
			{
				lsDialogTitle : 'Conductiva',
				lsDialogOkMessage : '',
				lsOnSuccessHandler : function(obj) {},
				lsOnBeforeSubmit : function(jform) {return true},
				lsOnAfterResponse : function(obj) {}, 
				error: function(e) {
					var message = "";
					message = message + "<b>Tipo</b>: " + e.type + "<br>";
					message = message + "<b>Mensaje</b>: " + e.message + "<br>";
					if(e.error)
						message = message + "<b>Error</b>: " + e.error + "<br>";
					cisAlert(message, this.lsDialogTitle);
				},
				objectResponse: function(obj) {
					if(obj.error) {
						cisAlert(obj.error, this.lsDialogTitle);
					} else if(obj.result==true){
						if(this.lsDialogOkMessage && this.lsDialogOkMessage!='')
							cisAlert(this.lsDialogOkMessage, this.lsDialogTitle, this.lsOnSuccessHandler, obj);
						else
							this.lsOnSuccessHandler(obj);
					} else {
						cisAlert('No se pudo completar la operación por un error indeterminado', this.lsDialogTitle);
					}
				}
			}, settings);
	
	settings.beforeSubmit = settings.lsOnBeforeSubmit;
	settings.afterResponse = settings.lsOnAfterResponse;
	cisAjaxSubmit(jform, settings);
}

function lsLoadPage(url) {
	document.location = url;
}

var __USE_GENERIC_LOADING__ = true;

$().ajaxSend(function(r,s){
	if(__USE_GENERIC_LOADING__)
		$("#contentLoading").show();
});

$().ajaxStop(function(r,s){
	if(__USE_GENERIC_LOADING__)
		$("#contentLoading").fadeOut("fast");
});

function invalidateGenericLoading() {
	__USE_GENERIC_LOADING__ = false;
}

var __FLASH_MESSAGE_COUNT__ = 0;

function addFlashMessage(msg, options) {
	__FLASH_MESSAGE_COUNT__++;
	options = $.extend({}, {type : 'info'}, options);
	
	var html = options.showCloseButton ? 
			  "<div class='" + options.type + " jqSelFlashMessage' id='flashMessage_"+__FLASH_MESSAGE_COUNT__+"'>"+msg+"<div class='close'><a href='javascript:closeFlashMessage(\""+__FLASH_MESSAGE_COUNT__+"\");'>&nbsp;</a></div></div>"
			: "<div class='" + options.type + " jqSelFlashMessage' id='flashMessage_"+__FLASH_MESSAGE_COUNT__+"'>"+msg+"</div>";
				
	$("#flash").show().append(html);
	return __FLASH_MESSAGE_COUNT__;
}

function addFlashInfo(msg,options){
	options = $.extend({}, options, { type : "info"});
	return addFlashMessage(msg, options);
}

function addFlashError(msg,options){
	options = $.extend({}, options, { type : "error"});
	return addFlashMessage(msg, options);
}

function closeFlashMessage(id) {
	$("#flashMessage_"+id).hide().remove();
}
function closeAllFlashMessages() {
	$("#flash .jqSelFlashMessage").hide().remove();
}
function ajaxTableSessionExpired() {
	addFlashError('Tu sesión ha caducado, tendrás que <a href="/">volver a identificarte</a> para continuar');
}

function getAnchorIdFromLocation(anchorNames) {
	var index = -1;
	try {
		var currentLocation = document.location.toString();
		if (currentLocation.match('#')) {
			var anchor = currentLocation.split('#')[1];
			for(var i=0;i<anchorNames.length;i++) {
				if(anchorNames[i]==anchor) {
					index = i;
					break;
				}
			}
			if(index==-1) {
				var candidateId = parseInt(anchor);
				if(!isNaN(candidateId)) {
					if(candidateId>=0 && candidateId<anchorNames.length)
						index = candidateId;
				}
			}
		}
	}catch(e) {
		if(console && console.info)
			console.info("Error determining tab name: " + e);
	}
	if(index==-1)
		index = 0;
	return index;
};

function lsFormat(source, params) {
	if ( arguments.length == 1 ) 
		return function() {
			var args = jQuery.makeArray(arguments);
			args.unshift(source);
			return lsFormat.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = jQuery.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	jQuery.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};



