$(function () {
    $.easing.def = 'easeInOutCirc';
    $('#top-link').topLink({ min: 300 });
    $('#top-link').click(function (e) {
        e.preventDefault();
        goToByScroll('body', 0);
    });
    $('.fadeInOut').hover(function () {
        $(this).stop(true, false).animate({ opacity: 0.6 }, 'slow');
    }, function () {
        $(this).stop(true, false).animate({ opacity: 1 });
    });
    $("table.default tr:even td").addClass("even");
    $("form.default input[type='text'] , form.default input[type='password'], form.default textarea").addClass("inputText")
	.focus(function () { $(this).addClass("inputTextFocus") })
	.blur(function () { $(this).removeClass("inputTextFocus") });
    $('.field-clear').focus(function () {
        var valorCampo = $(this).val();
        $(this).addClass('focus').val("")
		.blur(function () { $(this).removeClass('focus'); });
    });
    $('form.default :file').addClass("inputFile");
    $('.msg-dica').prepend('<div class="arrow-border"></div><div class="arrow"></div><div class="icon"></div>');
	
	/* ----- JQUERY UI --------------------------------------------------------------------  */
    $('.ui-accordion').accordion({ header: '.ui-accordion-header', autoHeight: false });
    $('.ui-tabs').tabs();
    $('.ui-button').button();
    $(".ui-button-gear").button({ icons: { primary: 'ui-icon-gear' }});
    $(".ui-button-extlink").button({ icons: { secondary: 'ui-icon-extlink' }});
    $('.ui-button-seta').button({ icons: { primary: 'ui-icon-circle-triangle-e' }});
    $('.ui-button-close-notext').button({ icons: { primary: 'ui-icon-close' }, text: false });
	
	/* ----- FORMS LOGIN | FORM PESQUISA | VALIDAÇÃO | FORM FOTTERFIXED -------------------------------------  */
	$("#fixedBottom").delay(2000).animate({ bottom: 0 }, 1600 , 'easeInOutCirc');
	$("#fixedBottom .forms a").live('click', function (event) {
        event.preventDefault();
		$(this).addClass('active').siblings('a').removeClass('active');
		if ( $(this).hasClass('email') ) {
			$('#fixedBottom .forms form.email').show();
			$('#fixedBottom .forms form.fone').hide();
		} else {
			$('#fixedBottom .forms form.fone').show('');
			$('#fixedBottom .forms form.email').hide();
		}	
	});
	$("#fixedBottom .forms .ico-erro, #fancybox-close").live('click', function (event) {
		$('#fixedBottom .forms').stop(true, false).animate({ bottom: -520 }, 1500 , 'easeInCirc' , function() { $('#fixedBottom .buttons').fadeIn('slow'); } ); 
	});
	$("#fixedBottom .buttons a.email, #fixedBottom .buttons a.fone").live('click', function (event) {
    	event.preventDefault();
		$('#fixedBottom .buttons').fadeOut( 700 , 'easeOutCirc' , function() { $('#fixedBottom .forms').stop(true, false).animate({ bottom: -60 }, 2000 , 'easeOutBounce' ); } );		 		 
		if ( $(this).hasClass('email') ) {
			$('#fixedBottom .forms a.email').addClass('active');
			$('#fixedBottom .forms a.fone').removeClass('active');
			$('#fixedBottom .forms form.email').show();
			$('#fixedBottom .forms form.fone').hide();
		} else {
			$('#fixedBottom .forms a.fone').addClass('active');
			$('#fixedBottom .forms a.email').removeClass('active');
			$('#fixedBottom .forms form.fone').show();
			$('#fixedBottom .forms form.email').hide();
		}	
	});
    $("#nav-login").hide();
    $("#nav-login .ico-erro").live('click', function (event) {
        event.preventDefault();
        $("#nav-login").hide();
        $('#link-form-painel , #link-form-webmail').removeClass('selected');
        $("#nav").fadeIn('slow');
    });
    $("#link-form-painel , .link-form-painel").live('click', function (event) {
        event.preventDefault();
        goToByScroll('body', 0);
        $("#link-form-webmail").removeClass('selected');
        if ($("#form-painel").is(":hidden")) {
            $('#link-form-painel').addClass('selected');
            $("#nav, #form-webmail").hide();
            $("#form-painel, #nav-login").fadeIn('slow');
        } else {
            $("#nav-login").hide();
            $('#link-form-painel').removeClass('selected');
            $("#nav").fadeIn('slow');
        }
    });
    $("#link-form-webmail").live('click', function (event) {
        event.preventDefault();
        $("#link-form-painel").removeClass('selected');
        if ($("#form-webmail").is(":hidden")) {
            $(this).addClass('selected');
            $("#nav, #form-painel").hide();
            $("#form-webmail , #nav-login").fadeIn('slow');
        } else {
            $("#nav-login").hide();
            $("#link-form-webmail").removeClass('selected');
            $("#nav").fadeIn('slow');
        }
    });
    $("#searchformWiki .button-lupa").live('click', function () {
        var keyword_inputwiki = $("#searchform .inputText").val();
        $("#searchformWiki").attr('action', 'http://wiki.tehospedo.com.br/w/Especial:Busca?search=' + keyword_inputwiki + '&go=Ir').submit();
    });
    $("#formAtendimento").bValidator();
    $("#form-webmail").bValidator();
    $("#form-painel").bValidator();
    $("#searchformWiki").bValidator();
    $("#form-suporte-painel").bValidator();
    $("#form-hospedagem").bValidator();
    $("#form-registro_hospedagem").bValidator();
	$("#form-transferencia-dominio form").bValidator();
	
	/* ---- EQUAL HEIGHT & FANCYBOX  -------------------------------------------------------------- */
    $('a[rel=fancybox_group]').fancybox({ 'transitionIn': 'elastic' });
    $("a.link-chat").fancybox({ 'width': 470, 'height': 470, 'autoScale': false, 'type': 'iframe' });
    equalHeight($(".equalheight-a"));
    equalHeight($(".equalheight-b"));
    equalHeight($(".equalheight-c"));
    equalHeight($(".equalheight-d")); 
	$('.ntha td:nth-child(1), .ntha th:nth-child(1)').addClass('ntha');	
	$('.ntha-tdleft td:nth-child(1)').addClass('ntha-tdleft');
	
	/* ----- FUNÇÃO MENU PRINCIPAL E ASSINATURA SIMPLES (AS-)-------------------------------------  */
    $('.megamenu > a').each(function(){
		var nav = $(this);
		nav.click(function () {
			$('.megamenu > a').removeClass('active').siblings('div').hide().end().find('.seta').removeClass('active');
			if ( nav.hasClass("active")) {
				nav.removeClass('active').siblings('div').hide().end().find('.seta').removeClass('active');
			} else {
				nav.addClass('active').siblings('div').show().end().find('.seta').addClass('active');
			}
    	});
	});
    $(".megamenu div").mouseenter(function () {
        	$(this).addClass('active');
    	}).mouseleave(function () {
        	if ($(this).hasClass("active")) {
            $(this).removeClass('active').stop(false, true).fadeOut('fast').siblings('a').removeClass('active').find('.seta').removeClass('active');
        }
    });	
	
    $('.as-apenas-hospedar').click(function () {
        $('#as-registrar-hospedar').hide();
        $('#as-hospedar').fadeIn('slow');
        goToByScroll('#as-hospedar');
        $('#as-hospedar #dominio').focus();
    });
    $('.as-registrar-e-hospedar').click(function () {
        $('#as-hospedar').hide();
        $('#as-registrar-hospedar').fadeIn('slow');
        goToByScroll('#as-registrar-hospedar');
        $('#as-registrar-hospedar .inputText').focus();
    });
    $('.as-fechar-registrar-hospedar, .as-fechar-hospedar').click(function () {
        $('#as-registrar-hospedar, #as-hospedar').fadeOut();
        goToByScroll('.content');
    });
    $('#as-verifica-dominio').keypress(function (e) {
        if (e.which == 13) {
            $(".as-verificar").click();
        }
    });
    $(".as-verificar").click(function (event) {
        event.preventDefault();
        $('#as-pesquisando-div').hide();
        $(this).after('<div class="msg-alerta" id="as-pesquisando-div">Pesquisando! Aguarde alguns segundos</div>');
        $('#as-registrando, #as-resultado , #as-transferir').hide();
        $.ajax({
            url: "/ajax/registro/",
            type: "GET",
            data: ({ dominio: $("#as-verifica-dominio").val() }),
            success: function (result) {
                $('#as-resultado-wrap , #as-registrando-dominio').text("").html("");
                $('#as-registrando, #as-resultado').hide();
                $('#as-dominio-hospedagem').val("");
                $('#as-resultado-wrap').wrapInner("<ul id='as-resultado'/>");
                $("#as-pesquisando-div").hide();
                var res = jQuery.parseJSON(result);
                var index = 0;
                $.each(res, function (i, item) {
                    var last = index;
                    index++;
                    if (index == 1) {
                        $('#as-resultado').wrapInner("<li id='as-resultado" + index + "div' class='as-resultado-divs' />");
                    } else {
                        $("#as-resultado" + last + "div").after("<li id='as-resultado" + index + "div' class='as-resultado-divs' />");
                    }
                    var id = "h4" + i;
                    $.each(item, function (i2, item2) {
                        if (i2 == 'status') {
                            if (item2 == 'available') {
                                $("#as-resultado" + index + "div").addClass('msg-ok').append("<a class='right link-disponivel' onclick='javascript:as_registrar(\"" + i + "\")'>Selecionar</a>" + i);
                            } else {
                                $("#as-resultado" + index + "div").addClass('msg-erro').append("<a class='right link-transferir' onclick='javascript:as_transferir(\"" + i + "\")'>Transferir</a>Indisponível: " + i);
                            }
                        }});
                });}
        }); //END $ajax
    });
}); // END Document Ready $

