////////////////////////////////////////////////////////////////////////////////
// Globals
//
var ratingforms = [];
var commentforms = [];
var hidden_inputs = [];


/* Debugging functions, for IE */
if (console === undefined) {
    var console = {
            log: function(e) {},
            error: function(e) { alert(e); },
            warn: function(w) {}
    };

    function dir(x, indent) {
      var indent_str = '';
      if (indent !== undefined) {
        for(var i=0; i < indent; i++) {
          indent_str += "\t";
        } 
      }
      var out = [];
      for(var i in x) {
        if (typeof(x[i]) === 'function')
          continue;
        if (typeof(x[i]) !== 'object') {
          out.push( i + " : '" + x[i] + "' (" + typeof(x[i]) + ")" );
        } else {
          out.push( i + " : " + typeof(x[i]));
        }
      }
      return  indent_str + out.sort().join("\r\n" + indent_str);
    }

    function dbg(n, x) {
      if (n !== undefined && x === undefined) {
        x = n;
        n = "DBG";
      }
      alert(
          n + ":\r\n" 
          + (typeof(x) === 'object'
              ? dir(x)
              : x + " (" + typeof(x) + ")")
      );
    }

}


////////////////////////////////////////////////////////////////////////////////
// onload functions
//
$(function() {

    /* Add onclick handler to all anchor tags classed as 'rate_resource' */
    $('ul.resource-user-input li.rate a').each(function(idx,item) {
        $(item).click(function(event) {
            event.preventDefault(); 
            event.stopPropagation(); 
            closeRatings();
            closeComments();
            var link = $(this);
            // Locate rating form, navigating DOM from current link object
            var targetBox = $('div.user-add-rating', link.parents('div.matrix-resource'));
            if (targetBox) {
                var controls = $('ul.resource-user-input', targetBox.parents('div.matrix-resource'));
                controls.addClass('hide');
                hidden_inputs.push(controls);
                ratingforms.push(targetBox);
                targetBox.removeClass('hide');
            }
        });
    });

    /* js enabled initializations */
    $('.user-comments').hide();
    $('li.view-comments').removeClass('hide');
    
    $('.add-comment-nojs').hide();
    $('.add-comment-js').removeClass('hide');
    
    /* Make view comments links work */
    $('li.view-comments a').each(function(idx,item) {
        $(item).click(function(event) {
                event.preventDefault();
                closeRatings();
                closeComments();
                var link = $(this);
                var targetBox = $('div.user-comments', link.parents('div.matrix-resource'));
                targetBox.show();
                //targetBox.removeClass('hide');
                commentforms.push(targetBox);
            });
        });

    /* Make cancel buttons work to close rating forms and comment forms */
    $('p.user-cancel-input a').each(function(idx,item) {
        $(item).click(function(event) {
                event.preventDefault();
                closeRatings();
                closeComments();
            });
        });

    // Add onclick handlers to star rating buttons\
    $('form.add_rating input.rating-button').each(function(idx,item) {
        $(item).click(function(event) {
          event.preventDefault();
          try {
          var frm = $(this.form);
          var contentobject_id = $("input[name='contentobject_id']", frm)[0];
          var rating = this.name.replace(/^rating_/, '');
          var rating_sum = $("input[name='rating_sum']", frm)[0];
          var num_ratings = $("input[name='num_ratings']", frm)[0];
          submitRating('/ratings/rate', this, contentobject_id.value, rating, num_ratings.value, rating_sum.value);
          } catch(e) {
          }
        });
    });

    /* Add onclick handler to all anchor tags classed as 'add_comment' */
    $('ul.resource-user-input li.add-comment a').each(function(idx,item) {
        $(item).click(function(event) {
            // Don't do default action
            event.preventDefault(); 

            // Hide other forms
            closeRatings();
            closeComments();

            // Locate rating form, navigating DOM from current link object
            var link = $(this);
            var targetBox = $('div.user-add-comment', link.parents('div.matrix-resource'));

            if (targetBox) {
                var controls = $('ul.resource-user-input', targetBox.parents('div.matrix-resource'));
                controls.addClass('hide');
                hidden_inputs.push(controls);
                commentforms.push(targetBox);
                // Create Recaptch
                //
                // Locate container div
                var ctr;
                ctr = $('div.security-block', targetBox);

                if (!ctr.length) {
                    targetBox.append('<div class="security-block">&nbsp;</div>');
                }
                try {
                    ctr = $('div.security-block', targetBox)[0];
                } catch(e) {
                    console.error(e); 
                }
                
                // Create it
                console.log("keys = ", recaptcha_keys);

                Recaptcha.create(
                    recaptcha_keys.public, ctr,
                    {
                        theme: 'red',
                        callback: function(a,b,c) {
                            console.log('recaptcha created');
                            //Recaptcha.destroy();
                            }
                    }
                );
                // Show form
                targetBox.removeClass('hide');
            }
        });
    }); // end of add_comment onclick

}); // end of onload function

