﻿var structure = {

    sectionID: null,
    originalHeight: 0,
    _queueCount: 0,
    _queueListener: null,
    _queueErrorListener: null,
    locale: '',

    _rpcList: [
		'#footer .nav-social-channels li a',
		'#header h1 a',
		'#header .nav-language-change li a'
	],

    _baseMotion: {
        duration: 300,
        queue: false
    },

    init: function() {

        $.each($('.nav-properties-by-state dd select:eq(1) option'), function (i, el) {
            el = $(el);
            if (el.val() == 'morumbi' || el.val() == 'mooca' || el.val() == 'analia-franco') {
                var t = el.text() + ' - Entregue';
                el.text(t).css('font-weight', 'bold'); //.appendTo($('.nav-properties-by-state dd select:eq(1)'));
            }
        });

        trace('structure : init');

        structure.locale = $('body').hasClass('en-us') ? 'en-us' : 'pt-br';
        
        $('#footer .nav-social-channels li a').attr('target', '_blank').neoHover();

        structure.sectionID = $('#site > #main-content > .section-id:eq(0)').attr('id');
        if (structure.sectionID != null &&
			structure.sectionID != '' &&
			structure.sectionID != undefined

		) structure._getMainJs();
		
		//structure.structure();
        menuFooter.init();
        onAtt.init();
        bandeiras.init();
        channels.init();

		//$(window).bind('resize', structure.structure);

        $.getScriptSafe(getUrl('/static/js/shared/tracking.js'), function(e) {
            if (tracking) tracking.init();
        });
    },
    
    structure: function(){
		trace('structure : structure');
		
		var _width = $(window).width();
		
		$('body').width(_width).css({'overflow-x':'hidden'});
    },

    preRender: function() {
        structure.originalHeight = $('#main-content').innerHeight();

        $(window).bind('resize', structure.placeFooter);

        structure.setMinHeight();

        $('#header .nav-sitemap li:eq(0)').addClass('first');
        $('#header .nav-sitemap li:last').addClass('last');
        $('#header .nav-sitemap li a').wrapInner('<span/>');

        $('#footer .nav-sitemap ul').wrap('<div/>');
        $('#footer .nav-sitemap ul li:first').addClass('first');
        $('#footer .nav-sitemap ul li:last').addClass('last');

        structure.placeFooter();

        $('#nav-on-att-fixed')
			.wrapInner($('<span/>').addClass('c-left'))
			.wrapInner($('<span/>').addClass('c-right'))
			.bind('mouseenter', function(e) {
			    $(e.currentTarget).animate({ backgroundPosition: '0 0' }, structure._baseMotion)
			})
			.bind('mouseleave', function(e) {
			    $(e.currentTarget).animate({ backgroundPosition: '0 41px' }, structure._baseMotion)
			});

        $.each(structure._rpcList, function(i, el) {
            $(el).addClass('rpc');
        });
    },

    ready: function() { },

    setMinHeight: function() {
        trace('structure : setMinHeight');

        var windowHeight = $(window).height();
        var restHeight = $('#header').outerHeight(true) + $('#alt-content').outerHeight(true) + $('#footer').outerHeight(true);
        var minHeight = windowHeight - restHeight;
        var fnHeight = structure.originalHeight < minHeight ? minHeight : structure.originalHeight;

        $('#main-content').height(fnHeight);
    },

    placeFooter: function() {
        $('.fixed-bottom-bar h2').css({ left: $('#footer .nav-sitemap > div').offset().left.round() });

        var posx = ($('.nav-social-channels').offset().left.round() + $('.nav-social-channels').outerWidth(true)) - $('#footer .lnkNeotix').width();
        $('#footer .lnkNeotix').css({ left: posx, visibility: 'visible' });
    },

    _getMainJs: function() {
        trace('structure : _getMainJs');

        $('#site').css({ visibility: 'hidden' });

        structure._queueCount++;

        $.getScriptSafe(getUrl('/static/js/sections/{0}/default.js?{1}'.format([structure.sectionID, new Date().getTime()])), function(e) {
            structure._queueCount--;

            var _data = e.replace(' ', '').replace('	', '');
            var _sectionName = _data.substr(3, _data.indexOf('=') - 3);
            var _section = eval(_sectionName);
            var _cssAutoLoad = _section.cssAutoLoad == false ? false : true;

            if (_cssAutoLoad) {
                structure._queueCount++;
                structure._getCss(getUrl('/static/css/sections/{0}/default.css'.format([structure.sectionID])));
            }

            if (_section.requires && _section.requires.css) {
                $.each(_section.requires.css, function(i, el) {
                    structure._queueCount++;
                    structure._getCss(getUrl(el));
                });
            }

            if (_section.requires && _section.requires.js) {
                $.each(_section.requires.js, function(i, el) {
                    structure._queueCount++;
                    $.getScriptSafe(getUrl(el), function() {
                        structure._queueCount--;
                    });
                });
            }

            structure._queueListener = setInterval(function() {
                if (structure._queueCount == 0) {
                    clearInterval(structure._queueListener);

                    structure.preRender();

                    if (_section.preRender) {
                        trace(structure.sectionID + ' : preRender')
                        _section.preRender();
                    }

                    $('#site').css({ visibility: 'visible' });

                    $('.main-loading').hide();

                    structure.ready();

                    trace(structure.sectionID + ' : init');

                    _section.init();

                    tagClickTale.init();
                }
            }, 100);
        });
    },

    _getCss: function(src) {
        trace('structure : _getCss');

        $.ajax({
            success: function(e) {
                trace('structure : _getCss : Success [{0}]'.format([src]));
                structure._queueCount--;

                if (e != undefined) $('<style type="text/css">{0}</style>'.format([e._replace('root/', root)])).appendTo('head');
            },
            error: function(e) {
                trace('structure : _getCss : Error [{0}]'.format([src]));
                trace(e);
                structure._queueCount--;
            },
            dataType: 'text',
            url: src + '?' + new Date().getTime()
        })
    },

    mountSelectsHausByState: function() {
        $.each($('.ddlEstado option'), function(i, item) {
            $(item).attr('rel', i);
        });

        $('.ddlEstado').bind('change', function(e) {
            var rel = $(this).children('option:selected').attr('rel');
            $('.ddlImoveis').hide();
            $('.ddlImoveis').eq(rel).show();

            var txt = $(this).children('option:selected').text();
            $(this).prev().text(txt);
        })
        .css({ opacity: '0' })
        .trigger('change');

        $('.ddlImoveis')
        .bind('change', function(e) {
            $(this).parent().find('span').text('Redirecionando...');
            var val = $(this).children('option:selected').val();
            var url = getUrl('/escolha-o-seu/' + val + '.aspx');
            document.location.href = url;
        })
        .css({ opacity: '0' })
    }
};

