var structure = {

    baseUrl: "",
    currentState: "",
    trackingCallbackList: new Array(),

    trackingReady: function(callback) {
        this.trackingCallbackList.push(callback);
    },

    init: function() {
        structure.currentState = $('.breadcrumb input').eq(0).val();

        structure.eyeCandies.init();
        structure.rightBar.init();
        structure.favorites.init();

        $('.bt_brookfield_en').neoHover();

        $.getScript(structure.baseUrl + 'static/js/shared/text-search.js', function(data, status) {
            setTimeout(function() {
                textSearch.init();
            }, 500);
        });

        $.getScript(structure.baseUrl + 'static/js/shared/tracking.js', function(data, status) {
            $.each(structure.trackingCallbackList, function(i, item) { item(); });
            setTimeout(function() {
                tracking.init();
            }, 500);
        });

        try { filter.init(); } catch (e) { };

        if ($('#flash-phone').length == 1) {

            var data = $.trim($('#flash-phone').text());
            swfobject.embedSWF(structure.baseUrl + "static/swf/nav-phone.swf", "flash-phone", "100%", "32", "10", "expressInstall.swf", { 'txtPhone': data }, { 'wmode': 'transparent' }, {});
        }

        $.each($('.flag'), function(i, dom) {
            var nav = $(dom).find('.nav-pic');
            var pic = $(dom).find('.nav-pic img');

            var imgTh = pic.attr('src');
            var imgBg = pic.css('background-image').replace('url(', '').replace(')', '').split('"').join('');

            pic.attr('src', imgBg);
            pic.css('background-image', 'url(' + imgTh + ')');
        });

        $("#btIniciar_atendimento").find('span').animate({ opacity: 0 });
        $("#btIniciar_atendimento").bind('mouseenter', function() {
            $(this).find('span').show().animate({ opacity: 1 }, { duration: 400, queue: false }).bind('mouseout', function() {
                $(this).animate({ opacity: 0 }, { duration: 400, queue: false, complete: function() {
                    $(this).hide();
                } 
                });
            });
        });
        //$("#btIniciar_atendimento span").unbind('mouseover, mouseout, mouseleave').removeAttr('style');

    },
    /* 
    ------------------------------------------------------------------------------------------------------------------
    Favoritos*/
    favorites: {
        current: null,
        init: function() {
            $("a[rel~='nav-fav']").bind('click', function(e) {
                e.preventDefault();
                $.ajax({
                    url: '/meus-favoritos/trocar-status.aspx',
                    type: 'POST',
                    cache: false,
                    context: this,
                    data: 'id=' + $(this).attr('href').replace('?', ''),
                    success: function(e) {
                        eval(e);

                        $("div.right-bar dl.favorites dd a").html("Ver favoritos (" + e.count + ")");

                        if ($(this).hasClass('neo-hover')) {
                            if ($(this).hasClass('add')) {
                                $(this)
								.removeClass('add')
								.addClass('remove')
								.attr('title', 'Remover dos favoritos')
								.neoHover()
								.find('span')
								.html('Remover dos favoritos')
								.mouseenter();

                                if (structure.currentState == 'sp') tracking.funnel.steps01.call('65750');

                            } else {
                                $(this)
								.removeClass('remove')
								.addClass('add')
								.attr('title', 'Adicionar aos favoritos')
								.neoHover()
								.find('span')
								.html('Adicionar aos favoritos')
								.mouseenter();
                            }
                        }
                        else {
                            if ($(this).hasClass('add')) {
                                $(this)
								.removeClass('add')
								.addClass('remove')
								.attr('title', 'Remover dos favoritos')
								.html('Remover dos favoritos');

                                if (structure.currentState == 'sp') tracking.funnel.steps01.call('65750');

                            } else {
                                $(this)
								.removeClass('remove')
								.addClass('add')
								.attr('title', 'Adicionar aos favoritos')
								.html('Adicionar aos favoritos');
                            }
                        }
                    }
                });
            })
        }
    },
    /* 
    ------------------------------------------------------------------------------------------------------------------
    Atendimento online*/
    onAtt: {
        init: function() {
        },

        call: function(url) {

            if (structure.currentState == 'sp') {
                tracking.yahooTag();
                tracking.google.call('LYbFCPeEqAEQ0ZmG6wM');

                if (document.location.href.toLowerCase().indexOf("minhacasaminhavidafase2") > 0) {
                    tracking.realmedia.steps.call(4);
                    tracking.realmedia.specialSteps.call(4);
                }
                else {
                    tracking.realmedia.steps.call(1);
                    tracking.realmedia.specialSteps.call(1);
                }
            }

            var _url = url;

            _url += _url.indexOf("?") > 0 ? "&origem=" : "?origem=";
            _url += document.title.substring(27, document.title.length);
            _url = _url.split(" ").join("_");

            window.open(_url, 'onAtt', 'width=700,height=500');
        }
    },
    /* 
    ------------------------------------------------------------------------------------------------------------------
    */
    rightBar: {
        init: function() {
            this.newsletter.init();
        },

        newsletter: {
            defaultText: "",

            init: function() {
                structure.trackingReady(function() {
                    if ($('dl.future-releases').hasClass('track-me') && structure.currentState == 'sp') {
                        tracking.google.call('jVG8CO2JqAEQ0ZmG6wM');
                        tracking.funnel.steps01.call('65746');
                    }
                });

                this.defaultText = $('.right-bar dl.future-releases dd label').text();

                $('#txtFutureReleases').val(this.defaultText);
                $('#txtFutureReleases').focus(this.focus);
                $('#txtFutureReleases').blur(this.blur);
            },

            focus: function() {
                if ($(this).val() == structure.rightBar.newsletter.defaultText) {
                    $(this).val("");
                }
            },

            blur: function() {
                if ($(this).val() == "") {
                    $(this).val(structure.rightBar.newsletter.defaultText);
                }
            }
        }
    },

    eyeCandies: {
        init: function() {
            structure.eyeCandies.mainNav.init();
            structure.eyeCandies.whiteButtons.init();
            structure.eyeCandies.breadcumb.init();
            $('.neo-hover').neoHover();
            $('.neo-list-hover a').neoHover();
            $('.footer .nav-social-medias li a').neoHighlight({ hoverButton: true, hasLink: false, duration: 400, opacity: .4 });
        },

        breadcumb: {
            opened: false,
            dropdown: '',
            dropdownHeight: 0,


            init: function() {
                var breadcumb = $('.header .white-bar .breadcrumb');
                var currentState = breadcumb.find('dd ul li.current a').text();

                this.dropdown = breadcumb.find('.dropdown-states').eq(0);

                breadcumb.find('#breadcrumb-sel-label').eq(0).html(currentState).css('color', '#000');
                breadcumb.find('.current-state').eq(0).html(currentState);

                this.dropdownHeight = this.dropdown.height();

                this.dropdown.css('height', '0').animate({ opacity: 0 });

                $(document).bind('click', function(e) {
                    var allowAccess = false;
                    var origEl = "";

                    try {
                        origEl = e.srcElement ? e.srcElement : e.originalTarget;
                        var test = origEl.toString();
                        allowAccess = true;

                    } catch (e) { };


                    if (allowAccess && $(origEl).attr('id') == 'breadcrumb-sel-label') {
                        if (structure.eyeCandies.breadcumb.opened) {
                            structure.eyeCandies.breadcumb.close();
                        }
                        else {
                            structure.eyeCandies.breadcumb.open();
                        }
                    }
                    else {
                        if (structure.eyeCandies.breadcumb.opened) {
                            structure.eyeCandies.breadcumb.close();
                        }
                    }
                });

                var selItems = breadcumb.find('dd ul li a');

                selItems.bind('click', function() {
                    $('#breadcrumb-sel-label').eq(0).html('Aguarde ...').css('color', '#bbb');
                    structure.eyeCandies.breadcumb.close()
                });

                selItems.bind('mouseover', function() {
                    $(this).animate({
                        backgroundPosition: '0 0',
                        'color': '#ffffff'
                    }, {
                        duration: 300,
                        easing: 'linear',
                        queue: false
                    });
                });

                selItems.bind('mouseout', function() {
                    $(this).animate({
                        backgroundPosition: '-139px 0',
                        'color': $(this).parent().hasClass('current') ? '#00467e' : '#000000'
                    }, {
                        duration: 300,
                        easing: 'linear',
                        queue: false
                    });
                });
            },

            open: function() {
                //$('.header .white-bar .breadcrumb .dropdown-states').show();
                structure.eyeCandies.breadcumb.dropdown.animate({
                    height: structure.eyeCandies.breadcumb.dropdownHeight,
                    opacity: 1
                }, {
                    duration: 300,
                    easing: 'linear',
                    queue: false
                });

                if ($.browser.msie && $.browser.version < 7) $('.header .gray-bar .search-advanced select').eq(0).hide();
                structure.eyeCandies.breadcumb.opened = true;
            },

            close: function() {
                //$('.header .white-bar .breadcrumb .dropdown-states').hide();
                structure.eyeCandies.breadcumb.dropdown.animate({
                    height: 0,
                    opacity: 0
                }, {
                    duration: 300,
                    easing: 'linear',
                    queue: false
                });

                if ($.browser.msie && $.browser.version < 7) $('.header .gray-bar .search-advanced select').eq(0).show();
                structure.eyeCandies.breadcumb.opened = false;
            }
        },

        mainNav: {

            init: function() {
                this.mount();

                //if ($.browser.msie && $.browser.version <= 6) {
                if (1 == 6) {
                    $('.header .blue-bar .nav-sitemap li a').attr("class", "native-hover");
                }
                else {
                    $('.header .blue-bar .nav-sitemap li a .hover').fadeTo(0, 0);
                    $('.header .blue-bar .nav-sitemap li a .hover').css("top", "0");
                    $('.header .blue-bar .nav-sitemap li a').bind("mouseover", this.mouseover);
                    $('.header .blue-bar .nav-sitemap li a').bind("mouseout", this.mouseout);
                }
            },

            mount: function() {
                $.each($('.header .blue-bar .nav-sitemap li a'), function(i, item) {
                    var defText = $(item).text();
                    $(item).html('<span class="text">' + defText + '</span><span class="hover"></span>');
                });
            },

            mouseover: function() {
                $(this).find('.hover').animate(
                {
                    opacity: 1,
                    top: -37
                }, this.defMotionOpts);
            },

            mouseout: function() {
                $(this).find('.hover').animate(
                {
                    opacity: 0,
                    top: 0
                }, this.defMotionOpts);
            },

            defMotionOpts: {
                duration: 300,
                easing: 'linear',
                queue: false
            }
        },

        whiteButtons: {
            init: function() {
                this.mount();
            },

            mount: function() {
                $.each($('.nav-bt-white'), function(i, item) {
                    var defText = $(item).text();
                    var w = $(item).css('width').replace('px', '');
                    var lw = 12;
                    var rw = 15;
                    var cw = w - (lw + rw);
                    $(item).html('<span class="text"><span class="l"></span><span class="c" style="width:' + cw + 'px;">' + defText + '</span><span class="r"></span><span class="hover"><span class="l"></span><span class="c" style="width:' + cw + 'px;"></span><span class="r"></span></span>');
                });
            },

            mouseover: function() {

            },

            mouseout: function() {

            },

            defMotionOpts: {
                duration: 300,
                easing: 'linear',
                queue: false
            }
        }
    },

    layoutAdjustments:
    {
        init: function() {

            var win = $(window);
            var header = $('.all-content > .header');
            var content = $('.all-content > .content');
            var footer = $('.all-content > .footer');
            var elsHeights = 0;
            var cntHeights = 0;
            var totalHeight = 0;

            elsHeights += header.height();
            elsHeights += Number(header.css('margin-top').replace('px', ''));
            elsHeights += Number(header.css('margin-bottom').replace('px', ''));
            elsHeights += Number(header.css('padding-top').replace('px', ''));
            elsHeights += Number(header.css('padding-bottom').replace('px', ''));

            elsHeights += footer.height();
            elsHeights += Number(footer.css('margin-top').replace('px', ''));
            elsHeights += Number(footer.css('margin-bottom').replace('px', ''));
            elsHeights += Number(footer.css('padding-top').replace('px', ''));
            elsHeights += Number(footer.css('padding-bottom').replace('px', ''));

            cntHeights += Number(content.css('margin-top').replace('px', ''));
            cntHeights += Number(content.css('margin-bottom').replace('px', ''));
            cntHeights += Number(content.css('padding-top').replace('px', ''));
            cntHeights += Number(content.css('padding-bottom').replace('px', ''));

            totalHeight = elsHeights + cntHeights + content.height();

            if (totalHeight < win.height()) {
                content.height(win.height() - (elsHeights + cntHeights));
            }

            $(window).resize(structure.layoutAdjustments.init);
        }
    },

    modalGalleries: {
        defaults: {
            overlayBgColor: '#00254F',
            overlayOpacity: 0.9,
            imageLoading: '../static/img/shared/modal-gallery/ico-load.gif',
            imageBtnClose: '../static/img/shared/modal-gallery/nav-close.gif',
            imageBtnPrev: '../static/img/shared/modal-gallery/nav-prev.gif',
            imageBtnNext: '../static/img/shared/modal-gallery/nav-next.gif',
            imageBlank: '../static/img/shared/modal-gallery/spacer.gif',
            txtImage: "Imagem",
            txtOf: "de"
        }
    },


    trace: function(params) {
        try {
            console.log(params);
        } catch (err) {
            //alert(params)
        };
    }
};

