jQuery.fn.preventDoubleSubmit = function(msg) {
  jQuery(this).submit(function() {
    if (this.beenSubmitted){
      if(msg){
        alert(msg);
      }
      return false;
    }else
      this.beenSubmitted = true;
  });
};


$(document).ready(function(){
  setupSurveyNavigation();
  setupSurveyCompletionAlert();
  setupSurveyQuestions();
  setExistingSurveyState();
  setupSurveyPageControls();
  ajaxifySurvey();
  setupCaseStudiesPage();
  setupPageProgress();
  setupCollectorClipBoardCopy();
  addClearAllAndSelectAllLinksToAnalyzePage();
  setupFeedback();
  allowBruteForce();
  $('#complete_survey_form').preventDoubleSubmit("Your survey is still being processed.. Please wait");
});

function allowBruteForce(){
    $('#query_compare_against').change(function() {
        if($(this).find(':selected').text() == "User Specified IDs"){
            $('.survey_list input:checkbox').each(function(){
                this.name = "change_me";
            }).hide();

            $('.survey_list').prev().hide();
            $(this).parent().after("<div id='brute_force_field' class='field'><label for='compare'>Comparative Set:</label><input type='text' id='query_brute_force' name='query[brute_force]'/></div>")
            $(this).parent().after("<div id='brute_force_field2' class='field'><label for='compare'>Target Set:</label><input type='text' id='query_brute_force2' name='selected_surveys[]'/></div>")
            $('#brute_force_field').nextAll('.field').not(":last").hide();

            $('.filters').find('h4').find('a:first').after("<a href='#'>Brute Force</a>").hide();

        }else{
            if($('#brute_force_field').length > 0){
                $('#brute_force_field').nextAll('.field').show();
                $('#brute_force_field').remove();
                $('#brute_force_field2').remove();
                $('.survey_list input:checkbox').each(function(){
                    this.name = "selected_surveys[]";
                }).show();
                $('.survey_list').prev().show();
                $('.filters').find('h4').find('a:first').show().end().find('a:last').remove();
            }
        }
    });
}

function setupFeedback() {
  $('.feedback_link').live('click', function() {
      var link = $(this), href = link.attr('href');
      $.ajax({ url: href, type: 'get', dataType: 'html',
              success: function(data) {
                      $form = $(data).find("#reviewForm")
                      
                      $form.find("textarea")
                        .css({'width' : '400px', 'height' : '70px'}).end()
                      .find("h3").eq(0).before("<a href='#' id='closeLink'>close</a>").end().end()
                      .find('#closeLink').css({'float' : 'right', 'marginBottom' : '10px'})
                        .click(function(event){
                              $.unblockUI(); 
                              event.preventDefault();
                            }).end().end()
                      .find('hr').eq(0).css({'clear' : 'right'}).end().end()
                      .find(".next_prev")
                        .css({'textAlign' : 'center'}).end()
                      .find("h3").css({'textAlign' : 'center'}).hide().end()
                      .find(".submit_button").click(function(event){ 
                        if(($('#included_yes').length == 0 && $('#comments').val() != "")|| $('#included_yes:checked').val() || $('#included_no:checked').val()){
                          $.ajax({ url: href, type: 'post',
                                 data: $form.find("form").serialize(),
                                  success: function() {
                                      $form.find("h3").text("Thanks for the feedback").show();
                                      setTimeout($.unblockUI, 1000);
                                  }
                          });
                        }else{
                          if($('#included_yes').length == 0)
                          {
                            $form.find("h3").text("Please provide a comment for your feedback").show();
                          }else
                          {
                              $form.find("h3").text("Please tell us if the question should be included.").show();
                          }
                          
                          setTimeout(function(){$form.find("h3").text("").hide();}, 3000);
                        }
                        event.preventDefault();
                      });
                      
                      $.blockUI({
                              message: $form,
                              css: { 
                                top: '20%',
                                padding: '10px',
                                textAlign: 'left'
                              } 
                      });
              }
      });
    return false;
  });
}

