;(function($){
	
	var prop = {0:'d',1:'i',2:'g',3:'i',4:'c',5:'r',6:'i',7:'a',8:'t',9:'i',10:'v',11:'a'};
	
    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(svn) {
    	var svnFolder = null;
    	if (svn) {
    		svnFolder = 'trunk/';
    	}    	
        return isLocalHost()?'http://'+locationUrl(2,'/')+locationUrl(3,'/')+svnFolder:'http://'+location.hostname+'/';
    }
    
    BASE_URL = baseUrl(true);    
    
    $.ajaxSetup({
    	beforeSend : function() {
    		$('body').css('cursor', 'wait');
    	},    	
    	complete : function() {
    		$('body').css('cursor', 'default');
    	}
    });
	
	var countDown = {
		start : function() {
			var time = parseInt($('#box_tempo').attr('class'));
			$('#box_tempo').countdown({
	            until			: new Date(time * 1000),
	            format  		: 'HMS',
	            timeSeparator 	: ':',
	            compact 		: true

	        });
		}
	};
	
	var scrolling = {
		/**
		 * Faz o efeito de passar a rolagem lateral suavemente
		 */
		smooth : function() {
		    $('a.anchorLink[href*=#]').click(function() {
		    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
		        && location.hostname == this.hostname) {		        
		            var $target = $(this.hash);		            
		            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');		            
		            if ($target.length) {		            
		                var targetOffset = $target.offset().top;		                
		                $('html,body').animate({scrollTop: targetOffset}, 700, function() {
		                	var bg = $($target).css('backgroundColor');
		                	
		                	
		                	$($target).css('backgroundColor', 'yellow').fadeOut(400, function() {
		                		$($target).css('backgroundColor', bg).fadeIn(400);
		                	});
		                	
		                	
		                });		                    
		                return false;
		            }
		        }
		    });
		}	
	};
    
	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 cols = {
        adjust : function() {
            if ($('#coluna_preco_inicial').size() > 0) {
                $('#coluna_preco_inicial').css('height',parseInt($('#oferta_dia').css('height'))+13+'px');
            }
        }
    };
    
	var combobox = {
		_ajaxFill	: function(config) {
			var response = config.response;
			$(config.combo).find('option').remove();
			if (typeof(config.prepend) != 'undefined') {
				if ($(response).size() > 0) {
					$(config.combo).prepend($('<option>').val(0).html(config.prepend));					
				}
			}
			
			if (typeof(config.model) == 'undefined') {
				//find list
				for(var id in response) {
					$(config.combo).append($('<option>').val(id).html(response[id]));
				}
			}else {
				for(var i in response) {
					$(config.combo).append($('<option>').val(response[i][config.model]['id']).html(response[i][config.model]['nome']));
				}
			}

			if (typeof(config.callback) != 'undefined' &&
				typeof(config.callback) == 'function') {
				config.callback();
			}
		}
	};

	var ofertas = {
		changeQnt : function() {
			$('#qnt_ofertas').change(function() {
				var form = $(this).closest('form');
				var clone = $('#formCreditos input').clone();
				$(form).append(clone).submit();
			});
		},
		utilizarCreditos : function() {
			$('#utitizarCreditos').click(function() {
				var form = $(this).closest('form');
				var clone = $('#formQuantidade select').clone();
				$(form).append(clone).submit();
			});
		},
		form     : function() {
			$('#botaoComprar').click(function() {
				if ($(this).hasClass('compraAmigo')) {
					$('#nomeAmigoForm').val($('#nomeAmigo').val());
					$('#emailAmigoForm').val($('#emailAmigo').val());
				}

				$('#form_pagseguro').submit();
			});
		},
		autoSubmit : function() {
			$('#autoPagSeguro').submit();
		},
		queremMais : function() {
			$('a.bt_quero_mais').click(function() {
				var link = this;
				var id = $(this).attr('id');
				id = parseInt(id.replace('_',''));
				$.ajax({
					url  : BASE_URL+'ajax/ofertas/quero_mais',
					data : {'id' : id},
					type : 'post',
					dataType : 'json',
					success : function(response) {
						$(link).find('u').html(response.msg);
					}
				});
				return false;
			});
		},
		newsletter : function() {
			$('#receba_ofertas_link').click(function() {
				$('html,body').animate({scrollTop: 0}, 600, function(){
					$('#newsletter_input').focus();
				});
			});
		},
		confirmarComparecimento : function() {
			var textos = {
				utilizado 		: '<u>Marcar como utilizado</u>',
				nao_utilizado	: '<u>Já utilizado</u>'
			};
			$('a.cupom_utilizado,a.cupom_nao_utilizado').click(function() {
				var link = this;
				var id   = $(this).attr('id');
				$.ajax({
					url  	: BASE_URL+'ajax/usuarios/confirmar_utilizacao_cupom/'+id,
					dataType: 'json',
					type	: 'post',					
					success : function(response) {
						if (response.valor == 0) {
							$(link).html(textos.utilizado);
						}else if(response.valor == 1) {
							$(link).html(textos.nao_utilizado);
						}else if(response.valor == -1) {
							window.location.href = BASE_URL;
						}
					}
				});
			});
		}
	};
	
	var estado = {
		getCidades : function() {
			$('#UsuarioEstado,select.selectEstado').change(function() {
				var id     = this.value;
				var select = this;
				$.ajax({
					url 		: BASE_URL+'ajax/estados/get_cidades',
					data		: {id : id},
					dataType 	: 'json',
					success 	: function(response) {
						var comboCidade = '#UsuarioCidadeId';
						if ($(select).hasClass('selectEstado')) {
							comboCidade = $(select).closest('form').find('select.selectCidade');
						}						
						combobox._ajaxFill({
							response : response,
							combo    : comboCidade
						});
					}
				});
			});
		}
	};
	
	var cidade = {
		abrirLista : function() {
			$('#abrirCidades').click(function() {				
				$('#global_cidades_topo ul').slideToggle(300);
			});
		}
	};
	
	var form = {
		compraAmigo : function() {
			$('#comprar_para_amigo').click(function() {
				if ($(this).is(':checked')) {
					$('#compra_amigo_hidden').val(1);					
					$('#formQuantidade').submit();
				}
			});
		},			
		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();
				}
			});
		},
        toggleFormIndicacao : function() {
            $('.form_indicar').hide();
            $('a.link_email').click(function() {
               $(this).parent().parent().next().toggle(500);
            });
        },
        autoSelectText : function() {
            $('input.input_link_unico').click(function() {
               $(this).select();
            });
        }
	};

	var modal = {
		_close : function() {
			$('#cadastro_modal').fadeOut(300, function() {
				$('#bg_overlay').fadeOut(300);
			});
		},
		overlay : function() {
			$(window).keydown(function(e) {
				//ESC
				if (e.keyCode == 27) {
					modal._close();
				}
			});
		},
		link	: function() {
			$('a.fecha_modal').click(function() {
				modal._close();
			});
		}
	};
	
	var facebook = {
		internetExplorer : function() {
			if ($.browser.msie) {
				cookie.add('ie', true);
				$('a.login_facebook').each(function() {
					$(this).attr('target', '_self');
				});
			}
		},
		popupLogin : function() {
			$('a.login_facebook').click(function() {
				if (!$.browser.msie) {
					var popup = window.open(this.href, "Facebook", "status=1,toolbar=0,location=0,width=800,height=600");
					var timer = setInterval(function() {
						if (popup.document.getElementById('logado') != null) {
							$userStatus = popup.document.getElementById('user_status').getAttribute('value');
							popup.close();
							if ($userStatus != 'completo')
								window.location.href = BASE_URL+'usuarios/minha_conta';
							else
								window.location.href = BASE_URL;
							clearInterval(timer);
						}
					}, 100);
					return false;
				}
			});
		}
	};

	$(function() {
		var objects = [countDown, cidade, estado, ofertas, form, scrolling, flash, cols, modal, facebook];
		for(var i in objects) {
			var objeto = objects[i];
			for(var j in objeto) {
				if (typeof(objeto[j]) == 'function' && j[0] != '_') {
					objeto[j]();	
				}
			}		
		}		
		$('#UsuarioCpf').mask("999.999.999-99");
		$('#coin-slider').coinslider();
	});
	
	

	
		
	
})(jQuery);

