/**
 * ajax-process.js
 *
 * $Id: ajax-processor.js 262 2010-07-17 23:35:58Z zpatz $
 * $URL: https://www.toofast.ca/svn/toofast/trunk/ajax-processor.js $
 *
 *  jQuery form functions to complement ajax-process.php
 *
 */

var AJAX_PROCESSOR = "ajax-processor.php";

/**
 * updateQuestions
 *
 *  Update questions from specified survey
 *
 */
function updateQuestions() {

    // Serialize question form
    var params = $( "form#questions" ).serialize();
    // Serialize and append session form
    params += "&" + $( "form#session" ).serialize();
    // Append the serialized question sort
    params += "&" + $( "#questionSort" ).sortable( "serialize" );
    // Append function name
    params += "&func=updateQuestions";

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }
                // Display message and link
                var returnMsg = $( "output", data ).text();
                var htmlContent = "<h1>Thank you for modifying your questions.</h1>\n" +
                    "<h4>" + returnMsg + "</h4>\n" +
                    "<input type=\"button\" name=\"submit\" value=\"Survey Options\" " +
                    "onClick=\"HttpRequestSurveyControl(" + $( ":input[name='LoginID']" ).val() + "," + $( ":input[name='SurveyID']" ).val() + ");\">";
                $( "#rightContent" ).html( htmlContent );
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * listSurveyPass
 *
 *  List survey passwords from a specified LoginID
 */
function listSurveyPass( loginID ) {

    // Serialize the session form
    var params = $( "form#session" ).serialize();
    // Append LoginID and SurveyID
    params += "&LoginID=" + loginID;
    // Append function name
    params += "&func=getAuth";

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }
                // Load the listsurveypass.php page
                $( "#rightContent" ).load( "listsurveypass.php", params );
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * getResultsByDateForm
 *
 *  Load the results by date form.
 */
function getResultsByDateForm( surveyID, page ) {

    // Serialize the session form
    var params = $( "form#session" ).serialize();
    // Add the SurveyID to the params
    params += "&SurveyID=" + surveyID;
    // Append function name
    params += "&func=getAuth";

   if (page == "normal")
    {
      var prebetween = "prebetween.php";
    }
   else if (page == "pdf")
    {
      var prebetween = "prebetween_pdf.php";
    }
   else
    {
      var prebetween = "prebetween.php";
    }

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }
                // Load the prebetween.php page
                $( "#rightContent" ).load( prebetween, params, function() {
                    $( "#firstdate" ).datepicker( {
                        maxDate: 'now',
                        showButtonPanel: true,
                        changeMonth: true,
                        changeYear: true
                    });
                    $( "#lastdate" ).datepicker( {
                        maxDate: 'now',
                        showButtonPanel: true,
                        changeMonth: true,
                        changeYear: true
                    });
                });
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * getQuestions
 *
 *  Retrieve the questions from a specified survey
 */
function getQuestions( loginID, surveyID, addQuestion ) {

    // Serialize the session form
    var params = $( "form#session" ).serialize();
    // Append LoginID and SurveyID
    params += "&LoginID=" + loginID + "&SurveyID=" + surveyID;
    // Add question
    params = addQuestion == true ? params + "&addone=1" : params;
    // Append function name
    params += "&func=getAuth";

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }
                // Load the addormodifyquestions.php page
                $( "#rightContent" ).load( "addormodifyquestions.php", params, function() {
                    $( "#questionSort" ).sortable( { 
                        placeholder: "ui-sortable-placeholder", 
                        update: function( e, ui ) {
                             // position = $(e.target).children().index(ui.item);
                             // $(ui.item).children("index").html(position);
                        }
                    });
                    // Initialize thickbox links
                    tb_init( "a.thickbox" );                
                });
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * saveQuestion
 *
 *  Save a single question from the "Edit" link
 */
