/* ========================================================================== */
/* 
This file is not 'finished' and contains experimental code.
It currently has support for 'inline' editing (the editsomething functions) as 
well as panel-based editing (the peditsomething functions).
It needs to be determined later which one of these edit types will make it or 
works in the end.

Translations are now in the translations.js file and in the idw.translations 
namespace. 
*/
/* ========================================================================== */

idw.inplaceedit = {};
idw.inplaceedit.additional_parameters = {};
idw.inplaceedit.history = 99;
idw.inplaceedit.pendingUpdates = {};
idw.inplaceedit.last_preview = '';
idw.inplaceedit.panels = {};
idw.inplaceedit.tooltips = {};
idw.inplaceedit.invitation_elements = {};
idw.inplaceedit.saved_elements = {};
idw.inplaceedit.saved_elements_original = {};
idw.inplaceedit.saved_elements_new = {};


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// New stuff after refactoring
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* Color the background of a text field when the user reaches certain string 
length limits. Also display the number of characters for this field. */
idw.inplaceedit.check_field_length = function(field_id, notarea_id, lower_limit, upper_limit, max_limit)
{
    strlen = document.getElementById(field_id).value.length;

    if (strlen<lower_limit)
        {
        color = "";
        }
    else if (strlen<upper_limit)
        {
        color = "#FFFF80";
        }
    else if (strlen<max_limit)
        {
        color = "#FF8040";
        }
    else
        {
        color = "#FF0000";
        }
    document.getElementById(field_id).style.backgroundColor = color;
    document.getElementById(notarea_id).innerHTML = strlen;
};

idw.inplaceedit.isEmpty = function(ob){
   for(var i in ob){ return false;}
  return true;
}

/*
Add a text to a document and retrieve a preview.
When the answer is received, then the get_preview_callback is called to 
process the answer.
*/
idw.inplaceedit.add_document = function(document_type)
{
    var ud_dict = {
        'lang': idw.lang,
        'additional_parameters': idw.inplaceedit.additional_parameters
        };

    $.post("/objects/"+document_type+"/add_document", JSON.stringify(ud_dict), idw.inplaceedit.datahandlercallback,
        "json");
};

/*
Add a text to a document and retrieve a preview.
When the answer is received, then the get_preview_callback is called to 
process the answer.
*/
idw.inplaceedit.add_text = function(document_type, document_id, lang_id)
{
    var ud_dict = {
        'document_id': document_id,
        'lang_id': lang_id,
        'lang': idw.lang,
        'additional_parameters': idw.inplaceedit.additional_parameters
        };

    $.post("/objects/"+document_type+"/add_text", JSON.stringify(ud_dict), idw.inplaceedit.datahandlercallback, "json");
};

/*
Delete a text to a document and retrieve a preview.
When the answer is received, then the get_preview_callback is called to 
process the answer.
*/
idw.inplaceedit.del_text = function(document_type, document_id, lang_id)
{
    var ud_dict = {
        'document_id': document_id,
        'lang_id': lang_id,
        'lang': idw.lang,
        'additional_parameters': idw.inplaceedit.additional_parameters
        };

    $.post("/objects/"+document_type+"/del_text", JSON.stringify(ud_dict), idw.inplaceedit.datahandlercallback, "json");
};

/* 
Panel callback 
This is hooked to the click event of the DIVs of the preview.

Open a overlay panel and load the edit field in it.
*/
idw.inplaceedit.peditcallback = function()
{
    if (this.id[0]=='#')
        {
        /* This is an action div, so no panel is required. */
        /* this dictionary is the data for the RPC-style request and is transmitted 
           to the server in JSON encoding */
        var ud_dict = {
            'name': this.id,
            'value': this.id,
            'lang': idw.lang
            };
        /* send the request and hook the callback to get_form_field_callback_p */
        $.post("/objects/"+ idw.inplaceedit.document_type +"/process_action", JSON.stringify(ud_dict), idw.inplaceedit.datahandlercallback,
            "json");
        }
    else
        {
        /* this dictionary is the data for the RPC-style request and is transmitted 
           to the server in JSON encoding */
        var ud_dict = {
            'name': this.id,
            'value': this.id,
            'lang': idw.lang
            };
        /* send the request and hook the callback to get_form_field_callback_p */
        $.post("/objects/"+ idw.inplaceedit.document_type +"/get_form_field", JSON.stringify(ud_dict), idw.inplaceedit.datahandlercallback,
            "json");
        }
};