var channels = {

    keepOpen: false,
    modeOpened: false,

    init: function() {
        channels.schedule.init();
        channels.callYou.init();

        $('#header .nav-contact-channels')
			.bind('mouseenter', channels.mainMouseEnter)
			.bind('mouseleave', channels.mainMouseLeave)

        channels.verifyMode();
        setTimeout(channels.verifyMode, 1000);
        
        $('#header .nav-contact-channels li.schedule-a-visit').bind('click', function(e) {
            var el = $(e.currentTarget);

            $('.nav-contact-channels li').removeClass('on')
            el.addClass('on');

            channels.schedule.el.css({
                top: el.offset().top - 5,
                left: el.offset().left - 1
            })
			.removeClass('internal-mode');

            channels.keepOpen = true;

            channels.schedule.show();
            channels.callYou.hide();
        })

        $('#header .nav-contact-channels li.maxhaus-call-you').bind('click', function(e) {
            var el = $(e.currentTarget);

            $('.nav-contact-channels li').removeClass('on');
            el.addClass('on');

            channels.callYou.el.css({
                top: el.offset().top.round() - 5,
                left: el.offset().left.round() - 1
            })
			.removeClass('internal-mode');

            channels.keepOpen = true;

            channels.callYou.show();
            channels.schedule.hide();
        })
    },
    
    verifyMode: function(){
        channels.modeOpened = $('#header .nav-contact-channels').hasClass('opened');
        
        if (channels.modeOpened) {
            $('#header .nav-contact-channels')
                .trigger('mouseenter')
                .unbind('mouseenter')
			    .unbind('mouseleave')
        }
    },
    
    schedule: {
        el: null,
        opened: false,

        init: function() {
            channels.schedule.el = $('<div/>')
				.attr({ id: 'schedule-holder' })
				.appendTo('#site');

            $('<div/>')
				.addClass('call-handler')
				.appendTo(channels.schedule.el)
				.bind('click', function(e) {
				    $('#header .nav-contact-channels li.maxhaus-call-you').trigger('click');
				});

            $('<div/>')
				.addClass('on-att-handler')
				.appendTo(channels.schedule.el);

            var content = $('<div/>')
				.addClass('content')
				.html($('.nav-contact-channels li.schedule-a-visit dl dd').html())
				.appendTo(channels.schedule.el);

            $('.nav-contact-channels li.schedule-a-visit dl dd').html('');

            $('#schedule-holder .content .nav-cancel').bind('click', function(e) {
                e.preventDefault();
                channels.keepOpen = false;
                channels.schedule.hide();

                $('.nav-contact-channels li').removeClass('on');

            }).neoHover();

            $.datepicker.setDefaults($.datepicker.regional[structure.locale == 'en-us' ? '' : 'pt-BR'])
            $('#schedule-holder .content .calendar .holder').datepicker({
                onSelect: function(dateText, inst) {
                    $('#schedule-holder .content #txt-date-visit').val(dateText);
                }
            })

            scheduleVisit.init();
        },

        show: function() {
            trace('channels : schedule : show');

            channels.schedule.el
				.show()
				.animate({
				    height: 294
				}, channels.mainFx);

            channels.schedule.opened = true;
        },

        hide: function() {
            if (channels.schedule.opened) {
                trace('channels : schedule : hide');

                var foo = $.extend({ complete: function() {
                    channels.schedule.el.hide();
                    $('#header .nav-contact-channels').trigger('mouseleave');
                }
                }, channels.mainFx);

                channels.schedule.el.animate({
                    height: 0
                }, foo);

                channels.schedule.opened = false;
            }
        }
    },

    callYou: {
        el: null,
        opened: false,

        init: function() {
            channels.callYou.el = $('<div/>')
				.attr({ id: 'call-you-holder' })
				.appendTo('#site');

            var content = $('<div/>')
				.addClass('content')
				.html($('.nav-contact-channels li.maxhaus-call-you dl dd').html())
				.appendTo(channels.callYou.el)

            $('.nav-contact-channels li.maxhaus-call-you dl dd').html('');

            /*$('<a/>')
            .addClass('nav-close')
            .text('Fechar')
            .bind('click', function(e) {
            e.preventDefault();

				    channels.keepOpen = false;
            channels.callYou.hide();
            })
            .appendTo(content);
            */
            $('#call-you-holder .call-form .nav-close').bind('click', function(e) {
                e.preventDefault();
                channels.keepOpen = false;
                channels.callYou.hide();

                $('li.maxhaus-call-you').removeClass('on');
            }).neoHover();

            callYouForm.init();
        },

        show: function() {
            trace('channels : callYou : show');

            channels.callYou.el
				.show()
				.animate({
				    height: 158
				}, channels.mainFx)

            channels.callYou.opened = true;

        },

        hide: function() {
            if (channels.callYou.opened) {
                trace('channels : callYou : hide');

                var foo = $.extend({ complete: function() {
                    channels.callYou.el.hide();
                    $('#header .nav-contact-channels').trigger('mouseleave');
                }
                }, channels.mainFx);

                channels.callYou.el.animate({
                    height: 0
                }, foo);

                channels.callYou.opened = false;
            }
        }
    },

    mainFx: {
        duration: 300,
        queue: false
    },

    mainMouseEnter: function(e) {
        $('#header .nav-contact-channels li.schedule-a-visit').animate({ left: 000 }, channels.mainFx);
        $('#header .nav-contact-channels li.maxhaus-call-you').animate({ left: 110 }, channels.mainFx);
        $('#header .nav-contact-channels li.on-att').animate({ left: 264 }, channels.mainFx);
    },

    mainMouseLeave: function(e) {
        if (!channels.keepOpen) {
            $('#header .nav-contact-channels li.schedule-a-visit').animate({ left: 262 }, channels.mainFx);
            $('#header .nav-contact-channels li.maxhaus-call-you').animate({ left: 302 }, channels.mainFx);
            $('#header .nav-contact-channels li.on-att').animate({ left: 343 }, channels.mainFx);
        }
        $('#header .nav-contact-channels li').removeClass('on');
    }
}

