var dynamicComboObjects = new Object();

function DynamicCombo(index, prefix, target,  mandatoryAware, isOther, isPosting ) {
	var VAL_OCULTO = 4;
	var VAL_ESPERA = 2;
	var VAL_CREADO = 1;
	var VAL_NUEVO = 0;
	var prefix;
	var target;
	var mandatory;
	var mandatoryAware;
	var div;
	this.isOther = (isOther == true);
	this.index = index;
	this.prefix = prefix;
	this.target = target;
	this.mandatoryAware = mandatoryAware;
	this.state = VAL_NUEVO;
}

DynamicCombo.prototype.createDiv = function(id, className) {
	var col = document.createElement('div');
	col.className = className;
	if (id != '') { 
		col.id = id;
	}
	return col;
}

DynamicCombo.prototype.isLeaf = function() { 
	return this.leaf;
}

DynamicCombo.prototype.readData = function(sResult, oParam )
{
	var oTarget = oParam.target;
	var oXml = sResult;
	var sItems = oParam.tagItems;
	var sItem = oParam.tagItem;
	
	if ( oXml == null ) {
		removeChildsCombo(oTarget.getPrefix(), oTarget.getIndex() + 1, oTarget.isLeaf());
		return;
	}
	
	var oItems = oXml.getElementsByTagName(sItems);
	
	if ( oItems == null ||  oItems[0] == null )  {
		return;
	}
	var category = oItems[0].getAttribute('categoryLabel');
	var mandatory = oItems[0].getAttribute('mandatory');
	var leaf = oItems[0].getAttribute('leaf');
	var isOther = oItems[0].getAttribute('other');
	
	if( ! (category != null && category != '') ) {
		return;
	}

	oTarget.createPlaceHolder(category, mandatory);
	oTarget.leaf = !(leaf == false || "false" == leaf);
	oTarget.mandatory = !(mandatory == false || "false" == mandatory);

	var oCombo; /* creo el combo o el text y lo agrego al div*/ 
	if  ( "true" == isOther || isOther == true  ) {
		oCombo = oTarget.createOther(category, mandatory);
	} else {
		oCombo = oTarget.createCombo(category, mandatory);

		oCombo.onchange = null;		

		oCombo.name = oTarget.getPrefix() + '_sel_' + oTarget.getIndex();
		oCombo.id = oTarget.getPrefix()  + '_sel_' + oTarget.getIndex();
		oCombo.setAttribute('mandatory', oTarget.getMandatory() );
		oCombo.setAttribute('prefix', oTarget.getPrefix() );
		oCombo.setAttribute('index', oTarget.getIndex() );
		oCombo.setAttribute('label', category);
		oCombo.className = dynamicComboConfig.selectClassName;

		var oNodos = oXml.getElementsByTagName(sItem);
		var x=0;
		for(x = 0; x < oNodos.length; x++ )
		{
			var oNodo = oNodos[x];
			var oItem = document.createElement("option");
			oItem.text = oNodo.getAttribute("name");
			var selected = oNodo.getAttribute('selected');
			oItem.value = parseInt(oNodo.getAttribute("id"));
			oItem.setAttribute('other', oNodo.getAttribute('other'));
			oItem.setAttribute('leaf', oNodo.getAttribute('leaf'));
			oCombo.options.add(oItem);

			//selecciono opcion.
			if ( selected && "true" == selected.toLowerCase() ) {
				oCombo.selectedIndex = x;
			}
		}
		
		/*FIXME @aobara: Se que es medio grasa, pero como el hermoso IE no soporta baseURI para recibir por querystring el origen del xml,
		 * voy a buscar el botón que sólo está en Posting. Debería hacerser de alguna otra forma, por ejemplo pasarlo al controller
		 * y que en el xml de respuesta le agregue un tag con el origen*/
		var btn = document.getElementById('botonVerMapa');
		oCombo.onchange = function() {
			
			if (btn != null){
				showHideMap(false);
			}
			onDinCombo(  this.options[this.selectedIndex].getAttribute('leaf'), this.getAttribute('prefix'),  this.getAttribute('index'), this.value, this.options[this.selectedIndex].getAttribute("other"), this.getAttribute("label"), false,true );
		};
	}
	return;
}

DynamicCombo.prototype.getMandatory = function() {
	return this.mandatory;
}


DynamicCombo.prototype.getIndex = function() {
	return this.index;
}

DynamicCombo.prototype.getPrefix = function() { 
	return this.prefix;
}

DynamicCombo.prototype.getApplyMandatory = function () {
	return this.mandatoryAware == true || "true" == this.mandatoryAware;
}

DynamicCombo.prototype.getColA = function () {
	if ( this.colA == null) { 
		this.colA = document.getElementById(this.getPrefix() + dynamicComboConfig.containerA + this.getIndex());
	}
	return this.colA;
}

DynamicCombo.prototype.getColB = function () {
	if ( this.colB == null) { 
		this.colB = document.getElementById(this.getPrefix() + dynamicComboConfig.containerB + this.getIndex());
	}
	return this.colB;
}

