/**
 * ---------------------------- //
 * Classe com metodos comuns
 * ---------------------------- //
 **/
var structure = {
    
    isLoad : false,
    
    init : function() {
        if(!this.isLoad) this.isLoad = true;
        else return false;
        structure.header.init();
//      structure.footer.init();
        structure.internal.init();
        
//      if(ROOT_TREE == 'Hotsites') hotsite.init();
    },
        
    /**
     * ----------------- //
     * Header [start]
     * ----------------- // 
     **/
    header : {

        init : function() {
            structure.header.form.init();
            // structure.header.care();

            /**
             * Add Rounded Corners
             **/

            var navBg = null;
            var titleBg = null;
            var careBg = null;

            if ($('body').attr('id') == 'marinheiro'){
                titleBg = '#006d95';
                navBg = '#0b889e';
                careBg = '#02a4bb';
            } else if ( $('body').attr('id') == 'somerj' ) {
                titleBg = '#d8d9db';
                navBg = '#088879';
                careBg = '#0aa995';
            } else if ( $('body').attr('id') == 'aeronautica' ) {
                titleBg = '#82b007';
                navBg = '#4c8c2c';
                careBg = '#699e42';
            } else {
                titleBg = '#5a9600';
                navBg = '#5a9600';
                careBg = '#5a9600';
            }

            $('> li > a', '#areaLogin #navigation > ul').cornerz({ radius: 6, corners:'tl tr', background : navBg });
            $('h3, fieldset', '#areaLogin form').cornerz({ radius: 6, background : titleBg });
            $('label', '#areaLogin form').cornerz({ radius: 6, background : '#6ba11a' });
            $('> h3', '#care').cornerz({ radius:6, corners:'tl tr bl', background : careBg });

            if( $.browser.msie ) {
                $( 'label.password-login' ).css( { width : 144 } );
            }
            /*
            $('> ul > li > a', '#navigation').bind('click', function(){
                return false;
            });
            */

        },

        /**
         * ------------------- //
         * Form - Header
         * ------------------- //
         **/
        form : {

            init : function(){

                var initval = 'Nº do cartão';
                $( '#areaLogin form #usuario' ).setMask('99999999999999999').val(initval).focusin( function() {
                    $(this).val( ( $(this).val() == initval) ? '' : $(this).val() );
                } ).focusout( function() {
                    $(this).val( ( $(this).val() == '') ? initval : $(this).val() );
                });

                $('#areaLogin form').submit(function() {
                    structure.header.form.validate();
                    return false;
                });
            },

            validate : function(){

                var form = $('#areaLogin form');
                if( $('#usuario', form).val() == 'Nº do cartão'){
                    helpers.errorAlert( $('#areaLogin'), 'Número do cartão está incorreto.');
                } else if( $('#usuario', form).val().length < 1){
                    helpers.errorAlert( $('#areaLogin'), 'Número do cartão está incorreto.');
                } else if( $('#senha', form).val().length < 1){
                    helpers.errorAlert( $('#areaLogin'), 'Preencha corretamente sua senha.');
                } else {
                    this.sendData();
                }
            },

            sendData : function(){

                helpers.errorAlert( $('#areaLogin'), 'Aguarde...', {'bgcolor':'#d3d3c3', 'color':'#3c493e', 'cornerzColor': '#B9D300', 'autoFadeOut': false, 'animTime':0});
                var form = $('#areaLogin form');
                var url = form.attr('action');

                var data = {
                    cartao: $("#usuario", form).val(),
                    senha: $("#senha", form).val()
                }

                $.ajax({
                    url: url,
                    data: data,
                    type: 'POST',
                    success: function(data) {
                        if (data == "logado") {
                            window.location = AREA_EXCLUSIVA_URL;
                        }else if(data == 'escolha_contrato'){
                            disparaModalRequest('/area-exclusiva/multiplo-cadastro/');
                        } else {
                            helpers.errorAlert( $('#areaLogin'), data, {'fadeOutDelay': 5000, 'cornerzColor': '#B9D300'});
                        }
                    },
                    error: function(request){
                        helpers.errorAlert( $('#areaLogin'), 'Dados inválidos.', {'fadeOutDelay': 5000, 'cornerzColor': '#B9D300'});
                    }
                });

                return false;

            }

        },

        /**
         * ------------------- //
         * Care - Header
         * ------------------- //
         **/
        care : function() {

            /**
             * Insert images dynamic
             **/
            $( '#care ul li' ).each( function() {

                var tagImg  = "<img src='"+ $( this ).find( 'a' ).attr( 'rel' ) +"' />";

                $( tagImg ).appendTo( $( this ) );

            } );

            $( '#care ul li' ).click( function() {
                $( this ).find( 'a' ).trigger( 'click' );
            } );

            /**
             * Mouse Events
             */
            var elm = $( '#care ul' );
            var h   = elm.height();
            elm.hide().css( { height:0 } );

            $( '#care' ).mouseleave( function() {

                elm.stop().animate( { height:0 }, { duration:300, complete: function(){
                    elm.hide();
                }});

            }).mouseenter( function(){
                elm.show().stop().animate( { height:h }, { duration:300 });
            });

            /**
             * --------------------------------- //
             * Mouse over dos itens do submenu
             * --------------------------------- //
             **/
            elm.find( 'li' ).mouseenter( function() {
                $( this ).find( 'div.border-color-box' ).show();
            } ).mouseleave( function() {
                $( this ).find( 'div.border-color-box' ).hide();
            } );

            $( '#care ul li' ).show();

        }

        /**
         * ------------------- //
         * Navigation - Header
         * ------------------- //
         **/
        /*
        navigation : function() {
            helpers.menu.init();
        }
        */

    },

    internal : {

        init : function(){

            structure.internal.breadcrumb();
            structure.internal.addRoudedCorners();

            $('input[placeholder]').placeholder();

            // Veja também - mouseFX
            helpers.buttonFx( $('> a', '#see-more .services'), '#ff8f2a');
            helpers.buttonFx( $('> a', '#see-more .plans'), '#00bacb');

            //Banner de Sustentabilidade
            var banner = $('#sustainability li:last-child');
            var imagePath = banner.attr('data-image');

//          banner.css({ backgroundImage: 'url("' + imagePath + '")' });

            $('#sustainability').bind('click', function(){
                window.location = $('> a', '#sustainability li').attr('href');
            });

            // Eventos da barra do corretor
            var el = $( '#simulate-contact' );

            $( 'a.pop-send-message', el ).unbind( 'click' ).bind( 'click', function() {
                window.location = "#" + jQuery.url.setUrl( $( this ).attr( 'href' ) ).attr( "anchor" );
                helpers.openModal( $( this ).attr( 'href' ), care.init);
                return false;
            } );

        },

        breadcrumb : function() {

            $('#breadcrumb li:last-child').addClass('current-page');

        },

        addRoudedCorners : function() {

            /* Sustainability banner include */
            $('#sustainability li:first-child').cornerz({radius:6, background : '#f8f8e9'});
            $('#sustainability li:last-child').cornerz({radius:6, corners:'tl tr bl', background : '#f8f8e9'});

            /* See more include */
            $('.services ul').cornerz({ radius: 6, background : '#f8f8e9' });

            /* Simulate / Contact include */

            var simulateContact = $( '#simulate-contact' );

            $('> li', simulateContact).cornerz({ radius: 6, background : '#f8f8e9' });
            $('> .green-left > div > a', simulateContact).cornerz({ radius: 6, background : '#5a9600' });
            $('> .green-right > a', simulateContact).cornerz({ radius: 6, background : '#b9d300' });

        }

    },

    /**
     * ----------------- //
     * Header [end]
     * ----------------- //
     **/

    /**
     * ----------------- //
     * Footer [start]
     * ----------------- //
     **/
    footer : {

        init : function() {

            /**
             * Social Network config
             **/
            $('#footer_social_network li, #holder-social li').bind('mouseenter', function(){
                $(this).find('h3').stop().hide();
                $(this).find('h4').stop().fadeTo(250, 1);
            })
            .bind('mouseleave', function(){
                $(this).find('h3').stop().show();
                $(this).find('h4').stop().fadeTo(250, 0);
            })
            .bind('click', function(){
                window.open($(this).find('a').attr('href'));
            });

            /**
             * Exclusive Areas config
             **/
            $('#footer_exclusive_areas li').find('img').hide();
            for(var i=0; i < $('#footer_exclusive_areas li').length; i++)
            {
                var obj = $('#footer_exclusive_areas li:eq(' + i + ')');
                var img = obj.find('img').attr('src');
                obj.css({'background':'#a6c1b0 url(' + img + ') no-repeat'});
            }

            $('#footer_exclusive_areas li').bind('mouseenter', function(){
                $(this).find('h3').stop().hide();
                $(this).find('h4').stop().fadeTo(250, 1);
                $(this).css({'background-color' : $(this).attr('rel'), 'background-position' : '0 -60px'});
            })
            .bind('mouseleave', function(){
                $(this).find('h3').stop().show();
                $(this).find('h4').stop().fadeTo(250, 0);
                $(this).css({'background-color' : '', 'background-position' : '0 0'});
            })
            .bind('click', function(){
                self.location = $(this).find('a').attr('href');
            });

            /**
             * Lightbox config
             **/
            /*
            $('#footer_info a.lightbox').bind('click', function(){
                helpers.openModal( $( this ).attr( 'href' ), structure.footer.onLoadModal );
                return false;
            });
            */
            /**
             * Check if user has local storage
             */

            if(localStorage.length) {
                $('div.hide-medic').hide();
                structure.footer.showMedics();
            } else {
                $('div.show-medic').hide();
                // $('#footer_search aside > h3').hide();
            }

            /**
             * Add Rounded Corners
             **/

            $('.itens-social-network li').cornerz({radius:6, background : '#d0dbca'});
            $('#footer_exclusive_areas').cornerz({radius:6, corners:'tr', background : '#f8f8e9'});
            $('#footer_exclusive_areas li').cornerz({radius:6, background : '#d0dbca'});
            $('#footer-medical-guide').cornerz({radius:6, corners:'tl', background : '#f8f8e9'});
            $('#fb').cornerz({radius:6, background : '#005746'});
            $('aside > div', '#footer_search').cornerz({radius:6, background : '#005746'});
            $('h3', '#footer_search aside div.show-medic').cornerz({radius:6, corners:'bl br'});
            $('> h3', '#footer_search aside').cornerz({radius:6, background : '#005746'});
            //$('#fancybox-outer').cornerz({radius:6, corners:'tl tr bl'});

            helpers.buttonFx( $('.bt-medical-guide'), '#33796b' );

        },

        onLoadModal : function(){
            $('.pop section').cornerz( { radius : 6, corners : "tl tr bl" } );
        },

        addMedic : function(){

            //TODO: passar itens para serem adicionados: nome, endereço e telefone;
            // Pegar itens dos elementos html;
            $.getJSON(MEDIA_URL + 'assets/json/medics.json', function(data) {
                var value = data.medic[0].name + ';' + data.medic[0].area + ';' + data.medic[0].adr + ';' + data.medic[0].phone;
                localStorage.setItem( value, value );
            });

        },

        showMedics : function() {

            for(i = 0; i < localStorage.length; i++) {
                var arr = localStorage.key(i).split(';');
                var html = '<li class="vcard">' +
                           '<h5 class="fn">' + arr[0] + '</h5>' +
                           '<div class="details">' +
                           '<p class="type">' + arr[1] + '</p>' +
                           '<p class="adr">' +
                           '<span class="street-address">' + arr[2] + '</span>' +
                           '</p>' +
                           '<p class="tel">Tel.: ' + arr[3] + '</p>' +
                           '</div>' +
                           '</li>';

                $('div.show-medic ul').append( html );
                $('h5', 'div.show-medic ul').cornerz({radius:6, corners:'tl tr'});
            }

        },

        removeMedics : function() {

            localStorage.clear();

        },

        popAccess : function() {

            $.fn.colorbox( {
                href      : '',
                width    : 840,
                height  : 560,
                scrolling : false
            } );

        }

    }
    /**
     * ----------------- //
     * Footer [end]
     * ----------------- // 
     **/        
        
}

