$(function(){
  headerSearchInput();
  delete_questionImage();
  delete_questionFile();
  create_comment();
  delete_comment();
  delete_answer();
  delete_question();
  questionPoints();
  questionIsAnswer();
  questionNotice();
  questionLocked();
  questionBookmark();
  profileQuestionsMini();
  voteChoice();
  voteRefresh();
  notificationList();
});

function headerSearchInput(){
  var cache = [];
  $( "#headerSearchInput,#mainContentSearchInput").autocomplete({
    minLength: 2,
    delay: 100,
    zIndex: 903,
    source: function( request, response ) {
      var term = request.term;
      if ( term in cache ) {
        response( cache[ term ] );
        return;
      }
      var lastXhr = $.getJSON( REPLY.ajaxurl + "ajax/autocomplete.php?callback=?", 
      {
        q: request.term
      }, 
      function( data, status, xhr ) {
        /*
        for(var i = 0; i < data.length; i++){          
          data[i] = data[i].replace(new RegExp(term, 'gi'),'<mark>$1</mark>');
        }
         */
        cache[ term ] = data;
        if ( xhr === lastXhr ) {
          response( data );
        }
      });      
    },
    open: function(e,ui) {
      var 
      termTemplate = "<mark>%s</mark>",    
      acData = $(this).data('autocomplete'),
      styledTerm = termTemplate.replace('%s', acData.term.replace(/[^a-z0-9]+/gi,''));

      acData
      .menu
      .element
      .find('li a')
      .each(function() {
        var me = $(this);
        me.html( me.html().replace(new RegExp(acData.term, 'gi'), styledTerm));
      });
    }
  });
  
}
 
function delete_questionImage(){
  $(".ajaxDeleteImage").click(function(){

    var data = $(this).data();
    
    qConfirm(REPLY.lang.ajaxDeleteImage.confirm, REPLY.lang.warning,function(ret){
      if(ret){
        $.getJSON( 
          REPLY.ajaxurl + "question-image/delete?callback=?", 
          {
            id: data.id,
            key: data.key 
          }
          , function(response){
            qAlert(response.content, response.title);        
            if(!response.error){         
              $("#divImages" + data.key).slideUp(300);
            }     
          }
          );      
      }
    });
        
    return false;
  });
}

function delete_questionFile(){
  $(".ajaxDeleteFile").click(function(){

    var data = $(this).data();
    
    qConfirm(REPLY.lang.ajaxDeleteFile.confirm, REPLY.lang.warning,function(ret){
      if(ret){
        $.getJSON( 
          REPLY.ajaxurl + "question-file/delete?callback=?", 
          {
            id: data.id,
            key: data.key 
          }
          , function(response){
            qAlert(response.content, response.title);        
            if(!response.error){         
              $("#divFiles" + data.key).slideUp(300);
            }     
          }
          );      
      }
    });
        
    return false;
  });
}

