$(document).ready(function() {   

   /**
    *   User reviews - requires jQuery 1.6.x or > 
    * 
    */ /******************************************************************/
    
    $('#reset_rating').live('click',function(){
        $(this).parent().siblings('.star_wrap_u').find('.interactive_star_rate span').animate({width:0});
        $(this).parent().html('');
        get_user_rating();
        $('input#userrate').val('');
    });
    
    get_user_rating();
    
    $('textarea[name="user_text"]').each(function() {
        var input = $('#' + this.id);
        var count = $('#' + this.id + '_count');
        count.show();
        word_count(input, count);
        $(this).keyup(function() {
            word_count(input, count);
            var word_array = this.value.split(/[\s\.\?]+/);
            var maxwords = 200;
            var total_words = word_array.length;
            if(total_words>maxwords){
                var new_string = '';
                for(var i = 0; i < maxwords; i++) { new_string += word_array[i] + " "; }
                this.value = new_string;
                count.removeClass('blue').addClass('red');
            }else if(count.hasClass('red')){
                count.removeClass('red').addClass('blue');    
            }
        });
    });
    
    $('#submit_userreview').click(function(ev){
        ev.preventDefault();
         var ud = {};
         $.each($('#user_response').serializeArray(), function(i, field) {
            ud[field.name] = field.value;
         });
         
         $('input#userrate').val('');
         $list_user_reviews = $('#list_user_reviews');
         $this_button = $(this);
         $this_button.prop("disabled", "disabled");
         $('<img class="whirligig" src="/wp-content/themes/'+$theme_folder+'/images/gl_left_loader.gif" alt="" />').insertAfter($this_button);
         
         __user_review_validate(ud.user_name,ud.user_email,ud.userrate,ud.user_text);
         if(skip_process==1)return false;
         
         $.get($pcs_domain+'wp-content/plugins/nmp-user-reviews/nmp_user_reviews_ajax.php', { id:ud.poid, na:ud.user_name, em:ud.user_email, vo:ud.nl_chk, ra:ud.userrate, re:ud.user_text }, function(data) {
             scrollWin($('#tab_user'));
             var dat_split = data.split("~");
             if(dat_split[0]==1&&dat_split[1]==1){
                 $list_user_reviews.append('<div class="submit_success hide bgreen breathp breathn"><span class="tick"></span><span class="strong">Thank you.</span> Your review has been submitted and will be available soon.</div>');
                 $list_user_reviews.find('.submit_success').fadeIn('slow').delay(3000).fadeOut('slow');
             }else if(dat_split[0]==0&&dat_split[1]==1){
                 $list_user_reviews.append('<div class="submit_fail hide bgreen breathp breathn"><span class="cross"></span><span class="strong">We\'re sorry.</span> There was an error processing your review at this time. Please accept our sincere apologies and know that we are working to fix this issue ASAP. (ref:1)</div>');
             }else if(dat_split[0]==1&&dat_split[1]==0){
                 $list_user_reviews.append('<div class="submit_fail hide bgreen breathp breathn"><span class="cross"></span><span class="strong">We\'re sorry.</span> There was an error processing your review at this time. Please accept our sincere apologies and know that we are working to fix this issue ASAP. (ref:2)</div>');
             }else if(dat_split[0]==0&&dat_split[1]==0){
                 $list_user_reviews.append('<div class="submit_fail hide bgreen breathp breathn"><span class="cross"></span><span class="strong">We\'re sorry.</span> There was an error processing your review at this time. Please accept our sincere apologies and know that we are working to fix this issue ASAP. (ref:3)</div>');
             }
             $list_user_reviews.find('.submit_fail').fadeIn('slow').delay(3000).fadeOut('slow');
             $this_button.parent().find("img").remove();
         });
    });
    
    /***/ /***************************************************************/
    
});    
    
function word_count(field, count) {
    var number = 0;
    var matches = field.val().match(/\b/g);
    if(matches) {
        number = matches.length/2;
    }
    count.text(number);
}
function get_user_rating(){
    $('.interactive_star_rate').mousemove(function(e) {
        $this_star = $(this);
        var parentOffset = $this_star.parent().offset();
        var width_of_parent = 87;
        var rel_x = e.pageX - parentOffset.left;
        var r_width = Math.ceil((rel_x/width_of_parent)*100)+1;
        $this_star.children("span").css({
           width:r_width+'%',
           display:'block' 
        }).html('&nbsp;');
        var outof10 = r_width/10;
        var outof5 = outof10/2;
        var message = '<span class="orange">'+outof5.toFixed(1)+'</span> out of <span class="orange">5</span>';
        $('#rating_mess').html(message);
        set_user_rating(outof10);
    });
    $('.interactive_star_rate').live("mouseleave",function(e) {
        if(!$('#reset_rating').length){
            $this_star.children("span").css({
               width:0+'%',
               display:'block' 
            }).html('');
            $('input#userrate').val('');
            var message = '<span>click to rate</span>';
            $('#rating_mess').html(message);
        }
    });
}
function set_user_rating(width){
    $('input#userrate').val(width);
    $('.interactive_star_rate').click(function(){
        var outof5 = width/2;
        var message = 'you\'ve given a <span class="orange">'+outof5.toFixed(1)+'</span> star rating &nbsp;<span class="close" id="reset_rating"></span>';
        $('#rating_mess').html(message);
        $(this).unbind('mousemove');
    });
}
function __user_review_validate(u,e,ra,re){
    
    var to_display = "";
    
    if(ra==0||ra=="0"||typeof ra == "undefined"){
        ra = "~ we can't save your review without a rating";
    }else if(isNaN(ra)){
        ra = "~ the rating provided is invalid.";
    }
    
    u  = (u =="")? "~ please provide your name for accreditation" : u;
    re = (re=="")? "~ your review was missing" : re;
    if((typeof e == "undefined")||e==null||e==""){
        e = "~ we need your email to validate your review";
    }else{
        $.ajax($pcs_domain+'wp-content/plugins/nmp-user-reviews/nmp_user_reviews_ajax.php?ea='+e,{
            async:false,
            success:function(vali) {
                e = (vali==1) ? e : "~ your email is invalid. Please check and try again"
            }
        })
    }
    var begin_display  = "We found some errors:\n\n";
        
        u_chk  =  u.substring(0,1);if(u_chk =='~')to_display += u+"\n"
        e_chk  =  e.substring(0,1);if(e_chk =='~')to_display += e+"\n"
        ra_chk = ra.substring(0,1);if(ra_chk=='~')to_display += ra+"\n"
        re_chk = re.substring(0,1);if(re_chk=='~')to_display += re+"\n"
        
    var end_display = "\nPlease correct the above to continue";
    
    if(to_display!=""){
        $('form#user_response').find("button").prop("disabled", "");
        $('form#user_response').find("img").remove();
        alert(begin_display+to_display+end_display);
        skip_process = "1";
    }else{
        skip_process = "0";
    }
}