/* Murray's hover function for rating inputs */
$(function() {
    $(".rating-button")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^\.]+/) + "-hover.gif";
            $(this).attr("src", src);
        })
        .mouseout(function() {
            var src = $(this).attr("src").replace("-hover", "");
            $(this).attr("src", src);
        });
});


////////////////////////////////////////////////////////////////////////////////
// End of onload functions, now general functions
//

function closeComments() {
    for(var i in commentforms) {
        var div = commentforms[i];
        if (div && div.addClass) {
            div.addClass('hide');
        }
    }
    commentforms = [];
}

function closeRatings() {
    for(var i in ratingforms) {
        var div = ratingforms[i];
        if (div && div.addClass) {
            div.addClass('hide');
        }
    }
    for(var i in hidden_inputs) {
        var div = hidden_inputs[i];
        if (div && div.removeClass) {
            div.removeClass('hide');
        }
    }
    ratingforms = [];
}

function draw_rating(rating, num_ratings) {
    var li = document.createElement('li');
    li.title="Average rating of " + rating + ", calculated from " + num_ratings + " votes";
    li.className="resource-rating";

    var div = document.createElement('div');
    div.className = 'calculated-rating';

    for(var i=1; i<=5; i++) {
        var img = document.createElement('img');
        if (i==1) {
            img.alt = rating + " out of 5 stars";
        }
        if (rating > 0.5) {
            img.src="/extension/tki-nzc/design/tki-nzc/images/rating-star-full.gif";
        } else if (rating > 0) {
            img.src="/extension/tki-nzc/design/tki-nzc/images/rating-star-half.gif";
        } else {
            img.src="/extension/tki-nzc/design/tki-nzc/images/rating-star-empty.gif";
        }
        rating -= 1;
        div.appendChild(img);
    }
    var span = document.createElement('span');
    span.appendChild(document.createTextNode('(' + num_ratings + ')'));
    li.appendChild(div);
    li.appendChild(span);
    return li;
}

function submitRating(url, chosen_elt, contentobject_id, rating, rating_count, rating_sum) {
    var form = chosen_elt.form;
    // Find the rating text
    var rating_text = $(chosen_elt).parents('label');
    if (rating_text.length) {
        rating_text = rating_text.text();
    }

    // Post the data with AJAX
    $.post(url + '/' + contentobject_id + '/' + rating,
                {},
                function(data, status) {
                    if (status == 'success') {
                        // Find the anchor which showed the form
                        var res_elt = $(form).parents('div.matrix-resource');
                        var link = $('li.rate a', res_elt);
                        // Replace anchor with static text
                        rating_count = Number(rating_count) + 1;
                        rating_sum = Number(rating_sum) + rating;
                        link.replaceWith("You rated this resource as: '" + rating_text + "'");
                        var rating_elt = $('li.resource-rating', res_elt);
                        rating_elt.replaceWith( draw_rating(rating_sum / rating_count, rating_count) );
                        // Hide ratings box
                        closeRatings();
                    }
                },
                'text'
    );
}

