// Displays message and shedules it deletion after
function DisplayStatusMessage(msg, isError, leave)
{
    jQuery("#StatusDiv").html(msg).css("color", isError ? "red" : "green" );

    // Clear old timeout interval, if any
    if (gClearStatusInterval != null)
    {
        clearTimeout(gClearStatusInterval);
    }
    if(!leave)
    {
        // Schedule clear of message
        gClearStatusInterval = setTimeout(function() { jQuery("#StatusDiv").html(""); }, 1000 * 10);
    }
}

// Sends remarks form (w/o file)
function OnPostFaqClicked()
{
    // TODO: validation of input

    if (gIsRemarksSent && gIsFileUploaded)
    {
        PostPhotoInformation('');
        return;
    }

    if (gIsRemarksSent)
    {
        DisplayStatusMessage(gMsg.FaqIsSent, true);
        return;
    }

    if (gIsAjaxFinished && ValidateFaqForm())
    {
        gIsAjaxFinished = false;
        jQuery.ajax({
            url: "/help/help/uploadquestion"
                , data: (jQuery('#question_upload_form').serialize())
                , type: "POST"
                , cache: false
                , dataType: "json"
                , success: function(data) { OnPostFaqSuccess(data); }
                , error: function() { OnPostFaqFailed(); }
        });
    }
}

// Remarks was sent OK, so upload file if any
function OnPostFaqSuccess(data)
{
    //alert("Remarks is saved, ID: " + data["question_id"]);

    // Destroy FAQ inpput form and load content
    jQuery("#FormDiv").html(gMsg.FaqIsSentUploadPhoto);
    DisplayStatusMessage(gMsg.FaqIsSent);

    // Mark that remarks were sent and OK
    gIsAjaxFinished = true;
    gIsRemarksSent = true;
    gSwfUploadSettings.post_params = { "faq_id": data["question_id"] };
    gSwfUpload = new SWFUpload(gSwfUploadSettings);

}

// Remarks failed, do not upload file
function OnPostFaqFailed()
{
    // Remarks were not sent
    gIsAjaxFinished = true;
    gIsRemarksSent = false;
    //alert("Remarks failed!");
    DisplayStatusMessage(gMsg.FaqSendingError, true);
}

function ValidateFaqForm()
{
    var isOk = true;

    if (jQuery("#RemarkText").val().length < 2)
    {
        //jQuery("#StatusDiv").html(gMsg.FaqLengthTooShort).css("color", "red");
        DisplayStatusMessage(gMsg.FaqLengthTooShort, true);
        isOk = false;
    }

    return isOk;
}

function ValidatePhotoForm()
{
    var isOk = true;

    if (jQuery("#PhotoName").val().length < 2 )
    {
        //jQuery("#StatusDiv").html(gMsg.FaqLengthTooShort).css("color", "red");
        DisplayStatusMessage(gMsg.PhotoNameIsTooShort, true);
        isOk = false;
    }

    return isOk;
}

// Posts photo information, such as name
function PostPhotoInformation()
{
    if (gIsAjaxFinished && ValidatePhotoForm())
    {
        gIsAjaxFinished = false;
        jQuery.ajax({
            url: "/help/help/postphotoinfo"
                , data: "name=" + jQuery("#PhotoName").val()+"&id="+jQuery("#photo_id").val()
                , type: "POST"
                , success: function(data) { OnPostPhotoInformationSuccess(data); }
                , error: function() { OnPostPhotoInformationFailed(); }
        });
    }
}

// Information about photo is sent, form is completed
function OnPostPhotoInformationSuccess(data)
{
    // TODO: Close FAQ form (?)

    gIsAjaxFinished = true;
    jQuery("#PhotoPreviewDiv").html("");
    jQuery("#buttonSubmitSwfUpload").html("");
    DisplayStatusMessage(gMsg.FaqIsSentCompletely, false, true);

    //jQuery("#FileDiv").html(gMsg.PhotoInformationIsSent).css("color", "green");
}

