var benchmarkFormID = "checkPlanForm";
var benchmarkingWrapper = "benchmarkingWrapper";

var toolControllers = new Array();
toolControllers[0] = "includes/modules/tools/controllers/fn-dynamicBenchmarkingTool.php";
toolControllers[2] = "/includes/modules/tools/controllers/fn-benchmarkFlexible.php";
toolControllers[3] = "/includes/modules/tools/controllers/fn-dynamicBenchmarkingTool.php";
toolControllers[4] = "/includes/modules/tools/controllers/fn-feeBenchmarkingTool.php";
var current = "#step-1";
var next = 1;
var queryStr ="";
/** 
 * Jon Waterbury
 * 5/28/2011
 */
function registerEvent(type, title){
    var kindOfAction = type;
    //var labelText = $(id).innerHTML + " - [" + podID + "]";
    var labelText = title
    
    if (typeof(pageTracker) != "object") {
        _gaq.push(['_trackEvent', "Comparision Tool", kindOfAction, labelText]);
    }else{
        //alert("HELLO");
        pageTracker._trackEvent("Comparison Tool", kindOfAction, labelText);
    } 
}


function account_type_change(value){
    var showPassword = value == "guestAccount" ? "hide" : "show";
    showHideDivs("field_password", showPassword);
}
function guest_submit(benchmarkTypeID){
    var queryStr = $("#continueGuest").serialize();
    if(benchmarkTypeID == 2){
        tools_callbacks.exec_pre_flip();
        base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=intro&formAction=save&" + queryStr,"tools_post_page_flip();");
    }
    else if(benchmarkTypeID == 3 || benchmarkTypeID == 4){
        tools_callbacks.exec_pre_flip();
        base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=intro&formAction=save&" + queryStr,"evaluate_js(response);tools_post_page_flip();");
    }
}
/**
 *  Register Form 
 ***/
function register_form_submit(benchmarkTypeID){
    var queryStr = $("#" + benchmarkFormID).serialize();

    base_ajax("", "/includes/modules/tools/controllers/validateFlexible.php", queryStr, "register_form_response(response," + benchmarkTypeID + ");");
}
function profile_form_update(){
        var form = $("#update-profile-form");
        var queryStr = $(form).serialize();
        
        $.post('/includes/modules/tools/controllers/fn-dynamicBenchmarkingTool.php?update=profile&'+queryStr, function(data){
           if(data.result){
               document.location.href=window.document.location;
           }else{
               alert(data.msg);
           }
        
        }, "json");
        //base_ajax("", "/includes/modules/tools/controllers/validateFlexible.php", queryStr, "profile_form_response(response," + benchmarkTypeID + ");");       
}
function toggleUpdateProfile(){
    $("#profile-display").toggle();
    $("#update-profile").toggle();
}

function register_form_response(response, benchmarkTypeID){    	
    var errorObj = jQuery.parseJSON(response);
    if(errorObj.errors.length > 0){
        show_form_errors($("#" + benchmarkFormID), errorObj);
    }
    else if(response.indexOf("{\"errors\"") > -1){
        // show the questions
        var queryStr = $("#" + benchmarkFormID).serialize();
        if(benchmarkTypeID==0){
            //alert("no benchmark set naviagte to login.php");
            tools_callbacks.exec_pre_flip();
            base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=register-login&formAction=register&" + queryStr, "evaluate_js(response);tools_post_page_flip();");
        }
        if(benchmarkTypeID == 2){
            tools_callbacks.exec_pre_flip();
            base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=intro&formAction=register&" + queryStr,"tools_post_page_flip();");
        }
        else if(benchmarkTypeID == 3 || benchmarkTypeID == 4){
            tools_callbacks.exec_pre_flip();
            base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=intro&formAction=register&" + queryStr,"evaluate_js(response);tools_post_page_flip();");
        }
    }
    else{
        alert("Form did not validate");
    }
}
/**
 * Step 1: Intro Form Submit
 **/