/* Update the value of a field on the server when the user changes the value.
Read the value (depending on the type of the field) and transmit it to the 
server.
*/
idw.inplaceedit.update_field_value = function(field_id, field_name, obj_type, lang)
{ 
    inpelem = document.getElementById(field_id);
    /* Checkboxes and radiobuttons need a special type of handling. */
    if (inpelem.type=='checkbox')
        {
        var values = [];
        var nodename = inpelem.name;
        var namednodes = document.getElementsByName(nodename);

        for (var i = 0; i<namednodes.length; i++)
            {
            if (namednodes[i].type=='checkbox')
                {
                if (namednodes[i].checked)
                    {
                    values.push(namednodes[i].value);
                    }
                }
            }
        var ivalue = values;
        }
    else if (inpelem.type=='radio')
        {
        var ivalue = [];
        var nodename = inpelem.name;
        var namednodes = document.getElementsByName(nodename);
        for (var i = 0; i<namednodes.length; i++)
            {
            if (namednodes[i].type=='radio')
                {
                if (namednodes[i].checked)
                    {
                    ivalue = [namednodes[i].value];
                    }
                }
            }
        }
    else
        {
        /* All other types of field can be just asked for their value. */
        var ivalue = inpelem.value;
        };
    var ud_dict = {
        'name': field_name,
        'value': ivalue,
        'lang': lang,
        'additional_parameters': idw.inplaceedit.additional_parameters
        };
  	if ('lang_id' in idw.inplaceedit)
      	{
      	    ud_dict['lang_id'] = idw.inplaceedit.lang_id;
      	};
//    if (!idw.inplaceedit.pendingUpdates[field_name]) {
		idw.inplaceedit.pendingUpdates[field_name] = field_name;

		$.post("/objects/" + obj_type + "/update_field_data", JSON.stringify(ud_dict), idw.inplaceedit.datahandlercallback, "json");
//	}
};


/* 
Process errors for a document. 
*/
idw.inplaceedit.display_doc_errors = function(data)
{
    var tr = idw.translations.inplaceedit.messages[idw.lang];
    var m;
    var pr_parts = [];
    pr_parts.push('<div style="background-color:#C0C0C0; padding:5px;">');
    if ('validationerrors_texts' in data)
        {
        if (idw.inplaceedit.document_type == 'press_release')
            {
                m = tr.prl_errors;
            }
        else if (idw.inplaceedit.document_type == 'event')
            {
                m = tr.evl_errors;
            }
        else
            {
                m = tr.something_errors;
            };
        pr_parts.push('<div>' + m + '</div>');
        for (t in data.validationerrors_texts)
            {
            pr_parts.push('<div style="color:#A5051E;">'+data.validationerrors_texts[t]+'</div>')
            };
        }
    else
        {
        if (idw.inplaceedit.document_type == 'press_release')
            {
                m = tr.prl_ready;
            }
        else if (idw.inplaceedit.document_type == 'event')
            {
                m = tr.evl_ready;
            }
        else
            {
                m = tr.something_ready;
            };
        pr_parts.push('<div style="color:#047539;">' + m +'</div>');
        };
    pr_parts.push('</div>');
    $("#document_error_container").html(pr_parts.join('\n'));
};

idw.inplaceedit.display_intro = function()
{
    $("#document_intro_container").html(idw.translations.inplaceedit.messages[idw.lang].intro);
};


idw.inplaceedit.display_editnote = function()
{
    $("#document_editnote_container").html(idw.translations.inplaceedit.messages[idw.lang].editnote);
};


idw.inplaceedit.init_file_uploaders_cb = function()
{
    new AjaxUpload(this.id, {'action': '/objects/upload_file',  
                             'data': {'id': this.id, 
                                      'document_type':  idw.inplaceedit.document_type}, 
                             'name': this.id, 
                             });
};