var bandeiras = {
    _rel: null,

    init: function() {

        bandeiras.constructionBasic();

        $('.nav-language-change li a')
			.bind('mouseenter', bandeiras.bandeiras_mouseOver)
			.bind('mouseleave', bandeiras.bandeiras_mouseOut)
    },

    constructionBasic: function() {
        $('<span/>')
			.addClass('pt-br')
			.html('Portugu&#234;s')
			.appendTo('#header');

        $('<span/>')
			.addClass('en-us')
			.html('Ingl&#234;s')
			.appendTo('#header');
    },

    bandeiras_mouseOver: function(e) {
        e.preventDefault();

        bandeiras._rel = $(e.currentTarget).attr('rel');

        $('#header > span').eq(bandeiras._rel).animate({
            opacity: 1,
            top: 25
        }, {
            duration: 500,
            queue: false,
            easing: 'easeOutExpo'
        });
    },

    bandeiras_mouseOut: function(e) {
        e.preventDefault();

        $('#header > span').animate({
            opacity: 0,
            top: 15
        }, {
            duration: 500,
            queue: false,
            easing: 'easeOutExpo'
        });
    }
};

var menuFooter = {
    _rel: null,

    init: function() {
        trace('menuFooter : init')

        $('.nav-sitemap ul li a')
			.bind('mouseenter', menuFooter.menuFooter_mouseOver)
			.bind('mouseleave', menuFooter.menuFooter_mouseOut);

        $.each($('.nav-sitemap ul li a'), function(i, item) {
            $(item)
				.attr('rel', i);
        });
    },

    menuFooter_mouseOver: function(e) {
        trace('menuFooter: menuFooter_mouseOver')
        e.preventDefault();

        menuFooter._rel = $(e.currentTarget).attr('rel');

        $('.nav-sitemap ul li a').animate({
            opacity: 0.5
        }, {
            duration: 500,
            queue: false,
            easing: 'easeOutExpo'
        });

        $('.nav-sitemap ul li a').eq(menuFooter._rel).animate({
            opacity: 1
        }, {
            duration: 500,
            queue: false,
            easing: 'easeOutExpo'
        });
    },

    menuFooter_mouseOut: function(e) {
        trace('menuFooter: menuFooter_mouseOut')
        e.preventDefault();

        $('.nav-sitemap ul li a').animate({
            opacity: 1
        }, {
            duration: 500,
            queue: false,
            easing: 'easeOutExpo'
        });
    }
};

