$(document).ready(initEip);

var BRRE = BRRE || /<br>/ig;

function initEip() {
    $('.editable').each(function() { makeEditable(this); });
}

function makeEditable(n) {  
    $(n).hover(function() { $(this).addClass('editable-hover'); }, 
               function() { $(this).removeClass('editable-hover'); });
    $(n).click( function () { eipEdit(this); } );
}

function eipEdit(n) {
    // Hide the object itself
    $(n).hide();

    // Insert an editor component
    editorHTML = getEditorHTML(n);
    $(n).after(editorHTML);

    // Watch the save and edit buttons
    var editorId = n.id+'_editor';
    $('#'+editorId+'_save').click( function() { eipSave(n, editorId); });
    $('#'+editorId+'_cancel').click( function() { eipCancel(n, editorId); });
    
    // Watch for a return keypress
    if($(n).is('.eip_line')) {
	$('#'+editorId+'_f').keyup(function(evt) { if(evt.keyCode == 13) { eipSave(n, editorId); } } );
    }

    // Focus the editor field
    $('#'+editorId+'_f').focus();
}

function disableButtons(editorId,disable) {
    if (disable) {
	$('#'+editorId+'_save').attr('disabled','disabled');
	$('#'+editorId+'_cancel').attr('disabled','disabled');
    }
    else {
	$('#'+editorId+'_save').removeAttr('disabled');
	$('#'+editorId+'_cancel').removeAttr('disabled');
    }
}

function eipSave(n, editorId) {
    disableButtons(editorId,1);
    var fieldId = editorId+'_f';
    var newValue = richtext_fetch_text(fieldId);
    var propName = getPropName(editorId);
    var nid = getNid(n.id);
    var uid = null;

    var reload = 0;

    if ($(n).hasClass('checkConfirmed')) {
	if (propName == 'sharing') {
	    var re = /_request$/;
	    if(re.test(newValue)) {
		var userid=n.userid;
		if (!confirmSharingRequest(nid,userid,newValue)) { 
		    disableButtons(editorId,0);
		    return; 
		}
		else {
		    $(document.body).css("cursor","wait");
		}
	    }
	}
    }
    // Remove the richtext editor if it exists
    richtext_remove(editorId+'_f');

    if(!nid && $('#uid').length)
	var uid = $('#uid').html();

    // Put in a progress indicator to show that we are doing something
    $('#'+editorId+'_f').after('<img id="' + editorId + 
			       '_throbber" src="/images/eip_throbber.gif"/>');

    var url = settings['base_path']+'eip';

    var pars = {};
    pars[propName] = newValue;
    if(nid)
	pars['id'] = nid;
    else
	pars['uid'] = uid;

    $.ajax({
	url: url,
	type: 'POST',
	dataType: 'json',
	data: pars,
	success: eipCompleteJson
    });
}

function eipCompleteJson(rsp) {
    if ("1" == rsp.object.reload) { window.location.reload(true); }
    // Handle errors
    var errors = rsp.errors;
    if(errors.length > 0) {
	for(var i = 0; i < errors.length; i++) {
	    var prop_name = errors[i].field;
	    $('#'+prop_name+'_editor_throbber').remove();
	    var ed_name = prop_name + '_editor';
	    var sel_string = '#' + ed_name + ' > .form_error';
	    if ($(sel_string).length > 0) {
		$(sel_string).html(errors[i].error);
	    }
	    else {
		errorDiv = '<div id="error" class="form_error">'
		    + errors[i].error + '</div>';
		$('#'+prop_name+'_editor_f').after(errorDiv);
	    }
	    disableButtons(ed_name,0);
	    return;
	}
    }

    // Update the values of changed properties
    var object = rsp.object;
    $.each(object.properties, function(prop_name, prop_value) {
	if(object.type == 'node')
	    prop_name += '-'+object.id;
	var ed = $('#'+prop_name+'_editor');
	var sd = $('#'+prop_name+'_sel_div');
	if(sd.length) {
	    // Special handling for eip_select types
	    $('#'+prop_name+'_editor_buttons').remove();
	    $('#'+prop_name+'_editor_throbber').remove();
	    sd.html(ed.html());
	    ed.remove();
	    var sel = $('#'+prop_name+'_editor_f').get(0);
	    var opts = sel.options;
	    for(var i = 0; i < opts.length; i++) {
		var val = opts[i].value;
		if(val == prop_value) {
		    sel.selectedIndex = i;
		    var newVal = $(opts[i]).html();
		    var classes = $(opts[i]).attr('class');
		    if(classes) 
			newVal = '<span class="'+classes+'">'+newVal+'</span>';
		    $('#'+prop_name).html(newVal);
		} 
	    }
	} else {
	    $('#'+prop_name).html(prop_value);
	    ed.remove();
	}

	$('#'+prop_name).show().removeClass('editable-hover');    
    });
}

