/* all itens with the same height */
function sameHeight(classOrId, applyOnLine, numberOfCollumns){
	var heightElement = 0;
	$(classOrId).each(function(i){
		if(heightElement<this.clientHeight) heightElement = this.clientHeight;
		if(i==$(classOrId).length-1)$(classOrId).css({height:heightElement + 'px'});
	});
}

String.prototype.replaceAll = function(from, to){
    var str = this;
    var pos = str.indexOf(from);
	while (pos > -1){
		//alert(alert(pos))
		str = str.replace(from, to);
		pos = str.indexOf(from);
	}

    return (str);
}

// Estados / Cidades
function loadXML(sel,valXml) {
	if(sel!=''){valXml = sel.value.toLowerCase()}
	importXML(ListarCidades,'../xml/'+valXml+'.xml');
}

function importXML(f,u) {
	//document.getElementById('cidade').disabled = false;
	if (document.implementation && document.implementation.createDocument) {
		xmlHttp = new XMLHttpRequest();
		xmlHttp.onreadystatechange = f;
		xmlHttp.open("GET",u,true);
		xmlHttp.send(null);
	} else if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLDOM");
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4) f();
		};
		xmlHttp.load(u);

	} else {
		alert('Your browser can\'t handle this script');
		return;
	}
}	

function ListarCidades() {
	if (xmlHttp.readyState == 4){
		var objCombo = document.getElementById('cidade');
		objCombo.options.length = 0;
		try {
			var xmlDoc = (new DOMParser()).parseFromString(xmlHttp.responseText,"text/xml");
			var eItens =  xmlDoc.documentElement.getElementsByTagName('city');
			if (eItens.length == 0){
				objCombo.options[0] = new Option("Seleccione","");
				//objCombo.disabled = true;
				return;
			}
		} catch (e) {
			try{
				var eItens =  xmlHttp.documentElement.getElementsByTagName('city');
			} catch (e) {
				objCombo.options[0] = new Option("Seleccione","");
				//objCombo.disabled = true;
			}
		}
		if (eItens){
			objCombo.options[0] = new Option("Seleccione","");
			objCombo.options[0] = new Option("Cargando...","");
			for (i=0; i<eItens.length; i++) {
				var valores = eItens[i];
				var name = valores.attributes.getNamedItem('name').firstChild.data;
				objCombo.options[i+1]= new Option(name,name);
				//objCombo.disabled = false;
			}
			objCombo.options[0] = new Option("Seleccione","");
			objCombo.value=$('hCidade').val();
		}
	}
}

function hideErrorBox(boxError, fadeBg){
	
	$(boxError).fadeOut();
	$(fadeBg).fadeOut();
	$('select').css({
		visibility: 'visible'
	});
}

/* eventos detalhes - confirmar */
function confirmarPresenca(idDiv){
	$('.box-convidado').hide();
	$(idDiv).show();
}

function backContacts() {
	$('#inserir_contatos').show();
	$('#selecione_contatos').hide();
}

function selectAllNone(classField,checkedItem){
	$('.' + classField).each(function(i){
		this.checked =checkedItem;	
	});
}

function selectTab(genNumber){
	$('#txt_codigo_'+genNumber).val('');
	$('#sel_botella_'+genNumber).val('');
	
	var $indexCodes = $('.box-generated .boxes-codes').length;
	$('.no-list-type').html('<li>Para continuar debes llenar correctamente los espacios solicitados.</li>');
	var checkedBotellas = 0;
	$('.box-generated .rdo_codigobotella').each(function(){
		if (this.checked&&checkedBotellas==0) {checkedBotellas=1}
	})
	if(checkedBotellas==1){
		$('.botella-image').show();
	}
	else{
		$('.botella-image').hide();
	}
	
	$('#txt_codigo_' + genNumber).remove();
	
	$('.rdo-codigo-' + genNumber).each(function(i){	
		if (this.checked) {
			$('.label-' + genNumber + '-aba' + i).css('background-color','#bdb587');
			$('.box-codigo-'+ genNumber).hide().fadeIn("slow");
			var idCodigo = "'#txt_codigo_" + genNumber + "'";
			//var idBotella = "''";
			
			if (this.value == 'botella') {
				var idBotella = "'#sel_botella_" + genNumber + "'";
				$('.botella-box-'+ genNumber + ' select').addClass('required');
				$('.botella-box-'+ genNumber).show();
				$('text-codigo-botella').show();
				$('#txt_codigo_' + genNumber).remove();
				
				$('.box-codigo-'+ genNumber + ' .aba-codigo').append('<input type="text" name="txt_codigo_' + genNumber + '"  id="txt_codigo_' + genNumber + '" class="text-codigo required {minlengthcode: 16}" maxlength="16" style="width: 100px;" title="El campo Código es obligatorio" onblur="getCodeValidation('+ idCodigo+ ', ' + idBotella + ')" />');
			}
			else{
				var idBotella = "'no-botella'";
				$('#txt_codigo_' + genNumber).remove();
				$('.box-codigo-'+ genNumber + ' .aba-codigo').append('<input type="text" name="txt_codigo_' + genNumber + '"  id="txt_codigo_' + genNumber + '" class="text-codigo required {minlengthcode: 7}" maxlength="7" style="width: 45px;" title="El campo Código es obligatorio" onblur="getCodeValidation('+ idCodigo+ ', ' + idBotella + ')" />');
			}
			
		}
		else{
			$('.botella-box-'+ genNumber + ' select').removeClass('required');
			$('.botella-box-'+ genNumber).hide();
			$('.label-' + genNumber + '-aba' + i).css('background-color','');
		}
	});
}

