var dropdowns = new Array()

dropdown.prototype.montaHTML = montaHTML
dropdown.prototype.alinha = alinha
dropdown.prototype.abre_leque = abre_leque
dropdown.prototype.fecha_leque = fecha_leque
dropdown.prototype.selecionar = selecionar

dropdown.prototype.active_item_dropdown = "#fcf9cf"
dropdown.prototype.over_item_dropdown = "#c2c2c2"
dropdown.prototype.deslocamento_slide = 15

function $id(str) {
return document.getElementById(str);
}

function dropdown(id_compon, id_alvo, texto_drop, tamanho_fixo, altura_fixa, onselect, checkbox) { //construtor: id_compon:String-ID referente ao componente || id_alvo:String-ID referente ao elemento que armazena alguma variavel (apenas dropdowns selecionaveis usam esse) || texto_drop:String - valor inicial escrito    || tamanho_fixo:Number-width fixo do componente, deixe 0 para width automático || altura_fixa:Number- height fixo do componente, deixa 0 para automatico || onselect:Boolean-true para dropdowns que armazaenam dados e continuam a navegação, false para dropdowns que o clique já redireciona à um clique || checkbox:Boolean-true para quando selecionar o item não fechar a aba nem mudar a cor, apenas selecionar o check
this.id_compon = id_compon
this.id_caixa_select = 'cx-select' + Math.round(Math.random() * 40000)
this.id_item_select = 'item-select' + Math.round(Math.random() * 40000)
this.id_mascara = 'mascara' + Math.round(Math.random() * 40000)
this.id_combo = 'combo' + Math.round(Math.random() * 40000)
this.id_dispara = 'fire' + Math.round(Math.random() * 40000)
this.dropdown_antigo = '';
this.id_alvo = id_alvo;
this.montado = false;
this.texto_drop = texto_drop;
this.onselect = onselect;
this.checkbox = checkbox;

this.tamanho_fixo = tamanho_fixo
this.altura_fixa = altura_fixa

dropdowns.push(this)

}

function montaHTML(array_valores) {
var stringsHTML = new String()

with (this) {
	
	
stringsHTML = '<div id="'+id_compon+'">\
					<input type="hidden" id="' + id_alvo + '" name="' + id_alvo + '" />\
					<div class="cx_select" id="'+id_caixa_select+'">\
    					<div class="click_dropdown" >\
        					<img src="img/icoSeta.gif" id="'+id_dispara+'" />\
       				 	</div>\
        				<div id="'+id_item_select+'" class="selecionado_dropdown" >\
       				 		'+ texto_drop +'\
       				 	</div>\
   			  		</div>\
    		   		<div id="'+id_mascara+'" class="mascara_dropdown">\
						<div class="caixa_dropdown" id="'+id_combo+'" >\
    						<ul>'
							


for(var i=0;i < array_valores.length;i++) {
if (i / 2 == parseInt(i/2)) { var row = 1  }else{ var row = 2 }
stringsHTML+= '<li class="bg_row' + row + '"><a href="javascript:void(0)"  rel="' + array_valores[i][1]+ '">'+array_valores[i][0]+'</a></li>'
}
		
		
stringsHTML += 			  '</ul>\
						</div>\
    				</div>\
				</div>'
					
document.write(stringsHTML)

var t = $id(id_item_select).offsetWidth;

if(tamanho_fixo != 0) {
	//var fixie = document.fireEvent ? fixie = 0 : fixie = 0
	$id(id_caixa_select).style.width = tamanho_fixo +  'px'
}else{
$id(id_caixa_select).style.width = t  + 35 + 'px'
}



$id(id_dispara).onclick = function() { alinha() }

}

}

function alinha() {

with(this) {
var el_combo = $id(id_combo)
var el_masc = $id(id_mascara)

if(!el_combo.aberto) {

	if(!montado) {
	divs = el_combo.getElementsByTagName('LI')
	links = el_combo.getElementsByTagName('A')
	var a_largura_max = new Array()

	for(i=0;i<divs.length;i++) {

		a_largura_max.push(divs[i].offsetWidth)
		divs[i].onclick = function() { 
			if(onselect) {
			selecionar(this.firstChild);
			if(!checkbox) { $id(id_alvo).value = this.firstChild.rel }
			}else{
				document.location = this.firstChild.rel
			}
		}
		
		divs[i].onmouseover = function() {
			if(dropdown_antigo != this) {
				this.style.backgroundColor = over_item_dropdown
			}
		}
		divs[i].onmouseout = function() {
			if(dropdown_antigo != this) {
				this.style.backgroundColor = ''
			}
		}
		
	}

	a_largura_max.sort(function sortNumber(a,b) { return a - b; })
	a_largura_max.reverse()
	var largura_max = a_largura_max[0]
		
	if(String(navigator.userAgent).indexOf('MSIE 7.0') != -1) { largura_max+= 130 }
	
	if(largura_max < $id(id_caixa_select).offsetWidth) { largura_max = $id(id_caixa_select).offsetWidth; }
	
	var fixie = document.fireEvent ? fixie = -2 : fixie = -10
		
	if(altura_fixa != 0) { var fixscroll = -10 }else{ var fixscroll = 0 }
		
	for(i=0;i<divs.length;i++) {
		divs[i].style.width = largura_max + fixie + fixscroll + 'px';
	}
	
	el_masc.style.height = '0px'
	el_masc.style.width = largura_max + fixscroll + 10 + 'px';
	
	montado = true
	}
	
	el_combo.style.visibility = 'visible'
	
	abre_leque()
}else{
	fecha_leque()
}

}
}