function eipCancel(n, editorId) {
    disableButtons(editorId,1);
    var ed = $('#'+editorId);

    // Remove richtext editor if it exists
    richtext_remove(editorId+'_f');
    
    // Special handling for eip_select types
    var sd = $('#'+n.id+'_sel_div');
    if(sd.length) {
	$('#'+n.id+'_editor_buttons').remove();
	sd.html(ed.html());
    }
    
    ed.remove();
    $(n).show().removeClass('editable-hover');
}

/* 
 * Attempt to parse a numeric object ID from the given id string,
 * otherwise fallback onto #nid or #uid.
 */
function getNid(id) {
    var nid = null;
    if(/\-[0-9]+$/.test(id)) 
	nid = id.replace(/(.*)(\-)([0-9]+)$/, '$3');
    else if($('#nid').length)
	nid = $('#nid').html();
    return nid;
}

/*
 * Get the property name based on the editor ID 
 */
function getPropName(editorId) {
    var propName = editorId.replace(/_editor$/, '');
    var re = /-\d+$/;
    if(re.test(propName)) 
	propName = propName.replace(re, '');
    return propName;
}

/*
 * Fetch the current value of the given field prior to rendering into HTML
 */
function fetchOldText(field, id, type) {
    return url;
}

function getEditorHTML(n) {
    // Fetch the original text of this field from the server
    var oldText = breakTagsToNewlines($(n).html());
    if($(n).is('.eip_text')) 
	oldText = 'Loading...';
    oldText = jQuery.trim(oldText);

    var editorId = n.id+'_editor';
    var outHTML = '<div id="'+editorId+'">';
    if($(n).is('.eip_line')) {
	outHTML += '<input type="text" style="width: 300px;" id="'+editorId+
	    '_f" value="'+oldText+'"/>';
    } else if($(n).is('.eip_text')) {
	var editorFieldId = editorId+'_f';
	outHTML += '<textarea id="'+editorFieldId+
	    '" style="width: 90%; height: 200px">'+oldText+'</textarea>';
	outHTML += '<div>Switch to <a href="#" id="'+editorFieldId+
	    '_toggle">richtext</a></div>';
    } else if($(n).is('.eip_desc')) {
	var editorFieldId = editorId+'_f';
	outHTML += '<textarea id="'+editorFieldId+
	    '" style="width: 300px; height: 2.5em">'+oldText+'</textarea>';
    } else if($(n).is('.eip_select')) {
	// There is already a select for us to use, so grab it
	var sel_div = $('#'+n.id+'_sel_div');
	outHTML += sel_div.html();
	sel_div.html('');
    }

    outHTML += '<div id="'+editorId+'_buttons">';
    outHTML += '  <input id="'+editorId+'_save" type="button" value="Save"/>';
    outHTML += '  <input id="'+editorId+
	'_cancel" type="button" value="Cancel"/>';
    outHTML += '</div>';
    outHTML += '</div>';

    if($(n).is('.eip_text') || $(n).is('.eip_desc')) {
	var propName = getPropName(n.id);
	var id = getNid(n.id);
	var type = 'node';
	if(!getNid(n.id)) {
	    id = $('#uid').html();
	    type = 'user';
	}
	var path = 'eip/fetch/'+type+'/'+id+'/'+propName;
	var url = settings['base_path']+path;
	$.get(url, {}, function(data) { 
	    var mode = settings['text_edit_mode'];
	    var toggle = $('#'+editorId+'_f_toggle');
	    var newlineData = breakTagsToNewlines(data);
	    $('#'+editorId+'_f').val(newlineData); 
	    toggle.click(function() { return toggle_richtext(this); });
	    if(mode == 'richtext') 
		toggle_richtext(toggle.get(0));
	});    
    }
    return outHTML;
}

function confirmSharingRequest(nid,userid,newLevel) {
    var levelDescription;
    switch(newLevel) {
    case "peers_request": levelDescription="Public"; break;
    case "node_request":  levelDescription="Node members only"; break;
    case "none_request":  levelDescription="Project members only"; break;
    default : break;
    }
    var msg = "Click OK to request that the sharing level be changed to \"" + 
	levelDescription + "\".";
    return confirm(msg);
}

function breakTagsToNewlines(text) {
    return text.replace(BRRE, "\n");
}