function OnPostPhotoInformationFailed()
{
    gIsAjaxFinished = true;
    DisplayStatusMessage(gMsg.PhotoInformationError, true);
    //alert("Error saving photo info!");
    //jQuery("#FileDiv").html(gMsg.PhotoInformationError).css("color", "red");
}

function LoadFaqPhotoPreview(jsonArr)
{
    if (gIsAjaxFinished)
    {
        gIsAjaxFinished = false;
        jQuery.ajax({
            url: "/help/help/previewphoto"
                , type: "POST"
                , data: ({ 'jsonArr': jsonArr })
                , dataType: "html"
                , success: function(data) { OnLoadFaqPhotoPreviewSuccess(data); }
                , error: function() { OnLoadFaqPhotoPreviewFailed(); }
        });
    }
}

// Preview of photo w/ editable text is loaded
function OnLoadFaqPhotoPreviewSuccess(data)
{
    gIsAjaxFinished = true;
    DisplayStatusMessage(gMsg.PhotoPreviewIsLoaded);
    jQuery("#PhotoPreviewDiv").html(data).show();
}

function OnLoadFaqPhotoPreviewFailed()
{
    gIsAjaxFinished = true;
    DisplayStatusMessage(gMsg.PhotoPreviewLoadError, false);
}

/*
* SWF upload handlers
*/

// Called when file dialog is closed
function OnFileDialogCompleted()
{
    // Send only when remarks is saved
    if (gIsRemarksSent)
    {
        //alert("Starting file upload...");
        gSwfUpload.startUpload();
    }
}

// File(s) upload is  failed
function OnFileUploadFailed()
{
    //alert("Error uploading file!");
    DisplayStatusMessage(gMsg.PhotoUploadError, true);
    gIsFileUploaded = false;
}

// File(s) upload is OK
function OnFileUploadSuccess(file, serverData)
{
    // serverData could be any string, even JSON
    //alert("File is uploaded! " + serverData);

    // Destroy SWF upload form and message from FAQ form
    jQuery("#FileDiv").html("");
    jQuery("#FormDiv").html("");
    DisplayStatusMessage(gMsg.PhotoIsUploaded);
    gIsFileUploaded = true;

    // Load preview of photo w/ form
    LoadFaqPhotoPreview(serverData);
}

// File(s) upload is finished
function OnFileUploadComplete()
{
}

/*
*   End SWF handlers
*/
function resetStatusUploading()
{
    gIsAjaxFinished = true;
    /*
    *   Kind of state machine, just for readability :)
    */
    // Whether remarks were send OK.
    gIsRemarksSent = false;
    gIsFileUploaded = false;
    gSwfUpload = null;
}
//////////////////////// for answer
//Sends remarks form (w/o file)
function OnPostAnsverClicked()
{
    // TODO: validation of input

    if (gIsRemarksSent && gIsFileUploaded)
    {
        PostPhotoInformation();
        return;
    }

    if (gIsRemarksSent)
    {
        DisplayStatusMessage(gMsg.FaqIsSent, true);
        return;
    }

    if (gIsAjaxFinished)
    {
        gSwfUpload = null;
        gIsAjaxFinished = false;
        jQuery.ajax({
            url: "/help/help/uploadanswer"
                , data: (jQuery('#answer_upload_form').serialize())
                , type: "POST"
                , cache: false
                , dataType: "json"
                , success: function(data) { OnPostAnswerSuccess(data); }
                , error: function() { OnPostFaqFailed(); }
        });
    }
}

function OnPostAnswerSuccess(data)
{
    jQuery("#FormDiv").html(gMsg.FaqIsSentUploadPhoto);
    DisplayStatusMessage(gMsg.FaqIsSent);

    // Mark that remarks were sent and OK
    gIsAjaxFinished = true;
    gIsRemarksSent = true;
    gSwfUploadSettings.post_params = { "answer_id": data["question_id"] };
    gSwfUpload = new SWFUpload(gSwfUploadSettings);
}