/* ----- FUNÇÕES:  ASSINATURA SIMPLES -------------------------------------  */

function as_registrar(dominio) { 
    $('#as-resultado').fadeOut('slow');
    $('#as-registrando-dominio').text(dominio);
    $('#as-dominio-hospedagem').val(dominio);
    if (dominio.slice(-3) == '.br') { $('#valor-dominio').text('40,00'); } 
		else { $('#valor-dominio').text('15,00'); }
    $('#as-registrando').fadeIn('slow').find('#topcadastro-email-hospedagem').focus();
    goToByScroll('.as-verificar');
}

function as_transferir(dominio) { 
    $('#as-resultado').fadeOut('slow');
    $('.as-transferindo-dominio').text(dominio);
    $('#as-dominio-transferencia').val(dominio);
	$('#as-transferir').fadeIn('slow');
    $('#form-transferencia-dominio .inputText').focus();
    goToByScroll('.as-verificar');
}

function equalHeight(group) { 
    var tallest = 0;
    group.each(function () {
        var thisHeight = $(this).height();
        if (thisHeight > tallest) { tallest = thisHeight; }
    });
    group.height(tallest);
}

function goToByScroll(id, padding) {
    if (padding === undefined) {
        padding = 131;
    }
    topOffsetID = $(id).offset().top;
    $('html,body').animate({
        scrollTop: topOffsetID - padding
    }, 1500); //-131px Padding-top Body
}

function googleSearchForm( ) {
        var keyword_input = $("#searchform .field-clear").val();
		var url = $("#searchform").attr('action');
        $("#searchform").attr('action', url + keyword_input).submit();
}
	
$.fn.topLink = function (settings) {
    settings = jQuery.extend({ min: 1, ieOffset: 50 }, settings);
    return this.each(function () {
        var el = $(this);
        el.css('display', 'none');
        $(window).scroll(function () {
            if (!$.support.hrefNormalized) {
                el.css({
                    'position': 'absolute',
                    'top': $(window).scrollTop() + $(window).height() - settings.ieOffset
                });
            }
            if ($(window).scrollTop() >= settings.min) {
                el.fadeIn('slow');
                $('#nav').css('opacity', .9);
            } else {
                el.stop(true, true).fadeOut('fast');
                $('#nav').stop(true, true).css('opacity', 1);
            }
        });
    });
};