function intro_form_submit(benchmarkTypeID){
    var queryStr = $("#" + benchmarkFormID).serialize();
    base_ajax("", "/includes/modules/tools/controllers/validateFlexible.php", "formAction=intro&" + queryStr, "intro_form_submit_response(response," + benchmarkTypeID + ");");
}
function intro_form_submit_response(response, benchmarkTypeID){
    // alert(response);
    var errorObj = jQuery.parseJSON(response);
    //alert("after Json");
	
    //alert(Json.toString(errorObj));
    // if there are errors
    if(errorObj.errors.length > 0){
        show_form_errors($("#" + benchmarkFormID), errorObj);
    }
    else if(response.indexOf("{\"errors\"") > -1){
        // show the questions
        var queryStr = $("#" + benchmarkFormID).serialize();
        if(benchmarkTypeID == 2){
            tools_callbacks.exec_pre_flip();
            base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=showQuestions&formAction=save&" + queryStr,"tools_post_page_flip();");
        }
        else if(benchmarkTypeID == 3 || benchmarkTypeID == 4){
            tools_callbacks.exec_pre_flip();
            base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], "mode=pickQuestions&formAction=save&" + queryStr,"evaluate_js(response);tools_post_page_flip();");
        }
    }
    else{
        alert("Form did not validate");
    }
}
/**
 * STEP 2 -- Pick Questions
 *
 **/
function validate_question_picker(benchmarkTypeID){
    var selQuestions=  new Array();
    $("#selectedQuestions ul.selectedQuestions  > li").each(function(index) {
        selQuestions.push($(this).attr("qid"));
                
    });
    var value = selQuestions.length > 0 ? selQuestions.join(",") : "0";
    $("#userSelectedQuestions").val(value);
    // var temp = $("#userSelectedQuestions").val();
    $("#questionPickerContinue").html("Submitting questions, please wait...");
    $("#questionPickerContinue").attr("disabled", "disabled");
    if(value == "" || value == "0"){
        $("#questionPickerContinue").html("Continue");
        $("#questionPickerContinue").attr("disabled", "");
        alert("Please choose at least one question before continuing. ");
    }else{
        base_ajax(benchmarkingWrapper, toolControllers[benchmarkTypeID], $("#questionPickerForm").serialize());
    }
}

function questions_form_step(form_id, next_id){
    var form = $("#" + form_id);
    queryStr = $(form).serialize();
    $(form).find("#continueButton").attr("disabled","disabled");
    $(form).find("#continueButton").val("Submitting questions, please wait...");
    base_ajax("", "/includes/modules/tools/controllers/validateFlexible.php", "formAction=questions&" + queryStr, "validate_step(response);");
    next = next_id;
}
function goFormBack(cat_current){
    next = cat_current;
    var back = cat_current-1;
    //$("#continueButton").val("Continue");
    $('div.category-questions.current').removeClass('current');
    $("div#step-"+ back).addClass("current");
    var button = $("div#step-"+ back).find("#continueButton");
    $(button).val("Continue");
}
function hide_form_errors(div){
    $("#questionsErrorMessage").html("");
    $("#questionsErrorMessage").removeClass("warning");
    $("#questionsErrorMessage").css("display","none");
    //alert($(div).html());
    $(div).find("ol li.warning").each(function(){
           
        $(this).removeClass("warning");
    });
        
        
}

function validate_step(response){
    var errorObj = jQuery.parseJSON(response);
    //alert(errorObj.errors.length);
    // if there are errors
   
    if(errorObj.errors.length > 0){
        registerEvent('Generate Report', 'Error');
        $('.category-questions.current').find("#continueButton").attr("disabled","");
        $('.category-questions.current').find("#continueButton").val("Continue");
		
        $("#questionsErrorMessage").html("Please fill in all of the questions to continue. The questions marked in red are missing or incorrect.");
        $("#questionsErrorMessage").addClass("warning");
        $("#questionsErrorMessage").css("display","block");
		
        show_form_errors($("#" + benchmarkFormID), errorObj);
        window.location.href= "#topOfQuestions";
    }
    else if(response.indexOf("{\"errors\"") > -1){
        // @TODO  need to remove after next page
        // Save and and show the next set of questions
        if(next > -1){
            $("#continueButton").val("Continue");
            $('.category-questions.current').find("#continueButton").attr("disabled","");
            hide_form_errors($('div.category-questions.current'));
            $('div.category-questions.current').removeClass('current');
            
            // alert(next);
            base_ajax("", toolControllers[$("#benchmarkType").val()], "mode=results&formAction=save&" + queryStr + "&formFinished=0");
            $("div#step-"+ next).addClass("current");
        }else{
            registerEvent('Generate Report', 'Success');
            var qString = "";
            $(".category-form").each(function(index){
                qString = qString + $(this).serialize();
                
            });
            
            tools_callbacks.exec_pre_flip();
            base_ajax(benchmarkingWrapper, toolControllers[$("#benchmarkType").val()], "mode=results&formAction=save&" + qString + "&formFinished=1","tools_post_page_flip();", "alert('bomb')");
        }
    /** var queryStr = $("#" + benchmarkFormID).serialize();
        tools_callbacks.exec_pre_flip();
        base_ajax(benchmarkingWrapper, toolControllers[$("#benchmarkType").val()], "mode=results&formAction=save&" + queryStr,"tools_post_page_flip();", "alert('bomb')"); **/
    }
    else{
        alert("Form did not validate");
    }
        
}
function questions_form_submit(){
    var queryStr = $("#" + benchmarkFormID).serialize();
    //alert(queryStr);
    $("#continueButton").attr("disabled","disabled");
    $("#continueButton").val("Submitting questions, please wait...");
	
    base_ajax("", "/includes/modules/tools/controllers/validateFlexible.php", "formAction=questions&" + queryStr, "questions_form_submit_response(response);");
}