idw.inplaceedit.init_image_uploaders_cb = function()
{
    new AjaxUpload(this.id, {'action': '/objects/upload_image',  
                             'data': {'id': this.id, 
                                      'document_type':  idw.inplaceedit.document_type}, 
                             'name': this.id,
                             'onSubmit' : function(file , ext){
                                            if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext))){
                                                    // extension is not allowed
                                                    alert('Error: invalid file extension');
                                                    // cancel upload
                                                    return false;
                                            }}
                    });
};

idw.inplaceedit.init_uploaders = function()
{  // http://valums.com/ajax-upload/
    $('.iePrAtAttachment').each(idw.inplaceedit.init_file_uploaders_cb);
    $('.iePrImImage').each(idw.inplaceedit.init_image_uploaders_cb);
    $('.ieEvAttachment').each(idw.inplaceedit.init_file_uploaders_cb);
};


/* 
Process a preview for a document. 
*/
idw.inplaceedit.display_preview = function(data)
{
    //$('<div id="newtt" />').text("Hugo").insertAfter("#document_preview_container");
    // Put the HTML snippet returned by the server into the container
    $("#document_preview_container").html(data);
    // set up the 'active' actions of that element
    $("#document_preview_container [name='doc_elem_p']").click(idw.inplaceedit.peditcallback);

idw.inplaceedit.init_uploaders();

};

//   each(function()
//    {
////        if (this.id in idw.inplaceedit.tooltips)
////            {
////            /* re-initialize the existing tooltip */
////            idw.inplaceedit.tooltips[this.id].init("tt"+this.id, {
////                context: this.id,
////                xyoffset: [5, 5],
////                autodismissdelay: 1000000,
////                text: idw.translations.inplaceedit.messages[idw.lang].editinvitation
////                });
////            }
////        else
////            {
////            idw.inplaceedit.tooltips[this.id] = new YAHOO.widget.Tooltip("tt"+this.id, {
////                context: this.id,
////                xyoffset: [5, 5],
////                autodismissdelay: 1000000,
////                text: idw.translations.inplaceedit.messages[idw.lang].editinvitation
////                });
////            };
//    /* The following 'click' hooks the peditcallback to the click event. */
//    })

/*
Retrieve a preview for a certain document (press release).
When the answer is received, then the get_preview_callback is called to 
process the answer.
*/
idw.inplaceedit.get_preview = function(document_type, document_id, lang_id)
{
    var ud_dict = {
        'document_id': document_id,
        'lang_id': lang_id,
        'lang': idw.lang
        };

    $.post("/objects/"+document_type+"/get_single_preview", JSON.stringify(ud_dict),
        idw.inplaceedit.datahandlercallback, "json");
};