/*String.prototype.replace = function(x, y)
{
return this.split(x.toString()).join(y.toString());
}*/

/*---------------------------------------------------
Atalhos                                            */
var trace = structure.trace;
/*-------------------------------------------------*/

$(document).ready(function() {
	setTimeout(structure.init, 100);
});


function enviePlantaEmail(obj){

	var itensList = obj.parent().parent().parent().next().find("input:checked");
	var listagem = new Array();
	$.each(itensList, function(i, item){
		listagem.push($(item).val());
	});
	
	if(listagem.length != 0){
		var str = listagem.join("|");
		
		var url = $(obj).attr("href");
		url += "&idImagens="+str;

		var nObj = $(document.createElement("a"));
		nObj.attr("href",url);

		openModal(nObj, modalEnviePlantaEmail);
	}else{
		alert("Selecione uma planta!");
	}

}

function modalEnviePlantaEmail() {

	$('.form_modal #txtPaginaIndicada').val($(window).attr('location'));

	$('.btn_enviar').click(function() {
		var serializeForm = $('.form_modal').serialize() + "&txtOrigem=" + window.location.href + "&txtChaveArea=Interna de Imóveis - Barra de Navegação abaixo do banner";
		$.ajax({
			type: "POST",
			url: structure.baseUrl + "email/planta.aspx",
			data: serializeForm,
			beforeSend: function() {
				$('.box_error h1').remove();
				$('.box_error').append('<p class="box_load">ENVIANDO ...<img src="../static/img/shared/modal-gallery/ico-load.gif" width="16" height="16" /></p>');
				$('.btn_enviar').attr('disabled', 'disabled');

			},
			success: function(msg) {
				var res = eval(msg);
				$('.box_error h1, .box_load').remove();
				$('.btn_enviar').attr('disabled', '');

				if (res[0]['suceess'] == false) {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

				} else {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')
					if (structure.currentState == 'sp') {
						tracking.google.call('NsS8CN-HqAEQ0ZmG6wM');
					}
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}

		});
		return false;
	});
}

function modalIndique() {

	$('.form_modal #txtPaginaIndicada').val($(window).attr('location'));
	$('.btn_enviar').click(function() {
		var serializeForm = $('.form_modal').serialize() + "&txtOrigem=" + document.title + "&txtChaveArea=Interna de Imóveis - Barra de Navegação abaixo do banner";
		$.ajax({
			type: "POST",
			url: structure.baseUrl + "email/indiquePage.aspx",
			data: serializeForm,
			beforeSend: function() {
				$('.box_error h1').remove();
				$('.box_error').append('<p class="box_load">ENVIANDO ...<img src="../static/img/shared/modal-gallery/ico-load.gif" width="16" height="16" /></p>');
				$('.btn_enviar').attr('disabled', 'disabled');

			},
			success: function(msg) {
				var res = eval(msg);
				$('.box_error h1, .box_load').remove();
				$('.btn_enviar').attr('disabled', '');

				if (res[0]['suceess'] == false) {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

				} else {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')
					if (structure.currentState == 'sp') {
						tracking.google.call('NsS8CN-HqAEQ0ZmG6wM');
						tracking.funnel.steps01.call('65747');
					}
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}

		});
		return false;
	});
}

function modalLigue() {
	$('.btn_enviar').click(function() {
		var serializeForm = $('.form_modal').serialize();
		$.ajax({
			type: "POST",
			url: structure.baseUrl + "email/ligar.aspx",
			data: serializeForm + '&txtIdAtendimento=' + $('.idAtendimento').val() + "&txtOrigem=" + window.location.href + "&txtChaveArea=Barra de menus da direita",
			beforeSend: function() {
				$('.box_error h1').remove();
				$('.box_error').append('<p class="box_load">ENVIANDO ...<img src="../static/img/shared/modal-gallery/ico-load.gif" width="16" height="16" /></p>');
				$('.btn_enviar').attr('disabled', 'disabled');
			},

			success: function(msg) {
				var res = eval(msg);
				$('.box_error h1, .box_load').remove();
				$('.btn_enviar').attr('disabled', '');

				if (res[0]['suceess'] == false) {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

				} else {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

					if (structure.currentState == 'sp') {
						tracking.google.call('EnShCP2mtQEQ0ZmG6wM');
						tracking.funnel.steps01.call('65745');
					}
				}
			},

			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}

		});
		return false;
	});
}

function modalFacaUmaVisita() {
	$('.btn_fechar a').neoHover();

	$.getScript('static/js/lib/ui.datepicker.js', function(data, status) {
		$("#datepicker").datepicker({
			dateFormat: 'dd-mm-yy',
			monthNames: ['Janeiro', 'Fevereio', 'Marco', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
			dayNamesMin: ['Dom', 'Sab', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex'],
			onSelect: function(dateText, inst) {
				$('#txtDia').val(inst['selectedDay']);
				$('#txtMes').val(inst['selectedMonth'] + 1);
				$('#txtAno').val(inst['selectedYear']);
			}
		});
	});

	$('.btn_enviar').click(function() {
		var serializeForm = $('.form_modal').serialize();
		$.ajax({
			type: "POST",
			url: structure.baseUrl + "email/agendarPage.aspx",
			data: serializeForm + '&txtIdAtendimento=' + $('.idAtendimento').val() + "&txtOrigem=" + window.location.href + "&txtChaveArea=Barra de menus da direita",
			beforeSend: function() {
				$('.box_error h1').remove();
				$('.box_error').append('<p class="box_load">ENVIANDO ...<img src="../static/img/shared/modal-gallery/ico-load.gif" width="16" height="16" /></p>');
				$('.btn_enviar').attr('disabled', 'disabled');
			},

			success: function(msg) {
				var res = eval(msg);
				$('.box_error h1, .box_load').remove();
				$('.btn_enviar').attr('disabled', '');

				if (res[0]['suceess'] == false) {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

				} else {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

					if (structure.currentState == 'sp') {
						tracking.google.call('CHaDCNentQEQ0ZmG6wM');
						tracking.funnel.steps01.call('65744');
					}
				}
			},

			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}

		});
		return false;
	});
}
function modalFaleConosco() //quero comprar
{
	$('.btn_enviar').click(function() {
		var serializeForm = $('.form_modal').serialize();
		$.ajax({
			type: "POST",
			url: structure.baseUrl + "email/faleConoscoPage.aspx",
			data: serializeForm + '&txtIdAtendimento=' + $('.idAtendimento').val() + "&txtOrigem=" + window.location.href + "&txtChaveArea=Barra de menus da direita",
			beforeSend: function() {
				$('.box_error h1').remove();
				$('.box_error').append('<p class="box_load">ENVIANDO ...<img src="../static/img/shared/modal-gallery/ico-load.gif" width="16" height="16" /></p>');
				$('.btn_enviar').attr('disabled', 'disabled');
			},
			success: function(msg) {
				var res = eval(msg);
				$('.box_error h1, .box_load').remove();
				$('.btn_enviar').attr('disabled', '');

				if (res[0]['suceess'] == false) {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')

				} else {
					$('.box_error').append('<h1>' + res[0]['message'] + '</h1>')
					if (structure.currentState == 'sp') {
						tracking.google.call('3VHqCLmIqAEQ0ZmG6wM');
						tracking.funnel.steps01.call('65743');
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}

		});
		return false;
	});
}
/*CLOSE MODAL*/
function closeModal() {
	/*HIDE MODAL*/
	$('.view_modal').fadeTo('fast', 0, function() {
		$(this).remove();
	});

	/*HIDE BACKGROUND*/
	$('.bg_modal').fadeTo('fast', 0, function() {
		$(this).remove();

		/*SHOW SELECT*/
		$('select').css('visibility', 'visible');

		/*FLASH PHONE HIDE*/
		$('#flash-phone').css('visibility', 'visible');
	});
}

/*MODAL*/
function openModal(obj, callback) {
	/*CREATE ELEMENTS*/

	//window.scroll(0,0);
	var scroll = '';
	if ($.browser.msie) {
		scroll = document.documentElement.scrollTop;
	} else {
		scroll = $(window).attr('scrollY');
	}

	$('body').append('<img src="../static/img/shared/load.gif" width="88" height="78" alt="Carregando..." class="load" /><div class="bg_modal"></div><div class="view_modal"></div>');
	$('.bg_modal').width($('html')[0].scrollWidth).height($('html')[0].scrollHeight);

	/*OPACITY*/
	$('.view_modal').css('opacity', 0.5);
	$('.bg_modal').css('opacity', 0.5);

	/*FLASH PHONE HIDE*/
	$('#flash-phone').css('visibility', 'hidden');

	/*SELECTS HIDE*/
	$('select').css('visibility', 'hidden');

	/*SHOW BACKGROUND*/
	$('.bg_modal').fadeTo('fast', 0.5, function() {
		$('.view_modal').load(obj.attr('href'), function() {
			/*REMOVE LOAD*/
			$('.load').remove();

			/*CENTRALIZE MODAL*/
			$('.view_modal').css({ marginTop: (-parseInt($('.view_modal').height() / 2) + parseInt(scroll)), marginLeft: -parseInt($('.view_modal').width() / 2) });

			/*MODAL HIDE*/
			$('.view_modal').fadeTo('fast', 1);

			/*CLOSE MODAL*/
			$("a[rel='modalclose']").click(function() {
				closeModal();
				return false;
			})

			callback();
		});
	});
}

function initModal() {
	$("a[@rel='modal']").click(function() {
		openModal($(this));
		return false;
	});
}
