var Clear = {};
var dados_form = {};
var JString = new function StringMelhor() {

    this.render = function( str, key_value ) {
	var val, k;
        for ( k in key_value ) {
	    val = key_value[ k ];
            str = str.replace( '{%s}'.replace( '%s', k ), val );
        }

        return str;

    }

};

( function( $ ) {
$( document ).ready( function() {

var host = "http://www.cleareducacao.com.br/";

//! Referencia: https://pagseguro.uol.com.br/desenvolvedor/carrinho_proprio.jhtml#rmcl
Clear.form_pagamento = '<div id="pagar">'
+ '<form id="pagseguro" target="pagseguro" method="post" action="https://pagseguro.uol.com.br/checkout/checkout.jhtml" accept-charset="ISO-8859-1">'
+ '<input type="hidden" name="email_cobranca" value="cleareducacao@gmail.com">'
+ '<input type="hidden" name="tipo" value="CP"> <input type="hidden" name="moeda" value="BRL">'
+ '<input type="hidden" name="item_id_1" value="{id}">'
+ '<input type="hidden" name="item_descr_1" value="{descricao}">'
+ '<input type="hidden" name="item_valor_1" value="{valor}">'
+ '<input type="hidden" name="item_quant_1" value="1">'
+ '<input type="hidden" name="item_frete_1" value="0">'
+ '<input type="hidden" name="item_peso_1" value="0">'
+ '<input type="hidden" name="tipo_frete" value="EN">'
//INICIO DOS DADOS DO USUARIO
+ '<input type="hidden" name="ref_transacao" value="{ref_transacao}">'
+ '<input type="hidden" name="cliente_nome" value="{cliente_nome}">'
+ '<input type="hidden" name="cliente_cep" value="{cliente_cep}">'
+ '<input type="hidden" name="cliente_end" value="{cliente_end}">'
+ '<input type="hidden" name="cliente_num" value="{cliente_num}">'
+ '<input type="hidden" name="cliente_compl" value="{cliente_compl}">'
+ '<input type="hidden" name="cliente_bairro" value="{cliente_bairro}">'
+ '<input type="hidden" name="cliente_cidade" value="{cliente_cidade}">'
+ '<input type="hidden" name="cliente_uf" value="{cliente_uf}">'
+ '<input type="hidden" name="cliente_pais" value="{cliente_pais}">'
+ '<input type="hidden" name="cliente_ddd" value="{cliente_ddd}">'
+ '<input type="hidden" name="cliente_tel" value="{cliente_tel}">'
+ '<input type="hidden" name="cliente_email" value="{cliente_email}">'
//FIM DOS DADOS DO USUARIO
+ '<input type="image" src="https://p.simg.uol.com.br/out/pagseguro/i/botoes/pagamentos/99x61-pagar-assina.gif" name="submit" alt="Pague com PagSeguro - é rápido, grátis e seguro!" title="Pague com PagSeguro - é rápido, grátis e seguro!">'
+ '</form></div>';
//$('.passo-a-passo li').corner( '5px' );
//$(':input').corner('5px')
Clear.formPagSeguro = function( dados ) {
   var $ = jQuery;
   var html = '';
   var dados = dados || {};
   html = JString.render( Clear.form_pagamento, dados );
   if ( dados.id && dados.descricao && typeof( dados.valor ) != "undefined" ) {

   } else {
       //alert( "ERRO: Não foi possível pegar os valores.", dados.id, dados.descricao, dados.valor );
   }
   return html;
};

$( 'input[type="text"].data' ).mask( "99/99/9999" );
$( 'input[type="text"].cpf' ).mask( "999.999.999-99" );
$( 'input[type="text"].cep' ).mask( "99999-999" );
//$( 'input[type="text"].fone' ).mask( "(99) 9999-9999" );

Clear.pagar = function( ref_transacao ) {

   var $ = jQuery, form, valor;
   
   valor = $( 'select[name="curso_id"]:first option:selected' ).attr( 'valor' ).replace( ',', '.' ).replace('R$ ', '' );
   var dados = {
		id: $( ':input[name="curso_id"]:last' ).val(),
		ref_transacao: ref_transacao,
		descricao: 'Curso: ' + $( 'select[name="curso_id"] option:selected' ).text(),
		valor: valor,
		cliente_nome: $( 'input[name="cliente_nome"]:last' ).val(),
		cliente_cep:  $( 'input[name="cliente_cep"]:last' ).val(),
                cliente_end: $( 'input[name="cliente_tipo_logradouro"]:last' ).val() + ' ' +  $( 'input[name="cliente_logradouro"]:last' ).val(),
                cliente_num: $( 'input[name="cliente_numero"]:last' ).val(),
                cliente_compl: $( 'input[name="cliente_complemento"]:last' ).val(),
                cliente_bairro: $( 'input[name="cliente_bairro"]:last' ).val(),
                cliente_cidade: $( 'input[name="cliente_cidade"]:last' ).val(),
                cliente_uf: $( 'input[name="cliente_uf"]:last' ).val(),
                cliente_pais: 'BRA',
                cliente_ddd: $( 'input[name="cliente_telefone_residencial"]:last' ).val() + "".replace( '(', '' ).split( ')' )[ 0 ],
                cliente_tel: $( 'input[name="cliente_telefone_residencial"]:last' ).val(),
                cliente_email: $( 'input[name="cliente_email"]' ).val()
    };
    $( '.passo-a-passo .passo1' ).removeClass( 'passo_atual' );
    $( '.passo-a-passo .passo2' ).addClass( 'passo_atual' );
    $( '.wpcf7-form > *' ).not( '.wpcf7-mail-sent-ok' ).hide();
//    $( 'p.pessoa-tipo' ).remove();
    $( '.form-matricula-pf, .form-matricula-pj' ).hide();

    $( '#pagar' ).remove();

    form = Clear.formPagSeguro( dados );

    if ( valor && valor != '0' ) {
        ///alert( "Efetue o pagamento e acesse seu e-mail." );
        ///$( '#main .content:first' ).append( form );
	$( form ).insertAfter( '#passos_matricula' );
        $( '#pagar form' ).submit();
	$( document ).scrollTop( 0 );
    } else {
        alert( 'Curso sem custo.' );
    }
};
Clear.google_code = function( id_form ) { //return false;

	if ( !( id_form == "5" || id_form == "7" ) ) {
		return false;
	}

	//! '<!-- Google Code for Contatos Conversion Page -->'
	var html = '<script type="text/javascript">'
		+ '/* <![CDATA[ */'
		+ 'var google_conversion_id = 973204511;'
		+ 'var google_conversion_language = "pt";'
		+ 'var google_conversion_format = "2";'
		+ 'var google_conversion_color = "ffffff";'
		+ 'var google_conversion_label = "3D6JCMHQqAIQn9iH0AM";'
		+ 'var google_conversion_value = 0;'
		+ '/* ]]> */'
		+ '</script>'
		+ '<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">'
		+ '</script><noscript><div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/973204511/?label=3D6JCMHQqAIQn9iH0AM&amp;guid=ON&amp;script=0"/></div></noscript>';
	var iframe = document.createElement('iframe');
	iframe.style.width = '0';
	iframe.style.height = '0';
	iframe.src = host + '/utils/google_conversion.php';
	document.body.appendChild( iframe );
//		jQuery( 'body' ).append( html );

};

var slideOutName = "#slideoutContainer";   
var slideOutMenuYloc = null;	



    if ( $( slideOutName ).length > 0 ) {

        //************************************************************
	// floating reengergize menu event handler
	// requires dimensions.js plugin
	//************************************************************
		// get initial positioning of slideout menu
	slideOutMenuYloc = parseInt($(slideOutName).css("top").substring(0,$(slideOutName).css("top").indexOf("px")));
	//event listerner for scroll
	$(window).scroll(function () {
		//get the amount of scroll on window
		offset = slideOutMenuYloc+$(document).scrollTop();
		//subtract 170 from the offset because the panel needs at least that much 
		//to display entire panel in 1024x768 window
		offset=offset-170;
		//check if the offset is larger than the initial position of slideout menu
		if(offset>slideOutMenuYloc){
			//if new scrolled position larger the initial psoition use the new offset value
			offset = offset + "px";
		} else {
			//new scolled position not larger than initial position so use the initial position
			offset = slideOutMenuYloc + "px";
		}
		//float the slidemenu to new position
		$(slideOutName).animate({top:offset},{duration:300,queue:false});
		$('#slideoutTab').addClass("slideActive");
	});
	//************************************************************
	// animate action for slideout reengergize menu
	//************************************************************
	$('#slideoutTab a').toggle(function() {
		$(this).addClass("clicked");
		$('#slideoutContainer').animate({left:'0px'}, {queue:false, duration: 200});
		return false;
	}, function() {
		$(this).removeClass("clicked");
		$('#slideoutContainer').animate({left:'-500px'}, {queue:false, duration: 200});		
		return false;
	});
	//setTimeout( function() { $('#slideoutTab').show('slide', {direction: 'left'}, 1000); }, 3000 );

	if ( $.browser.msie && $.browser.version == '7.0' ) { $('#slideoutTab a').css( 'margin-left' , '10px' ); }
    }


/*
/// QUEBRA A DATA
jQuery('.post_extra_info time').each( function() {

    var post_time = jQuery( this ).text().split(' ').splice(0,3);
    post_time.splice( 1,1 );

    //var post_time_html = '<span>%d<br/></span>'.replace( '%s', post_time[ 0 ] );
    post_time[ 1 ] = post_time[ 1 ].substr( 0, 3 );
    var post_time_html = post_time.join( '<br />' );
//alert(post_time_html);
    jQuery( this ).html( post_time_html );

} );*/

$( '.container_select_cursos' ).each( function() {
	//$( 'select[name="curso_id"]:eq(0)' ).clone( true ).appendTo( this );
	var $select = $( 'select[name="curso_id"]:eq(0)' ).clone( true );
	var nome_curso = $( 'option:selected', $select ).text();
	$( 'input[name="curso_nome"]' ).val( nome_curso );
	$( 'input[name="curso_id"]' ).val( $select.val() );
	$select.appendTo( this ).hide();
	$( this ).append(  '<span class="nome_curso">' + nome_curso + '</span>' );
} );
$( 'select[name="curso_id"]:last' ).remove();

    $( '.busca_cep' ).bind( 'click', function() {
	var $eu = $( this ), $busca = $( this ), $form = $busca.parents( 'form:first' ), inputs = $form.find(':input');
	$( this ).text( 'Procurando...' );
        $.ajax( {
	    url: host + "utils/utils.php",
	    //data: "cep="+$( this ).val(),
	    data: "cep="+$( this ).parent().find('input.cep').val(),
	    dataType: "json",
	    //dataType: "text",
	    success: function( res ) {
		//console.log( res ); //alert(res.uf );
		/*inputs.each(function() { console.log(this.getAttribute('name') ); });
		for( var i in inputs ) {
		    var name = $( inputs[ i ] ).attr( "name" );
		    if ( res[ name ] == name ) {}
		} */
		$form.find('input[name="cliente_tipo_logradouro"]').val( res.tipo_logradouro );
		$form.find('input[name="cliente_logradouro"]').val( res.logradouro );
		$form.find('input[name="cliente_cidade"]').val( res.cidade );
		$form.find('input[name="cliente_bairro"]').val( res.bairro );
		$form.find('input[name="cliente_uf"]').val( res.uf );
		$form.find( 'input[name="cliente_numero"]' ).focus();
                $eu.text( 'Procurando... OK' );
		$eu.text( 'Procurar' );
	    },
	    error: function( e ) {
		$eu.text( 'Procurar' );
	    }
        } );
    } );
    $( 'input[name=cliente_tipo]' ).bind( 'click', function() {
		var $pj_campos = $( '#in_cliente_cnpj,#in_cliente_ie,#in_cliente_razao_social,#in_cliente_pj_responsavel,#in_cliente_pj_responsavel_email,#in_cliente_pj_responsavel_telefone' );
	if ( $( this ).val() == "PJ" ) {
		$( '.matricula_pessoa_fisica' ).hide();
		$( '.matricula_pessoa_juridica' ).show();
		$pj_campos.each( function() { 
			if ( $( this ).val() == "-" ) {
				$( this ).val( '' );
			}
		} );
		$( '#matricula_endereco' ).insertBefore( '#matricula_dados_pessoais_aluno' );
	} else {
		$( '.matricula_pessoa_fisica' ).show();
		$( '.matricula_pessoa_juridica' ).hide();
		$pj_campos.each( function() { 
			if ( $( this ).val() == "" ) {
				$( this ).val( '-' );
			}
		} );
		$( '#matricula_endereco' ).insertAfter( '#matricula_dados_pessoais_aluno' );
	}
	} );
    $( 'input[name=cliente_tipo]:first' ).trigger( 'click' );
    if ( !$.browser.msie ) { $( '.mini_tabs li' ).corner( 'top 5px' ); } //.parent().css('padding', '2px').corner("top 5px"); 
	//$(this).corner("round 8px").parent().css('padding', '4px').corner("round 10px");
    /*$( '#menu-comercial li:last a' ).corner( 'right' );
    $( '#menu-comercial li:first a' ).corner( 'left' );
    $( '.mini_tabs li' ).corner( 'top 5px' );
    $( '#slideoutContainer' ).corner( 'right' );
    $( '#nivo_slider_wrap, #nivo_slider, .nivo-slice' ).corner();
    $( '.nivo-caption' ).live( 'load', function() { $( this ).corner( 'bottom' ); } );*/
    $( '#outras_formas_pagamento_link, #outras_formas_pagamento_fechar' ).bind( 'click', function() {
       var $div = $( '#outras_formas_pagamento' );
        if ( $div.is( ':visible' ) ) {
               $div.hide();
       } else {
               $div.show();
       }
    } );

} ); //ready!

} )(jQuery);



