
function sendWindowForm( divForm, _form ){
	
	_form = $('#'+_form);
	
	if($(_form).validate().form()){
		divResp = 'emailResponse'+divForm;
		
			if($('#'+divResp).length < 1){
				$(_form).append('<div id="'+divResp+'" class="emailResponse"><div id="emailResponseMsg">Enviando...</div></div>');
			}
			$.ajax({
					  url: 'http://www.embreex.com.br/_Request/',
					  data: _form.serialize(),
					  dataType: 'json',
					  cache: false,
					  type: 'POST',
					  complete: function(resposta) {
						  try
							{
								res = jQuery.parseJSON( resposta.responseText );
								
								if(res.status == 'ok'){
									
									if(res.mensagem){
										$("body").append('<div id="dialog">'+res.mensagem+'</div>');
										$("#dialog").dialog({
													modal: true,
													buttons: {
														Ok: function() {
															$(this).dialog('destroy');
															$("#dialog").remove();
														}
													}
												});
									}else{
										$("body").append('<div id="dialog">'+res.erro+'</div>');
										$("#dialog").dialog({
													modal: true,
													buttons: {
														Ok: function() {
															$(this).dialog('destroy');
															$("#dialog").remove();
														}
													}
												});
									}
									if(res.script)
										eval(res.script);
								}else{
										$("body").append('<div id="dialog">'+res.mensagem+'</div>');
										$("#dialog").dialog({
													modal: true,
													buttons: {
														Ok: function() {
															$(this).dialog('destroy');
															$("#dialog").remove();
														}
													}
												});
								}
							}
							catch(e)
							{
							  $("body").append('<div id="dialog">'+resposta.responseText+'</div>');
							  $("#dialog").dialog({
										  modal: true,
										  buttons: {
											  Ok: function() {
												  $(this).dialog('destroy');
												  $("#dialog").remove();
											  }
										  }
									  });
							}
					  }
			});
	}
		
	return false;
}

var $ = jQuery;


