
//reload the page (document.location.href) with the given parameter map
function reloadPage(params) {
  var href = currHref;
  var first = true;
  for (var key in params) {
    if (first) {
      href += '?';
      first = false;
    } else {
      href += '&'
    }
    href += key + '=' + params[key];
  }
  location.href = href;
//	window.event.returnValue = false;
};

function showLoading() {
  $("#loading").vCenter();
  $("#loading").show();
};

function hideLoading() {
  $("#loading").fadeOut("fast");
};

$().ajaxSend( function(r, s) {
  $("#loading").vCenter();
  $("#loading").show();
});

$().ajaxStop( function(r, s) {
  $("#loading").fadeOut("fast");
});

/*
    retrieve a value from the id attribute of the input element(s) by removing any characters before the first '_'
    (included), place the retrieved value as the map value for the key idParamName inside the passed params, and call
    bind ajaxBoxAction to the element's event of the input type with the obtained parameters
*/
bindAjaxBoxActionWithId = function(elem, type, action, idParamName, params, options)
{
  //alert(params);
  if(typeof params === 'string')
  {
    var tmp = {};
    tmp[params] = '';
    params = tmp;
  }
  else
  {
    params = params || {};
  }
  $(elem).each(function() {
        var idParamValue = $(this).attr("id").split('_').slice(1).join('_');
        var myParams = $.extend({}, params);
        myParams[idParamName]=idParamValue;
      $(this).ajaxBoxAction(type, action, myParams, options);
  });
};

//Codice Fiscale
function checkCF(cf) {
  var validi, i, s, set1, set2, setpari, setdisp;
  if (cf == '')
      return false;
  cf = cf.toUpperCase().replace(/\W/g, '');
  if (cf.length != 16)
      return false;
  validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  for (i = 0; i < 16; i++) {
      if (validi.indexOf(cf.charAt(i)) == -1)
          return false;
  }
  set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
  setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
  s = 0;
  for (i = 1; i <= 13; i += 2)
      s += setpari.indexOf(set2.charAt(set1.indexOf(cf.charAt(i))));
  for (i = 0; i <= 14; i += 2)
      s += setdisp.indexOf(set2.charAt(set1.indexOf(cf.charAt(i))));
  if (s % 26 != cf.charCodeAt(15) - 'A'.charCodeAt(0))
      return false;

  return true;
}

/*
 **********************
 *  DOCUMENT.READY()  *
 **********************
 */
