$(function(){
	$("a[rel*=external]").attr("target", "_blank");
	
    if (typeof DD_belatedPNG != "undefined") {
        DD_belatedPNG.fix('.png-bg');
    }
    
    if ($('#box-newsletter').length) {                
        function sendNewsletterCreate() {
            $.post(rootUrl+'newsletterUsers/create',{name:$('#newsletter_name').val(),email:$('#newsletter_email').val()},function(response){
                alert(response);
            })
            return false;
        }
        $('#newsletter_form').RSV({errorTextIntro:"Erros foram encontrados, verifique-os e tente novamente",onCompleteHandler:sendNewsletterCreate,rules:["required,newsletter[name],Informe o seu nome","required,newsletter[email],Informe o seu email","valid_email,newsletter[email],Informe um email v\u00E1lido"]})
    }
    
    if($('#archive-list').length) {			
        $('#archive-list li:has(ul) a[rel="year-archive"]').click(function(){
	        $child = $(this).parent().find('ul');           
	        
	        if ($child.hasClass('expanded')) {
	            $child.slideUp('slow',function(){
		            $(this).removeClass('expanded');
		            $(this).addClass('collapsed');
	            });
	        } else {
	            if ($('#archive-list li ul.expanded').length) {
	                $('#archive-list li ul.expanded').slideUp('slow',function(){
		                $(this).removeClass('expanded');
		                $(this).addClass('collapsed');
		    
		                $child.slideDown('slow',function(){
			                $(this).removeClass('collapsed');
			                $(this).addClass('expanded');
		                });
	                });
	            } else {
	                $child.slideDown('slow',function(){
	                    $(this).removeClass('collapsed');
	                    $(this).addClass('expanded');
	                });
	            }
	        }
            return false;
        });
    }
    
    /* Imprensa */
    
    if ($('#news-list a').length) {
        $('#news-list a').click(function(){
            
            $('#news-content').html('Carregando...');
            
            var id = elmId($(this).attr('href'));
            
            $('#news-content').load(rootUrl+'home/pressNews',{id:id});
            
            return false;
        });
    }
    
    /* end Imprensa */
    
    /* Gastronomy */
    if ($('#restaurant_search').length) {
        $('#estado').change(function(){
            $('#cidade')[0].options[0].text = 'Carregando...';
            $.getJSON(rootUrl+'gastronomies/cities',{state_id:$(this).val()},function(response){                
                $('#cidade')[0].options.length = 1;
                $('#cidade')[0].options[0].text = 'Qualquer cidade';
                for (i = 0; i < response.length; i++) {
                    $('#cidade')[0].options[(i+1)] = new Option(response[i].name,response[i].id);    
                } 
            });
        });
        
        $('#restaurant_search').submit(function(){
            var action = $(this).attr('action')+'/';
            $(this).find('select').each(function(id,elm){
                if($(elm).find('option:selected').val() != "") {
                    action += $(elm).attr('id') + '/' + $(elm).find('option:selected').val()+'-'+$(elm).find('option:selected').text()+'/';
                }
            });
            window.location.href = action;                        
            return false;
        });
    }       
    /* end Gastronomy */
    
    /* Receipts */    
    if ($('input.rating').length) {        
        $('input.rating').rating({
            required:true,            
            focus: function(value, link){
                var tip = $('#rating-subtitle'); 
                tip[0].data = tip[0].data || tip.html();                
                tip.html(link.title || 'value: '+value); 
            }, 
            blur: function(value, link){ 
                var tip = $('#rating-subtitle'); 
                $('#rating-subtitle').html(tip[0].data || ''); 
            },
            callback: function(value,link) {
                var tip = $('#rating-subtitle'); 
                tip[0].data = link.title;                
                tip.html(link.title);                
            }            
        });
        $('#rating-submit').click(function(){
            $.post(rootUrl+'receipts/rate',{rating:$('input[name="rating"]').val(),receiptId:$('#receipt_id').val()},function(response){
               tracker('/sites/receitas/'+$('#receipt_slug').val()+'/voto');
               $('#rating-form').html(response);
            });
        })
    }
    
    if ($('input.readonly-rating').length) {
        $('input.readonly-rating').rating({readOnly:true});
    }
    
    $('a.mais-vista').click(function(){
        $(this).siblings('ul').toggle();
		return false;
    });
    
    $('a.mais-votada').click(function(){
        $(this).siblings('ul').toggle();
		return false;
    });
    
    $('a.mais-recente').click(function(){
        $(this).siblings('ul').toggle();
		return false;
    });
    
    if ($('#pesquisa_receita').length) {
        $('#pesquisa_receita').submit(function(){
            var action = $(this).attr('action');
            if ($('#produto').val() != "") {
                action += "produto/"+$('#produto').val()+"/";
            }
            if ($('input[name="autor[]"]:checked').length) {
                action += "autor/";
                var select = new Array();
                $('input[name="autor[]"]:checked').each(function(id,elm){
                    select[id] = $(elm).val(); 
                });
                action += select.join(',')+"/";
            }
            if ($('input[name="categoria[]"]:checked').length) {
                action += "categoria/";
                var select = new Array();
                $('input[name="categoria[]"]:checked').each(function(id,elm){
                    select[id] = $(elm).val(); 
                });
                action += select.join(',')+"/";
            }
            if ($('#busca').val()) {
                action += "palavras/"+$('#busca').val()+"/";
            }
            window.location.href = action;
            return false;
        });
    }
    
    if ($('#receipt-rules').length) {        
        $('#receipt-rules').click(function(){
            $('select').hide();            
            if ($('#layer').length) {
                $('#bg-layer').fadeIn('slow',function(){
                   $('#layer').show();
                   $('#bg-layer').unbind('click').click(function(){
                       $('#bg-layer').hide();
                       $('#layer').hide(); 
                       $('select').show();                       
                   });
                   
                   $('#layer').unbind('click').click(function(){
                       $('#bg-layer').hide();
                       $('#layer').hide();
                       $('select').show(); 
                   });
                });
            }
        });
    }
    
    if ($('#lebon_ingredients').length) {
        $('#lebon_ingredients').click(function(){
            if (!$('.textarea input[type="checkbox"]:checked').length) {
                alert('Selecione pelo menos um produto para adicionar!');
                return false;
            }
            var selected = new Array();
            $('.textarea input[type="checkbox"]:checked').each(function(id,elm){
                selected[id] = $(elm).val();
            });
            $.post(rootUrl+'receipts/ingredients',{products:[selected]},function(response){
                $('#lebon-ingredient-list').append(response);
                $('.textarea input[type="checkbox"]:checked').removeAttr('checked');        
            });
            return false;
        });
        
        $('a[rel="ingredient-remove"]').live('click',function(){
            if (confirm('Tem certeza?')) {
                $(this).parents('li.ingredientes').remove();
                return false;
            }
        });               
    }    
	
	$('a[rel="add-ingredient"]').click(function(){
        $.get(rootUrl+'receipts/otherIngredients',function(response){
            $('#other-ingredients-list').append(response);
        });
        return false;           
    });
	
    if ($('#receipt_form').length) {
        setFormValidation();
        if(!$('#user_name').length) {
	        $('#receipt_form').submit(userCheck);         
	        $('#receipt_form a.user-check').click(userCheck);
        }
    }
    
    if ($('#prepare-receipt-form').length) {
        $('#prepare-receipt-form').submit(function(){
            
            if (!$('#receipt_prepare_mode').val()) {
                alert('Informe o modo de preparo da receita.');
                return false;
            }
            
            if (!$('#receipt_prepare_time').val()) {
                alert('Informe o tempo de preparo da receita.');
                return false;
            }
            
            if (!$('#receipt_servings').val()) {
                alert('Informe o rendimento da receita.');
                return false;
            }
        
            return true;
        });
    }
    
    if ($('#receipt-summary-form').length) {
        $('#receipt-summary-form').submit(function(){
        
            if (!$('#receipt_name').val()) {
                alert('Informe o nome da receita.');
                return false;
            }
            
            if (!$('#receipt_receipt_category_id').val()) {
                alert('Informe a categoria da receita.');
                return false;
            }
            
            if (!$('#user_agreement:checked').length) {
                alert('Você deve concordar com os termos do regulamento.');
                return false;
            }
        
            return true;
        });
    }
    
    function userCheck() {
        if (!$('#user_cpf').val()) {
            alert('Informe o seu CPF');
        } else {        
            if (validateCpf($('#user_cpf').val()) == false) {
                alert('O CPF informado é inválido.');
            } else {        
	            $.post(rootUrl+'receipts/userCheck',{cpf:$('#user_cpf').val()},function(response){
	                $('#receipt_form ul.recipe-form:last').html(response);
	                $('#receipt_form').unbind('submit');
	                setFormValidation();
	            });
            }
        }
        return false;
    }
    
    function setFormValidation() {
        $('#user_cpf').setMask('cpf');        
        $('#user_ddd').setMask('99');
        $('#user_phone').setMask('9999-9999');
        $('#user_state').setMask('aa');
        $('#user_zipcode').setMask('cep');
        if ($('#user_name').length) {
            $('#receipt_form').RSV({errorTextIntro:'O seguintes erros impediram o envio do formulário:',errorJSItemBullet:'- ',rules:[
	            "required,user[name],O nome é obrigatório",
	            "required,user[email],O e-mail é obrigatório",	            
	            "valid_email,user[email],O e-mail informado é inválido"                       
	        ]});
        }               
    }
	
	if ($('#recipe-ingredients-form').length) {
		$('#ingredients_submit').click(function(){
			if ($('#lebon-ingredient-list ul li').length <= 0) {
				alert('Sua receita precisa ter pelo menos um ingrediente LeBon');
				return false;
			}			
		});
	}	
	
    /* end Receipts */
    
    
    /* Contact */
    
    if ($('#contact_form').length) {
        $('#contact_form').RSV({errorTextIntro:'O seguintes erros impediram o envio de seu contato:',errorJSItemBullet:'- ',rules:[
            "required,contact[name],O nome \u00E9 obrigat\u00F3rio",
            "required,contact[email],O e-mail \u00E9 obrigat\u00F3rio",
            "required,contact[message],A mensagem \u00E9 obrigat\u00F3ria",           
            "valid_email,contact[email],O e-mail informado \u00E9 inv\u00E1lido",
            "digits_only,contact[phone],O telefone informado \u00E9 inv\u00E1lido. Utilize somente n�meros"                       
        ]});
    }
    
    /* end Contact */
});

