window.onload = init;

//startup = init;

var ie = navigator.appName == 'Microsoft Internet Explorer';

var vMaiorA = new Alert('visualizar_maior'),

	newsA = new Alert('news'),

	errorA = new Alert('error'),

	numValue = 1;//adicao de campos de frase na descricao do produto

function init() {

	if(navigator.userAgent.toString().indexOf('MSIE 6') != -1 || navigator.userAgent.toString().indexOf('MSIE 5') != -1)document.execCommand("BackgroundImageCache",false,true);

	$A(document.getElementsByClassName('adicionar')).each(voltar_adicionar);//adiciona botao voltar na tela de descricao de produto

	$A(document.getElementsByTagName('a')).each(link_externo);

	$A(document.getElementsByClassName('ver_maior')).each(vMaior);

	//$A(document.getElementsByClassName('newsletter')).each(news);

	if($('bt_inserir_frase'))$('bt_inserir_frase').onclick = insere_campo_frases;

	qtd_produto();

	if($('login') && !ie) {

		$('txt_senha').type = 'text';

		$('txt_senha').value = 'senha';

		$('txt_login').value = 'login';

		$('txt_senha').onclick = function() {if(this.value == 'senha')this.value = '';this.type = 'password';};//Tem q corrigir no FF

		$('txt_login').onclick = function() {if(this.value == 'login')this.value = '';};

	}

	if($('bt_fechar') && $('bt_remove')) {

		$('bt_remove').onclick = function() {

			var ok = false;

			if(document.getElementsByTagName('table')[0].getElementsByTagName('input').length > 0) {

				var _inputs = document.getElementsByTagName('table')[0].getElementsByTagName('input');

				for(var i=0;i<_inputs.length;i++) {

					if(_inputs[i].checked) {

						ok=true;

						break;

					}

				}

			}

			if(ok)

				return true;

			else

				return false;

		}

		$('bt_fechar').onclick = function() {

			var _inputs = document.getElementsByTagName('table')[0].getElementsByTagName('input');

			if(_inputs.length > 0)

				for(var i=0;i<_inputs.length;i++)

					_inputs[i].checked = '';

			return true;

		}

	}

	/*
	if($('form_lojistas')) {//Validacao de lojistas

		var campos = Form.getElements($('form_lojistas')),

			labels = $A($('form_lojistas').getElementsByTagName('label')),

			ob = campos.findAll(function(campo) {

				return labels.find(function(label) {
					return (campo.id.toString()==label.getAttribute('for').toString() && label.innerHTML.toString().indexOf('*') == 0);

				});

			});

		$('mesmo_entrega').onclick = function(evento) {

			if(Event.element(evento).checked == true) {

				$('txt_endentrega_lojista').value = $('txt_end_lojista').value;

				$('txt_compendentrega_lojista').value = $('txt_compend_lojista').value;

				$('txt_bairroentrega_lojista').value = $('txt_bairro_lojista').value;

				$('txt_cidadeentrega_lojista').value = $('txt_cidade_lojista').value;

				$('cbox_ufentrega_lojista').selectedIndex = $('cbox_uf_lojista').selectedIndex;

				$('txt_entregashopping_lojista').value = $('txt_shopping_lojista').value;

				$('txt_cepentrega_lojista').value = $('txt_cep_lojista').value;

				$('txt_entregatelefone_lojista').value = $('txt_fone_lojista').value;

				$('txt_entregacontato_lojista').value = $('txt_contato_lojista').value;

			}

			else {

				$('txt_endentrega_lojista').value = '';

				$('txt_compendentrega_lojista').value = '';

				$('txt_bairroentrega_lojista').value = '';

				$('txt_cidadeentrega_lojista').value = '';

				$('cbox_ufentrega_lojista').selectedIndex = 0;

				$('txt_entregashopping_lojista').value = '';

				$('txt_cepentrega_lojista').value = '';

				$('txt_entregatelefone_lojista').value = '';

				$('txt_entregacontato_lojista').value = '';

			}

		}.bindAsEventListener($('mesmo_entrega'));

		$('mesmo_correspondencia').onclick = function(evento) {

			if(Event.element(evento).checked == true) {

				$('txt_endcorresp_lojista').value = $('txt_end_lojista').value;

				$('txt_compendcorresp_lojista').value = $('txt_compend_lojista').value;

				$('txt_bairrocorresp_lojista').value = $('txt_bairro_lojista').value;

				$('txt_cidadecorresp_lojista').value = $('txt_cidade_lojista').value;

				$('cbox_ufcorresp_lojista').selectedIndex = $('cbox_uf_lojista').selectedIndex;

				$('txt_correspondenciashopping_lojista').value = $('txt_shopping_lojista').value;

				$('txt_cepcorresp_lojista').value = $('txt_cep_lojista').value;

				$('txt_correspondenciatelefone_lojista').value = $('txt_fone_lojista').value;

				$('txt_correspondenciafax_lojista').value = $('txt_fax_lojista').value;

				$('txt_correspondenciaemail_lojista').value = $('txt_email_lojista').value;

			}

			else {

				$('txt_endcorresp_lojista').value = '';

				$('txt_compendcorresp_lojista').value = '';

				$('txt_bairrocorresp_lojista').value = '';

				$('txt_cidadecorresp_lojista').value = '';

				$('cbox_ufcorresp_lojista').selectedIndex = 0;

				$('txt_correspondenciashopping_lojista').value = '';

				$('txt_cepcorresp_lojista').value = '';

				$('txt_correspondenciatelefone_lojista').value = '';

				$('txt_correspondenciafax_lojista').value = '';

				$('txt_correspondenciaemail_lojista').value = '';

			}

		}.bindAsEventListener($('mesmo_correspondencia'));

		$('form_lojistas').onsubmit = function() {

			var check = ob.all(function(campo) {

    			if($F(campo) != '' && $F(campo).toString().match(/^[ ]*$/gi) == null) {

					if(campo.id == 'txt_cnpj_lojista')

						return function() {

							cpf = $F(campo);

							if(cpf.length != 11)return false;

							for(var j=0,ok=false;j<cpf.length;j++)if(cpf.charAt(0) != cpf.charAt(j))ok = true;

							if(!ok || cpf == '12345678909')return false;

	

							cpf = cpf.split('');

							var m = 0;

							do {

								for(var i=10+m,d=0;i>1;i--)

									d += cpf[(10+m)-i] * i;

								if((d%11<2?0:11-(d%11)) != cpf[cpf.length-(2-m)])return false;

								m++;

							}while(m<2);

							return true;

						}

					else

						return true;

			}

				else

					return false;

			});

			if(!check) {

				alert('Preencha todos os campos marcados com *');

				var check2 = ob.detect(function(campo) {

	    				if($F(campo) == '' || $F(campo).toString().match(/^[ ]*$/gi) != null)

						return true;

					else

						return false;

				});

				check2.focus();

				return false;

			}

			else

				return true;

		}

	}

	if($('form_representantes')) {//Validacao de representantes

		var campos = Form.getElements($('form_representantes')),

			labels = $A($('form_representantes').getElementsByTagName('label')),

			ob = campos.findAll(function(campo) {

				return labels.find(function(label) {

					return (campo.id.toString()==label.getAttribute('for').toString() && label.innerHTML.toString().indexOf('*') == 0);

				});

			});

		$('form_representantes').onsubmit = function() {

			var check = ob.all(function(campo) {

    			if($F(campo) != '' && $F(campo).toString().match(/^[ ]*$/gi) == null) {

					if(campo.id == 'txt_cpf_representante')

						return function() {

							cnpj = $F(campo);

							if(cnpj.length != 14)return false;

							cnpj = cnpj.split('');

							var m=0;

							do {

								for(var i=0,j=5+m,d=0;i<cnpj.length-(2-m);i++,j--) {

									if(j<2)j=9;

									d += cnpj[i] * j;

								}

								if((d%11<2?0:11-(d%11)) != cnpj[cnpj.length-(2-m)])return false;

								m++;

							}while(m<2);

							return true;

						}

					else

						return true;

				}

				else

					return false;

			});

			if(!check) {

				alert('Preencha todos os campos marcados com *');

				var check2 = ob.detect(function(campo) {

    				if($F(campo) == '' || $F(campo).toString().match(/^[ ]*$/gi) != null)

						return true;

					else

						return false;

				});

				check2.focus();

				return false;

			}

			else

				return true;

		}

	}

	if($('ondeEncontrar')) {

		$('cbox_estado').selectedIndex = 0;

		$('cbox_estado').onchange = function() {

			if($F('cbox_estado') != '') {

				var estado = new Ajax.Request('xml.php',{

					method: 'get',

					parameters: 'estado='+$F('cbox_estado'),

					onSuccess: preencheCidade

				});

			}

			else {

				$('cbox_cidade').options.length = 0;

				$('cbox_cidade').options[0] = new Option("Seleciona um Estado","");

			}

		}

		$('cbox_cidade').onchange = function() {

			if($F('cbox_cidade') != '') {

				$('lojas').innerHTML = 'Aguarde...';

				var lojist = new Ajax.Request('xml.php',{

					method: 'get',

					parameters: 'estado='+$F('cbox_estado')+'&cidade='+$F('cbox_cidade'),

					onSuccess: preencheLojista,

					onFailure: function() {alert('erro');}

				});

			}

		}

	}
	*/

};

