/**
 * Recupera o valor de uma variável da query string
 * @param string variable A variável que se deseja o valor
 * @return string O valor da variável
 */
function querystring( variable ){
	var qs		= window.location.href.split( "?" )[ 1 ];
	var args	= qs.split( "&" );
	var ret		= false;

	for ( var i = 0 , t = args.length ; i < t ; i++ ){
		var parts	= args[ i ].split( "=" );
		var name	= parts[ 0 ];

		if ( variable === name ){
			if ( parts[ 1 ] !== undefined ){
				ret = parts[ 1 ];
			} else {
				ret = true;
			}

			break;
		}
	}

	return( ret );
}

function adicionais(){
	$( "input[rel=adicional]" ).click( function(){
		var total = $( "th[class=t2]" ).attr( "rel" );
		var itens = [];
		var parte = $( this ).attr( "value" ).split( "::" );

		total = parseFloat( total.split( "R$" ).join( "" ).split( "," ).join( "." ) );

		if ( parte[ 0 ] == "CONSTRUTOR" ){
			var obj = $( "div.construtor" );

			if ( $(this).attr( "checked" ) ){
				if ( !obj.is( ":visible" ) )
					obj.fadeIn( "slow" );
			} else {
				if ( obj.is( ":visible" ) )
					obj.fadeOut( "slow" );
			}
		}

		$( "input[type=checkbox]:visible" ).each( function(){
			var conteudo = $( this ).attr( "value" ).split( "::" );
			var partes;

			if ( $( this ).attr( "checked" ) ) {

				if ( conteudo.length > 1 ) {
					var valor = parseFloat( conteudo[ 2 ].split( "R$" ).join( "" ).split( "," ).join( "." ) );

					if ( !isNaN( valor ) ) {
						total += valor;
					}
				}
			}
		} );

		if ( total != 0 ) {
			total = "" + Math.round( total * 1000 ) / 1000;

			if ( ( partes = total.split( "." ) ).length == 2 ) {
				if ( partes[ 1 ].length == 1 ) {
					total = total + "0";
				}
			}
		}

		$( "th[ class=t2 ] span" ).text( "R$ " + total );
		$( "th[ class=t2 ] input" ).val( total );
	} );
}

function add( valor ){
	var total = $( "th[ class=t2 ] input" ).val();
	var partes = [];

	total = parseFloat( total.split( "R$" ).join( "" ).split( "," ).join( "." ) );

	total += valor;

	if ( total != 0 ) {
		total = "" + Math.round( total * 1000 ) / 1000;

		if ( ( partes = total.split( "." ) ).length == 2 ) {
			if ( partes[ 1 ].length == 1 ) {
				total = total + "0";
			}
		}
	}

	$( "th[ class=t2 ] span" ).text( "R$ " + total );
	$( "th[ class=t2 ] input" ).val( total );
}

function enviaContrato(){
	var tdc = $( "#tdc" ).attr( "rel" );

	if ( tdc == "servicos,acesso,wireless" ){
		alert( "Atenção !!!\n\nSerá necessário uma verificação de viabilidade técnica para a instalação do acesso WiFi.\nSomente após constatado a viabilidade técnica para o local que o presente contrato passará a ter valor e somente então será enviado a cobrança relativa ao serviço." );
	}

	$( "#formContrato" ).submit();
}

function verifica_formato_nome( nome ){
	var ret		= true;
	var formato	= /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	var teste	= nome + "@com4.com.br";

	ret = formato.test( teste );

	return( ret );
}

/*
 * ON LOAD DA PAGINA
 */
