﻿// Globals

// Constants
var ALTERNATE_INDEX_ROOT_FORM = -1;  // alternateIndex == -1 when the root form of a word is used


function deserializePoem( jsonText )
{
    g_poem = eval ( "(" + jsonText.replace(/\n/g, "\\n") + ")" );

    if ( !g_poem.poemStyle ) g_poem.poemStyle = "dragdrop";
    g_poem.freestyleTop = 10;
    g_poem.freestyleLeft = 10;
}

// typeAndWordsJSON should contain the wordsInPoem and poemStyle objects in JSON without the surrounding curly braces
function serializePoem_common( typeAndWordsJSON, textPoem, divWithPoemFields, leftPixel, topPixel )
{
    var numberOfRatings = $( "divNumberOfRatings" ).innerHTML;
    if ( numberOfRatings > 0 )
    {
        if (!confirm( "Do you want to remove the ratings on this PicLit?\n\n" + 
            ( numberOfRatings > 1 ? numberOfRatings + " people have" : "One person has" ) +
            " rated this PicLit, but saving a new version of the PicLit means we'll discard any ratings."))
        {
            return false;
        }
    }
    
    // add other elements
    var structuredPoem = "{ " + typeAndWordsJSON + ", \"textPoem\": \"" + textPoem.JSONEncode() + "\", ";
    
    structuredPoem += "\"alternates\": {  ";
    for ( var alternateIndex in g_poem.alternates )
    {
        structuredPoem += "\"" + alternateIndex + "\": " + stringArrayToJSON( g_poem.alternates[alternateIndex] ) + ", ";
    }
    structuredPoem = structuredPoem.substring( 0, structuredPoem.length - 2 ) + " }, ";

    for ( var i = 0 ; i < PARTS_OF_SPEECH.length; i++ )
    {    
        structuredPoem += "\"" + PARTS_OF_SPEECH[i] + "\": " + stringArrayToJSON( g_poem[PARTS_OF_SPEECH[i]] ) + ", ";
    }
    
    structuredPoem += "\"poemTemplateId\": " + g_poem.poemTemplateId + ", ";
    structuredPoem += "\"fontFamily\": \"" + g_poem.fontFamily + "\", ";
    structuredPoem += "\"textColor\": \"" + g_poem.textColor + "\" }";

    var inputTagsToPopulate = divWithPoemFields.getElementsByTagName( "input" );
    inputTagsToPopulate[0].value = g_poem.poemTemplateId;
    inputTagsToPopulate[1].value = textPoem;
    inputTagsToPopulate[2].value = structuredPoem;
    inputTagsToPopulate[3].value = document.getElementById( "divPoemId" ).innerHTML;
    // field [4] is numberOfRatings, provided by server
    inputTagsToPopulate[5].value = leftPixel;
    inputTagsToPopulate[6].value = topPixel;

    return true;
}