var mudancas = {
    init: function(){
        var year = 2014;
        $('.years-list li').click(function(){
            if ($(this).is('.active')) {
                return false;
            }
            var index = $('.years-list li').index($(this));
            $('.years-list li').removeClass('active');
            $(this).addClass('active');
            $('.zones-list li').removeClass('active').addClass('deactive');
            if (index == 0) {
                year = 2014;
                $('.zones-list li:eq(2), .zones-list li:eq(3)').removeClass('deactive');
                $('.zones-list li:eq(2)').addClass('active');
            } else if (index == 1) {
                year = 2013;
                $('.zones-list li').removeClass('deactive');
                $('.zones-list li:first').addClass('active');
            } else if (index == 2) {
                year = 2012;
            } else {
                year = 2011;
            }

            $('.wrap-' + year + ' li:first').show();
            $('.content-zones-wrap').fadeOut(600);
            setTimeout(function(){
                $('.wrap-' + year).fadeIn(600);
            }, 600);
        });

        $('.zones-list li').click(function(){
            if ($(this).is('.deactive') || $(this).is('.active')) {
                return false;
            }
            var index = $('.zones-list li').index($(this));
            $('.zones-list li').removeClass('active');
            $(this).addClass('active');
            $('.content-zones-wrap li').hide();

            if (year == 2014) {
                if (index == 2) {
                    $('.wrap-2014 li:first').fadeIn(600);
                } else {
                    $('.wrap-2014 li:eq(1)').fadeIn(600);
                }
            } else {
                $('.wrap-2013 li:eq(' + index + ')').fadeIn(600);
            }
        });
    }
};