var zoom = 1;
$(document).ready(function(){
	
			$('input:text').setMask();
			
			$("#cadastreseForm").validate();
			$("#formularioForm").validate({
				rules: { 
						senha: { 
							required: false, 
							minlength: 5 
						}, 
						confirmacao: { 
							required: false, 
							minlength: 5, 
							equalTo: "#senha" 
						}, 
//						email: { 
//							required: true, 
//							email: true, 
//							remote: "emails.php" 
//						},
						nome: {
						  required: "#pessoaFisica:checked"
						},
						cpf: {
						  required: "#pessoaFisica:checked"
						},
						rg: {
						  required: "#pessoaFisica:checked"
						},
						razao_social: {
						  required: "#pessoaJuridica:checked"
						},
						cnpj: {
						  required: "#pessoaJuridica:checked"
						}
					}, 
				messages: {
					cpf: "Este campo &eacute; obrigat&oacute;rio.",
					telefone: "Este campo &eacute; obrigat&oacute;rio.",
					endereco: "Este campo &eacute; obrigat&oacute;rio.",
					numero: "Este campo &eacute; obrigat&oacute;rio.",
					remote: "Please fix this field.",
					email: "Este e-mail n&atilde;o &eacute; v&aacute;lido.",
					url: "Please enter a valid URL.",
					date: "Please enter a valid date.",
					dateISO: "Please enter a valid date (ISO).",
					dateDE: "Bitte geben Sie ein gültiges Datum ein.",
					number: "Please enter a valid number.",
					numberDE: "Bitte geben Sie eine Nummer ein.",
					digits: "Please enter only digits",
					creditcard: "Please enter a valid credit card number.",
					equalTo: "Digite igual ao campo Senha.",
					accept: "Please enter a value with a valid extension.",
				}
			});
			
				$('#loopedSlider').loopedSlider({containerClick: false,autoStart:10000});
				$('.previous,.next').css('opacity',100);		
				$('#loopedSlider').mouseout(function(){$('.previous,.next').css('opacity',100);})
				
				
				$('#mycarousel').jcarousel({
					  vertical: true,
					  scroll: 1
					  });
				  
				  
				if (swfobject.hasFlashPlayerVersion("10")) {
					var att = { data:"http://www.embreex.com.br/_flash/logo.swf", width:"282", height:"226" };
					var par = { menu:"false", wmode:"transparent" };
					var id = "logo";
					var myFlashContent = swfobject.createSWF(att, par, id);
					
					var att = { data:"http://www.embreex.com.br/_flash/mazaya.swf", width:"80", height:"30" };
					var par = { menu:"false", wmode:"transparent" };
					var id = "flashMazaya";
					var myFlashContent = swfobject.createSWF(att, par, id);
				}
				
				$(".toggle_container").hide();
			
				$("h2.trigger").toggle(function(){
					$(this).addClass("active"); 
					}, function () {
					$(this).removeClass("active");
				});
				
				$("h2.trigger").click(function(){
					$(".toggle_container").hide();
					$(this).next(".toggle_container").slideToggle("slow,");
				});
				
				//$("#nn li").hover(function(){$(this).children('ul').fadeIn(100);$(this).children('ul').fadeOut(100);});
				
				$('#tab').tabs({ fxFade: true, fxSpeed: 'fast' });
				
				$('#tabs-mapa').tabs({ fxFade: true, fxSpeed: 'fast' });
				
				$("#tab-map").accordion();
					
				$("#slider").easySlider();
				
				
				$(".produto").click(function(event){
											event.preventDefault();
											exibeProduto(this)
								});
				$(".pergunta").click(function(event){
											event.preventDefault();
											exibePergunta(this)
								});		   
		   
				$("#content-holder").tabs();
				
				$("#area").tabs();
				
				var controle = '<div class="angulo"></div>';
				//var botoes = '<a href="#" class="esq">Esq</a><a href="#" class="dir">Dir</a>';
				preencheBack();
				inicializaSimulador();
				$(".equipamento, .elemento").draggable({
					appendTo: '#ambiente',
					helper: 'clone', containment: 'parent',
					start:  function(event, ui) {
						var h = ui.helper.clone();
						$('#preview').html('<h5>Inserindo: '+h.find('img').attr('alt')+'</h5>');
					}
				});
				$("#ambiente").droppable({
					drop: function(event, ui) {
						if(ui.helper.hasClass("equipamento")){
							var h = ui.helper.clone();
							
							h.removeClass("equipamento ui-draggable-dragging ui-draggable").addClass('item').css({position:"absolute"}).appendTo(this);//.append(controle);
							h.find('.wrapper, img').removeAttr('height');//.transform({scale: [zoom,zoom]});
							
							$.ajax({
									url: 'http://www.embreex.com.br/_Request/salvarSimulacao',
									data: { html : $('#innerAmbiente').html(), idcadastros: $("#idcadastros").val(), idclientes: $("#idclientes").val(), referencia: $("#referencia").val(), idsimulacoes: $("#idsimulacoes").val()},
									type: "POST"
							});
							
							inicializaSimulador();
							
						}
						if(ui.helper.hasClass("elemento")){
							var h = ui.helper.clone();
							
							h.removeClass("elemento ui-draggable-dragging ui-draggable").addClass('parede').css({position:"absolute"}).appendTo(this);//.append(controle);
							h.find('.wrapper, img').removeAttr('height');//.transform({scale: [zoom,zoom]});
							
							$.ajax({
									url: 'http://www.embreex.com.br/_Request/salvarSimulacao',
									data: { html : $('#innerAmbiente').html(), idcadastros: $("#idcadastros").val(), idclientes: $("#idclientes").val(), referencia: $("#referencia").val(), idsimulacoes: $("#idsimulacoes").val()},
									type: "POST"
							});
							
							inicializaSimulador();
							
						}
					}
				});
				$(".botao").button();
				$("a.salvar").click(function() {
						salvar()
				})
				$("a.print").click(function() {
						window.print();
				})
//				$("#ambiente").draggable({ cancel: ".item, .elemento" })
//				$("#ambiente").click(function() {
//						var disabled = $( "#ambiente" ).draggable( "option", "disabled" );//
////						if(disabled)
////							$(this).draggable("option", "disabled", false).addClass("moveable");
////						else
////							$(this).draggable("option", "disabled", true).removeClass("moveable");
//				})
				$("#content-slider").slider({
					animate: true,
					change: handleSliderChange,
					slide: handleSliderSlide
				});
				$(".resizable").resizable({
					maxWidth: 20,
					minHeight: 150,
					minWidth: 20
				});
				$(".medida").each(function(){
								  if($(this).attr('id') == 'width')
								  	_value = $("#ambiente").width();
								  else
								  	_value = $("#ambiente").height();
									
								  $("#input_" + $(this).attr('id')).val( _value / 100);
																						 
								  $(this).slider({
										animate: true,
										value:_value,
										range: "min",
										min: 300,
										max: 3000,
										step: 50,
										slide: function(event, ui) {
											$("#ambiente").css(event.target.id, ui.value + 'px');
											$("#input_" + event.target.id).val(roundNumber(ui.value / 100,2));
											preencheBack();
										}
									});
				});
				$(".scale").slider({
					animate: true,
					value:1,
					range: "min",
					min: 0.05,
					max: 2,
					step: 0.05,
					slide: function(event, ui) {
						$("#ambiente").transform({scale: [ui.value,ui.value]});
						$("#input_scale").val((ui.value * 100) + '%');
					}
				});
				
				$("a.group").fancybox({
					'hideOnContentClick': false
				});

			
});
function alteraMedida( _ele){
	return;
}
function inicializaSimulador(){
							

						$('.item img')
							.click(function() {
								
								$('.comandos').remove();
								_com = $('<div class="comandos">');
								
								_girar = $('<div>Girar:<div class="anguloObj"></div></div>');
								_deletar = $('<a href="#" onclick="$(this).parent().parent().remove()" class="botao">Excluir Item</a>');
								_ok = $('<a href="#" onclick="$(\'.comandos\').remove()" class="botao">Ok</a>');
								$(_com).append(_girar);
								$(_com).append(_deletar);
								$(_com).append(_ok);
								
								$(this).parent().append(_com);
								
								$(".botao").button();
								
								obj = $(this);
								$(".anguloObj").slider({
									animate: true,
									value:0,
									min: 0,
									max: 360,
									range: "min",
									step: 10,
									slide: function(event, ui) {
										obj.transform({rotate: ui.value}, { forceMatrix: true, preserve: true})
									}
								});
							});
							
						$('.item').draggable({containment: 'parent', cancel: ".angulo,.anguloObj,.ui-resizable-handle" });
						
													
						
						
						$(".parede div").resizable()
							.click(function() {
								
								$('.comandos').remove();
								_com = $('<div class="comandos">');
								
								_girar = $('<div>Girar:<div class="anguloObj"></div></div>');
								_deletar = $('<a href="#" onclick="$(this).parent().parent().remove()" class="botao">Excluir Item</a>');
								_ok = $('<a href="#" onclick="$(\'.comandos\').remove()" class="botao">Ok</a>');
								$(_com).append(_girar);
								$(_com).append(_deletar);
								$(_com).append(_ok);
								
								$(this).parent().append(_com);
								
								$(".botao").button();
								
								obj = $(this);
								$(".anguloObj").slider({
									animate: true,
									value:0,
									min: 0,
									max: 360,
									range: "min",
									step: 10,
									slide: function(event, ui) {
										obj.transform({rotate: ui.value}, { forceMatrix: true, preserve: true})
									}
								});
							});;
						$(".parede").draggable({containment: 'parent', cancel: ".angulo,.anguloObj,.ui-resizable-handle" })
						
						$(".angulo").slider({
								animate: true,
								value:0,
								min: 0,
								max: 360,
								range: "min",
								step: 10,
								slide: function(event, ui) {
									$(this).prev("div").children().transform({rotate: ui.value}, { forceMatrix: true, preserve: true})
								}
							});
										
}
function preencheBack(){
				$("#ambienteBackContainer").html('');
				var amb = '<div class="ambienteBack"></div>';
				w = parseInt($("#ambiente").width() / 100) + 2;
				h = parseInt($("#ambiente").height() / 100) + 2;
				//$('#preview').html(w+' '+h+' '+(w * h)+' '+zoom+' '+(w * 200) );
				
				$("#ambienteBackContainer").css({width : (w * 100) + 'px',height: (h * 100)+'px'});
				for(i = 0; i < (w * h) ; i++)
					$("#ambienteBackContainer").append(amb);
				
				if($.browser.msie && $.browser.version == '8.0' ){
					//$("#ambienteBackContainer").css({width : w+'px',height: h+'px'});
					$(".ambienteBack").each(function(){
						$(this).css({height : (100 * zoom)+'px',width:(100 * zoom)+'px'});
					});
				}
}