function agregarCodigos(){
	var $indexCodes = $('.box-generated .boxes-codes').length;
	
	if($indexCodes!=0){
		var item = 0;
		item = $('.box-generated  .select-botella')[$indexCodes-1].name;
		
		item = item.replaceAll('sel_botella_','');
		$indexCodes = parseInt(item)+ 1;
		
	}
	$('#code_amount').val(parseInt($indexCodes)+1);
	var $html = $('.template-code').html();
	
	$html = $html.replaceAll('gen',$indexCodes);
	$html = $html.replaceAll('gen2',$indexCodes);
	$html = $html.replaceAll('required-field','required');
	
	$('.box-generated').append($html);
	$('.codes-box-0 label.remove-link').hide();
}

function removerCodigos(indexCode){
	$('.codes-box-' + indexCode).remove();
	$('.clear-' + indexCode).remove();
	var $indexCodes = $('.box-generated .boxes-codes').length;
	$('#code_amount').val(parseInt($indexCodes));

	var checkedBotellas = 0;
	$('.box-generated .rdo_codigobotella').each(function(){
		if (this.checked&&checkedBotellas==0) {checkedBotellas=1}
	})
	
	if(checkedBotellas==1){
		$('.botella-image').show();
	}
	else{
		$('.botella-image').hide();
	}
}

function hideListaContatos(){
	var arrLista = [$('#txtEmailLista'),$('#selServico'), $('#txtSenhaLista')];
	for (var i=0; i<arrLista.length;i++)arrLista[i].value='';
	
	var lista = $('#lista_contatos input');
	for (var i=0; i<lista.length;i++){
		lista[i].checked=false;
		lista[i].setAttribute('obligatory','false');
	}
	$('#lista_contatos').css('display','none');
	$('#sugerir').css('display','block');
}

function openCloseList(listName){
	if(listName=='contatos') {
		$('#tu_email, #servico, #tu_password').removeClass("required");
		$('#invitar, #aseguro').addClass("required");
		$('#invitar').addClass("textareaEmail");

		$('#manual').hide();
		$('#contatos').show();

		$('#a1 a').removeClass('on');
		$('#a2 a').addClass('on');
	}
	else{
		$('#tu_email, #servico, #tu_password').addClass("required");
		$('#invitar, #aseguro').removeClass("required");
		$('#invitar').removeClass("textareaEmail");

		$('#manual').show();
		$('#contatos').hide();

		$('#a1 a').addClass('on');
		$('#a2 a').removeClass('on');
	}
}

function loadItensPagination(loadIn,targetPage){
	$(loadIn).load(targetPage);
}

function findWhisky(combo,valueGet){
	
	if ($('.left-content').find('.lista-donde').length > 0) {
		if(valueGet)combo.value=valueGet;
		if (combo.value != '') {
			loadItensPagination('.venda', '../inc/getPuntosVenda.jsp?page=1&cityId=' + combo.value + '');
			loadItensPagination('.consumo', '../inc/getCentrosConsumo.jsp?page=1&cityId=' + combo.value + '');
			$('.tit-ciudad').html(combo[combo.selectedIndex].text).show();
			$('.display-none').show();
		}
		else {
			$('.display-none').hide();
		}
	}
	else{
		parent.location = 'donde_estamos.jsp?cityId='+combo.value;
	}
}

function showHide(div, val) {
	var state = $('#'+div).css('display');
	if (state == 'none') {
		$('#'+div).show();
		$('#t'+val).html('[ &ndash; ]');
	} else {
		$('#'+div).hide();
		$('#t'+val).html('[ + ]');
	}
}

function goToPage(pageName){
	if (pageName != '') {
		window.location = pageName;
	}
}

function setConsumo(){
	var consumesFS = $("#consumesFS input");
	var itens='';
	consumesFS.each(function(i){	
		if(consumesFS[i].checked){itens+= consumesFS[i].value + ',';}
	})
	document.getElementById("totalConsumes").value=itens;	
}

function setCheckToHidden(checkFieldId,hiddenField){
	var checkItens = $(checkFieldId);
	var itens='';
	
	checkItens.each(function(i){	
		if(checkItens[i].checked){itens+= checkItens[i].value + ',';}
	})
	$(hiddenField).val(itens);
}