/*
Display a list of press releases that this user can edit
*/
idw.inplaceedit.display_list_of_editable_documents = function(data)
{
    // save the previously active accordion position
    var oldindex = $("#accordion h3").index($("#accordion h3.ui-state-active"));
    var documents = data;
    var doc_type = idw.inplaceedit.document_type;
    var pr_html = [];
    pr_html.push('<div id="accordion">');

    for (var pr_id in documents)
        {
        var pr_parts = [];
        var pr = documents[pr_id];
        pr_parts.push('<h3><a href="#">'+idw.translations.inplaceedit.messages[idw.lang][doc_type + '_nr']+pr_id
            +"</a></h3>");
        pr_parts.push('<div class="editablePrList">');
//        pr_parts.push('<div>')
//        pr_parts.push('<div style="display:inline">'+idw.translations.inplaceedit.messages[idw.lang].pressrelease_texts
//            +'</div>');
//        pr_parts.push('</div>')
        /* List of the language versions */
        for (var l in pr.langs)
            {
            pr_l = pr.langs[l];

            if (pr_l.lang_id!=0)
                { // The additional language variants get a prefix and then the title
                lang_variant_string = idw.translations.inplaceedit.messages[idw.lang].text_lang_number+pr_l.lang_id
                    +': ';
                }
            else
                { // The title alone is used for the first text variant
                lang_variant_string = '';
                };

            if (pr_l.title!=null)
                { // If the title is set, use it
                title_string = pr_l.title;
                }
            else
                { // otherwise display a text that states that the title isn't set
                title_string = idw.translations.inplaceedit.messages[idw.lang].no_title_set;
                };
            pr_parts.push('<div>');
            pr_parts.push(
                '<div class="editablePrText Link" style="display:inline" onclick="idw.inplaceedit.get_preview(\''+idw.inplaceedit.document_type+'\', '
                +pr_id+', '+l+');">'+lang_variant_string+title_string+'</div>')

            if (pr_l.lang_id!=0) // Delete link only can be used for additional language versions
                {
                pr_parts.push(
                    '<div class="editablePrText Link" style="display:inline" onclick="idw.inplaceedit.del_text(\''+idw.inplaceedit.document_type+'\', '
                    +pr_id+', '+l+');">['+idw.translations.inplaceedit.messages[idw.lang].del_text+']</div>');
                }
            pr_parts.push('</div>');
            };
        /* New lang variant */
        pr_parts.push(
            '<div class="editablePrText" onclick="idw.inplaceedit.add_text(\''+idw.inplaceedit.document_type+'\', '
            +pr_id+', \'new\');">['+idw.translations.inplaceedit.messages[idw.lang].new_text+']</div>')
        pr_parts.push("</div>");
        pr_html.push(pr_parts.join('\n'))
        };
    /* New press release */
    pr_html.push('<h3><a href="#">'+idw.translations.inplaceedit.messages[idw.lang]['new_' + doc_type]+"</a></h3>");
    pr_html.push('<div class="editablePrList">');
    pr_html.push('<div class="editablePrText" onclick="idw.inplaceedit.add_document(\''+idw.inplaceedit.document_type+'\');">['
        +idw.translations.inplaceedit.messages[idw.lang]['new_' + doc_type]+']</div>')
    pr_html.push("</div>");
    pr_html.push("</div>");
    // Set the content of the container that holds the list
    $("#document_list_container").html(pr_html.join("\n"));
    // initialize the accordion
    $("#accordion").accordion({
        'fillSpace': true,
        'collapsible': true
        });

    // restore the previously active accordion position
    if (oldindex
        >0) //Yes, 0. It should be >-1 but the first item is opened by default and activate on an active item deactivates it.
        {
        $("#accordion").accordion('activate', oldindex);
        };
};

/*
Takes the form field code sent by the server and puts it in the prepared panel. 
The "OK" is also added to close the panel.
The form fields are expected to auto-submit their data on change (or similar event).
*/
idw.inplaceedit.display_form_field = function(data)
{
    var name = data.name;
    var htmldata = data.form_field;
    var myid = name.replace(/@/g, "\\@");
    if ($("#helppanel_"+myid).length==0)
        { // create new panel
        var buttonobjecth = {};
        buttonobjecth[idw.translations.inplaceedit.messages[idw.lang].formfieldpanelokbutton] =  function()
            {
                $(this).dialog('close');
            };
        $("#"+myid).before('<div id="helppanel_'+name+'">'+data.help_text+'</div>');
        $("#helppanel_"+myid).dialog({
            'autoOpen': false,
            'width': 'auto',
            'minHeight': 20,
            'minWidth': 400,
            'buttons': buttonobjecth,
            'title': idw.translations.inplaceedit.messages[idw.lang].formfieldhelppaneltitle_pre + data.field_name + idw.translations.inplaceedit.messages[idw.lang].formfieldhelppaneltitle_post
            });
        }
    else
        {
        $("#helppanel_"+myid).html(data.help_text).dialog('open');
        };

    if ($("#panel_"+myid).length==0)
        { // create new panel
        $("#"+myid).before('<div id="panel_'+name+'">'+htmldata+'</div>');
        var buttonobjectp = {};
        buttonobjectp[idw.translations.inplaceedit.messages[idw.lang].formfieldpanelokbutton] =  function()
                    {
                    $(this).dialog('close');
                    };
        buttonobjectp[idw.translations.inplaceedit.messages[idw.lang].formfieldpanelhelpbutton] = function()
                    {
                        $("#helppanel_"+myid).dialog('open');
                    };
        $("#panel_"+myid).dialog({
            width: 'auto',
            minHeight: 20,
            minWidth: 20,
            buttons: buttonobjectp,
            title: idw.translations.inplaceedit.messages[idw.lang].formfieldpaneltitle_pre + data.field_name + idw.translations.inplaceedit.messages[idw.lang].formfieldpaneltitle_post
            });
        }
    else
        {
        $("#panel_"+myid).html(htmldata).dialog('open');
        };
};

