/*
 * Functions to be used in display_rating_form.py and perhaps other scripts
 * that enable users to vote for movies.
 * They heavily rely on jQuery library.
 */

/* Current ratings array (updated on each ajax vote) */
$.rating_namespace = {
  ratings : Array()
} 
    
function validateShortReviewForm() {

    var short_review = $("#id_short_review").val(); 
    
    if (short_review=='') 
    {
        display_error(gettext('You forgot to write a review!'), $("#error-message-placeholder-shortreview")); 
        return false;
    }
    else if (short_review!='' && short_review.length<10) 
    {
        display_error(gettext('Review is too short (at least 10 characters)!'), $("#error-message-placeholder-shortreview"));  
        return false;
    }
    else if (short_review!='' && short_review.length>500) 
    {
        display_error(gettext('Review is too long (max 500 chars). You entered')+short_review.length+")!", $("#error-message-placeholder-shortreview"));  
        return false;
    } 
    else 
    {
        return true;
    }

}

function ajaxize_rate_form(form) {
    var rating = get_rating(form);
    $("div.rating_stars",form).replaceWith(stars(form, rating));
    var on_succ = function(data) {
      	processJson(form,data);
    }
    var ajax_url = form.attr('action')+'json';
    form.ajaxForm({ 
        // dataType identifies the expected content type of the server response 
        dataType:  'json', 
        
        url: ajax_url,
        
        // validation before sending the form
        beforeSubmit:function(data,form) {
          return validateRatingForm(form); 
        },          
        
        // success identifies the function to invoke when the server response 
        // has been received 
        success: on_succ
    });
} 

function get_rating(form) {
	return $($('[name$=rating]',form)[0]).val();
}

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    
    // hide the rating element
    $("form.rating-form input").hide();    

    // bind form using ajaxForm 
    $('form.rating-form').each(function(i,form) {
      ajaxize_rate_form($(form));
    });

});


/* TODO: handle errors on server side */
/* TODO: sukces w przypadku advanced-rating nawet bez oceny... */
/* TODO: use jquery validator: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ */

function processJson(form,data) { 
    // 'data' is the json object returned from the server
    // expected vars:
    // success: True / False
    // reason: reason for failure (in case success==False
    if (data.success==true) {
        display_info("<img src=\"/static/img/success.png\" title=\"gettext('Success')\" alt=\"gettext('Success')\" />", $(".info-message-placeholder",form));
    }
    else {
        if (data.reason=="LOGIN")
        {
            // TODO: redirect as in FLM-77
            display_error(gettext('Please log in to vote'), $(".error-message-placeholder",form));
            // konto -> localize!
            window.location = "/login?next=" + document.location.pathname + "&reason=vote";
            exit();                
        } 
        else
        {      
            display_error(gettext('Epic fail... Reason being: ')+data.reason, $(".error-message-placeholder",form));
        }
    }
}


function validateRatingForm(form) {
    var rating = get_rating(form);
    var int_rating = parseInt(rating);           
   
    if (isNaN(int_rating)) 
    {
        display_error(gettext('You have not rated the movie.'), $(".error-message-placeholder"));  
        return false;
    }    
    else if (int_rating<1 || int_rating>10) 
    {
        display_error(gettext('You have not rated the movie.'), $(".error-message-placeholder"));  
        return false;
    }
    else 
    {
        return true;
    }
}

/* shows cancel button for rating */
function show_cancel_button(form)
{   
    // TODO: błąd 'nie oceniles filmu' jak nie ma oceny
    // powinnismy sprawdzac czy glosowalismy na dany obiekt 
    // i tylko wtedy umożliwiać cofnięcie głosu    
    id = $(form).attr('id')    
    var old_rating = parseInt($.rating_namespace.ratings[id]);
    if (old_rating>0) {
        $(".cancel-rating",form).show();
    }  
}

/* shows cancel button for rating */
function hide_all_cancel_buttons()
{   
    $(".cancel-rating").hide();
}


/* Updates the rating visually only, on mouse over the ratings */
function update_stars_user(div, number)
{
    form = $(div).parents('form').get(0);
    hide_all_cancel_buttons();
    show_cancel_button(form);
    update_stars(form, number);
}
    