var scheduleVisit = {

    vMaxHaus: null,
    vName: null,
    vEmail: null,
    vDDD: null,
    vPhone: null,
    vDay: null,
    vHour: null,
    vCheck: false,

    init: function() {

        scheduleVisit.vMaxHaus = $("#txt-maxhaus");
        scheduleVisit.vName = $("#txtName");
        scheduleVisit.vEmail = $("#txtEmail");
        scheduleVisit.vDDD = $("#txtDdd");
        scheduleVisit.vPhone = $("#txtPhone");
        scheduleVisit.vDay = $("#txt-date-visit");
        scheduleVisit.vHour = $("#txt-hour-visit");

        $('#schedule-holder .schedule-form li').find("input, textarea").val('');

        $('#txtDdd').bind('keypress', scheduleVisit.formataTEL);
        $('#txtPhone').bind('keypress', scheduleVisit.formataTEL);
        $('#txt-date-visit').bind('keypress', scheduleVisit.formataTEL);
        //$('#txt-hour-visit').bind('keypress', scheduleVisit.formataTEL);

        $('#schedule-holder .schedule-form li').find('input, textarea').keyup(scheduleVisit.validaForm);

        $('#txt-maxhaus').bind('change', function() {
            $(this).prev().text($(this).find(':selected').text());

        }).css({ opacity: '0' });

        $('#schedule-holder .nav-schedule')
			.bind('click', scheduleVisit.checkAll)
			.neoHoverButtom();

        $('#schedule-holder .form-right a').bind('click', function() {
            $('#schedule-holder .form-right').slideUp();
        }).neoHover();
    },

    /* ------------------------------------------
    * @add funcoes de validacao
    * ------------------------------------------
    */

    checkEmail: function(obj) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(obj).val())) return true;
        else return false;
    },

    checkBlank: function(obj) {
        if ($(obj).val() != '') return true;
        else return false;
    },

    checkNaN: function(obj) {
        if (isNaN($(obj).val()) == true) return true;
        else return false;
    },

    onlyNumbers: function(obj) {
        setTimeout(function() {
            str = $(obj).val();
            str = str.replace(/\D/g, "");
            $(obj).val(str);
        }, 1);
    },

    formataTEL: function() {
        var _this = this;
        setTimeout(function() {
            var str = $(_this).val();
            str = str.replace(/\D/g, "");
            //str = str.replace(/^(\d\d)(\d)/g, "($1)$2");
            str = str.replace(/(\d{4})(\d)/, "$1-$2");

            $(_this).val(str);

            if (str.length == 9)
                $(_this).removeClass("erro");
            else
                $(_this).addClass("erro");

        }, 1);
    },

    checkAll: function() {
        scheduleVisit.vCheck = true;

        if (scheduleVisit.vMaxHaus.find(':selected').val() == 0) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vMaxHaus.parent().addClass('erro');
        } else {
            scheduleVisit.vMaxHaus.parent().removeClass('erro');
        }

        if (!scheduleVisit.checkBlank(scheduleVisit.vName)) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vName.parent().addClass('erro');
        }

        if (!scheduleVisit.checkBlank(scheduleVisit.vEmail) || !scheduleVisit.checkEmail(scheduleVisit.vEmail)) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vEmail.parent().addClass('erro');
        }

        if (!scheduleVisit.checkBlank(scheduleVisit.vDDD)) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vDDD.parent().addClass('erro');
        }

        if (!scheduleVisit.checkBlank(scheduleVisit.vPhone)) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vPhone.parent().addClass('erro');
        }

        if (!scheduleVisit.checkBlank(scheduleVisit.vDay)) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vDay.parent().addClass('erro');
        }

        if (!scheduleVisit.checkBlank(scheduleVisit.vHour)) {
            scheduleVisit.vCheck = false;
            scheduleVisit.vHour.parent().addClass('erro');
        }

        if (scheduleVisit.vCheck) {
            scheduleVisit.enviarCadastro();
        }

        return this.vCheck;
    },

    validaForm: function() {
        if (!scheduleVisit.checkBlank($(this))) {
            $(this).parent().addClass('erro');
        } else if ($(this).attr("id") == "email" && !scheduleVisit.checkEmail($(this))) {
            $(this).parent().addClass('erro');
        } else {
            $(this).parent().removeClass("erro");
        }

        return false;
    },

    enviarCadastro: function() {

        var _maxhaus = scheduleVisit.vMaxHaus.find('option:selected').text();
        var _name = scheduleVisit.vName.val();
        var _email = scheduleVisit.vEmail.val();
        var _ddd = scheduleVisit.vDDD.val();
        var _phone = scheduleVisit.vPhone.val();
        var _day = scheduleVisit.vDay.val();
        var _hour = scheduleVisit.vHour.val();
        var _source = location.href;

        $.ajax({
            type: "POST",

            url: getUrl("/ajax/schedule/sender.aspx"),

            global: true,

            data: {
                "haus": _maxhaus,
                "name": _name,
                "email": _email,
                "area-code": _ddd,
                "phone": _phone,
                "date": _day,
                "hour": _hour,
                "source": _source
            },

            success: function(msg) {
                if (msg.toLowerCase() == "true") {
                    $('#schedule-holder .form-right').slideDown(function() {
                        $('#schedule-holder .schedule-form li').find("input, textarea").val('');
                        $('#schedule-holder .schedule-form li select').val(0);
                        if (channels.schedule.el.hasClass('internal-mode')) {
                            tracking.dtalk.call('/menu_lateral/agendou_visita/clique');
                        } else {
                            tracking.dtalk.call('/agendou_visita/sucesso');
                        }

                        tracking.dtalk.gwoCall('agendou_visita');
                    });

                    setTimeout(function() {
                        $('#schedule-holder .form-right').slideUp();
                    }, 5000);

                } else {
                    scheduleVisit.errorCadastro();
                }
            },
            error: function(msg) {
                scheduleVisit.errorCadastro();
            }
        });
    },

    errorCadastro: function() {
        $('#schedule-holder .form-right').slideUp();
        $('#schedule-holder .schedule-form li .form-wrong').show(function() {
        });

        setTimeout(function() {
            $('#schedule-holder .schedule-form li .form-wrong').hide();
        }, 5000);
    }
};

