var Site = function() {
    
    
    return {
      
        initCommon: function() {

			if (/MSIE [678]./i.test(navigator.userAgent)) {
				// maldicao de samanta
			}
			
			$("#search").find("select.selectbox").customStyle({});
			
			$("#btn-talk-to-us, #btn-talk-to-us-2").live("click", function () {
				showModalDlg("Fale Conosco", "/form/talk-to-us", 530);
				return false;
			});
			$("#btn-add-property, #btn-add-property-2").live("click", function () {
				showModalDlg("Cadastre seu Im&oacute;vel", "/form/add-property", 700);
				return false;
			});
			$("#btn-request-property, #btn-request-property-2").live("click", function () {
				showModalDlg("Encomende seu Im&oacute;vel", "/form/request-property", 700);
				return false;
			});
			$("#btn-newsletter").live("click", function () {
				showModalDlg("Cadastro Newsletter", "/form/news", 400);
				return false;
			});
			$("#btn-we-call-you, #btn-we-call-you-2, #btn-we-call-you-3, #btn-we-call-you-4").live("click", function () {
				showModalDlg("Ligamos para voc&ecirc;", "/form/call-to-you", 530);
				return false;
			});
			$("#btn-work-with-us").live("click", function () {
				showModalDlg("Trabalhe Conosco", "/form/work-with-us", 700);
				return false;
			});

			$("#services").click(function(){
				$(this).toggleClass("active");
				$("#services-itens").toggle();
			});
          
        },
		
		initHome: function() {
			
			$("#destaques-list").carouFredSel({
                visible: 4,
                prev: {
                    button: "#destaque_prev",
                    items: 3
                },
                next: {
                    button: "#destaque_next",
                    items: 3
                },
                auto: {
                    play: false
                },
                height: 300,
                circular: false,
                infinite: false
            });
			
			$("#main").find("ul.box").find(".details").equalHeight();
			
		},
	  
        initDetails: function() {
			
			$("#imoveis-relacionados").carouFredSel({
                items: 3,
                scroll: {
                    items: 3
                },
                next: '#imoveis-relacionados-next',
                prev: '#imoveis-relacionados-prev',
                direction: 'up',
                auto: false,
                circular: false,
                infinite: false,
                height: 'variable'
            });
			
			$("#carac").carouFredSel({
                visible: 4,
                prev: {
                    button: "#carac_prev",
                    items: 3
                },
                next: {
                    button: "#carac_next",
                    items: 3
                },
                auto: {
                    play: false
                },
                height: 'auto',
                circular: false,
                infinite: false
            });
			
			$("#open-gallery").click(function () {
				if (!/no-photo.gif/.test($("#main-photo").attr("src"))) {
					if (globals.oldie) {
						$("#gallery").show();
					} else {
						$("#gallery").fadeIn();
					}
					globals.init();
				}
				return false;
			});
			
			/*if ($("#galeria-container").html() != null && $("#thumbs").find("li").length > 0) {
                // TAMANHO DOS LI DAS THUMBS (COM MARGIN E PADDING)
                var ThumbsWidth = 91;
                var ThumbsHeight = 91;
                
                var ThumbsNum = $('#thumbs').width() / ThumbsWidth;
                
                var gallery = $('#thumbs').galleriffic({
                    delay: 7000,
                    numThumbs: Math.floor(ThumbsNum),
                    preloadAhead: 10,
                    enableTopPager: true,
                    enableBottomPager: false,
                    maxPagesToShow: 2,
                    imageContainerSel: '#slideshow',
                    controlsContainerSel: '#controls',
                    captionContainerSel: '#caption',
                    loadingContainerSel: '#loading',
                    renderSSControls: true,
                    renderNavControls: true,
                    playLinkText: 'Iniciar Slideshow',
                    pauseLinkText: 'Pausar Slideshow',
                    prevLinkText: '',
                    nextLinkText: '',
                    nextPageLinkText: 'Pr&oacute;xima &rsaquo;',
                    prevPageLinkText: '&lsaquo; Anterior',
                    enableHistory: false,
                    autoStart: false,
                    syncTransitions: true,
                    defaultTransitionDuration: 600,
                    onSlideChange: function(prevIndex, nextIndex) {
                        // 'this' refers to the gallery, which is an extension of $('#thumbs')
                        //this.find('ul.thumbs').children().eq(prevIndex).fadeTo('fast', 0.65).end().eq(nextIndex).fadeTo('fast', 1.0);
                        this.find('ul.thumbs').height(ThumbsHeight);
                    },
                    onPageTransitionOut: function(callback) {
                        this.fadeTo('fast', 0.0, callback);
                    },
                    onPageTransitionIn: function() {
                        this.fadeTo('fast', 1.0);
                    }
                });
                
                
                $("#gallery .next").live("click", function() {
                    gallery.next();
                });
                $("#gallery .prev").live("click", function() {
                    gallery.previous();
                });
                
                $("#open-gallery").fancybox({
                    inline: true,
                    href: '#galeria-container',
                    centerOnScroll: true,
                    scrolling: false
                });
            
            }
            
            $("#galeria").hide();*/
          
        }
      
      
    }  
    
    
}();

/* Faux Columns: $(selector).equalHeight() */
(function($){$.fn.equalHeight=function(){var tallest=0;this.each(function(){var thisHeight=$(this).height();if(thisHeight>tallest)tallest=thisHeight});this.each(function(){$(this).height(tallest)})}})(jQuery);

