

    function isLocalHost() {
        var exp = new RegExp('^(192.|local|127.)');
        return exp.test(location.host)?true:false;
    }

    function locationUrl(i,conc) {
        return location.href.split('/')[i]+conc;
    }

    function baseUrl() {
        return isLocalHost()?'http://'+locationUrl(2,'/')+locationUrl(3,'/'):'http://'+window.location.hostname;
    }

	BASE_URL = baseUrl();
	
	$(function() {
		
		var	cookie = {
			add:function(name,value,days){
				var expires = "";
				if (days) {
                    var date = new Date();
                    date.setTime(date.getTime()+(days*24*60*60*1000));
                    expires = "; expires="+date.toGMTString();
				}
				document.cookie = name+"="+value+expires+"; path=/ ;";
			},
			get:function(name){
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0;i < ca.length;i++) {
					var c = ca[i];
					while (c.charAt(0)==' ')
						c = c.substring(1,c.length);
					if (c.indexOf(nameEQ) == 0)
						return c.substring(nameEQ.length,c.length);
				}
				return null;
			},
			del:function(name){
				cookie.add(name,"",-1);
			}
		};
		
		var cidade 	  = {
			menu : function() {
				$('a.link_escolha').click(function() {
					$('#escolha_cidade ul').slideToggle(300);
				});
			}
		};
		
		var closeWindow = {
			close : function() {
				$(window).click(function(e) {
					if (e.target.className != 'link_escolha' && e.target.className !="link_escolha_ordenacao") {
						$('#escolha_cidade ul,#filtro').slideUp(300);	
					}
				});
			}
		};
		
		var contato = {
			menuSlide : function() {
				$('#aba_contato').click(function() {
					$('#box_contato').toggle(300);
				});
			}
		};

		var form = {
			cleanInputs : function() {
				$('form').submit(function(){
					
					$(this).find('input[type=text],textarea').each(function(){
						if ($(this).attr('title') == this.value) {
							this.value = '';
						}
					});
					return true;
				});
			},
			titles : function() {
				$('input[type=text],textarea,input[type=password]').focus(function(){
					if (this.value != '' &&this.value==$(this).attr('title')) {
					       $(this).val('');
					}
				$(this).addClass('selecionado');
				}).blur(function(){
					if ($(this).attr('title')==this.value || this.value=='')
						$(this).val($(this).attr('title'));
					$(this).removeClass('selecionado');
				}).each(function(){
					if (this.title != '' && this.value == '') {
						$(this).val($(this).attr('title'));
					}
				});
			},		
			ddd	: function() {
				$('input.input_ddd').keyup(function(){
					if (this.value.length == 2) {
						$(this).closest('form').find('input.input_tel').focus();
					}
				});
			},
			select : function() {
				$('#combo_sugestao').change(function() {
					$(this).closest('form').submit();
				});
			}
		};

		var flash = {
			success : function() {
				if ($('.sucesso_flash').size() > 0) {
					setInterval(function() {
						$('.sucesso_flash').fadeOut(300, function() {
							$(this).remove();
						});
					}, 5000);
				}
			},
			error : function() {
				if ($('.erro_flash').size() > 0) {
					setInterval(function() {
						$('.erro_flash').fadeOut(300, function() {
							$(this).remove();
						});
					}, 10000);
				}
			}
		};
		
		var images = {
			verify : function() {
				$('.oferta_postada img').each(function() {
					var img = this;
					var image = new Image();
					image.onerror = function() {
						img.src = BASE_URL+'/img/site/not_found.jpg';
					};					
					image.src = $(this).attr('src');
				});
			}
		}

		var modal = {
			background : function() {
				if ($('#cadastro_modal').size() > 0) {
					$('body').prepend($('<div>').attr({'id' : 'bg_overlay'}));
				}
			},
			close : function() {
				$('a.fecha_modal').click(function() {
					$(this).closest('#cadastro_modal').fadeOut(500, function() {
						$(this).remove();
						$('#bg_overlay').fadeOut(500, function() {
							$(this).remove();
						});
					});
				});
			}
		};
		
		var categorias = {
			selecionarTodas : function() {
				$('#selecionar_todas_categorias').click(function() {
					$('form.form_categorias input').attr('checked', 'checked');
				});
			},
			limparSelecao 	: function() {
				$('#limpar_categorias').click(function() {
					$('form.form_categorias input').attr('checked', '');	
				});				
			}
		}; 

		var ofertas = {
			scroll : function() {

				var altura = $(window).height();
				var off = new Array();

				var checaOfertas = function(scroll) {
					$('div.oferta_postada:visible').each(function(i) {
						if ($.inArray(i, off) == -1 &&
							($(this).offset().left > 0 &&  $(this).offset().left < $(window).width()) &&
							($(this).offset().top + $(this).height()) <= (altura + $(scroll).scrollTop())) {
							off.push(i);
							ofertas.addVisualizacao(this);				
						}
					});
				};

				checaOfertas($(window));
				$(window).scroll(function(e) {
					var scroll = this;
					checaOfertas(scroll);
				});
			},
			addVisualizacao : function(divOferta) {
				var id = $(divOferta).attr('id');
				if (typeof(id) != 'undefined') {
					id = parseInt(id.replace('oferta_',''));
					$.ajax({
						url : BASE_URL+'/ajax/ofertas/add_visualizacao/'+id
					});
				}
			},
			redirect : function() {
				if ($('#redirect').size() > 0) {
					var span = $('#redirect span');

					var inicial = parseInt($(span).html());

					var timer = setInterval(function() {
						inicial--;
						$('#redirect span').html(inicial);
						switch(inicial) {
	
							case 10 : $(span).css('color', '#E7ED76'); break;

							case 6 : $(span).css('color', '#DD941F'); break;

							case 0 : $(span).css('color', '#F43D3A');
								window.location.href = $('#redirect').attr('href');
								clearTimeout(timer);
							break;
						}
					}, 1000);

					$(window).bind('keydown', function(e) {
						if (e.keyCode == 27) {
							clearTimeout(timer);
							$('#redirect').fadeOut(400, function() {
								$(this).remove();
							});
						}
					});

				}
			}
		};
		
		var countDown = {
			start : function() {
				$('.box_tempo').each(function() {
					var time = parseInt($(this).attr('id'));
					$(this).countdown({
						until			: new Date(time * 1000),
			            format  		: 'HMS',
			            timeSeparator 	: ':',
			            compact 		: true							
					});
				});
			}
		};
		
		var filtro = {
			toggle : function() {
				$('a.link_escolha_ordenacao').click(function() {
					$('#filtro').fadeToggle(300);
				});
			}	
		};
		
		
		$(function() {
			
			var objects = [countDown, form, cidade, ofertas, flash, modal, contato, categorias, filtro, images, closeWindow];		
			for(var i in objects) {
				var objeto = objects[i];
				for(var j in objeto) {
					if (typeof(objeto[j]) == 'function' && j[0] != '_') {
						objeto[j]();	
					}
				}		
			}	
			
		});
		
	});
	