function preencheLojista(requisicao) {

	var valores = requisicao.responseText,

		lojistas = valores.split(';'),

		_dl = document.createElement('dl'), _dt, _dd, _p, _a,

		lojista;

	for(var i=0;i<lojistas.length;i++) {

		lojista = lojistas[i].split('|');

		_dd = document.createElement('dd');

		for(var j=0;j<lojista.length;j++) {

			if(j==0) {

				_dt = document.createElement('dt');

				_dt.appendChild(document.createTextNode(lojista[j]));

				_dl.appendChild(_dt);

			}

			else {

				_p = document.createElement('p');

				if(lojista[j].indexOf('http') != -1) {

					_a = document.createElement('a');

					_a.setAttribute('href',lojista[j]);

					_a.appendChild(document.createTextNode(lojista[j]));

					_p.appendChild(_a);

				}

				else

					_p.appendChild(document.createTextNode(lojista[j]));

				_dd.appendChild(_p);

			}

		}

		_dl.appendChild(_dd);

	}

	_dl.id = 'lojas';

	$('lojas').parentNode.replaceChild(_dl, $('lojas'));

};

function preencheCidade(requisicao) {

	var valores = requisicao.responseText;

	if(valores == "") {

		$('cbox_cidade').options[0] = new Option("Nenhuma Cidade Localizada","");

		$('cbox_cidade').onchange = '';

	}

	else {

		$('cbox_cidade').options.length = 0;

		$('cbox_cidade').options[0] = new Option("Selecione uma Cidade","");

		for(var i=0;i<valores.split(' - ').length;i++) {

			$('cbox_cidade').options[i+1] = new Option(valores.split(' - ')[i],valores.split(' - ')[i]);

		}

	}

};