function saveQuestion() {

    // Serialize the question
    var params = $( "form#singleQuestion" ).serialize();
    // Serialize the session form
    params += "&" + $( "form#session" ).serialize();
    // Add the function
    params += "&func=saveQuestion";

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }
                // Display message and close thickbox
                var questionID = $( "form#singleQuestion #questionID" ).val();
                var questionText = $( "form#singleQuestion #Question" ).val();
                $( "#qtext" + questionID ).text( questionText.ellipsis( 40 ) );
                $( "#qtext" + questionID ).attr( "title", questionText );
                tb_remove();
                var returnMsg = $( "output", data ).text();
                ajaxMessage( returnMsg, 6000 );
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * removeQuestion
 *
 *  Remove a single question from the database.
 */
function removeQuestion( questionID ) {

    // Change the question background to stand out
    $( "#questionOrder_" + questionID ).addClass( "selectedQuestion" );
    var answer = confirm( "Confirm question removal?" );

    if( !answer ) {
        $( "#questionOrder_" + questionID ).removeClass( "selectedQuestion" );
        return false;
    }

    // Specifiy the questionID to remove
    var params = "questionID=" + questionID;
    // Serialize the session form
    params += "&" + $( "form#session" ).serialize();
    // Add the function
    params += "&func=removeQuestion";

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }

                // Update the questionCount
                var questionCount = $( "form#questions :input[name='questionCount']" );
                var newCount = $( questionCount ).val() > 0 ? $( questionCount ).val() - 1 : 0;
                $( questionCount ).val( newCount );

                // Remove the question and display message
                var returnMsg = $( "output", data ).text();
                $( "#questionOrder_" + questionID ).remove();
                ajaxMessage( returnMsg, 6000 );
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * cloneSurvey
 *
 *  Clone a question set from an exising survey.
 */
function cloneSurvey( fromID, toID ) {

    // Send the from surveyID and to surveyID
    var params = "fromID=" + fromID + "&toID=" + toID;
    // Serialize and append session form
    params += "&" + $( "form#session" ).serialize();
    // Append function name
    params += "&func=cloneSurvey";

    $.post( AJAX_PROCESSOR, params,
        function( data, textStatus ) {
            if( $( "retval", data ).text() == "0" ) {
                var sesskey = $( "sesskey", data ).text();
                // Update with a new sesskey
                if( sesskey.length > 0 ) {
                    $( "form#session :input[name='sesskey']" ).val( sesskey );
                }

                // Load the addormodifyquestions.php page for the new survey
                var loginID = $( "form#howmanyquestions :input[name='LoginID']" ).val();
                params = $( "form#session" ).serialize();
                params += "&LoginID=" + loginID + "&SurveyID=" + toID;
                $( "#rightContent" ).load( "addormodifyquestions.php", params, function() {
                    $( "#questionSort" ).sortable( { 
                        placeholder: "ui-sortable-placeholder", 
                        update: function( e, ui ) {
                             // position = $(e.target).children().index(ui.item);
                             // $(ui.item).children("index").html(position);
                        }
                    });
                    tb_init( "a.thickbox" );

                    // Show message
                    var returnMsg = $( "output", data ).text();
                    ajaxMessage( returnMsg, 6000 );
                });
            } else {
                // Session timed out or something else went wrong
                alert( $( "retmsg", data ).text() );
                //redirectURL( "logout.php" );
            }
    }, "xml" );
}


/**
 * ajaxMessage
 *
 *  Display a message in the statusMessage DIV tag for specified
 *  milliseconds
 */
function ajaxMessage( msgTxt, timeout ) {

    var statusMessage = $( "#statusMessage:not(:visible)" );

    if( statusMessage.length > 0 ) {
        $( "#statusMessage" )
            .text( msgTxt )
            .fadeIn( "medium" )
            .animate( { opacity: 1.0 }, timeout )
            .fadeOut( "medium" );
    } else {
        $( "#statusMessage")
            .stop( true )
            .fadeOut( "fast", function() {
                ajaxMessage( msgTxt, timeout );
            });
    }
}


/**
 * redirectURL
 *
 *  Redirect a user to the specified page.
 */
function redirectURL( url ) {

    window.location.href = url;
}


/**
 * String prototype to truncate text and add ellipsis
 */
String.prototype.ellipsis = function( length ) {
    var tmpStr = this.toString();
    if( tmpStr.length > length )
    {
        tmpStr = tmpStr.substring( 0, length ) + "...";
    }
    return tmpStr;
}