idw.inplaceedit.update_form_field_errormessage = function(data)
{
    /* Get the error message area for the field */
    var em_area = document.getElementById("form_errormessage_"+data['name']);
    if (em_area)
    if ('errortext' in data)
        {
        em_area.innerHTML = data['errortext'];
        em_area.style.display = 'block';
        }
    else
        {
        em_area.innerHTML = '';
        em_area.style.display = 'none';
        }
};


/* 
Handle the returned data from the server

This is stateless in that the place the data is put is determined by the data, not
the function that is used. This way the server can determine what is written for 
different requests. In some cases it can reduce the ammount of data that needs updating
by only updating data that changed. For example we don't need to update the list of
documents if that list didn't change.
*/
idw.inplaceedit.datahandlercallback = function(data_in, status, xmlrequest)
{
    var data = data_in['data'];
    
    //alert(JSON.stringify(data));
    /* hand the press release list data on to the appropriate function */
    if ('errors' in data)
        {
            if (window.console)
            {
                console.error(data.errors);
            }
        };
    if ('document_type' in data)
        {
        idw.inplaceedit.document_type = data.document_type;
        };
    if ('doc_list' in data)
        {
        idw.inplaceedit.display_list_of_editable_documents(data.doc_list);
        };

    if ('preview' in data)
        {
        idw.inplaceedit.display_preview(data.preview);
        idw.inplaceedit.display_editnote();
        };

    if ('preview_key' in data)
        {
        idw.inplaceedit.last_preview = data.preview_key;
        }
    if ('lang_id' in data)
        {
        idw.inplaceedit.lang_id = data.lang_id;
        }
    if ('doc_errors' in data)
        {
        idw.inplaceedit.display_doc_errors(data.doc_errors);
        };

    if ('form_field' in data)
        {
        idw.inplaceedit.display_form_field(data.form_field);
        };

    if ('form_field_errormessage' in data)
        {
        idw.inplaceedit.update_form_field_errormessage(data.form_field_errormessage);
		if ('errortext' in data.form_field_errormessage) {
			idw.inplaceedit.pendingUpdates[data.form_field_errormessage.name] = data.form_field_errormessage.errortext;
		}
		else {
			delete idw.inplaceedit.pendingUpdates[data.form_field_errormessage.name]
		}
        }
    if ("subscription_filter" in idw) 
        {
			
		if ($.inArray(idw.subscription_filter.curStep, idw.subscription_filter.history) ==-1) 
		{
			$(".SForm_error").css('background-color', 'inherit');
			idw.subscription_filter.history.push(idw.subscription_filter.curStep);
		}	
		else	
		{
			$(".SForm_error").css('color', 'red');
		}
		
		if (typeof(idw.subscription_filter.refresh!="undefined"))
		    {
		        if (idw.subscription_filter.refresh)
		            {
                        idw.subscription_filter.updateProgress();
                    };
            };
        };
    //idw.subscription_filter.updateProgress();
};


/* 
This function is used for debugging to help get an idea why a POST request failed.
Current main suspect is Opera 10.5b which may have some JS issues.
*/
idw.inplaceedit.ParseError = function(a, b, c)
{
    if (window.console)
    {
        console.error('ParseError' + a.responseText);
    }
};


idw.inplaceedit.reload_preview = function()
{
    var pw_re_obj = /^@p(\d+)-@l(\d+)-preview$/;
    result = idw.inplaceedit.last_preview.match(pw_re_obj);
    if (result != null)
        {
        idw.inplaceedit.get_preview(idw.inplaceedit.document_type, result[1], result[2]);
        }
};

idw.inplaceedit.init = function()
{
// save the history length
idw.inplaceedit.history  = history.length;

    $.ajaxSetup({
        timeout: 10000,
        error: idw.inplaceedit.ParseError
        });

};

$(document).ready(idw.inplaceedit.init)