function qtd_produto() {

	if(!$('produto'))return;

	document.getElementsByClassName('text','produto').each(function(element) {if(!element.getAttribute('value') || element.getAttribute('value') == '')element.setAttribute('value','qtd');element.onclick = function() {if(this.value == 'qtd')this.value = '';}});

};

function voltar_adicionar(element) {//colocando o botao voltar na pagina do produto

	if(Element.hasClassName(element.parentNode,'right'))element.parentNode.innerHTML = '<button class="voltar" onClick="javascript:history.go(-1);">voltar</button>' + element.parentNode.innerHTML;

};

function link_externo(element) {//coloca TARGET=_BLANK nos links

	element = $(element);

	if(element.getAttribute('rel') && element.getAttribute('rel').toLowerCase() == 'externo')element.setAttribute('target', '_blank');

};

function errorX() {

	errorA.alert('<p>Desculpe-nos o transtorno, tente novamente mais tarde.</p>');

};

function vMaior(element) {

	element = $(element);

	var url = element.href;

	element.setAttribute('href', '#');

	element.onclick = function() {

		var XHR = new Ajax.Request(url, {

							   method: 'get',

							   onLoading: vMaiorA.background.bind(vMaiorA),

							   onSuccess: vMaiorA.alert.bind(vMaiorA),

							   onFailure: errorX

							   });

	};

};