function abre_leque() {
with(this) {
	var el_combo = $id(id_combo)
	var el_masc = $id(id_mascara)
	
	el_combo.aberto = true
	var altura = String(el_masc.style.height).replace('px','')
	var altura = new Number(altura)
	if(altura_fixa != 0) { 
		var mascara_max = altura_fixa
		el_masc.style.overflowY = 'auto';
		
		if(String(navigator.userAgent).indexOf('Opera') != -1) { el_masc.style.overflow = 'auto'; } //fix opera pro scroll
		
		if(String(navigator.userAgent).indexOf('Firefox') != -1) { //fix firefox pro positionamento vertical da div
			el_masc.style.marginTop = $id(id_caixa_select).offsetHeight + 'px'
		}
	}else{ 
		var mascara_max = el_combo.offsetHeight 
	}
	var timer_leque = window.setInterval(
	function () { 
		if(altura >= mascara_max) {
			clearInterval(timer_leque)
		}
	altura = altura + deslocamento_slide
	el_masc.style.height = altura + 'px'
	}
	,1)
}
}

function fecha_leque() {
with(this) {
	var el_combo = $id(id_combo)
	var el_masc = $id(id_mascara)
	
	
	var altura = String(el_masc.style.height).replace('px','')
	var mascara_min = 0
	var timer_leque = window.setInterval(
	function () { 
		if(altura <= mascara_min) {
			clearInterval(timer_leque)
			el_combo.aberto = false
		}
	altura = altura - deslocamento_slide
	if(altura < 0) altura = 0
	el_masc.style.height = altura + 'px'
	}
	,1)
}
}

function selecionar(el) {
with(this) {
	
	$id(id_item_select).whiteSpace = "normal"
	var ie = document.fireEvent ? $id(id_item_select).style.width = $id(id_item_select).offsetWidth : null
	$id(id_item_select).style.overflow = "hidden"
	$id(id_item_select).style.position = "relative"

if(checkbox != true) {
	try { dropdown_antigo.style.backgroundColor = '' }catch(e) {}
	$id(id_item_select).firstChild.nodeValue = el.firstChild.nodeValue
	dropdown_antigo = el.parentNode 
	el.parentNode.style.backgroundColor = active_item_dropdown 
	fecha_leque()
}else{
		if(el.firstChild.checked != false) {  
			//el.firstChild.checked = 'checked' - setar condição ao contrário, se o clique for na palavra e nao no checkbox!
			if(String($id(id_alvo).value).indexOf(el.firstChild.id) == -1) {
				$id(id_alvo).value = $id(id_alvo).value + el.firstChild.id + "_"
			}
		}else if (el.firstChild.checked != true) { 
			//el.firstChild.checked = ''
			$id(id_alvo).value  = String($id(id_alvo).value).replace(el.firstChild.id + "_",'')
			
		}
}
   //#div1
    if ($(el).parent().parent().parent().parent().parent().attr("id") == "drop1"){
        CreateSelect('divbairro',$(el).attr("rel"));
    }
    //CreateSelect('divbairro',$("#cidade").val(l"));
    //  alert($id(id_item_select).firstChild.nodeValue.attr("rel"));
//}
}
}

function verifica_clique_dropdown(e) {

	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
		
		for(var i=0;i<dropdowns.length;i++) {
			var nodes = targ
			var clique_area = false;
		do {
		try { var nodes = nodes.parentNode }catch(e){ break }

			try { if(nodes.id==dropdowns[i].id_compon) { var clique_area = true; } }catch(e) {}
		
		}while(nodes != null || clique_area)
			if(!clique_area) { dropdowns[i].fecha_leque();  }
			//dropdowns[i].fecha_leque();   #####não fecha mais ao clicar fora
		}
}

function inicio() {
var IE = document.fireEvent ? document.body.onclick = verifica_clique_dropdown : window.onclick = verifica_clique_dropdown
}

window.onload = inicio