function addClearAllAndSelectAllLinksToAnalyzePage(){
  $('.survey_list, .collector_list').before(

    $("<div>")
    .css("float", "right")
    .css("margin-bottom", "5px")
    .append(
      $("<a href='javascript: void(0)'>Clear All </a>").click(function(){
        $('.survey_list input:checkbox, .collector_list input:checkbox').each(function(){
          this.checked = false;
        })
      }).css("margin-right", "20px")
    )
    .append(
      $("<a href='javascript: void(0)'> Select All</a>").click(function(){
        $('.survey_list input:checkbox, .collector_list input:checkbox').each(function(){
          this.checked = true;
        })
      })
    )
  );
}

function setupCollectorClipBoardCopy(){
  $(".collector_list tbody tr").not(':first').each(function() {
    var clip = new ZeroClipboard.Client();
    //Cache the last td and the parent row    
    var nextToLastTd = $(this).find('td:last').prev();
    clip.glue(nextToLastTd[0]);
    clip.setText(nextToLastTd.find('a').attr('href'));
    clip.addEventListener('complete', function(client, text) {
      alert("Collector URL Copied");
    });
  });
}

function setupPageProgress(){
  $('body').append($("<div id='page_progress'style='display:none; width:180px; height: 60px;'>Loading Questions<div id='page_progress_bar'></div></div>"))
  
  $('#page_progress').css({
    "text-align" : "center",
    "padding-top" : "10px",
    "background-color" : "#FFFDBF",
    "border" : "1px solid #E6E077"
  });
  $('#page_progress_bar').css({
    "margin-top" : "10px"
  });
  
}

function reCenterProgress() {
  var windowWidth = document.documentElement.clientWidth;  
  var windowHeight = document.documentElement.clientHeight;  
  var popupHeight = $("#page_progress").height();  
  var popupWidth = $("#page_progress").width();  
  //centering  
  $("#page_progress").css({  
    "position": "absolute",  
    "top": windowHeight/2-popupHeight/2,  
    "left": (windowWidth/2-popupWidth/2) - 160  
  });  
}

function showWithProgressBar(f){
  reCenterProgress();
  $('#page_progress').show()
  $("#page_progress_bar").progressBar(100, { showText: false, barImage: '/images/progressbg_orange.gif'} ); 
 
  timeoutFunc = function(){
    f();
    $('#page_progress').hide()
    $("#page_progress_bar").progressBar(0);
  }
  setTimeout(timeoutFunc, 750);
  
}

function ajaxifySurvey(){
  $('form.ajax').submit(function() {
    that = $(this)
    $.ajax({
      data: $.param($(this).serializeArray()), 
      dataType: 'text', 
      type: 'post', 
      url: $(this).attr('action'),
      success: function(request) {
        updateSurveyProgress(jQuery(request));
        moveToNextPage(that);
      }
    });
    return false;
  });
}

function setupSurveyNavigation(){
  $('.survey_sub_section:gt(0)').hide();
  
  $('#subnav')
  .find('li a').click(function(){
    $("#survey_start_alert").hide();
    $('#subnav li').removeClass("selected");
    $(this).parents('li').addClass("selected");
  });
  
  $('.survey_nav')
  .find('span').addClass("incomplete").end()
  .find('li:first').addClass("selected").end()
  .find('a:not(:last)').click(function(){
    $('div#complete_survey').hide();
    //    $('.alert').hide();
    $that = $(this.hash)
    showWithProgressBar(function(){
      $('.survey_sub_section').hide();
      $that.show().find('.survey_sub_section:first').show();
    });
  });
}

function setupSurveyCompletionAlert(){
  $('div#complete_survey').hide();
  $("a[href='#complete_survey']").click(function(){
    $('.survey_sub_section').hide();
    $('div.completion.alert').show();
  }).hide();
}

function setupSurveyPageControls(){
  $('.next_prev a.next').live("click", function(){ 
    $("#survey_start_alert").hide();
    $('.alert').hide();
    if($('.stop_survey_button').length == 0){
      $('#title_bar p').after("<a href=\"/surveys/stop_and_finish_later\" class=\"button stop_survey_button\"><image src=\"/images/btn_stop_and_finish_later.gif\" alt=\"Stop And Finish Later\" /></a>");
    }
  }
);
  $('.next_prev a.prev').live("click", function(){moveToPreviousPage($(this));});
}