function news(element) {

	element = $(element);

	var url = this.url = element.href;

	element.setAttribute('href', 'javascript:void(0);');

	element.onclick = function() {

		var XHR = new Ajax.Request(url, {

								   method: 'get',

								   onLoading: newsA.background,

								   onSuccess: newsA.alert.bind(newsA),

								   onComplete: newsletter.bind(this),

								   onFailure: errorX

								   });

	}.bind(this);

};



function newsletter() {

	

	$('content_alert').getElementsByTagName('form')[0].onsubmit = function() {

		var form = $('content_alert').getElementsByTagName('form')[0],

			serial = Form.serialize(form);

		alert(url + '-'+serial);

		var _XHR = new Ajax.Request(url, {

									method:'post',

									parameters:serial,

									onSuccess: function(resposta) {

										alert(resposta.responseText)

										if(resposta.responseText.indexOf('Cadastrado com sucesso') != -1)

											newsA.remove();

										else

											errorX();

									}

									});

		return false;

	}.bind(this);

};



document.createElementName = function(tagName, name) {

	var element;

	if(navigator.appName == 'Microsoft Internet Explorer')

		element = document.createElement('<'+tagName+' name="'+name+'">');

	else {

		element = document.createElement(tagName);

		element.name = name;

	}

	return element;

};



function insere_campo_frases() {

	var _select = document.createElementName('select','cbox_frase_'+numValue),

	_input = document.createElementName('input','txt_quantidade_'+numValue),

	_br = document.createElement('br'),

	_campos = $('campos');

	_input.setAttribute('id', 'txt_quantidade_'+numValue);

	_input.setAttribute('type','text');

	_input.setAttribute('maxlength', '4');

	_input.className = 'text';

	_select.setAttribute('id', 'cbox_frase_'+numValue);

	_select.options[0] = new Option('Selecione uma frase ou tema','');

	for(var i=0;i<_optionsProdutos.length;i++)

		_select.options[i+1] = new Option(_optionsProdutos[i][0],_optionsProdutos[i][1]);

	_campos.appendChild(_input);

	_campos.appendChild(document.createTextNode(' '));

	_campos.appendChild(_select);

	_campos.appendChild(_br);

	if(ie && numValue < 5)

		_campos.parentNode.style.paddingBottom = '141px';

	else

		_campos.parentNode.style.paddingBottom = '';

	numValue++;

};



function myProps(Obj,s) {

	var str = new String();

	try {

		if(typeof Obj != 'object' && typeof Obj != 'array')throw 'error';

		for(var prop=0;prop<Obj.length;prop++)

			str += Obj[prop] + (s || '\n');

		if(str == '')throw 'nada';

		return (str);

	}

	catch(e) {

		if(e == 'error')return ('error');

		try {

			str = '';

			for(prop in Obj)

				str += prop + ' = ' + Obj[prop] + (s || '\n');

			return (str);

		}

		catch(e) {

			return ('error');

		}

	}

};



Validator = Class.create();

Object.extend(Validator.prototype,{

	initialize: function(form) {

		this.form = form?$(form):document.forms[0];

		this.fields = Form.getElements(this.form).findAll(function(element) {

			return Element.hasClassName(element,'ob');//Nome da classe para validar

		});

		this.submiter = $A(this.form.getElementsByTagName('*')).find(function(element) {return element.getAttribute('type') == 'submit';});

		this.submiter.onclick = this.validate.bind(this);

	},

	validate: function() {

		this.invalid = this.fields.findAll(function (element) {

			//element = $(element);//Descomentar caso seja mexido na parte onde seta this.fields

			return (!$F(element) || $F(element).length == 0);

		});

		if(this.invalid.length > 0) {

			this.labels = $A(document.getElementsByTagName('label')).findAll(function(label) {

				return (this.invalid.find(function(field) {

					//field = $(field);//Descomentar caso seja descomentado acima tbm

					return (label.getAttribute('for') == field.id);

				}));

			}.bind(this));

			this.labels = this.labels.pluck('innerHTML');

			alert('Favor preencher os seguintes campos:\n'+this.labels.join('\n'));

			return false;

		}

	}

});