DynamicCombo.prototype.createPlaceHolder = function(label, mandatory) {
	if ( this.getDiv() == null ) {
		this.div = this.createDiv(this.getPrefix() + dynamicComboConfig.container + this.getIndex(), dynamicComboConfig.rowClassName );
		this.colA = this.createDiv(this.getPrefix() + dynamicComboConfig.containerA + this.getIndex(), dynamicComboConfig.leftClassName);
		this.colB = this.createDiv(this.getPrefix() + dynamicComboConfig.containerB + this.getIndex(), dynamicComboConfig.rightClassName);
		this.div.appendChild(this.colA);
		this.div.appendChild(this.colB);
		
		var divFix = this.createDiv('', 'fix3');
		this.div.appendChild(divFix);
		
		var id2 = this.getPrefix() + dynamicComboConfig.mainComboContainer;
		document.getElementById(id2).appendChild(this.div);
	} 
	
	this.getDiv().style.display="block";
	if (dynamicComboConfig.dynamicLabels) {
		this.appendLabel(this.getColA(),  ( mandatory == 'true' || mandatory == true ), label);
	}
	
}

DynamicCombo.prototype.appendLabel = function (colA, mandatory, category ) {
	var label;
	this.getColA().innerHTML = "";

	if( mandatory && this.getApplyMandatory()) {
		label = document.createElement("span");  
		label.innerHTML = "* ";	
		label.className = dynamicComboConfig.mandatoryClassName;
		this.getColA().appendChild(label);
	} 
	label = document.createTextNode(category + ':');
	this.getColA().appendChild(label);
}

DynamicCombo.prototype.mkParam = function(values) { 
	var ret =""; /* esto esta bien*/
	for ( var i in values ) {  
		if ( ret != "" ) {
			ret = ret + "&";
		}
		ret = ret + (i + "=" + values[i]); 
	}
	return ret;
}

DynamicCombo.prototype.getChild = function () {
	if ( this.child == null ) {
		var id; 
		if ( this.isOther == false ) {  
			id = this.getPrefix() + '_sel_' + this.getIndex();
		} else {
			if (isFiscalOther(this.prefix)){
				id = dynamicComboConfig.otherFId;
			}else{
				id = dynamicComboConfig.otherId;
			}
		}
		this.child = document.getElementById( id );
	}
	return this.child;
}

DynamicCombo.prototype.getDiv = function () {
	if ( this.div == null ) { 
		var id = this.getPrefix() + dynamicComboConfig.container + this.getIndex();
		this.div = document.getElementById(id);
	}
	return this.div;
}

DynamicCombo.prototype.drawOther = function ( other ) {
	
	var mandatory = this.getApplyMandatory();
	this.createPlaceHolder(other, mandatory);
	this.createOther(other, mandatory);
}

DynamicCombo.prototype.hide = function( flag ) {

	var child = this.getChild();
	
	if ( child == null ) {
		return;
	}
	
	if ( child.selectedIndex != null ) { 
		child.selectedIndex = 0;
	}

	child.disabled = true;
	
	if ( flag ) {
		var div = this.getDiv();
		div.style.display = "none";
	} 
}

DynamicCombo.prototype.draw = function (context) {
	var oParam ={
		target: this,
		tagItems:'Items',
		tagItem:'Item'
	};
	var oXml = new HTMLHttpRequest(this.readData,oParam);
	var url	= "locationChannel.xml";

	if ( dynamicComboConfig.locationChannelURL != null )  {
		url = dynamicComboConfig.locationChannelURL;
	}

	var sURL = url + '?' + this.mkParam(context);
	oXml.loadXML(sURL);	
}


function removeChildsCombo(prefix, index, flag ) {
	while ( dynamicComboObjects[prefix + index] ) { 
		dynamicComboObjects[prefix + (index )].hide(flag);
		index ++;
	} 
}

function dispatchBranch(isLeaf, prefix, index, value, context, other, flag ){ 
	nextInt = parseInt(index) + 1;
	// remove all childs ...
	
	if ( dynamicComboObjects[prefix + nextInt] == null ) { 
		dynamicComboObjects[prefix + nextInt] = new DynamicCombo(nextInt, prefix, value, dynamicComboConfig.applyMandatory);
	}

	removeChildsCombo(prefix, flag ? nextInt  + 1: nextInt , true);
	dynamicComboObjects[prefix + nextInt].draw(context);
	refreshLocationChannelId(prefix, index, value);
	
}
         
function dispatchLeaf(isLeaf, prefix, index, value, context, other, label, flag ) { 
	removeAndUpdate(prefix, flag ? index  + 1: index, value, other, label );
	
	if  ( ! ( other == true || other == "true" ) ) {
		return; 
	}
	if ( dynamicComboObjects[prefix + fxd_index] == null ) {
		dynamicComboObjects[prefix + fxd_index] = new DynamicCombo(fxd_index, prefix, selectedValue, dynamicComboConfig.applyMandatory);
	}
	dynamicComboObjects[prefix + fxd_index].hide();
	dynamicComboObjects[prefix + fxd_index].drawOther(dynamicComboConfig.otherLabel + label);
	
}