/* BigTarget */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(3($){$.k.l=3(d){4 e=$.r({},$.k.l.u,d);5 g.K(3(){4 a=$(g);4 b=a.9(\'J\');4 c=a.9(\'1\');4 o=$.H?$.r({},e,a.F()):e;a.C(o.m).n(3(){$h=$(g);$h.y(o.j);2(s o.1!=\'q\'&&o.1===i&&c!=\'\'){$h.9(\'1\',c)}},3(){$h.w(o.j);2(s o.1!=\'q\'&&o.1===i&&c!=\'\'){$h.G(\'1\')}}).x(3(){2(p()==""){2(a.z(\'[A*=B]\')){8.D(b);5 E}f{8.v=b}}})})};3 p(){2(8.7){5 8.7().I()}f 2(6.7){5 6.7()}f 2(6.t){5 6.t.L().M}};$.k.l.u={j:\'n\',m:\'N:O(0)\',1:i}})(P);',52,52,'|title|if|function|var|return|document|getSelection|window|attr||||||else|this||true|hoverClass|fn|bigTarget|clickZone|hover||getSelectedText|undefined|extend|typeof|selection|defaults|location|removeClass|click|addClass|is|rel|external|parents|open|false|data|removeAttr|meta|toString|href|each|createRange|text|li|eq|jQuery'.split('|'),0,{}));

function modalDlgAfterSave($container, result) {
    if (result == "OK") {
        $container.html('<p class="alert-message success">Obrigado. Entraremos em contato em breve!</p>');
    } else {
        $container.html('<p class="alert-message error">Ocorreu um erro em nossos servidores. Desculpe-nos pelo transtorno.</p>');
    }
}

var dlgFormLoading = false;

function showModalDlg(title, url, width) {
	if (!dlgFormLoading) {
		dlgFormLoading = true;
		var id = "dialog-container";
		$("html").css("cursor", "wait");
		var $btn = null;
		var $container = null;
		function hide ($target) {
			if (/MSIE [678]./i.test(navigator.userAgent)) {
				$target.remove();
			} else {
				$target.find(".modal").slideUp().end().fadeOut(function() {
					$(this).remove();
				});
			}
			resetState();
		};
		function resetState() {
			document.body.style.cursor = "default";
			$btn.remove();
		}
		$.get(url, function(data) {
			$("body").append('<div class="overlay" id="' + id + '"><div class="modal"><div class="modal-header"><div class="bg"><h3>' + title + '</h3><a href="#" class="close">&times;</a></div></div><div class="modal-body clearfix">' + data + '</div><div class="modal-footer"><button class="btn primary" id="' + id + '-send">Enviar</button><a href="#" class="btn secondary close">Sair</a> </div></div></div>');
			$container = $("#" + id);
			$btn = $container.find(".primary");
			var $modal = $container.find(".modal").width(width);
			var $form = $("#dlg-form").find("input:text").first().focus().end().end();
			$form.ajaxForm({
				beforeSubmit: function() {
					$btn.text("Enviando...").prop("disabled", true).addClass("disabled");
					document.body.style.cursor = "wait";
				},
				success: function(responseText, statusText, xhr, $form) {
					modalDlgAfterSave($("#dialog-container").find(".modal-body"), responseText);
					resetState();
				}
			});
			$form.find("input.required").blur(function() {
				if ($(this).val() == "") {
					$(this).addClass("error");
				} else {
					$(this).removeClass("error");
				}
			});
			$form.find("input.email").blur(function() {
				if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($(this).val())) {
					$(this).addClass("error");
				} else {
					$(this).removeClass("error");
				}
			});
			$("#dlg-form").find(".carousel").carouFredSel({
				circular: false,
				infinite: false,
				direction: "up",
				align: "top",
				height: 235,
				items: {
					visible: 1
				},
				scroll: {
					items: 1,
					fx: "directscroll"
				},
				auto: false,
				prev: {
					button: "#prev_question",
					key: "left"
				},
				next: {
					button: "#next_question",
					key: "right"
				},
				pagination  : "#pag"
			});
			$modal.css("marginTop", -$modal.height() / 2).css("marginLeft", -width / 2);
			$container.find(".primary").live("click", function() {
				if (!$(this).hasClass("disabled")) {
					if ($("#dlg-form").find("input.error").length > 0 || $("#dlg-form").find("input.text").val() == "") {
						$container.find(".alert-message").show().addClass("error").html("Preencha corretamentes os campos indicados.<br />Se houver o campo e-mail, o formato &eacute; o seguinte: exemplo@email.com").end().find("input").first().focus();
					} else {
						$("#dlg-form").submit();
					}
				}
				return false;
			});
			$container.find(".close").live("click", function(e) {
				hide($container);
				e.stopPropagation();
				dlgFormLoading = false;
				return false;
			});
			$(document).click(function (e) {
				if ($container.has(e.target).length === 0) {
					dlgFormLoading = false;
					hide($container);
				}
			});
			$form.find("input:text").setMask();
			$("#dlg-form").find(".adjacent").find("input").live("keydown keyup", function (e) {
				if (e.which == 9) {
					return false;
				}
			});
			$("html").css("cursor", "default");
		}).error(function() {
			alert("Ocorreu um erro em nossos servidores. Por favor, tente entrar em contato com as informações no rodapé da página.");
		});
	}
}

function reloadCombo(combo, url) {
    $.getJSON(encodeURI(url), function (response) {
        var options = '';
        options += '<option value="-1">- Selecione -</option>';
        for (var i = 0; i < response.length; i++) {
            options += '<option value="' + response[i].name + '">' + response[i].name + '</option>';
        }
        $(combo).html(options);
    });

}
