

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?_=1283977947035");
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.theme.css?_=1283977947035");
	cis.loadCss("/cis/lib/jquery-ui-1.7.2/themes/conductiva/ui.dialog.css?_=1283977947035");
	cis.loadJs("/cis/lib/jquery-ui-1.7.2/ui.core.min.js?_=1283977947035");
	if(navigator.userAgent.indexOf("MSIE 6")>=0)
		cis.loadJs("/cis/lib/jquery-1.3.2/bgiframe/jquery.bgiframe.min.js?_=1283977947035");
	cis.loadJs("/cis/lib/jquery-ui-1.7.2/ui.dialog.min.js?_=1283977947035", 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?_=1283977947035');
	cis.loadJs("/cis/lib/jquery-1.3.2/alerts/jquery.alerts.min.js?_=1283977947035", function(){
		$.alerts.okButton = '&nbsp;OK&nbsp;';
		$.alerts.cancelButton = '&nbsp;Cancel&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)},
			htmlResponse: false, 
			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(settings.htmlResponse || 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 = settings.htmlResponse ? html : (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( settings.htmlResponse ? js : {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($) {

	var isDisabled = function(element) {
		return element.attr("disabled");
	};

	var enableAction = function(element, opts) {
		element.removeAttr("disabled");
		element.attr("value", element.attr("originalLabel"));
		element.css("width", "auto");
	};

	var disableAction = function(element, opts) {

		var disabled = isDisabled(element);

		if (!disabled) {
			var disabledLabel = element.attr("disabledLabel");
			if (!disabledLabel) {
				disabledLabel = "... please, wait ...";
			}

			element.attr("originalLabel", element.val());
			element.css("width", (element.width()) + "px");
			element.attr("disabled", "true");
			element.attr("value", disabledLabel);
		} else {
			element.attr("disabled", "true");
		}
	};

	$.fn.clickSafe = function(opts) {
		var options = $.extend({}, opts);

		if (opts.disabledLabel) {
			this.attr("disabledLabel", opts.disabledLabel);
		}

		if (opts == 'enable') {
			enableAction(this, opts);
		} else if (opts == 'disable') {
			disableAction(this, opts);
		}

	};

})(jQuery);

function isValidSpanishTaxNumber(nif) {
	var cifLetters = "ABCDEFGHJKLMNPQRSUVW";
	
	if(nif=='') 
		return true;
	
	var controlIsLetter, controlIsNumber, isNIE, isNIF;
	
	var _validateCIF = function(nif, controlNumber) {
		if(nif.length!=9)
			return false;
		
		var sumDigitsHelper = new Array(0,2,4,6,8,1,3,5,7,9);
	
		var temp = 0;
		for(var i=2; i<=6; i+=2) {
			temp = temp + sumDigitsHelper[ parseInt(nif.substr(i-1,1)) ];
			temp = temp + parseInt(nif.substr(i,1));
		}
		temp = temp + sumDigitsHelper[ parseInt(nif.substr(7,1)) ];
		temp = (10 - ( temp % 10)) % 10;
		
		var control = controlNumber ? temp : "ABCDEFGHIJ".charAt(temp);
		
		return control==nif.substring(8,9);
	};
	var _validateNIF = function(nif, isNIE) {
		if(isNIE) {
			if(nif.length!=9)
				return false;
			
			var c0 = nif.charAt(0);
			switch(c0) {
			case 'X': nif = nif.substring(1); break;
			case 'Y': nif = '1' + nif.substring(1); break;
			case 'Z': nif = '2' + nif.substring(1); break;
			default: return false;
			}
		} else {
			if(nif.length>9)
				return false;
		}
		var num = parseInt(nif.substring(0, nif.length-1));
		var control = nif.substring(nif.length-1, nif.length);
		return control == "TRWAGMYFPDXBNJZSQVHLCKET".charAt(num % 23);
	};
	
	nif = nif.toUpperCase();
	var c0 = nif.charAt(0);
	var isCIF = false;
	switch(c0) {
	case 'A':case 'B':case 'D':case 'E':case 'F':case 'G':case 'H':case 'J':case 'U':case 'V':
		return _validateCIF(nif, true);
		break;
	case 'C':case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R':case 'S':case 'W':
		return _validateCIF(nif, false);
		break;
	case 'X':case 'Y':case 'Z':
		return _validateNIF(nif, true);
		break;
	default:
		return _validateNIF(nif, false);
	}
	
}

$.fn.popup = function(opts) {

	var options = $.extend({}, opts);

	function clickHandler(e) {
		// si el usuario ha utilizado una tecla de control
		// no hacemos nada
		if (e.ctrlKey || e.shiftKey || e.metaKey)
			return;

		// abrimos la ventana
		var w = window.open(this.href, options.name,'width='+options.width+',height='+options.height+',toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no');
//		window.open(this.href, 'feedback', 'width=715,height=500,toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no');
		if (w && !w.closed) {
			// si efectivamente hemos logrado abrirla
			// la ponemos en foco
			w.focus();
			// y cancelamos el comportamiento por defecto
			// del enlace
			e.preventDefault();
		}
	}

	this
		.filter('a[@href]') // que no se nos cuele algo que no sea un enlace
		.bind('click', clickHandler);

	return this; // permitimos concatenabilidad

}

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="en";

var	_editor_url = "/cis/lib/flasharea/";// path to FlashArea 
var	_textarearich_url = "/cis/lib/textarearich/";// path to FlashArea 

var __cisAppVersionId = "1283977947035";

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="Field cannot be void.";
var error_email="Email is not valid.";
var error_date="Invalid date format (ex. 12-07-1975)";
var error_passwordsNoMatch="Passwords do not match.";
var error_passwordIncorrectFormat="Password can only contain letters and numbers and must have a char length between 4 and 15 characters.";
var error_number="Field can only contain numbers.";

var confirm_imageRemove="Selected image will be removed. Continue?";
		
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;
}

