﻿var Site = function () {

	var LastProps = {
		
		properties: $.jStorage.index(),
		limit: 5,
	
		insert: function ( o ) {
			
			if ( this.get().length >= this.limit && !$.jStorage.get( o.id ) ) {
			
				$.jStorage.deleteKey( this.get()[ this.limit - 1 ].id );
				
			}
			
			$.jStorage.set( o.id, $.toJSON( o ) );
			this.properties = $.jStorage.index();
			
		
		},
		
		get: function () {
		
			var props = [];
			for ( var i = -1, il = this.properties.length; ++i < il; ) {
				props.push( $.parseJSON( $.jStorage.get( this.properties[i] ) ) );
			}
			
			//console.log( props );
			
			return props.sort( function( a, b ) {
				if ( a.timestamp < b.timestamp ) return 1;
				if ( a.timestamp > b.timestamp ) return -1;
				return 0;
			});
			
		
		}
		
	};

	return {

		insertProperty: function ( p ) {
		
			LastProps.insert( p );
		
		},
		
		printLastProperties: function () {
		
		
			if ( LastProps.get().length > 0 ) {
		
				var $lp = $('#last-properties').show().find('ul');
				
				$.map( LastProps.get(), function ( p ) {
					
					$lp.append( $('<li />').html(
						'<a href="/index/details/id/' + p.id + '#main"><span class="img"><img src="' + p.thumb + '" alt="" /></span>' + 
						'<span class="description"><strong>' + p.type + '</strong><strong>' + p.address + '</strong></span></a>'
					) );
				
				});
				
			}
		
		},
		
		printLastPropertiesHome: function () {
		
		
			if ( LastProps.get().length > 0 ) {
		
				var $lp = $('#last-properties-home').show().find('ul');
				
				$.map( LastProps.get(), function ( p ) {
					
					$lp.append( $('<li />').html(
						'<a href="/index/details/id/' + p.id + '#main"><img src="' + p.thumb + '" alt="" />' + 
						'<span class="description"><strong>' + p.type + '</strong><strong>' + p.address + '</strong>' + p.details + '</span></a>'
					) );
				
				});
				
				window.onload = function () {
					$lp.find('a').equalHeight();
				}
				
			}
		
		},
	
		initCommon: function () {
			
			Plug.init();

			$('#sidebar').children().last().addClass('last');
			
			$('form').find('select.selectbox').selectbox();
			
			$(window).on('resize', function () {
				if ($(this).width() < 1055) {
					$("#fixed-corretor").hide();
				} else {
					$("#fixed-corretor").show();
				}
			});
			
			if ($(window).width() < 1055) {
				$("#fixed-corretor").hide();
			} else {

				if ( !Plug.oldIE ) {
					var $w = $(window);
					var $fs = $('#fixed-corretor').css({
						position: 'absolute',
						marginTop: 0
					});
					function animateFixedSide() {
						$('#fixed-corretor').stop().animate({
							top: ( $w.scrollTop() ) + ( $w.height() - $('#fixed-corretor').height() ) / 2
						}, 450)
					};
					animateFixedSide();
					$(window).on('scroll', function () {
						animateFixedSide();
					});
				}
				
			}

		},

		initHome: function () {
			
			var $boxes = $('#main').find('ul.box').children();

			$boxes.equalHeight();

			if (Plug.oldIE) {
				$boxes.find('a').bigTarget({
					hoverClass: 'hover'
				});
			}

			var carousels = ["#carousel-locacao", "#carousel-lancamentos", "#carousel-prontos"];
            for (var i=0,lg=carousels.length;i<lg;i++) {
                var items = 2;
				var $li = $(carousels[i]).children("li");
                if ($li.length == 0) {
                    $(carousels[i]).append("<li class='caroufredsel-none first'>N&atilde;o h&aacute; im&oacute;veis nesta categoria.</li><li class='last hidden'>" + carousels[i] + "</li>");
                    items = 2;
                } else {
					$li.first().addClass('first').end().last().addClass('last');
				}
                $(carousels[i]).carouFredSel({
                    items: items,
                    scroll: {
                        items: items,
                        duration: 600,
						easing: 'easeInBack'
                    },
                    auto: false,
					circular: true,
					infinite: true,
					height: 'auto'
                });
            }
			var tallest = 0;
			for (var i=0,lg=carousels.length;i<lg;i++) {
				var thisHeight = $(carousels[i]).height();
				if (thisHeight > tallest) tallest = thisHeight;
			}
			for (var i=0,lg=carousels.length;i<lg;i++) {
				$(carousels[i]).height( tallest ).parent().height( tallest );
			}
			
			// Tabs
			$('#st_horizontal').slideTabs({
				autoHeight: true,
				contentAnim: 'fade',
				contentAnimTime: 200
			});

			$("#st-home-next").click(function (e) {
				e.preventDefault();
				$('#st_horizontal div.st_active_view').find('ul').first().trigger('next');
			});

			$("#st-home-prev").click(function (e) {
				e.preventDefault();
				$('#st_horizontal div.st_active_view').find('ul').first().trigger('prev');
			});

			$("#slider-images").carouFredSel({
				items: 1,
				auto: {
					pauseOnHover: true
				},
				scroll: {
					fx: 'crossfade',
					duration: 800
				}
			});
			
			/*var $next = $('#st-home-next');
			var $prev = $('#st-home-prev');
			
			function checkForDisabled() {
				var $ul = $('#st_horizontal div.st_active_view').find('ul').first();
				var _liLen = $ul.children().length;
				$ul.trigger('getCurrentItems', function($lis) {
					console.log( $lis );
					if ( _liLen <= 3 ) {
						$next.addClass('disabled');
						$prev.addClass('disabled');
					} else {
						console.log(1);
						if ($lis.filter('.first').length > 0) {
							console.log('has first');
							$prev.addClass('disabled');
						} else if ($lis.filter('.last').length > 0) {
							console.log('has last');
							$next.addClass('disabled');
						} else {
							$next.removeClass('disabled');
							$prev.removeClass('disabled');
						}
					}
				});
			}*/
			
			
			/*var $st_horizontal = $('#st_horizontal');
			var $st_tabs = $st_horizontal.find('ul.st_tabs');
			$("#st-home-next").click(function (e) {
				e.preventDefault();
				var $active = $st_horizontal.find('div.st_active_view').find("ul");
				$active.trigger("getCurrentItems", function (x) {
					if (x.last().text() == $active.find("li.last").text()) {
						$st_tabs.find('a.active').parent().next().find("a").click();
					} else {
						$active.trigger("next");
					}
				});
				//checkForDisabled();
			});
			$("#st-home-prev").click(function (e) {
				e.preventDefault();
				var $active = $st_horizontal.find('div.st_active_view').find("ul").first();
				$active.trigger("getCurrentItems", function (x) {
					if (x.first().text() == $active.find("li.first").text()) {
						$st_tabs.find('a.active').parent().prev().find("a").click();
					} else {
						$active.trigger("prev");
					}
				});
				//checkForDisabled();
			});*/
			
			/*$('#main')
				.find('ul.box')
					.each2(function () {
						this.children().equalHeight()
							.find('a').bigTarget({
								hoverClass: 'hover'
							});
					});
			
			$("#destaques-list").carouFredSel({
				items: 4,
				prev: {
					button: "#destaques-prev"
				},
				next: {
					button: "#destaques-next"
				},
				scroll: {
					easing: 'easeOutBack',
					duration: 600
				},
				auto: {
					play: false
				},
				height: 'auto',
				circular: false,
				infinite: false
			});
			
			$("#slider-images").carouFredSel({
				items: 1,
				height: 278,
				align: 'center',
				auto: {
					pauseOnHover: true
				},
				scroll: {
					fx: 'crossfade',
					duration: 800
				}
			});*/
			
		},

		initSearch: function () {
			
			$('#search-results').find('div.video a').fancybox();

		},

		initDetails: function () {
		
			$('#property-photo-items').find('a').fancybox({
				prevEffect		: 'elastic',
				nextEffect		: 'elastic',
				helpers	: {
					title	: {
						type: 'inside'
					},
					overlay	: {
						opacity : 0.8,
						css : {
							'background-color' : '#000'
						}
					},
					thumbs	: {
						width	: 50,
						height	: 50
					}
				}
			});
			$("#open-gallery").on('click', function (e) {
				$("#property-photo-items").find('a').first().click();
				e.preventDefault();
			});
			$('#youtube').fancybox();
			
			/*$("#details-plug").children().equalHeight();
			$("#details-paymodes").children().equalHeight();*/
			
			$("#carac").carouFredSel({
                items: 3,
                prev: {
                    button: "#carac_prev"
                },
                next: {
                    button: "#carac_next"
                },
                auto: {
                    play: false
                },
                height: 'auto',
                circular: false,
                infinite: false
            });
			
			var $form = $('#gostei-imovel');
			$form.find('input:text').setMask();
			$form.ajaxForm({
				error: function() {
					alert('Erro ao enviar o formulário. Por favor, tente novamente mais tarde.');
				},
				beforeSerialize: function () {
					$form.find("button.submit").prop("disabled", true).css("cursor", "wait");
				},
				success: function (data) {
					if (data == "OK") {
						$form.slideUp("medium", function () {
							$(this).html('<div class="alert-message success">Enviado com sucesso!</div>').slideDown();
						});
					} else {
						alert('Por favor, preencha os campos corretamente.');
					}
					$form.find("button.submit").prop("disabled", false).css("cursor", "default");
				}
			});
			
		}

	}

}();

function reloadCombo(combo, url, first_opt, second_opt) {
    $(combo).prop("disabled", true).parent().find(".styleSelect").removeClass("disabled").find("span").text("Carregando..");
    $.getJSON(encodeURI(url), function (response) {
        var options = '';
        options += '<option value="-1">' + first_opt + '</option>';
        options += '<option value="-1">' + second_opt + '</option>';
        for (var i = 0; i < response.length; i++) {
            options += '<option value="' + response[i].value + '">' + response[i].label + '</option>';
        }
        $(combo).html(options);
        $(combo).prop("disabled", false).next().removeClass("disabled").children().text(first_opt);
    });
}

function clearDisableCombo(combo, first_opt) {
    $(combo).prop("disabled", true).next().addClass("disabled").children().text(first_opt);
    $(combo).val(-1);
}