var callYouForm = {

    vName: null,
    vDDD: null,
    vPhone: null,
    vCheck: false,

    init: function() {

        callYouForm.vName = $("#txt-call-name");
        callYouForm.vDDD = $("#txt-call-ddd");
        callYouForm.vPhone = $("#txt-call-phone");

        $('#call-you-holder .call-form li').find("input, textarea").val('');

        $('#txt-call-ddd').bind('keypress', callYouForm.formataTEL);
        $('#txt-call-phone').bind('keypress', callYouForm.formataTEL);

        $('#call-you-holder .call-form li').find('input, textarea').keyup(callYouForm.validaForm);

        $('#call-you-holder .call-form .nav-send')
			.bind('click', callYouForm.checkAll).neoHoverButtom();

        $('#call-you-holder .form-right a').bind('click', function() {
            $('#call-you-holder .form-right').slideUp();
        }).neoHover();
    },

    /* ------------------------------------------
    * @add funcoes de validacao
    * ------------------------------------------
    */

    checkEmail: function(obj) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(obj).val())) return true;
        else return false;
    },

    checkBlank: function(obj) {
        if ($(obj).val() != '') return true;
        else return false;
    },

    checkNaN: function(obj) {
        if (isNaN($(obj).val()) == true) return true;
        else return false;
    },

    onlyNumbers: function(obj) {
        setTimeout(function() {
            str = $(obj).val();
            str = str.replace(/\D/g, "");
            $(obj).val(str);
        }, 1);
    },

    formataTEL: function() {
        var _this = this;
        setTimeout(function() {
            var str = $(_this).val();
            str = str.replace(/\D/g, "");
            //str = str.replace(/^(\d\d)(\d)/g, "($1)$2");
            str = str.replace(/(\d{4})(\d)/, "$1-$2");

            $(_this).val(str);

            if (str.length == 9)
                $(_this).removeClass("erro");
            else
                $(_this).addClass("erro");

        }, 1);
    },

    checkAll: function() {
        callYouForm.vCheck = true;

        if (!callYouForm.checkBlank(callYouForm.vName)) {
            callYouForm.vCheck = false;
            callYouForm.vName.parent().addClass('erro');
        }

        if (!callYouForm.checkBlank(callYouForm.vDDD)) {
            callYouForm.vCheck = false;
            callYouForm.vDDD.parent().addClass('erro');
        }

        if (!callYouForm.checkBlank(callYouForm.vPhone)) {
            callYouForm.vCheck = false;
            callYouForm.vPhone.parent().addClass('erro');
        }

        if (callYouForm.vCheck) {
            callYouForm.enviarCadastro();
        }

        return this.vCheck;
    },

    validaForm: function() {
        if (!callYouForm.checkBlank($(this))) {
            $(this).parent().addClass('erro');
        } else if ($(this).attr("id") == "email" && !callYouForm.checkEmail($(this))) {
            $(this).parent().addClass('erro');
        } else {
            $(this).parent().removeClass("erro");
        }

        return false;
    },

    enviarCadastro: function() {

        var _name = callYouForm.vName.val();
        var _ddd = callYouForm.vDDD.val();
        var _phone = callYouForm.vPhone.val();
        var _source = location.href;

        $.ajax({
            type: "POST",

            url: getUrl('/ajax/call/sender.aspx'),

            global: true,

            data: {
                "name": _name,
                "area-code": _ddd,
                "phone": _phone,
                "source": _source
            },

            success: function(msg) {
                if (msg.toLowerCase() == "true") {
                    $('#call-you-holder .form-right').slideDown(function() {
                        $('#call-you-holder .call-form li').find("input, textarea").val('');
                        if (channels.callYou.el.hasClass('internal-mode')) {
                            tracking.dtalk.call('/menu_lateral/receber_ligacao/clique');
                        } else {
                            tracking.dtalk.call('/menu_superior/receber_ligacao/clique');
                        }
                        tracking.dtalk.gwoCall('receber_ligacao');
                    });

                    setTimeout(function() {
                        $('#call-you-holder .form-right').slideUp();
                    }, 5000);

                } else {
                    callYouForm.errorCadastro();
                }
            },
            error: function(msg) {
                callYouForm.errorCadastro();
            }
        });
    },

    errorCadastro: function() {
        $('#call-you-holder .form-right').slideUp();
        $('#call-you-holder .call-form li .form-wrong').show(function() {
        });

        setTimeout(function() {
            $('#call-you-holder .call-form li .form-wrong').hide();
        }, 5000);
    }
};