function salvar(){
	$.ajax({
								url: 'http://www.embreex.com.br/_Request/salvarSimulacao',
								data: { html : $('#innerAmbiente').html(), idclientes: $("#idclientes").val(), referencia: $("#referencia").val(), idsimulacoes: $("#idsimulacoes").val()},
								type: "POST"
						});
}
function configuracoes(){
	$('#simuladorConfigs').dialog({
			modal: true,
			width: 400,
			buttons: {
				Salvar: function() {
                	salvar();
					$( this ).dialog( 'close' );
				}
			}});
}
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return newnumber; // Output the result to the form field (change for your purposes)
}

function handleSliderChange(e, ui)
{
  var maxScroll = $("#content-scroll").attr("scrollWidth") - $("#content-scroll").width();
  $("#content-scroll").animate({scrollLeft: ui.value * (maxScroll / 100) }, 1000);
}

function handleSliderSlide(e, ui)
{
  var maxScroll = $("#content-scroll").attr("scrollWidth") - $("#content-scroll").width();
  $("#content-scroll").attr({scrollLeft: ui.value * (maxScroll / 100) });
}
function exibeProduto( _id ){
	
	$.ajax({url : _id.toString().replace("Produtos","_Request/Produtos"),
		success: function(data) {
			$('#coluna-2-interno').html(data);
			$('#tab').tabs({ fxFade: true, fxSpeed: 'fast' });
			$("#slider").easySlider();
				$("a.group").fancybox({
					'hideOnContentClick': false
				});
		}
	});
}


	function carregaCep( _cep ){
		$('#carregandoCEP').html("Consultando CEP " + _cep).fadeIn();
		$.ajax({
			url: 'http://www.embreex.com.br/_Request' + '/carregaCEP/'+_cep, 
			complete: function(resposta){
					var res = $.parseJSON( resposta.responseText );
					if(res){
						if(res.logradouro){
							$('#endereco').val(res.logradouro);
						}
						$('#carregandoCEP').html('Selecionando estado');
						if(res.estado){
							//$('#idestados').selectedIndex = res.estado;
							$('#estado').val(res.estado);
						}
						$('#carregandoCEP').html('Selecionando cidade');
						if(res.cidade){
							$('#carregandoCEP').html('Buscando lista de cidades');
							$('#cidade').load('http://www.embreex.com.br/_Request' + '/carregaCidades/'+res.estado+"/"+res.cidade,
								function() {
									if(res.bairro){
										$('#carregandoCEP').html('Buscando lista de bairros');
										$('#bairro').load('http://www.embreex.com.br/_Request' + '/carregaBairros/'+res.cidade+"/"+res.bairro);
									}else{
										$('#bairro').html("<option value=''>Outro:</option>").disable();
										$('#bairro').append('<input type="text" id="bairro" name="bairro" class="input inputTextoPequeno" value="">');
									}
								});
						}
					}else{
						alert('O CEP digitado não é válido')
					}
					$('#carregandoCEP').html('Carregando...').fadeOut();
			}
		});
		
	}
	function carregaCidades( _estado , _preSeleciona ){
		$('#carregandoCEP').html("Carregando lista de cidades").show();
		$('#cidade').html("<option value=''>Carregando</option>");
		$('#cidade').load('http://www.embreex.com.br/_Request' + '/carregaCidades/'+_estado+"/"+_preSeleciona,
			function() {
				$('#carregandoCEP').html('Carregando...').hide();
			});
		$('#bairro').html("<option value=''>Selecione uma cidade</option>");
		
	}
	
	function carregaBairros( _cidade , _preSeleciona){
		$('#carregandoCEP').html("Carregando lista de bairros").show();
		$('#bairro').html("<option value=''>Carregando</option>");
		$('#bairro').load('http://www.embreex.com.br/_Request' + '/carregaBairros/'+_cidade+"/"+_preSeleciona,
			function() {
				$('#carregandoCEP').html('Carregando...').hide();
			});
		
	}