function questions_form_submit_response(response){
    //alert(response);
    var errorObj = jQuery.parseJSON(response);
    //alert(errorObj.errors.length);
    // if there are errors
    if(errorObj.errors.length > 0){
        registerEvent('Generate Report', 'Error');
        $("#continueButton").attr("disabled","");
        $("#continueButton").val("Continue");
		
        $("#questionsErrorMessage").html("Please fill in all of the questions to continue. The questions marked in red are missing or incorrect.");
        $("#questionsErrorMessage").addClass("warning");
        $("#questionsErrorMessage").css("display","block");
		
        show_form_errors($("#" + benchmarkFormID), errorObj);
        window.location.href= "#topOfQuestions";
    }
    else if(response.indexOf("{\"errors\"") > -1){
        registerEvent('Generate Report', 'Success');
        // show the questions
        var queryStr = $("#" + benchmarkFormID).serialize();
        tools_callbacks.exec_pre_flip();
        base_ajax(benchmarkingWrapper, toolControllers[$("#benchmarkType").val()], "mode=results&formAction=save&" + queryStr,"tools_post_page_flip();", "alert('bomb')");
    }
    else{
        alert("Form did not validate");
    }
}

function remove_benchmark(bid, tid) {
    $('#advisorBenchmarkList').remove("#b" + bid);
    var testing = $("li#b" + bid);
    $(testing).remove();
    if($('#advisorBenchmarkList').children().length == 0)
        showHideDivs('benchMessage', 'show');
	
    base_ajax("", toolControllers[tid], "mode=remove&benchID=" + bid + "&tid=" + tid);
}

function switch_to_benchmark_page(step, benchID, benchmarkType){
    tools_callbacks.exec_pre_flip();
    base_ajax(benchmarkingWrapper, toolControllers[benchmarkType], "nextStep=" + step + "&benchID=" + benchID + "&referringPage=" + window.location.href, "evaluate_js(response);tools_post_page_flip();");
}

function tools_post_page_flip() {
    window.location.href='#top';
    window.scrollTo(1,0);
	
    if (window.flip_submits != undefined) {
        flip_submits();
    }
    tools_callbacks.exec_post_flip();
}

function tools_generate_pdf(benchID, benchmarkType) {
	
    if(benchmarkType == 2){
        var lText = "Generating report ... please wait.";
        var formString = $("#input").serialize();
        var extraString = "&=" + formString;
    }else{
       
        var lText = "Generating report ... please wait.";
        if(benchmarkType == 3){
            lText += " Depending on number of questions chosen, this may take several minutes.";
        }
        var extraString = "";
    }
	
    $('#status').html("<img src='/includes/modules/tools/images/loader.gif' alt='Loading' />&nbsp;&nbsp; <span style='color:#234879'>" + lText + "</span>");
	
    base_ajax(benchmarkingWrapper, toolControllers[benchmarkType], "mode=pdfLink&formFinished=1&benchID=" + benchID + extraString);
}

function upload_customization_form_submit(){
  
    var value = location.href;
    document.getElementById("currentPage").value = value;
    document.getElementById("customReportInputForm").submit();
}