var onAtt = {
    dtUrl: 'http://www6.directtalk.com.br/chat/?idd=F98C0001016C3000110E',

    init: function () {
        //onAtt.random();

        //Link do escolha o seu, com multiplas url's alimentadas via admin
        if (structure.sectionID == 'pick-yours') $('#pick-yours .side-content .nav-contact-channels li.on-att a').bind('click', onAtt.aHandler);

        //Link do contato, apenas DT
        if (structure.sectionID == 'contact') onAtt.mountDtLink($('.contact-left > ul > li:eq(1) a'));

        //Link do header, apenas DT
        onAtt.mountDtLink($('#header .nav-contact-channels li.on-att a'));

        //Link do footer, apenas DT
        onAtt.mountDtLink($('#nav-on-att-fixed'));

        onAtt.mountDtLink($('.fixed-bottom-bar h2').wrap('<a/>')).parent().addClass('online-att');

        onAtt.mountDtLink($('.fixed-bottom-bar p > span').wrap('<a/>')).parent().addClass('online-att');
    },

    random: function () {
        var rndID = Boolean(Math.round(Math.random())) ? 'fixed-bottom-bar' : 'fixed-bottom-bar-vermelho';
        $('.fixed-bottom-bar').attr('id', rndID);
    },

    mountDtLink: function (el) {
        el
			.attr('href', onAtt.dtUrl)
			.addClass('dt')
			.bind('click', onAtt.aHandler);

        return el;
    },

    call: function (el) {
        var url = $.trim($(el).attr('href'));
        url = $(el).hasClass('dt') ? dpc_core.get_linker_url(url) : url;
        window.open(url, "atendimento", "width=530,height=500,top=0,resizable=no,scrollbars=no,statusbar=yes");
        tracking.dtalk.gwoCall('atendimento_online');
    },

    aHandler: function (e) {
        e.preventDefault();
        onAtt.call(e.currentTarget);
    }
}

var WRInitTime;
var tagClickTale = {
    init: function() {
        WRInitTime = (new Date()).getTime();
        $('<div/>').attr({ id: 'ClickTaleDiv' }).css({ display: 'none' }).appendTo('body');

        setTimeout(tagClickTale.call, 1000);
    },

    call: function() {
        if (document.location.protocol != 'https:') {
            $.getScript('http://s.clicktale.net/WRb6.js', tagClickTale.step2);
        } else {
            tagClickTale.step2();
        }
    },

    step2: function() {
        if (typeof ClickTale == 'function') {
            trace('clicktale : call : step2')
            ClickTale(44959, 0.15, "www");
        }
    }
};

$(document).ready(structure.init);