var bannerfix = {
    init: function(){
        var actual = 5;
        var total = $('.nivo-controlNav .nivo-control').length;
        var wnav = total * 119;
        $('.nivo-controlNav, .nivo-controlNav-tooltips').width(wnav);
        $('.nivo-controlNav').after('<div class="arrowbanner left"/><div class="arrowbanner right"/>');
        $('.arrowbanner').click(function(){
            if ($(this).is('.left')) {
                if (actual == 5) {
                    return false;
                }
                $('.nivo-controlNav .nivo-control, .nivo-controlNav-tooltips').animate({'left': '+=119px'}, 600);
                actual--;
            } else {
                if (actual == total) {
                    return false;
                }
                $('.nivo-controlNav .nivo-control, .nivo-controlNav-tooltips').animate({'left': '-=119px'}, 600);
                actual++;
            }
        });
    }
};

$( document ).ready( function() {
    structure.init();
    //$('#nav > li:last').click(function(){
      //  var url = $(this).children('a').attr('href');
       // window.location.assign(url);
    //});

    $('#nav > li > a').each(function(){
		if ($(this).attr('href') == 'http://unimedrio.credit360.com/home') {
            return false;
        }else if ($(this).attr('href') == '/unimed-rio/') {
			$(this).removeAttr('href');
		}else if($(this).attr('href') == '/sua-sa%C3%BAde/'){
			$(this).removeAttr('href');
		}else if($(this).attr('href') == '/rede-propria'){
			$(this).attr("target","_blank");
		}	
        //$(this).removeAttr('href');
    });

    $('.rede-de-atendimento > li a').unbind('click');
    $('.rede-de-atendimento > li a').click(function(e){
        e.preventDefault();
        window.open($(this).attr('href'), '_blank');
    });
    

    $(window).load(function(){
        bannerfix.init();
    });
	
	
	/*SCRIPTS PARA OS NOVOS LAYOUTS DE SERVIÇOS*/

var atualDropList = 0; 
$('.topItem-servico div.selectButtonService').unbind('click').bind('click', function showOptionsService(event) {
    var indice = $(this).parent('.topItem-servico').index('.topItem-servico') + 1;
    $('.topItem-servico div.selectButtonService').unbind('click', showOptionsService);

    if (indice == atualDropList) {
        $('.topItem-servico:nth-child('+ indice +') div.selectButtonService').removeClass('active');
        $('.topItem-servico:nth-child('+ indice +') .contentDropList').slideUp(400 , function (argument) {
            $('.topItem-servico div.selectButtonService').unbind('click').bind('click', showOptionsService);            
        });
        atualDropList = 0; 
    }else{
        
        $('.topItem-servico div.selectButtonService').removeClass('active');
        $('.topItem-servico .contentDropList' ).slideUp(400); 
        $('.topItem-servico:nth-child('+ indice +') div.selectButtonService').addClass('active');
        atualDropList = indice;  

        setTimeout(function(){
         $('.topItem-servico:nth-child('+ indice +') .contentDropList').slideDown(400);      
         $('.topItem-servico div.selectButtonService').unbind('click').bind('click', showOptionsService).delay(400);
         
     }, 100); 
    }
});
	
} );