$( function(){
	var dados_dominio	= false;
	var dados_acesso	= false;
	var validando_user	= false;
	var podeir			= true;
	var enviar			= false;

	$( "div.construtor" ).replaceWith( "<div class='construtor'><label for='codigolayout'><b>Código do layout: </b><span><input id='codigolayout' size='8' type='text' name='codigolayout' /></span></label></div>" );
	$( "div.construtor" ).hide();

	$( "tr.dominio" ).hide();

	$( "table#dados_acesso" ).each( function(){
		dados_acesso = true;
		podeir = false;
	} );

	$( "table#dados_dominio" ).each( function(){
		dados_dominio = true;
		podeir = true;
	} );

	$( "input[ type=checkbox ]" ).css( {
		background		: "none",
		border			: "none",
		lineHeight		: "19px",
		verticalAlign	: "middle"
	} );

	$( "#checkdominiosim" ).click( function(){
		if ( $( this ).attr( "checked" ) ) {
			$( "#checkdominionao" ).attr( "checked" , "" );
			$( "tr.nao" ).hide();
			$( "tr.sim" ).show();
		} else {
			$( "tr.sim" ).hide();
		}
	} );

	$( "#checkdominionao" ).click( function(){
		if ( $( this ).attr( "checked" ) ) {
			$( "#checkdominiosim" ).attr( "checked" , "" );
			$( "tr.sim" ).hide();
			$( "tr.nao" ).show();
		} else {
			$( "tr.nao" ).hide();
		}
	} );

	$( "img[ rel=check ]" )
		.click( function(){
			var campo = $( "#nao" ).val();
			var dominio = [ "name" , ( campo ).split( "www." ).join( "" ) ].join( "=" );
			var suffix = [ "sufix" , ( $( "#suffix" ).val() ) ].join( "=" );

			if ( campo.split( " " ).join( "" ).length ) {
				podeir = false;

				$.ajax( {
					type		: "POST" ,
					url			: "?session=registro_dominios.php&ajax" ,
					data		: [ dominio , suffix ].join( "&" ) ,
					async		: false ,
					dataType	: "html" ,
					success		: function( msg ){
						if ( msg == "<indisponivel />" ) {
							alert( "Domínio indisponível para registro" );
						} else {
							var total = 0;
							podeir = true;

							$( "#adicionais" ).each( function(){
								total++ ;
							} );

							if ( total ) {
								$( "#adicionais" ).append( msg );
							} else {
								$( "#carrinho" )
									.append( "<tfoot id='adicionais'><tr><td><h1>Adicionais</h1></td></tr><tr><th class=\"t2 noBorder_left\" colspan=\"2\">Descrição</th><th class=\"t2\">Total</th></tr>" + msg + "</tfoot>" );
							}
						}
					}
					} );
			} else {
				alert( "Você precisa especificar o domínio que deseja registrar." );
			}
		} );

	$( "a.fechar" ).click( function(){
		if ( validando_user ){
			enviar = true;
			alert( "Aguarde, verificando se o nome de usuário escolhido está disponível..." );
		} else if ( podeir ) {
			if ( dados_acesso ) {
				var login = $( "#login" ).val();
				var senha = $( "#senha" ).val();

				if ( ( senha.length >= 6 ) && login.length && verifica_formato_nome( login ) ){
					$( ".fConfigs" ).submit();
				} else {
					if ( !login.length ){
						alert( "Você deve especificar o nome de usuário e senha com que deseja conectar" );
					} else if ( senha.length < 6 ){
						alert( "A senha deve ter no mínimo 6 caracteres entre letras e números." );
					} else if ( !verifica_formato_nome( login ) ){
						alert( "O nome escolhido possui caracteres inválidos\n\nNão utilize espaços, pontos ou qualquer caracter acentuado como: ç, ã, ê..." );
					}
				}
			} else if ( dados_dominio ) {
				var sim = $( "#sim" ).val();
				var nao = $( "#nao" ).val();

				if ( sim.length || nao.length ) {
					$( ".fConfigs" ).submit();
				} else {
					alert( "Você deve especificar o nome do domínio para a hospedagem." );
				}

			} else {
				$( ".fConfigs" ).submit();
			}
		} else {
			alert( "Para fechar o pedido é necessário que todos os campos estejam preenchidos" );
		}
	} );

	$( "#login" ).change( function(){
		var login = $( this ).val();

		if ( verifica_formato_nome( login ) ){
			validando_user = true;

			if ( login.length ){
				$.ajax( {
					type		: "POST",
					url			: "?session=verifica_login.php&ajax",
					data		: { login : login },
					async		: false,
					dataType	: "json",
					success		: function( msg ){
						if ( msg.sucesso !== true ){
							podeir = false;
							$( "#login" ).val( "" );
							alert( "O nome de usuário escolhido já está em uso, por favor escolha outro." );
						} else {
							podeir = true;

							if ( enviar ){
								enviar = false;
								validando_user = false;
								$( "a.fechar" ).click();
							}
						}
					},
					complete	: function(){
						validando_user = false;
					}
				} );
			} else {
				alert( "O nome de usuário não pode ficar em branco." );
			}
		} else {
			alert( "O nome escolhido possui caracteres inválidos\n\nNão utilize espaços, pontos ou qualquer caracter acentuado como: ç, ã, ê..." );
		}
	} );

	if ( $( "#login" ).val() != undefined ){
		if ( $( "#login" ).val().length ){
			var login = $( "#login" ).val();

			$.ajax( {
				type		: "POST",
				url			: "?session=verifica_login.php&ajax",
				data		: { login : login },
				async		: false,
				dataType	: "json",
				success		: function( msg ){
					if ( msg.sucesso !== true ){
						podeir = false;
						$( "#login" ).val( "" );
						$( "#senha" ).val( "" );
					} else {
						podeir = true;
					}
				},
				complete	: function(){
					validando_user = false;
				}
			} );
		}
	}

	$( "#senha" ).change( function(){
		var senha = $(this).val();

		if ( senha.length < 6 ){
			alert( "A senha deve ter no mínimo 6 caracteres, entre letras e números." );
		}
	} );

	adicionais();

	$( "a[rel=add_cart]" ).click( function(){
		var url = $( this ).attr( "href" );
		var array = url.split( "," )

		var id		= array[ 0 ]; // key do sistema com4
		var tipo	= array[ 1 ]; // tipo de produto
		var valor	= array[ 2 ]; // valor do serviço
		var nome	= array[ 3 ]; // nome do serviço
		var area	= array[ 4 ]; // area do servico
		var taxa	= array[ 5 ]; // Taxa de instalação
		var cidade	= array[ 5 ]; // Cidade
		var pcla	= array[ 6 ]; // Número de parcelas
		var dados	= "id=" + id + "&tipo=" + tipo + "&valor=" + valor + "&nome=" + escape( nome );
		var passo	= querystring( "passo" );
		var sessao	= querystring( "session" );
		var post	= true;

		if ( area != undefined ) {
			area = area.split( "-" ).join( "," );
		}

		switch ( sessao ){
			case "servicos,acesso,netsuper":
				dados = dados + "&sessao=" + area + "&cidade=" + cidade + "";
				break;
			case "servicos,acesso,wireless":
				dados = dados + "&sessao=" + area + "&taxa=" + taxa + "&pcla=" + pcla + "";
				break;
			default:
				dados = dados + "&sessao=" + area + "";
		}

		if ( sessao == "servicos,acesso,netsuper" ){
			var link = "?session=carrinho_login";

			post = passo === false;

			if ( passo === false ){
				if ( confirm( "Para sua maior comodidade a Com4 pode solicitar junto a CTBC o acesso Netsuper para você, para isso clique em \"Ok\" e escolha o plano desejado.\n\nCaso você queira solicitar o plano de acesso diretamente pela CTBC clique em \"Cancelar\"." ) ){
					link = "?session=servicos,acesso,netsuper&cidade=" + querystring( "cidade" ) + "&passo=2";
				}
			} else if ( passo == 2 ){
				var plano = $( this ).attr( "href" );

				if ( plano !== undefined ){
					plano = plano.split( "," )[ 0 ];
					window.location.href = "?session=servicos,acesso,netsuper&cidade=" + querystring( "cidade" ) + "&plano=" + plano + "&passo=3";
				} else {
					window.location.href = "?session=servicos,acesso,netsuper&cidade=" + querystring( "cidade" ) + "&passo=2";
				}
			} else if ( passo == 3 ){
				var plano = querystring( "plano" );
				var modem = $( this ).attr( "href" );

				window.location.href = "?session=servicos,acesso,netsuper&cidade=" + querystring( "cidade" ) + "&plano=" + plano + "&modem=" + modem + "&passo=4";
			}

			if ( post ){
				$.post( "?session=carrinho_add.php&act=add&ajax" , dados , function( data ){
					window.location.href = link;
				} );
			}
		} else {
			$.post( "?session=carrinho_add.php&act=add&ajax" , dados , function( data ){
				window.location.href = "?session=carrinho_login";
			} );
		}


		return false;
	} );

	$( "a[rel=del_cart]" ).click( function(){
		$( this ).parents( "tr" ).remove();

		var url = $( this ).attr( "href" );
		var array = url.split( "," )

		var item = array[ 0 ]; // item para ser removido

		dados = "item=" + item;
		$.post( "?session=carrinho_add.php&act=del&ajax" , dados , function( data ){
			$( this ).parents( "tr" ).remove();
		} );

		return false;
	} );


	//POP-UP CONSULTA --------------------------------------->
	$(".abreform").click(function(){
		var array = ___getPageSize();
		var w = array[0];
		var h = array[1];
		//alert(screen.availHeight);

		$("div#formConsulta").css({
			width:w,
			height:h,
			opacity: 0.9
		}).fadeIn();

		$("div#formulario").fadeIn();

		return false;
	});

	$('div#formConsulta').click(function(){
		$('div#formConsulta').fadeOut();
		$('div#formulario').fadeOut();
	});

	$('#botao_fechar').click(function(){
		$('div#formConsulta').fadeOut();
		$('div#formulario').fadeOut();
	});

	//<----------------------------------------------------------

} );


function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};