function test_debugging(text){
//alert(text);
}

function array_find(ar, value){
    for(var i = 0; i < ar.length; i++){
        if(ar[i] == value){
            return i;
        }
    }
    return -1;
}

function check_field_rules(field){
    //alert(questionRules.length);
    for(var i = 0; i < questionRules.length; i++){
        if(questionRules[i]["field"] == field){
            var fieldValue = $("#" + field).val();
            test_debugging(field + "-" + fieldValue);
            // see if the value is one of the answers of the field rules list
            if(array_find(questionRules[i]["answers"],fieldValue) > -1){
                test_debugging("value found");
                // show the sub questions
                //alert("number of sub questions is '" + questionRules[i]["subQuestions"].length + "'");
                for(var j = 0; j < questionRules[i]["subQuestions"].length; j++){
                    $("#field_" + questionRules[i]["subQuestions"][j]).css("display","block");
                }
            }else{ // the field value does not appear in the field rules list
                test_debugging("value NOT found");
                // hide the sub questions
                for(var j = 0; j < questionRules[i]["subQuestions"].length; j++){
                    $("#field_" + questionRules[i]["subQuestions"][j]).css("display","none");
                    var elem =  $("#" + questionRules[i]["subQuestions"][j]);
                    $("#" + questionRules[i]["subQuestions"][j]).val("");
                    // also hide any of the sub question's sub question's
                    for(var k = 0; k < questionRules.length; k++){
                        if(questionRules[k]["field"] == questionRules[i]["subQuestions"][j]){
                            for(var l = 0; l < questionRules[k]["subQuestions"].length; l++){
                                $("#field_" + questionRules[k]["subQuestions"][l]).css("display","none");
                                $("#" + questionRules[i]["subQuestions"][j]).val("");
                            }
                        }
                    }
                }
            }
        }
    }
}
function commentsChanged(){
    if(document.getElementById("commentsType").value==1){
        document.getElementById("commentsTextArea").innerHTML='<textarea name="advisorInput" style="height: 150px; width: 100%;"></TEXTAREA>'
    }else{
        if(document.getElementById("commentsType").value==2){
            document.getElementById("commentsTextArea").innerHTML="<div>A blank input page will be provided for you.</div>"
        }else{
            document.getElementById("commentsTextArea").innerHTML="<div>There will not be an input page provided.</div>"
        }
    }
}

function questions_form_submitTEST(){
    var queryStr = $("#" + benchmarkFormID).serialize();
    //say_hi();
    base_ajax("", "/includes/modules/tools/controllers/validateFlexible.php", "formAction=questions&" + queryStr, "questions_form_submit_responseTEST(response);");
}

function questions_form_submit_responseTEST(response){
    //alert(response);
    var errorObj = jQuery.parseJSON(response);
	
    // if there are errors
    if(errorObj.errors.length > 0){
        $("#questionsErrorMessage").html("Please fill in all of the questions to continue. The questions marked in red are missing or incorrect.");
        $("#questionsErrorMessage").addClass("warning");
        $("#questionsErrorMessage").css("display","block");
		
        show_form_errors($("#" + benchmarkFormID), errorObj);
        window.location.href= "#topOfQuestions";
    }
    else if(response.indexOf("{\"errors\"") > -1){
        // show the questions
        var queryStr = $("#" + benchmarkFormID).serialize();
		
        base_ajax(benchmarkingWrapper, toolControllers[$("#benchmarkType").val()], "mode=results&formAction=save&" + queryStr,"window.location.href='#top';");
    }
    else{
        alert("Form did not validate");
    }
}

var tools_callbacks = {
    'pre_flip_callbacks': [],
    'add_pre_flip_callback': function(cb) {
        tools_callbacks.pre_flip_callbacks.push(cb);
    },
    'post_flip_callbacks': [],
    'add_post_flip_callback': function(cb) {
        tools_callbacks.post_flip_callbacks.push(cb);
    },
    'exec_pre_flip': function() {
        jQuery.each(tools_callbacks.pre_flip_callbacks,function(cb) {
            cb.apply();
        });
    },
    'exec_post_flip': function() {
        jQuery.each(tools_callbacks.post_flip_callbacks,function(cb) {
            cb.apply();
        });
    }
};