/* Updates the rating visually only */
function update_stars(form, number)
{       
    var cur_rating = parseInt(number) + 1;
    var rating_type = $('[name$=form_type]',form).val()

    stars = $('.stars div,.main-stars div',form);
    
    var type = 'other';
    if ( parseInt(rating_type) == 1) {
        type = 'main';  
    }
    
    for(i=0; i<10; i++) {
	var s=$(stars[i])
	if(i<cur_rating) {
	        s.removeClass("star-inactive-"+type);
	        s.removeClass("star-inactive-"+type+"-"+(i+1));
	        s.addClass("star-active-"+type);
	        s.addClass("star-active-"+type+"-"+(i+1));
	} else {
	        s.removeClass("star-active-"+type);
	        s.removeClass("star-active-"+type+"-"+(i+1));
	        s.addClass("star-inactive-"+type);
	        s.addClass("star-inactive-"+type+"-"+(i+1));
	}
    }
    // update the form
    $($("[name$=rating]",form)[0]).val(cur_rating);
}

/* Revert to current rating (executed on mouse out of the rating div) */
function revert_stars(div)
{    
    form = $(div).parents('form').get(0);
    id = $(form).attr('id')    
    var old_rating = parseInt($.rating_namespace.ratings[id]);
    update_stars(form, old_rating);      
}

/* Confirm the rating, executed on click on particular star. Sends the ajax form. */
function update_stars_perm(div, number)
{    
    form = $(div).parents('form').get(0);

    // update visually
    update_stars(form, parseInt(number));
    
    // update the js variable  
    id = $(form).attr('id')
    $.rating_namespace.ratings[id] = number;
   
    // submit rating form    
    $(form).submit();    
    
    // show cancel button
    show_cancel_button(form);
}

function cancel_rating_perm(div)
{   
    form = $(div).parents('form').get(0);
    var rating_type = $('[name$=form_type]',form).val()
    // update the rating form to set cancel to 1  
    $("[name$=cancel_rating]",form).val('1');
        
    // submit rating form    
    $(form).submit();    
    
    // update temp rating array
    id = $(form).attr('id')    
    $.rating_namespace.ratings[id] = -1;
    
    // visually show null rating
    update_stars(form, -1);
}

function stars(form, how_many_stars) {

//    var prev_rating = $("#id_"+rating_type+"-rating").val()-1;
    var rating_type = $('[name$=form_type]',form).val()
    id = $(form).attr('id')    
    $.rating_namespace.ratings[id] = how_many_stars-1;
    
    var type = 'other';
    var cls = 'stars';
    if ( parseInt(rating_type) == 1) {
        type = 'main';
	cls = 'main-stars';
    }
    output = '<div class="'+cls+'">';
    for(i=0; i<how_many_stars; i++) {
        line = '<div class="star-active-'+type+' star-active-'+type+'-' + (i+1) + '" id="id-star-' + rating_type + '-' + i + 
            '" onmouseover="javascript:update_stars_user(this,'+i+')"' +
            '" onclick="javascript:update_stars_perm(this,'+i+')"' +
            '" onmouseout="javascript:revert_stars(this)"' +            
            ' />';
        output += line; 
    }
    for(j=i; j<10; j++) {
        line = '<div class="star-inactive-'+type+' star-inactive-'+type+'-' + (j+1) + '" id="id-star-' + rating_type + '-' + j +
             '" onmouseover="javascript:update_stars_user(this,'+j+')"' +
             '" onclick="javascript:update_stars_perm(this,'+j+')"' +
             '" onmouseout="javascript:revert_stars(this)"' +  
             ' />';
        output += line; 
    }
    
    /* cancel rating */    
    output += '<div style="display:none;" class="cancel-rating" id="cancel-rating-'+rating_type;
    output += '" onclick="javascript:cancel_rating_perm(this)"';
    output += '"><img src="/static/img/undovote.png" title="'+gettext('Cancel rating')+'" alt="'+gettext('Cancel rating')+'" /></div>';
    
    output += '</div>';
    
    return output;
}