function create_comment(){
  $("#mainContent .comments form[id^='commentForm']").submit(function(){
    return false;
  });
  $("#mainContent .comments form[id^='commentForm']")
  .bind("jqv.form.result", function(event , errorFound){
    
    if(!errorFound){
      var data = {
        id: $(this).data().id,
        text: $(this).find("[name='text']").val(),
        isanonymous: $(this).find("[name='isanonymous']:checked").val(),
        notify: $(this).find("[name='notify']:checked").val()
      }
      
      $("#question" + data.id + " .comments .new-comment," + 
        "#answer" + data.id + " .comments .new-comment").fadeTo(300, 0.5);
      
      /*
      $.getJSON( 
        REPLY.ajaxurl + "question-comment/create?callback=?",
        data
        , function(response){
          if(!response.error){
            if($("#question" + data.id + " .comments p:last," +
              "#answer" + data.id + " .comments p:last").length){
              $("#question" + data.id + " .comments p:last," +
                "#answer" + data.id + " .comments p:last").after(response.html);
            }else{
              $("#question" + data.id + " .comments," +
                "#answer" + data.id + " .comments").prepend(response.html);
            }
            $("#question" + data.id + " .comments .new-comment," + 
              "#answer" + data.id + " .comments .new-comment").slideUp(300);
            $("#question" + data.id + " .comments .add," + 
              "#answer" + data.id + " .comments .add").slideDown(300);
            
            $("#question" + data.id + " .comments .new-comment textarea," + 
              "#answer" + data.id + " .comments .new-comment textarea").val("");
            
            var notice = $("#question" + data.id + " .ajaxQuestionNotice," + 
              "#answer" + data.id + " .ajaxQuestionNotice");
            if(response.notify){
              notice.addClass("active");
            }else{              
              notice.removeClass("active");
            }           
          }else{            
            qAlert(response.content, response.title);
          }
          $("#question" + data.id + " .comments .new-comment," + 
            "#answer" + data.id + " .comments .new-comment").fadeTo(300,1);
        }
        );*/
      
      $.post(REPLY.ajaxurl + "question-comment/create?callback=?", data, function(response) {
        if(!response.error){
          if($("#question" + data.id + " .comments p:last," +
            "#answer" + data.id + " .comments p:last").length){
            $("#question" + data.id + " .comments p:last," +
              "#answer" + data.id + " .comments p:last").after(response.html);
          }else{
            $("#question" + data.id + " .comments," +
              "#answer" + data.id + " .comments").prepend(response.html);
          }
          $("#question" + data.id + " .comments .new-comment," + 
            "#answer" + data.id + " .comments .new-comment").slideUp(300);
          $("#question" + data.id + " .comments .add," + 
            "#answer" + data.id + " .comments .add").slideDown(300);
            
          $("#question" + data.id + " .comments .new-comment textarea," + 
            "#answer" + data.id + " .comments .new-comment textarea").val("");
            
          var notice = $("#question" + data.id + " .ajaxQuestionNotice," + 
            "#answer" + data.id + " .ajaxQuestionNotice");
          if(response.notify){
            notice.addClass("active");
          }else{              
            notice.removeClass("active");
          }           
        }else{            
          qAlert(response.content, response.title);
        }
        $("#question" + data.id + " .comments .new-comment," + 
          "#answer" + data.id + " .comments .new-comment").fadeTo(300,1);
      }, "json");

    }
    return false;
  });
  
  $("#mainContent .comments .add a").click(function(){
    $(this).parent().parent().find('div').slideToggle(300);
    return false;
  });
  
  $("#mainContent .comments .new-comment a").click(function(){
    $(this).parent().parent().parent().find('div').slideToggle(300);
    return false;
  });
}

function delete_comment(){
  $(".ajaxDeleteComment").live('click', function(){

    var data = $(this).data();
    
    qConfirm(REPLY.lang.ajaxDeleteComment.confirm, REPLY.lang.warning,function(ret){
      if(ret){
        $.getJSON( 
          REPLY.ajaxurl + "question-comment/delete?callback=?", 
          {
            id: data.id
          }
          , function(response){
            qAlert(response.content, response.title);        
            if(!response.error){         
              $("#comment" + data.id).slideUp(300);
            }     
          }
          );      
      }
    });
    return false;
  });
}

function delete_answer(){
  $(".ajaxDeleteAnswer").bind('click', function(){

    var data = $(this).data();
    
    qConfirm(REPLY.lang.ajaxDeleteAnswer.confirm, REPLY.lang.warning,function(ret){
      if(ret){
        $.getJSON( 
          REPLY.ajaxurl + "question-answer/delete?callback=?", 
          {
            id: data.id
          }
          , function(response){                
            if(!response.error){         
              $("#answer" + data.id).slideUp(300);
            }else{
              qAlert(response.content, response.title);
            }
          }
          );      
      }
    });
    return false;
  });
}

function delete_question(){
  $(".ajaxDeleteQuestion").bind('click', function(){

    var data = $(this).data();
    
    qConfirm(REPLY.lang.ajaxDeleteQuestion.confirm, REPLY.lang.warning,function(ret){
      if(ret){
        $.getJSON( 
          REPLY.ajaxurl + "question-question/delete?callback=?", 
          {
            id: data.id
          }
          , function(response){                
            if(!response.error){
              window.location.href = response.url;
            }else{
              qAlert(response.content, response.title);
            }
          }
          );      
      }
    });
    return false;
  });
}

