$(document).ready(function(){
    
    $(".display").tablesorter(); //sorter
    $('.nosort').unbind(); //stops columns with this class from sorting
    $(function(){ $("input:checkbox, :input:radio, select").uniform(); });  //skin form elements
    update_randomized_dropdown();                                   //we want to run it on every page load
    $(".dnd .randomize" ).click(update_randomized_dropdown);        //When randomize box is checked we do quick recalculation  	
	hide_show_add_answer_link()                                     //do it on page load
	$('#sortable_answers').sortable({ cursor: 'move' });            //make answers draggable
    $('#ReportStart, #ReportEnd, #ReportFilterStart, #ReportFilterEnd').datepicker();
    $('#ReportStart, #ReportEnd, #ReportFilterStart, #ReportFilterEnd').datepicker("option", "dateFormat", 'yy-mm-dd');

    
    //check uncheck all checkboxes with class
    $('.check_uncheck_all').change(function(){
        var $checkboxes = $(this).closest('table').find('div.checker span');
        $(this).attr('checked') == true ? $checkboxes.addClass('checked') : $checkboxes.removeClass('checked');
        $(this).attr('checked') == true ? $checkboxes.find('input:checkbox').attr('checked', 'checked') : $checkboxes.find('input:checkbox').removeAttr('checked');
        
        //.each(function(index){
          //  $(this).attr('checked', 'checked');
        //});
    });
    //do the same thing when the dropdown changes
	$('#QuestionQuestionTypeId').change(function(){
		hide_show_add_answer_link()
	});
    
    //Save entire question order on drag and drop
    // Initialise the table
    $(".dnd").tableDnD({
        onDragClass: "draggable",
        onDrop: function(table, row) {
            $('.ajax_save').show();

            var var_rows = table.tBodies[0].rows;
            json = {};
            json.SurveyQuestion = [];
    
            for(var i=0; i< var_rows.length; i++) {
                //reset vars so we don't pollute the data
                var var_survey_question_id ="";
                var var_required = "N";
                var var_randomize = "N";
            
                //get the id of the row to be updated
                var_survey_question_id = $('#'+var_rows[i].id).find("a.remove_from_survey").attr("survey_question_id");
                var_survey_id = $('#'+var_rows[i].id).find("a.remove_from_survey").attr("survey_id");
                //set required and randomized options
                if($('#'+var_rows[i].id).find("input.required:checked").length == 1){ var_required = 'Y';}
                if($('#'+var_rows[i].id).find("input.randomize:checked").length == 1){ var_randomize = 'Y';}    

                json.SurveyQuestion[i] = {};
                json.SurveyQuestion[i].position = i+1;
                json.SurveyQuestion[i].id = var_survey_question_id;
                json.SurveyQuestion[i].required = var_required;
                json.SurveyQuestion[i].randomize = var_randomize;
            }
            
            //Save the number of questions to store
            json.Survey = {};
            json.Survey.random_questions = $("#randomize option:selected").val();
            json.Survey.id = var_survey_id;
        
            var_data = $.toJSON(json);
            //alert(var_data);
            var_url = "/surveys/question_position_set/" + table.id + "/";

            
            $.ajax({
                type: 'POST',
                url: var_url,
                data:  {data: var_data},
                success: function(result) {
                    if(result == 'success'){
                        $('.ajax_save').text('saved!');
                        $('.ajax_save').fadeOut(1000);
                    }else{
                        $('.ajax_save').hide();
                        alert("An error has occurred in communicating with the server.\n Please try again!");
                    }
                }
             });
                        
        }
    });
    
    //SAVES ALL QUESTIONS IN THEIR CORRECT ORDER
    $(".save_survey_question").click(function() {
        $('.ajax_save').show();

        //setup json object
        json = {};
        json.SurveyQuestion = [];
            
        //get the survey id and question id    
        var_question_id = $(this).parent().attr('id');    
        var_survey_id = $('#'+var_question_id).find("a.remove_from_survey").attr("survey_id");
        
        $('#table_'+var_survey_id+' tbody tr').each(function(i){
            //alert($(this).html());//debug
            //reset vars so we don't pollute the data
            var var_survey_question_id  = "";
            var var_required            = "N";
            var var_randomize           = "N";
            var var_display_horizontal  = "N";
       
            //get the id of the row to be updated
            var_survey_question_id = $(this).find("a.remove_from_survey").attr("survey_question_id");
            var_survey_id = $(this).find("a.remove_from_survey").attr("survey_id");
            
            //set required and randomized options
            if($(this).find("input.required:checked").length == 1){ var_required = 'Y';}
            if($(this).find("input.randomize:checked").length == 1){ var_randomize = 'Y';}    
            if($(this).find("input.horizontal:checked").length == 1){ var_display_horizontal = 'Y';}  

            json.SurveyQuestion[i]                      = {};
            json.SurveyQuestion[i].position             = i+1;
            json.SurveyQuestion[i].id                   = var_survey_question_id;
            json.SurveyQuestion[i].required             = var_required;
            json.SurveyQuestion[i].randomize            = var_randomize;
            json.SurveyQuestion[i].display_horizontal   = var_display_horizontal;
        });
        //Save the number of questions to store
        json.Survey                     = {};
        json.Survey.random_questions    = $("#randomize option:selected").val();
        json.Survey.id                  = var_survey_id;  
        var_data                        = $.toJSON(json);
        var_url                         = "/surveys/question_position_set/" + var_question_id  + "/";

        
        $.ajax({
            type: 'POST',
            url: var_url,
            data:  {data: var_data},
            success: function(result) {
                if(result == 'success'){
                    $('.ajax_save').text('saved!');
                    $('.ajax_save').fadeOut(1000);
                }else{
                    $('.ajax_save').hide();
                    alert("An error has occurred in communicating with the server.\n Please try again!");
                }
            }
         });
        return false;
    });


    //Inserts answers when link is clicked, makes them sortable and allow the 'remove' link to work
    $("#show_answer").click(function() {
        //get the number of answers presently on the page
        var_number_of_answers = $(".ajax_answer").size();
        var_number_of_answers_index = var_number_of_answers - 1;
        if(var_number_of_answers > 0){
            //var_last_answer = $(".ajax_answer").get(var_number_of_answers_index);
            var_last_answer = $(".ajax_answer:last");
            var_answer_count = $(var_last_answer).find("input").attr("count");
            var_answer_count++;
        }else{
            var_answer_count = 1;
        }
		
        //content inserted
        var_content = "<div class=\"ajax_answer\"><label for=\"Answer" + var_answer_count + "AnswerText\">Answer " + var_answer_count + ":</label><input type=\"text\" count=\""+ var_answer_count + "\" id=\"Answer" + var_answer_count + "AnswerText\" name=\"data[Answer][" + var_answer_count + "][answer_text]\" /> <a href=\"/questions/create\" class=\"remove_answer\">remove</a></div>";
        $(var_content).appendTo("#sortable_answers");

        //bind javascript action to the links
        $(".remove_answer").bind("click", function(e){
            $(this).parent().remove();
            return false;
        });

		//refresh sortability to it applies to new items
		$('#sortable_answers').sortable('refresh');
        //stop link from going anywhere
        return false;
    });
    
    //PUT UP CONFIRMATION BEFORE DELETIONS
    $(".delete a").click(function() {
        var agree = confirm("Are you sure you want to delete this item?");
        if(agree){
            return true;
        }else{
            return false;
        }
    });
    
    //remove answers for questions using ajax
    $(".remove_edited_answer").click(function() {
        //get the id of answer to delete
        var agree = confirm("This will permanently remove this answer.\n Do you want to continue?");
        
        if(!agree)
            return false;
        
        var_id= $(this).attr("id");
        //Send to ajax to remove
        $.ajax({
           type: "GET",
           url: "/answers/delete/global/" + var_id,
           data: "",
           //use ajax callback to remove element from dom
           success: function(returned_data){
            if(returned_data == 'deleted'){
                $("#" + var_id).parent().remove();
            }else{
                alert("An error has occurred in communicating with the server. Please try again!");
            }
           },
           error: function(returned_data){
               alert("An error has occurred in communicating with the server. Please try again!");
           }
        });
        
        return false;
    });

    //add questions to a survey
    $(".add_to_survey").click(function() {                        
        var_question_id= $(this).attr("question_id");
        var_survey_id= $(this).attr("survey_id");
        var_position = $('#table_'+var_survey_id+' tbody tr').length + 1;
        
        //if the question is already in the surveys selected questions it won't add it
        if($('#'+var_question_id).length == 0){
            $('.ajax_save').text('adding ...');
            $('.ajax_save').show();
            
            $.ajax({
               type: "GET",
               url: "/surveys/question_add/"+var_survey_id+"/"+var_question_id+"/"+var_position,
               data: "",
               //use ajax callback to remove element from dom
               success: function(returned_data){
                if((returned_data == 'error') || (returned_data.substr(0,7) != "<tr id=")){
                    alert("An error has occurred in communicating with the server. Please try again!");
                }else{
                    $('table#table_' + var_survey_id).append(returned_data);
                    //bind javascript action to the links
                    $(".remove_from_survey").bind("click", function(e){
                        var agree = confirm("Are you sure you want to delete this item?");
                        if(!agree)
                            return false;
                        
                        $(this).parent().parent().remove();
                        return false;
                    });
                    $('.dnd').tableDnDUpdate();
                    $('.ajax_save').text('added.');
                    $('.ajax_save').fadeOut(1000);
                }
               },
               error: function(returned_data){
                   alert("An error has occurred in communicating with the server. Please try again!");
               }
            });    
        }else{
            alert("Question is already selected.");
        }
    
        return false;
    });
    
    $(".remove_from_survey").click(function(){
        $('.ajax_save').text('removing ...');
        $('.ajax_save').show();
        
        var agree = confirm("Are you sure you want to delete this item?\n It will be removed from the survey immediately.");
        if(!agree){return false};
        
        
            
        //get the right variables from the dom
        var_id = $(this).parent().parent().attr("id");
        var_survey_question_id= $(this).attr("survey_question_id");
        var_survey_id= $(this).attr("survey_id");
        
        //send the request
        $.ajax({
           type: "GET",
           url: '/surveys/question_remove/' + var_survey_id + '/' + var_survey_question_id,
           data: "",
           //use ajax callback to remove element from dom
           success: function(returned_data){
            if((returned_data == 'success')){
                $("#" + var_id).remove();
                $('.ajax_save').text('removed.');
                $('.ajax_save').fadeOut(1000);
                return false;
            }else{
                alert("An error has occurred in communicating with the server. Please try again!");
            }
           },
           error: function(returned_data){
               alert("An error has occurred in communicating with the server. Please try again!");
           }
        });   
            
        return false;
    });
    
	//make case insensitive contains
	$.expr[':'].icontains = function(obj, index, meta, stack){
		return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
	};

    //Cool little tag filter
    $('#tag_filter').keyup(function(){
		if($(this).val() != ''){
			var_search_for = $(this).val();
			$('table tr.pool').hide();
			$("td.tag:icontains(" + var_search_for  + ")").parent().show();
		}else{
			$('table tr.question_pool').show();
		}
    });

    //search box on page that lists All Questions
    $('#search_box').keyup(function(){
		if($(this).val() != ''){
			var_search_for = $(this).val();
			$('table tr.question_pool').hide();
			$("td:icontains(" + var_search_for  + ")").parent().show();
		}else{
			$('table tr.question_pool').show();
		}
    });
 });



//updates number of random questions that can be picked from the dropdown box
function update_randomized_dropdown(){
    var_random = $("input:checked.randomize").length;
    var_dropdown_options = $("#randomize").html();
    var_selected_option = $("#randomize option:selected").val(); // get the selected option

    //we want replace the contents on the fly, so the user always has the right options in front of them
    dropdown_options = "<option value=\"\">none</option>\n"
    for (i=1; i<= var_random; i++){
        var_selected = '';
        //some transparent magic to keep our selections saved
        if(i == var_selected_option){var_selected = ' selected ';}
        dropdown_options = dropdown_options + '<option value="'+ i +'"'+ var_selected +'>'+ i +'</option>'+"\n";
    }
    //alert(var_selected_option.val());
    $("#randomize").html(dropdown_options);

}
    
//@Questions create and edit page
//Remove add answer link if the wrong option is selected
function hide_show_add_answer_link(){
    if($('#QuestionQuestionTypeId option:selected').text() != 'Checkbox' &&
    $('#QuestionQuestionTypeId option:selected').text() != 'Radio' &&
    $('#QuestionQuestionTypeId option:selected').text() != 'Dropdown')
    {
        $('#show_answer').hide();
    }else{
        $('#show_answer').show();
    }
}