// Verifica telefone
function validaTipoTel(tipo, campo) {
	if ((tipo.value == 'C') || (tipo.value == 'R')) {
		$('#'+campo).attr('maxlength', 11);
	} else {
		$('#'+campo).val($('#'+campo).val().substr(0,10));
		$('#'+campo).attr('maxlength', 10);
	}
}
function getCodeValidation(fieldCode,fieldBrand){
	var code = $(fieldCode).val();
	var brandId = $(fieldBrand).val();
	
	if(brandId==undefined){brandId='';}
		
	if(fieldBrand!='no-botella'){
		if(code==''||brandId=='')return;
	}
	
	$('.bt-enviar').attr('disabled','disabled')
				   .addClass('disableButton');
	//window.open("/inc/getCodeValidation.jsp?code=" + code + '&brandId='+ brandId)
	$.ajax({
	
		url: "/inc/getCodeValidation.jsp?code=" + code + '&brandId='+ brandId,
		cache: false,
		success: function(html){
			
			//alert(html)
			if (code != '') {
				//alert(html)
				if (html == -1) {
					showErrorsDHTML('Sistema indisponible.');
					//fieldCode.val('');
				} else if (html == 1) {
					showErrorsDHTML('C&oacute;digo no valido.');
					$(fieldCode).val('')
				} else if (html == 2) {
					showErrorsDHTML('C&oacute;digo registrado.');
					$(fieldCode).val('')
				}
				$('.bt-enviar').removeAttr("disabled")
				   .removeClass('disableButton');
			}
		}
	});
	
}

function showErrorsDHTML(message){
	if(message=='')return false;
	$('#fade').show();
	$('#fade, .bt-Error').click(function(){
		hideErrorBox('.dhtml-errors', '#fade');
		$('li.msgGen').remove();
		$('.no-list-type').html('<li>Para continuar debes llenar correctamente los espacios solicitados.</li>');
	});
	
	document.onkeydown = function(e){ 	
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		if(keycode == 27){ // close
			hideErrorBox('.dhtml-errors', '#fade');
			$('.msgGen').remove();
			$('.no-list-type').html('<li>Para continuar debes llenar correctamente los espacios solicitados.</li>');
		}
	};
	

	$('.black_overlay').show();
	$('#light').show();
	$('.no-list-type').show();
	$('.no-list-type').html('');
	$('.no-list-type').html('<li>Para continuar debes llenar correctamente los espacios solicitados.</li><li class="msgGen">- '+message+'</li>');
	return false;
}

// Seta ordem dos premios
function setOrdPremio(pAtual, pNova) {

	// Pega as classes que serão trocadas
	var classAtual = $('#p'+pAtual).attr("class");
	var classNova  = $('#p'+pNova).attr("class");

	var hrefAtual = $('#p'+pAtual + ' a').attr("href");
	var hrefNova  = $('#p'+pNova + ' a').attr("href");

	// Regras
	$('#p'+pAtual).removeClass(classAtual);
	$('#p'+pAtual).addClass(classNova);
	$('#p'+pNova).removeClass(classNova);
	$('#p'+pNova).addClass(classAtual);

	$('#p'+pAtual + ' a').attr('href',hrefNova);
	$('#p'+pNova + ' a').attr('href',hrefAtual);
	
	var i=1
	$('.nav-registro li').each(function(){
		valor = $('#p'+i).attr("class");
		valor = valor.replace(/tit-ord/,"");
		valor = valor.replace(/ set/,"");
		$('#op'+i).val(valor);
		
		if(this.className.indexOf('set')!=-1){
			changeBg(i);
		}
		i++;
	});
}

function changeBg(item){
	var bg = ''
	switch(item){
		case 1:
			bg = 'top center';
			break;
		case 2:
			bg = 'center center';
			break;
		case 3:
			bg = 'bottom center';
			break
	}
	$('.nav-registro').css('background-position',bg);
}

function showHidePrize(elm) {
	var item='';	
	
	$('.content-registro').each(function(){$(this).hide();});
	$('#fragment-'+elm).show();
	
}

function validaContato(f){
	var i= 0, msg = '' ;
	$('.no-list-type').html('');
	$('.check-contato').each(function(){
		if(this.checked){i++;}
	})
	if(i==0){msg += 'Necesitas seleccionar al menos un contacto.';}
	if(!f.aseguro2.checked){msg+='El campo Aseguro es obligatorio.'}
	if(msg!=''){
		$('.no-list-type').html('');
		showErrorsDHTML(msg);
	}
	else{
		jQuery(f).ajaxSubmit({
			beforeSubmit: function () {
				$('#loading-final').show();
			},
			success: function(returnSubmit){
				$('#inserir_contatos').hide();
				$('#sucesso').show();
			} 
		});
	}
	return false;
}