function questionPoints(){
  $(".ajaxQuestionPoints").bind('click', function(){
    var its_other = $(this).closest(".left.other").size();
    if(its_other){
      var rating = $(this).data().rating;
      var q = $(this).data().q;
      $.getJSON( 
        REPLY.ajaxurl + "question-points/?callback=?", 
        {
          q: q,
          rating: rating
        }
        , function(response){
          if(!response.error){
            $("#question" + q + " .point-count," + 
              "#answer" + q + " .point-count")
            .text(response.rating)
            .effect("pulsate");
            $("#question" + q + " .point-add," + 
              "#answer" + q + " .point-add,"+
              "#question" + q + " .point-remove," + 
              "#answer" + q + " .point-remove").removeClass('active');
            if(rating > 0){
              $("#question" + q + " .point-add," + 
                "#answer" + q + " .point-add").addClass('active');
            }
            if(rating < 0){
              $("#question" + q + " .point-remove," + 
                "#answer" + q + " .point-remove").addClass('active');
            }
          }else{
            qAlert(response.content, response.title);
          }
        });
    }else{
      qAlert(REPLY.lang.ajaxQuestionPoints.own, REPLY.lang.warning);
    }
        
    return false;
  });  
}

function questionIsAnswer(){
  $(".ajaxQuestionIsAnswer").bind('click', function(){
    var q = $(this).data().q;
    $.getJSON(
      REPLY.ajaxurl + "question-is-answer/?callback=?", 
      {
        q: q
      }
      , function(response){
        if(!response.error){
          _questionIsAnswerAlertHelper(q,response);
        }else{
          qAlert(response.content, response.title);
        }
      });
    return false;
  });
}

function questionNotice(){
  $(".ajaxQuestionNotice").bind('click', function(){
    var q = $(this).data().q;
    $.getJSON(
      REPLY.ajaxurl + "question-notice?callback=?", 
      {
        q: q
      }
      , function(response){
        if(!response.error){
          if(response.type == 1){
            $("#question" + q + " .flag,"+
              "#answer" + q + " .flag").addClass("active");
          }else{
            $("#question" + q + " .flag,"+
              "#answer" + q + " .flag" ).removeClass("active");
          }
          qAlert(response.content, response.title);
        }else{
          qAlert(response.content, response.title);
        }
      });
    return false;
  });
}

function questionLocked(){
  $(".ajaxQuestionLocked").bind('click', function(){
    var q = $(this).data().q;
    $.getJSON(
      REPLY.ajaxurl + "question-locked?callback=?", 
      {
        q: q
      }
      , function(response){
        if(!response.error){
          if(response.type == 1){
            $("#question" + q + " .locked,"+
              "#answer" + q + " .locked").addClass("active");
          }else{
            $("#question" + q + " .locked,"+
              "#answer" + q + " .locked" ).removeClass("active");
          }
          qAlert(response.content, response.title, function(){
            window.location.reload();
          });
        }else{
          qAlert(response.content, response.title);
        }
      });
    return false;
  });
}

function questionBookmark(){
  $(".ajaxQuestionBookmark").bind('click', function(){
    var q = $(this).data().q;
    $.getJSON(
      REPLY.ajaxurl + "question-bookmark?callback=?", 
      {
        q: q
      }
      , function(response){
        if(!response.error){
          if(response.type == 1){
            $("#question" + q + " .bookmark").addClass("active");
          }else{
            $("#question" + q + " .bookmark").removeClass("active");
          }
          qAlert(response.content, response.title);
        }else{
          qAlert(response.content, response.title);
        }
      });
    return false;
  });
}

