jQuery(function($) {
    var emailRE=new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?","i");

    // function get_review_id() { return $(this).parent().attr('id').split("-")[2] }
    function get_review_id() { return $(this).closest('table').attr('id').split("-")[2] }

    $("a.ratingtip").hover(
        function(){ 
            $(this).siblings('#detailRating').fadeIn('fast');
        }, 
        function(){ 
            $(this).siblings('#detailRating').fadeOut('fast');
        } 
    );

    $("#reviews span.heart_button").click(function(){        
        var current = $(this);

        if (! tof.isLoggedIn) { showRegLogin( current.parent(), 'heart this review.'); return false; } 
        if (tof.is_recipe_owner) { showAjaxError( current.parent(), "Sorry, You can't heart your own" ); return false; }

        var id = get_review_id.apply(this);
        var action_url_prefix = '/review/' + id;
        ajaxHeart.apply( current, [action_url_prefix] );
    });


    $("#profile-toolbox span.heart_button").click(function(){
        var current = $(this);

        if ( ! tof.isLoggedIn ) { showRegLogin( current.parent(), 'heart this place.'); return false }

        var id = current.find('a').attr("rel").split(" ")[0];        
        var action_url_prefix = '/profile/' + id;
        ajaxHeart.apply( current, [action_url_prefix] );
    });
 

    $("a.abuse_review").click(function(){
        if ( ! tof.isLoggedIn ) { showRegLogin( $(this).parent(), 'flag this review.'); return false }

        var current = $(this);
        var reviewid = get_review_id.apply(this);
        var abuse_form = '<div class="popup flag-menu"><h2>Please flag with care:</h2>';
        abuse_form += '<form action="/review/'+ reviewid +'/abuse" method="post">';
        abuse_form += '<input name="flag-reason" value="1" type="radio">Offensive, Abusive, or Hate Speech<br>';
        abuse_form += '<input name="flag-reason" value="2" type="radio">Spam<br>';
        abuse_form += '<input name="flag-reason" value="3" type="radio">Requires Moderator attention<br>';
        abuse_form += '<div class="flag-comment">Why are you flagging this review?<br>';
        abuse_form += '<textarea id="flag-comment-'+ reviewid +'" name="flag-comment" cols="33" rows="4"></textarea>';
        abuse_form += '<div id="commentlimitinfo-'+ reviewid +'" class="cool">150 characters left.</div></div>';
        abuse_form += '<input class="flag-cancel Button" value="Cancel" type="button">';
        abuse_form += '<input class="flag-submit Button" value="Flag review" type="submit">';
        abuse_form += '</form></div>';

        var popup = $(this).parent().append( abuse_form ).find('div.popup');
        var form = popup.fadeIn('fast').find("form");
        form.submit(function(){ submitReviewAbuse.apply(current,[form]); return false; });
        form.find('.flag-cancel').click(function(){ 
            popup.fadeOut('fast',function(){$(this).remove()}); 
        });
        form.find('textarea[name=flag-comment]').keyup(function(){
            limitChars('flag-comment-'+reviewid, 150, 'commentlimitinfo-'+reviewid);
        });
        form.find("input[name='flag-reason']").click(function(){ 
            $(this).val() == 3 ? form.find('.flag-comment').show()
                               : form.find('.flag-comment').hide();
        });
        return false;
    });
    function submitReviewAbuse(form) {
        var current = $(this);
        var comment = form.find('textarea[name=flag-comment]').val();
        if ( (form.find("input[name='flag-reason']").val() == 3) && (comment.length == 0 || comment.length > 150 ) ) { 
            alert('Maximum length has been reached'); return false;
        }
        $.ajax({ url: form.attr('action'),
                 type: 'POST',
                 data: form.serialize(),
                 dataType: 'json',
                 success: function(data) {
                    if( data.success ){
                        form.closest('div.popup').fadeOut('fast',function(){$(this).remove()});
                        showAjaxSuccess( current.parent(), 'Thanks! We will look into it ASAP' );
                    } else {
                        alert_failed();
                    }
                 },
                 error: function(){ alert_failed() }
        });
    }

    $("#p-info-left td.more-locations").hover(
        function(){ 
            $(this).children('.popup-more-locations').fadeIn('fast');
        }, 
        function(){ 
            $(this).children('.popup-more-locations').fadeOut('fast');
        } 
    );

    $('#report_biz_error').keyup(function(){
        limitChars('report_biz_error', 200, 'charlimitinfo');
    });
    var reportBiz = $("#p-info-left td.report a");
    $(reportBiz).click(function(){
        var current = this;
        var form = $(current).next('div.popup').fadeIn('fast').find("form");
        $(form).submit(function(){submitProfileReport(this);return false;});
        $(form).find('.report-cancel').click(function(){$(current).next('div.popup').fadeOut('fast');return false });
        return false;
    });
    function submitProfileReport(form) {
        var content = $(form).find('textarea[name=content]').val();
        if ( content.length > 0 && content.length < 500 ) {
            if ( ! tof.isLoggedIn ) {
                var email = $(form).find('input[name=email]').val();
                if ( ! email.match(emailRE) ) {
                    alert('A valid email address is required'); return false;
                }
            }
        } else {
            alert('Maximum length has been reached'); return false;
        }

        $.ajax({ url: $(form).attr('action'),
                 type: 'POST',
                 data: $(form).serialize(),
                 dataType: 'json',
                 success: function(data) {
                    if( data.success ){
                        reportBiz.next('div.popup').hide();
                        showAjaxSuccess(reportBiz.parent(), 'Thanks! We will look into it ASAP' );
                    } else {
                        alert_failed();
                    }
                 },
                 error: function(){ alert_failed() }
        });
    }


    $("a.delete_review").click(function(){
        var current = this;
        var reviewid = get_review_id.apply(this);
        var response = confirm_delete('review');
        if ( response ) {
            $.ajax({ url: '/review/' + reviewid + '/delete',
                     type: 'POST',
                     data: {},
                     dataType: 'json',
                     success: function() {
                         $("#review-"+reviewid).fadeOut("slow");
                     },
                     error: function(){ alert_failed() }
            });
        }
        return false;
    });
}); 