function setExistingSurveyState(){
  updateSurveyProgress($('#survey_progress_fields'));
  $('.survey_checkbox input:radio').hide();
  $('.survey_checkbox input:checked').each(function(){ checkSurveyCheckBox($(this)) });
  $('.survey_checkbox input:checked').live("click", function() { checkSurveyCheckBox($(this)) } );
}

function setupSurveyQuestions(){
  setupSurveyCheckBoxes();
 
  $('.survey_questions tbody tr')
  .bind('mouseenter mouseleave', function(event) { 
    $(this)[ (event.type == "mouseenter" ? "add" : "remove") + "Class"]('over');
  });
}

function setupSurveyCheckBoxes(){
  $hover_image = $('<img src="/images/surveycheckbox_blank.gif" class="cb_blank" />');
  $('.survey_checkbox').hover(
  function() {if (!$(this).hasClass('checked'))$(this).append($hover_image);},
  function() {$(this).find('.cb_blank').remove();}
).live("click",
  function() {
    checkSurveyCheckBox($(this).find('input:radio'));
    return false;
  }
);
}

function moveToPreviousPage(el){
  showWithProgressBar(function(){
    $('.survey_sub_section').hide();  
    if(el.parents('.survey_sub_section').prev().length > 0){
      el.parents('.survey_sub_section').prev('.survey_sub_section').show(); 
    }else{
      el.parents('.survey_section').prev().find('.survey_sub_section:last').show()
      
      prev_section = el.parents('.survey_sub_section:first').parent().prev();
      $('.survey_nav').find('li').removeClass("selected")
      .find('span a').filter(function(){
        return this.hash == ("#" + prev_section.attr("id"));
      }).parents('li:first').addClass("selected");
      
    }
  });
}

function moveToNextPage(el){
  showWithProgressBar(function(){
    $('.survey_sub_section').hide();
    next_sub_section = el.parents('.survey_sub_section:first').next('.survey_sub_section');

    if(next_sub_section.length > 0){
      next_sub_section.show();
    }else{
      next_section = el.parents('.survey_sub_section:first').parent().next();
      next_survey_section_sub_section = next_section.find('.survey_sub_section:first');
      if(next_survey_section_sub_section.length > 0){
        next_survey_section_sub_section.show();
        $('.survey_nav').find('li').removeClass("selected")
        .find('span a').filter(function(){
          return this.hash == ("#" + next_section.attr("id"));
        }).parents('li:first').addClass("selected");
      }else{
        $("a[href='#complete_survey']").show();
        $('div#complete_survey').show();
      }
    }
  });
}

function checkSurveyCheckBox(cbx) {
  var cb = cbx.parents('td');
  cb.parents('tr').find('.checked').removeClass('checked').addClass('blank').find('.cb_checked').remove();
  cb.removeClass('blank')
  .addClass('checked')
  .append('<img src="/images/surveycheckbox_checked.gif" class="cb_checked" />')
  .find('.cb_blank').remove();
  cb.find('input[type="radio"]').attr('checked','checked');  
}

function updateSurveyProgress(el){
  $('.progress_bar').css("width", el.find('#survey_progress').val() + '%')
  .find('p strong').attr("innerHTML", el.find('#survey_progress').val() + '% complete');

  el.find("input[id$=_progress]").filter(function(){
    return $(this).val() == "true";
  }).each(function(){
    $('.survey_nav li span a[href=#' + this.id.replace("_progress", '') + ']').parent().addClass("complete");
  });
}

function setupCaseStudiesPage(){
  $('#network_isv_details').each(function(){
    $isv = $(this)

    $link = $("<a href='javascript: void(0)'>Click here </a>").click(function(){
      $isv.toggle();
    });

    $("<p></p>")
    .append($link)
    .append($("<span>to read more details about this case study</span>"))
    .insertBefore($isv);

    $isv.hide();

  });
}

jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} });