$(document).ready(function() {

    //flag content as inappropriate tag
    $("a.flagInappropriate").bind("click", function() {
        return $.ajaxBoxAction("/actions/registered/inappropriate.action",
            {
            removeFromSent: '',
            contentId : $(this).attr("id").split('_').slice(1).join('_')
            },
            {
                prompt: {text: "Segnalare come inappropriato?", isWarning: true},
                success: function() {
                    $(this).hide();
                    $(this).siblings('span.flagInappropriate').show();
                }
            }, this
        );
    });

    // Related page: rebinding
    $("div.contentBox_ros2 > h4").children("a").click(function() {
      if ($(this).parent().parent().attr("class").indexOf("close") >= 0)
      {
        $(this).parent().parent().children(".contentBoxSH").slideDown(500);
        $(this).parent().parent().removeClass("close");
      }
      else
      {
        $(this).parent().parent().children(".contentBoxSH").slideUp(500);
        $(this).parent().parent().addClass("close");
      }
    });

  // Rebinding showcategories in beta
  $("a#showMoreCatA").bind("click", function(event) {
    var status = $("#rawHide").hasClass("hide");

    if (status)
    {
      $("#rawHide").removeClass("hide");
      $(this).html("Nascondi le categorie");
    }
    else
    {
      $("#rawHide").addClass("hide");
      $(this).html("Mostra tutte categorie");
    }
  });

    //dashboard - create/edit article

    //update FCKeditor with the actual content to prevent
    //empty fields from being sent to the server
    $("#addArticle").mousedown(function(){
      FCKeditorAPI.GetInstance("articleBody").UpdateLinkedField();
    });
  if($('#thumbnailFile').length) {
        new AjaxUpload("#thumbnailFile",
        {
            action: contextPath + "/actions/registered/upload-article-image.action",
            name: "imageFile",
            onSubmit: function(file, ext) {
            //todo: insert client-side extension check here
            jslog.debug("submitted");
          },
              onComplete: function(file, response) {
                  jslog.debug("completed");
                  var xmlResp = $(response).children("xml");
                  var success = xmlResp.children("status").attr("success");
                  if(success == "true")
                  {
                      //var thumbUrl = contextPath + xmlResp.children("thumb").text();
                      var thumbUrl = contextPath + xmlResp.find("thumb").text();
                      var uuid = xmlResp.children("uuid").text();

                      jslog.debug(thumbUrl);
                      jslog.debug(uuid);

                      $("img#articleThumbnailImg").attr("src", thumbUrl);
                      $("#articleImageId").val(uuid);
                      $("span#cambiaImgDef").css("display", "none");
                  }
                  else
                  {
                      var errorMessage = xmlResp.children("status").text();
                      alert("Impossibile caricare il file.\n" + errorMessage);
                  }
              }
        });
  };

    //remove or add the tag names and ids from the list of tags
    //when the user clicks on them
    $('a.tagLink').bind('click', function() {
        var tagName = $(this).text();
        var tagId = $(this).attr('id').split('_').slice(1).join('_');

         var tagsEl = "#tagsSelected";
         var tagIdsEl = "#selectedTagIds";

         var currTags = $.trim($(tagsEl).val());
         var currTagIds = $(tagIdsEl).val();

         if(currTags == "")
         {
             $(tagsEl).val(tagName);
             $(tagIdsEl).val(tagId);
         }
         else if(currTags == tagName)
         {
             $(tagsEl).val("");
             $(tagIdsEl).val("");
         }
         else if(currTags.indexOf(tagName + ", ") > -1)
         {
             $(tagsEl).val(currTags.replace(tagName + ", ", ""));
             $(tagIdsEl).val(currTagIds.replace(tagId + ", ", ""));
         }
         else if(currTags.indexOf(", " + tagName) > -1)
         {
             $(tagsEl).val(currTags.replace(", " + tagName, ""));
             $(tagIdsEl).val(currTagIds.replace(", " + tagId, ""));
         }
         else
         {
             $(tagsEl).val(currTags + ", " + tagName);
             $(tagIdsEl).val(currTagIds + ", " + tagId);
         }
    });

    //default behavior for comments is "allowed" (quick and dirty to override stripes preload behavior)
    $("#allow").attr("checked", "checked");

  //end dashboard - create/edit article

    //messages and notifications

    //dashboard - create and send message
    $('#sendMessageForm').ajaxForm({
        url: contextPath + '/actions/registered/message.action',
        resetForm: true,
        dataType: 'json',
        success: function(json) {
            resetMessageBox();
            $.processStripesAjaxOutcome(json,
                function(text) { addMessageToBox(text, messageType.confirm); },
                function(text, field) { addMessageToBox(text, messageType.error, field); }
            );
            configureMessageBoxButtons(
                (json && !json.errors) ? function() {
                    location.href = contextPath + $('#outboxUrl').val();
                  window.event.returnValue = false;
                } : undefined
            );
            showMessageBox();
        }
    });

    //dashboard - delete message from inbox
    $("a.delete").bind("click", function() {
        $.ajaxBoxAction("/actions/registered/message.action",
            {
                delMessage: '',
                id : $(this).parent().parent().attr("id").split('_').slice(1).join('_')
            },
            {
                prompt: {text: "Cancellare il messaggio?", isWarning: true},
                success: function() { reloadPage(); }
            }
        );
        return false;
    });

    //dashboard - delete message from sent
    $("a.deleteSent").bind("click", function() {
        $.ajaxBoxAction("/actions/registered/message.action",
            {
            removeFromSent: '',
            id : $(this).parent().parent().attr("id").split('_').slice(1).join('_')
            },
            {
                prompt: {text: "Cancellare il messaggio?", isWarning: true},
                success: function() { reloadPage({on: 'sent'}); }
            },
            this
        );
        return false;
    });

    //dashboard and homepage (notification on unread message) - mark message as read
    $("a.markasread").bind("click", function() {
        var contentElem = $(this).parent().parent();
        $.ajaxBoxAction("/actions/registered/message.action",
            {
                markAsRead: '',
                id : contentElem.attr("id").split('_').slice(1).join('_')
            },
            function() {
                //remove the li or just the "mark as read" link
                var li = $(contentElem).filter("li");
                if (li.length) {
                    li.fadeOut(400);
                } else {
                    $(this).fadeOut(400);
                }
            },
            this
        );
        return false;
    });

    //dashboard and homepage (notification) - delete notification
    $("ul.scroll a.close").bind("click", function() {
        var contentElem = $(this).parent().parent();
        $.ajaxBoxAction("/actions/registered/notification.action",
            {
                del: '',
                id : contentElem.attr("id").split('_').slice(1).join('_')
            },
            function() { contentElem.fadeOut(400); },
            this
        );
        return false;
    });

    //end messages/notifications

    $("a#contributeId").bind("click", function(event) {
      event.preventDefault();
      openLogin();
    });

    // trim private survey
    $("#attivitaQuestionari tbody").find("tr").each(function(self) {
        if ($($(this).find("td").get(0)).text() == "") {
            $(this).empty();
    }
  });

    //comment/forumpost actions

    //dashboard - moderate comments to own articles
    $("a.commentModeration").bind("click", function() {
        var actionsElem = $(this).parent();
        var options = { commentId : actionsElem.attr("id").split('_').slice(1).join('_') };
        var eventName = $(this).is('.approve') ? 'approve' : 'block';
        options[eventName] = '';
        return $.ajaxBoxAction("/actions/registered/comment.action", options,
            function() {
                $(this).hide();
                $(this).siblings('.commentModeration').show();

                actionsElem.children('.status').text(
                    $(this).is('.approve') ? 'Approvato.' : 'Bloccato.'
                );
            },
            this
        );
    });

    //forum detail tag - create forum topic

    //update FCKeditor with the actual content to prevent
    //empty fields from being sent to the server
    $("#newForumTopicBtn").mousedown(function(){
      FCKeditorAPI.GetInstance("text").UpdateLinkedField();
    });

    $('#threadCreateForm').ajaxForm({
        url: contextPath + '/actions/registered/topic.action',
        resetForm: true,
        dataType: 'json',
        beforeSubmit: function() {
          $("#newForumTopicBtn").attr("disabled","disabled");
          $("#newForumTopicBtn").css("color", "#ccc");
        },
        success: function(json) {
            resetMessageBox();
            $.processStripesAjaxOutcome(json,
                function(text) { addMessageToBox(text, messageType.confirm); },
                function(text, field) { addMessageToBox(text, messageType.error, field); }
            );

            var topicUrl = undefined;

            if(json && json.response && json.response.content && json.response.content.topicHandle)
            {
                topicUrl = contextPath + json.response.content.topicHandle + '.html';
            }

            configureMessageBoxButtons(topicUrl);
            showMessageBox();
            $('#threadBody').clearFields();

            $("#newForumTopicBtn").removeAttr("disabled");
            $("#newForumTopicBtn").css("color", "#fff");
        }
    });

    // comment tag - delete comment
    bindAjaxBoxActionWithId('a.close2', 'click', "/actions/registered/comment.action", 'commentId',
        'delComment',
          {
            prompt: { text: "Cancellare il commento?", isWarning: true},
            success: function(response) {
              if(response.content === 'topicDeleted') {
                location.href = contextPath + $('#parentForumUrl').val();
                window.event.returnValue = false;
              }
              else {
                reloadPage({page: $('#currPage').val()});
              }
            }
          }
    );

    //comment tag - create or edit comment/forum post

    //update FCKeditor with the actual content to prevent
    //empty fields from being sent to the server - note that
    //placing this code inside the beforeSubmit option of
    //ajaxForm will not solve the problem
    $("#newComment").mousedown(function(){
      FCKeditorAPI.GetInstance("text").UpdateLinkedField();
    });

    $('#msgCommentForm').ajaxForm({
        url: contextPath + '/actions/registered/comment.action',
        resetForm: true,
        dataType: 'json',
        beforeSubmit: function() {
           $("#newComment").attr("disabled","disabled");
           $("#newComment").css("color", "#ccc");
        },
        success: function(json) {
            resetMessageBox();
            $.processStripesAjaxOutcome(json,
                function(text) { addMessageToBox(text, messageType.confirm); },
                function(text, field) { addMessageToBox(text, messageType.error, field); }
            );
            configureMessageBoxButtons(
                (json && !json.errors) ? function() {
                    reloadPage({page: $('#currPage').val()});
                } : undefined
            );
            showMessageBox();
            $('#text').clearFields();
            FCKeditorAPI.GetInstance("text").UpdateLinkedField();
            $("#newComment").removeAttr("disabled");
            $("#newComment").css("color", "#666");
        }
    });

    //quote comment/forum post
    $('a.msgQuoteLink').bind("click", function(e) {
      var author = $(this).parent().siblings(".msg_author").children(".author_name").text();
      var uuidvalue = $(this).attr('id').split("_")[1];
      var messageid = '#message_' + uuidvalue;
      var textToQuote="<div class='quote'><strong>" + author + "</strong> ha detto:<br/>" + $(messageid).html() + "</div>";

      //set the text to quote into FCKeditor
      FCKeditorAPI.GetInstance("text").SetHTML(textToQuote);
    });

    //edit comment/forum post
    $('a.msgEditLink').bind("click", function(e) {
      var author = $(this).parent().siblings(".msg_author").text();
      var uuidvalue = $(this).attr('id').split("_")[1];
      var messageid = '#message_' + uuidvalue;
      var textToEdit = $(messageid).html();

      //set the id of the message we're editing
      $("#commentId").val(uuidvalue);
      //set the text to edit into FCKeditor
      FCKeditorAPI.GetInstance("text").SetHTML(textToEdit);
    });

    // network actions

    //content page - become fan
    bindAjaxBoxActionWithId( 'a.fanButt', 'click', "/actions/registered/network.action", 'target',
        'becomeFan', function() {
            //update fan number without reloading the page
            var previousFans = parseInt($('#numApplicationFans').text());
            $('#numApplicationFans').text(previousFans + 1);
            $(".fanButt").hide();
            $("#fanMsg").show();
          }
    );

    //dashboard - remove from fan club
    bindAjaxBoxActionWithId('a.removeFanButt', 'click', "/actions/registered/network.action", 'target',
        'removeFan',
        {
            prompt: { text: "Vuoi essere rimosso dai fan?", isWarning: true },
            success: function() { reloadPage(); }
        }
    );

    //user profile page - request friendship
    bindAjaxBoxActionWithId('a.friendButt', 'click', "/actions/registered/network.action",  'target',
        'askFriendship'
    );

    //dashboard or notification - approve friendship
    bindAjaxBoxActionWithId('a.approveButt','click', "/actions/registered/network.action",  'target',
        'approveFriendship', function() {
            //remove the li (if action comes from a notification) or reload the page
            var li = $(this).parent().parent().filter("li");
            if (li.length) {
                li.fadeOut(400);
                reloadPage();
            } else {
            reloadPage();
            }
      }
    );

      //dashboard or notification - deny friendship
    bindAjaxBoxActionWithId('a.denyButt','click', "/actions/registered/network.action",  'target',
        'denyFriendship',
        {
            prompt: { text: "Vuoi rifiutare l&apos;amicizia?", isWarning: true},
            success: function() {
                //remove the li (if action comes from a notification) or reload the page
                var li = $(this).parent().parent().filter("li");
                if (li.length) {
                    li.fadeOut(400);
                } else {
                reloadPage();
                }
            }
        }
    );

      //dashboard - remove friend
//    bindAjaxBoxActionWithId('a.remButt','click', "/actions/registered/network.action",  'target',
//        'deleteFriend',
//        {
//            prompt: { text: "Rimuovere dagli amici?", isWarning: true },
//            success: function() { reloadPage(); }
//        }
//    );
  //dashboard - remove friend
    $("a.remButt'").bind("click", function() {
        var contentElem = $(this);
        $.ajaxBoxAction("/actions/registered/network.action",
            {
            target: contentElem.attr("id").split('_').slice(1).join('_'),
                deleteFriend : ''
            },
            {
                prompt: { text: "Rimuovere dagli amici?", isWarning: true },
                success: function() { reloadPage(); }
            }
        );
        return false;
    });


    // End Friendship

    // Disable search width empty value
    $(".searchFormFH").submit( function() {
        var idForm = this.id;
        var searchQuery;
        if (idForm.indexOf("FormH") > -1)
        {
            searchQuery = $(".searchField")[0].value;
        }
        else {
            searchQuery = $(".searchField")[1].value;
        }
      if (searchQuery.length < 3) {
        niceMessage("Inserire almeno 3 lettere.", true);
        return false;
      } else {
        return true;
      }
    });

    // SearchBox table dashboard
    var sb = $("body.dashboard div#messaggi1_comm1 .searchBar")[0];
    if (sb) {
        sb.style.position = "absolute";
        sb.style.top = "-30px";
        sb.style.right = "0px";
        sb.style.width = "700px";

        sb = $("body.dashboard div#messaggi1_comm2 .searchBar")[0];
        if (sb) {
          sb.style.position = "absolute";
          sb.style.top = "-30px";
          sb.style.right = "0px";
          sb.style.width = "700px";
        }
    }
});
/* // DOCUMENT READY // */