function elmId(id) {
    var link_id = id;
    var regular_expression = /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/; // elm_ID
    var elm_id = link_id.match(regular_expression); 
    return elm_id[1];
}

function ResizeSwf(height) {
    var dm = $('#menu-rapido-swf');    
    if (dm.length)
    {
        dm.css({height:(parseInt(height))+"px"});
    }
}

function validateCpf(value) {

    value = sanitizeCpf(value);      

    if (value.length < 11) {
        return false;
    } else {
        for (i = 0; i <= 9; i++) {            
            if (repeat(i,11) == value) {
                return false;
            }
        }
        
        verificatorDigit = value.substr(9,2);
        digits = value.split('');
        
        position = 10;
        sum = 0;
        
        for(i = 0; i <= 8; i++, position--) {
            sum += (digits[i] * position);            
        }
        
        digits[9] = sum % 11;
        digits[9] = (digits[9] < 2) ? 0 : 11 - digits[9];               
        
        position = 11;
        sum = 0;
        
        for(i = 0; i <= 9; i++, position--) {
            sum += (digits[i] * position);            
        }
        
        digits[10] = sum % 11;
        digits[10] = (digits[10] < 2) ? 0 : 11 - digits[10];         
               
        calculatedVerificatorDigit = digits[9] * 10 + parseInt(digits[10]);               
        if (calculatedVerificatorDigit != verificatorDigit) {
            return false;
        }
        return true;
    }
}

function sanitizeCpf(value) {
    while(value.match(/\D+/) != null) {
        value = value.replace(/\D+/,'');
    }
    return value;
}

function repeat(string,num)
{
    return new Array( num + 1 ).join( string );
}