function voteChoice(){
  $(".ajaxVoteChoice").live('click', function(){
    $(this).parent().effect('pulsate');
    var id = $(this).data().id;
    var poll_table = $(this).parent().parent().parent().parent();
    $.getJSON(
      REPLY.ajaxurl + "vote-choice?callback=?", 
      {
        id: id
      }
      , function(response){
        if(!response.error){
          $.each(response.data,function(id,data){
            var choice = poll_table.find("td .ajaxVoteChoice[data-id='" + id + "']");
            choice.css('width', data.width + '%');
            choice.parent().next().text(data.perc + '% (' + data.score + ')')
          });
          poll_table.find(".message").prepend(
            '<div style="display:none" class="ui-state-highlight ui-corner-all"><p><span class="ui-icon ui-icon-info"></span>'+ response.content +'</p></div>');
        }else{
          poll_table.find(".message").prepend(
            '<div style="display:none" class="ui-state-error ui-corner-all"><p><span class="ui-icon ui-icon-alert"></span>'+ response.content +'</p></div>');          
        }
        poll_table.find(".message > div:first").slideDown();
        setTimeout(function(){
          poll_table.find(".message > div:last").slideUp(null, function() { 
            $(this).remove();
          });
        },5000);
      });
    return false;
  });
}

function voteRefresh(){
  $(".ajaxVoteRefresh").live('click', function(){
    $(this).addClass('active').parent().effect('pulsate');
    var poll_div = $(this).parent().parent().parent().parent().parent();
    var css = poll_div.attr("class")
    poll_div.fadeTo(300, 0.4);
    $.getJSON(
      REPLY.ajaxurl + "vote-refresh?callback=?",
      {
        css: css
      },
      function(response){
        if(!response.error){
          var opacity = poll_div.css('opacity');
          poll_div.after(response.content);
          poll_div.next().css('opacity', opacity).fadeTo(300, 1);
          poll_div.remove();
        }else{
          qAlert(response.content, response.title);
        }       
      });
    return false;
  });
}

var timeout = 0;
function notificationList(){
  $("#ajaxNotificationList").bind('keyup', function(){    
    var category = $(this).data().category;
    var question = $(this).data().question;
    var name = $(this).val();
        
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      $("#inviteList").fadeTo(300, 0.4);
      $.getJSON( 
        REPLY.ajaxurl + "notification-list/?callback=?", 
        {
          category: category,
          question: question,
          name: name
        }
        , function(response){
          if(!response.error){
            $("#inviteList").stop().fadeTo(300, 1);
            $("#inviteList").html(response.content);
          }else{
            qAlert(response.content, response.title);
          }
        });   
    }, 200);
          
    return false;
  });  
}

function profileQuestionsMini(){
  $("#profileAsked .pagination a," +
    "#profileAnswered .pagination a," +
    "#profileBookmarked .pagination a," +
    "#profileNoticed .pagination a").live('click', function(){
    var conainer = $(this).closest('.container');
    var page = $(this).data().page;
    var type = conainer.data().type;
    var user = conainer.data().user;
    
    conainer.fadeTo(300, 0.4);
    $.getJSON(
      REPLY.ajaxurl + "profile-question-mini?callback=?",
      {
        page: page,
        type: type,
        user: user
      },
      function(response){
        if(!response.error){
          conainer.html(response.content);
        }else{
          qAlert(response.content, response.title);
        } 
        conainer.fadeTo(300, 1);
      });
    return false;
  });
}

function _questionIsAnswerAlertHelper(q,response){  
  if(!response.warning){
    if(response.action == 'set'){
      $(".answer").removeClass('is-answer');
      $("#answer" + q).addClass('is-answer').insertBefore(".answer:not(#answer" + q + "):first").effect('pulsate');
      $(".ajaxQuestionIsAnswer").addClass('isanswer-set').removeClass('isanswer-is');
      $("#answer" + q + " .ajaxQuestionIsAnswer").addClass('isanswer-is').removeClass('isanswer-set');;
      
    } else {
      $("#answer" + q).removeClass('is-answer');
      $("#answer" + q + " .ajaxQuestionIsAnswer").addClass('isanswer-set').removeClass('isanswer-is');
    }    
  } else{
    qConfirm(response.content, response.title, function(response){
      if(response){
        $.getJSON(
          REPLY.ajaxurl + "question-is-answer/?callback=?", 
          {
            q: q,
            sure: 1
          }
          , function(response){
            _questionIsAnswerAlertHelper(q,response);
          });
      }
    });
  }     
}