function dinCombo(isLeaf, prefix, index, value, context, other, label, flag) {
	if ( isLeaf == true || isLeaf == "true" ) {		
		dispatchLeaf(isLeaf, prefix, index, value, context, other, label );
	} else {
		dispatchBranch(isLeaf, prefix, index, value, context, other, flag );
	}	
	postProcessDinCombo(prefix);
}

function removeAndUpdate(prefix, index, selectedValue, other, label ){
	var indice = parseInt(index);
	refreshLocationChannelId(prefix, indice, selectedValue);
	
	fxd_index = parseInt(index ) + 1;
	index =  fxd_index;	
	
	while ( dynamicComboObjects[prefix + index] ) { 
		dynamicComboObjects[prefix + index].hide(true);
		index ++;
	}

	if  ( ! ( other == true || other == "true" ) ) {
		return; 
	}

	if ( dynamicComboObjects[prefix + fxd_index] == null ) {
		dynamicComboObjects[prefix + fxd_index] = new DynamicCombo(fxd_index, prefix, selectedValue, dynamicComboConfig.applyMandatory);
	}

	dynamicComboObjects[prefix + fxd_index].hide();
	dynamicComboObjects[prefix + fxd_index].drawOther('Otro ' + label);
}

function refreshLocationChannelId (prefix, index, selectedValue ) {
	var target;	
	if ( dynamicComboConfig.inputId ) {
		target = dynamicComboConfig.inputId;
	} else {
		target =  dynamicComboConfig.multiInputId[prefix];
	}

	if (! ( selectedValue == null || "" == selectedValue )  ) {
			
		document.getElementById(target).value = selectedValue;	
	} else {
		var id = parseInt(index) - 1;
		var object = document.getElementById(prefix + '_sel_' + id);
		
		if ( object ) {
			var text = object.value;
			document.getElementById(target).value = text;
		} else {
			document.getElementById(target).value = '';
		}
	}
}

DynamicCombo.prototype.createCombo = function(category, mandatory) { 
	if ( this.isOther == true ) { 
		this.getColB().removeChild(this.child);
		this.child = null;
	}

	if ( this.getChild() == null ) {  
		this.child = document.createElement('select');
		this.child.id = this.getPrefix() + '_sel_' + this.getIndex();
		this.child.name = dynamicComboConfig.otherId;
		this.child.className = dynamicComboConfig.selectClassName;
		
		this.getColB().appendChild(this.child);
	} else {
		this.child.options.length = 0;
	}
	this.defaultOption(this.getChild(), mandatory);
	this.getChild().disabled = false;		
	this.isOther = false;
	return this.child;
}

DynamicCombo.prototype.defaultOption = function ( select, mandatory ) { 
	var oItem = document.createElement("option");
	if ( ( mandatory != false && mandatory != "false" ) || dynamicComboConfig.indistinto == null ) { 
		oItem.text = dynamicComboConfig.seleccionar;
	} else { 
		oItem.text = dynamicComboConfig.indistinto;
	}
	oItem.value = '';
	select.options.add(oItem,0);
	select.options.selectedIndex = 0;
}

DynamicCombo.prototype.createOther = function(category, mandatory) {

	if ( this.isOther == false ) {

		if ( this.child ) {
			this.child.id = 'fixme';	
			this.child.style.display = 'none';
			this.child.style.visibility = 'hidden';
			this.child = null;
		}
	} 
	if ( this.getChild() == null ) {
		this.child = document.createElement('input');
		if (isFiscalOther(this.prefix)){
			this.child.id = dynamicComboConfig.otherFId;
			this.child.name = dynamicComboConfig.otherFId;	
		}else{
			this.child.id = dynamicComboConfig.otherId;
			this.child.name = dynamicComboConfig.otherId;
		}		
		this.child.className = dynamicComboConfig.selectClassName;
		this.child.maxLength=40;
		this.getColB().appendChild(this.getChild());
	}

	this.getChild().disabled = false;
	this.isOther = true;
}

DynamicCombo.prototype.dinOther = function( prefix, index, selectedValue, label, base, divConstants ) {

	nextInt = parseInt(index) + 1;

	refreshLocationChannelId(prefix, index, selectedValue, divConstants.inputId);

	generateDynamicInputBox(prefix, nextInt, selectedValue, label, base, divConstants);
}


function gup( name , url )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

function setMultiInputId(valor){
	if (valor == 'registration') {
		dynamicComboConfig['multiInputId'] = {'registration':'address.locationChannelId', 'legalAddressRegistration' :'userAccount.legalAddress.locationChannelId'};
	} else if (valor == 'my-data') {
		dynamicComboConfig['multiInputId'] = {'myaccount':'address.locationChannelId', 'myaccountLegalAddressRegistration' :'userAccount.legalAddress.locationChannelId'};
	}
}

