/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Andreas Mayer <andreas.mayer@open-xchange.com>
 * 
 */

registerView("infostore_new",null,null,null,null);
register("OX_SAVE_OBJECT", writeNewInfoItem);
register("OX_Cancel_Object", cancelNewInfoItem);

var newInfoJson = new JSON();
var bCreated = false;
var bEditId = -1;
var clickedItem = -1;	
var bDetachFile = false;
var infostore_categories = "";
var treeVisible = false;
var oAttachModule = false;
var configGetKey=corewindow.configGetKey;
var configSetKey=corewindow.configSetKey;
var configContainsKey=corewindow.configContainsKey;
var setEditedFolder = false;
var savePending = false;
var triggerReady = jQuery.noop;
var messageOnCancel = false;
var messageCloseWindow = _("Do you really want to discard your changes and close the window?");

if(url['edit_id'] != -1)
{
	bEditId = {id:url['edit_id'],folder:url['folder']};
}

function infoFormChanged() {
	setBeforeUnload(true);
}

function initInfoStoreCategories() {
	// add click on categories button
	addDOMEvent($("newinfostore_categories_button"), "click", function(e) {
		openInfoStoreCategoriesDialog();
	});
	
	// handle dbl click which attachs an inplace input field to div
	addDOMEvent($("newinfostore_categories_list"), "dblclick", function(e) {
		ox.categories.ui.attachInplaceInput($("newinfostore_categories_list"),
			function(value) {				
				// handle value
				var list = clone(ox.categories.getByString(infostore_categories, ox.categories.match.ALL, true));
				// add only if not empty!
				if (value && trimStr(value).length && !ox.categories.utils.existsInObject(trimStr(value), list)) {
					var category = { name: value, color: 0 };
					list.push(category);
					infostore_categories = ox.categories.utils.paramToString(list, "name");				
				}
				ox.categories.ui.drawCategoriesList(
						ox.categories.getByString(infostore_categories), 
						$("newinfostore_categories_list"));
			}
		);		
	});
}

function openInfoStoreCategoriesDialog() {
	ox.categories.ui.open((infostore_categories || ""), function(list, str) {
		infostore_categories = str;
		ox.categories.ui.drawCategoriesList(ox.categories.getByString(infostore_categories), 
				$("newinfostore_categories_list"));
	});
}

function setBeforeUnload(on){
    messageOnCancel = on;
}

function detachFile()
{
	if(bActive)
	{
		document.forms.newInfoForm2.reset();
	}
	else
	{
		function cbyes() {
			document.forms.newInfoForm2.filedisplay.value = '';
			document.forms.newInfoForm3.document_type.value = '';				
			bDetachFile = true;
		}
		newConfirm(_("Detach file"),_('Are you sure you want to detach the file from current Info Item?\n (all versions of the file will be removed)'),AlertPopup.YESNO,null,null,cbyes);
	}
}

function doAjaxGetInfoItemObject(oId,callback)
{
	var sAjaxRequest = AjaxRoot + "/infostore?action=get&id=" + oId.id + "&session=" + session;
	newInfoJson.get(sAjaxRequest, null,callback)
}
function fn_cb(sPAth) {
	document.getElementById('folder').value = sPAth;
}

function newInfoItemOnLoad() {
    
    // add default theme (should be in browser cache)
    var themeStyle = corewindow.oxThemeStyle || { name: "Default", path: "default" };
    ox.gui.themePath = getFullImgSrc("");
    removeCSSFilesForNewWindow(themeStyle.path);
    
	activemodule="infostore_new";
	initContents(activemodule);
	initInfoStoreCategories();
	initAll();
	
	window.setTimeout(function() {
	
		triggerReady = function () {
		    
		    ox.gui.initToolBarNewWindowInfoStore();
		    
    	    var metaData = {
                module: "infostore",
                activemodule: activemodule,
    	        handle: url.guid,
    	        id: (url.edit_id !== -1) ? url.edit_id : null,
    	        folder_id: (url.folder !== -1) ? url.folder : null,
    	        title: window.document.title
    	    };
    	    
    	    ox.api.window.core.triggerEvent("OX_Window_Ready", metaData, window);
		};
		
		initNewInfoStore();
        
	}, 0);
}
var config;
var oMailInfo = null;
var configGetKey;

function initNewInfoStore() {
	loadingComplete();
	config = corewindow.config;
	configGetKey = corewindow.configGetKey;
	internalCache = corewindow.internalCache;
	session = corewindow.session;	
	url = jQuery.extend((url || {}), ox.api.window.getData(url.guid));
	clickedItem = bEditId.folder || url['folder'];
	
	document.forms.newInfoForm.folder.disabled = true;
	document.forms.newInfoForm3.document_type.disabled = true;		
	
	if (bEditId != -1) {
		initForm(bEditId);
		
	} else {
		var currForm  = document.forms.newInfoForm2;
		currForm.filedisplay.value = url['filename'];
		bEditId.folder = configGetKey("folder.infostore");
		clickedItem = configGetKey("folder.infostore");
		
		// implement api prefill
		populateForm(null, url);
		
		if (url['attachmail'] && url['attachmail'] > 0) {
			oMailInfo = { mailid: url['mailid'], mailfolder: url['mailfolder'], attachmail: url['attachmail'] };
			
		} else if (url['attachmodule'] && url['attid'] > 0 && url['attobjid'] > 0 && url['attobjfolder'] > 0) {
			oAttachModule = { objid: url['attobjid'], objfolder:url['attobjfolder'], 
					attach: url['attid'], module: url['attachmodule'] };
		} else {
			currForm.filedisplay.value = "";
			clickedItem = bEditId.folder || url['folder'];
		}
		
		ox.api.folder.getPathString({
		    folder: clickedItem,
		    success: fn_cb
		});
	    
        // disable loading screen
        $("loading_data_bg").style.display="none";
        
        triggerReady();
	}
	
	// triggerEvent("OX_Configuration_Loaded");
	triggerEvent("OX_Switch_View","infostore_new");
	setTimeout(function () {
		triggerEvent("OX_menu_Change_Height", true);
	}, 0);

}
registerView("infostore_new",
	null,
	function () {
		try {
			setTimeout(function() {	
				    if ($("title")) $("title").focus();	
				}, 50);
		} catch (e) { }	
	},
	null,
	null,
	function () {
		try {
			setTimeout(function() {  
                    if ($("title")) $("title").focus(); 
                }, 50);
		} catch (e) { }
	});

function cancelNewInfoItem() {
	function cbyes() {
	    ctrl.close(true);
	}
	if (messageOnCancel) {
	    newConfirm(_("Close Window"),messageCloseWindow,AlertPopup.YESNO,null,null,cbyes,null);
	} else {
		cbyes();
	}
}

function initForm(sId)
{
	var nTimeStamp;
	var aObjectContent;
	function cb_get_info_o(arg)
	{
		if(arg && arg.error)
		{
			return;
		}
		nTimeStamp = arg.timestamp;
		aObjectContent = arg.data;
		//activate detach button
		if(aObjectContent.filename && aObjectContent.filename.length > 0)
			document.getElementById('but_detach').style.display = 'block';
		populateForm(nTimeStamp,aObjectContent);
		triggerReady();
	}
	doAjaxGetInfoItemObject(sId,cb_get_info_o);
}


var nObjectTimeStamp;
var objectVersion;
function populateForm(nTimeStamp,aObjectContent)
{
	nObjectTimeStamp = nTimeStamp;	
	var currForm  = document.forms.newInfoForm;
	
	// set title
	var title = aObjectContent.title || ""
	currForm.title.value = title;
	document.title = _("InfoItem") + (title ? ": " : "") + title;
	
	currForm.url.value = aObjectContent.url || "";	
	var folder = aObjectContent.folder_id || bEditId.folder || url['folder'] || configGetKey("folder.infostore");	
	ox.api.folder.getPathString({
	    folder: folder,
	    success: fn_cb
	});
	var currForm  = document.forms.newInfoForm2;	
	currForm.filedisplay.value = aObjectContent.filename || "";
	currForm  = document.forms.newInfoForm3;
	currForm.document_type.value = aObjectContent.file_mimetype || "";
	currForm  = document.forms.newInfoForm4;
	if (aObjectContent.categories) {		
		infostore_categories = aObjectContent.categories;
		// old server stores data as array for some reason. If so, we just convert it into a string
		if (Object.prototype.toString.call(infostore_categories) == "[object Array]") {
			infostore_categories = infostore_categories.join(", ");
		}
		// draw list
		if ($("newinfostore_categories_list")) {
			ox.categories.ui.drawCategoriesList(ox.categories.getByString(infostore_categories), 
					$("newinfostore_categories_list"));
		}
	}
	currForm  = document.forms.newInfoForm5;
	currForm.description.value = aObjectContent.description || "";	
	currForm.description.value = aObjectContent.description || ""; //ie7 fix #7577
    objectVersion = aObjectContent.version;
    
    // disable loading screen
    $("loading_data_bg").style.display="none";
}

var bActive = false;
function activateUpload()
{
	//disable dialog if mail attachment will saved
	if(oMailInfo)
		return ;
	if(!bActive)
	{
		document.getElementById('divfu2').style.display = 'none';
		document.getElementById('divfu1').style.display = 'inline';	
		document.getElementById('but_detach').style.display = 'block';					
		bActive = true;
	}
	else
	{
		document.getElementById('divfu1').style.display = 'none';
		document.getElementById('divfu2').style.display = 'inline';			
		bActive = false;
	}
}

function showTreeDialog()
{	
	centerPopupWindow($("TreeDialogNewInfoStore"));
	document.getElementById("TreeDialogNewInfoStore").style.display = "block";
	document.getElementById("TreeDialogNewInfoStore").style.top = "30px";
	document.getElementById("TreeDialogNewInfoStore").style.left = "170px";

	if(!bCreated)
		loadFolderTreeInfo();
}

function hideTree(){
	document.getElementById("TreeDialogNewInfoStore").style.display = "none";	
}

function toggleTreeDialog()
{	
	if(!treeVisible){
		centerPopupWindow($("TreeDialogNewInfoStore"));
		document.getElementById("TreeDialogNewInfoStore").style.display = "block";
		document.getElementById("TreeDialogNewInfoStore").style.top = "30px";
		document.getElementById("TreeDialogNewInfoStore").style.left = "170px";
		treeVisible = true;
		if(!bCreated) 
			{
			loadFolderTreeInfo();
			bCreated = true;
			}
	}
	else {
		document.getElementById("TreeDialogNewInfoStore").style.display = "none";
		treeVisible = false;
	}
}

function folderAction(data)
{
	var setEditedFolder = true;
	hideTree();
	clickedItem = data.id;
	ox.api.folder.getPathString({
	    folder: clickedItem,
	    success: fn_cb
	});
	infoFormChanged();
}


var aContextMenu = new Array();
var aFolderViewSettings = new Object();
var aFolderViewSettingsBM = new Object();
//Disable Email... 
aFolderViewSettings["default"] = 4;
aFolderViewSettingsBM["infostore"] = 8;
var disableOther=true;

function loadFolderTreeInfo()
{
	ox.api.ui.selectFolder({
    	type: "infostore",
    	id: "select-folder-popup-infostore",
    	callback: folderAction,
    	node: $('folder_tree_info')
    });
	bCreated = true;
}


function callback_new(arg) {
	if (arg.error) {
	    setModalBusy(false);
		savePending = false;
		newServerError(arg);
	} else {
		corewindow.OXInfoStoreMapping.createObject(newInfoItemToWrite);
		corewindow.triggerEvent("OX_Quota_Update");
		setTimeout(function () {
		    ctrl.close(true);
		}, 50);
	}
}

function callback_update(arg) {
	if (arg.error) {
        setModalBusy(false);
	    savePending = false;
		newServerError(arg);
	} else {
		corewindow.OXCache.newRequest(null, "infostore", { columns: null,
            objects: [corewindow.OXInfoStoreMapping.createKeyFromObject({
                module: "infostore", folder_id: bEditId.folder,
                id: bEditId.id
            })] }, null, emptyFunction, true);
		if (bEditId.folder != newInfoItemToWrite.folder_id) {
            corewindow.OXCache.newRequest(null, "infostore", { columns: null,
                objects: [corewindow.OXInfoStoreMapping.createKeyFromObject({
                    module: "infostore",
                    folder_id: newInfoItemToWrite.folder_id, id: bEditId.id
                })] }, null, emptyFunction, true);
		}
        corewindow.triggerEvent("OX_Quota_Update");
        setTimeout(function () {
            ctrl.close(true);
        },50);
	}
}

var newInfoItemToWrite;
function writeNewInfoItem() {	
	if(savePending) return;
	else savePending = true;
	
	var currForm  = document.forms.newInfoForm;
	var oObject = new Object();	
	oObject = getFormDataAsObject(currForm,oObject);
	currForm  = document.forms.newInfoForm2;	
	oObject = getFormDataAsObject(currForm,oObject);
	currForm  = document.forms.newInfoForm3;	
	oObject = getFormDataAsObject(currForm,oObject);	
	currForm  = document.forms.newInfoForm5;	
	newInfoItemToWrite = getFormDataAsObject(currForm,oObject);	

	if (infostore_categories.length) {
		oObject.categories = infostore_categories;
	}
	
	if (document.forms.newInfoForm2.file.value.length > 0 || oMailInfo || oAttachModule) {
		displayInputNoticeDialog();
        objectVersion++;
	} else {
		doStoreInfoItem();
        objectVersion = null;
    }
}

function displayInputNoticeDialog()
{
	newInput(_("Version comment"),"",_("Enter your version comment:"),null,			CreatePopup.VERSION,
											OKInputNotice,cancelInputNotice,null,cancelInputNotice,'textarea',NOCommentInput);
	//document.getElementById('inputNoticeDialog').style.display ='block';
}

function closeInputNoticeDialog()
{
	savePending = false;
	//document.getElementById('inputNoticeDialog').style.display ='none';
	CreatePopup.close(); //todo: ask jan, this may isn't the best way to close it ;)
}

function cancelInputNotice()
{
	savePending = false;
	//closeInputNoticeDialog();
}
function NOCommentInput(){
	savePending = false;
	$("create_window_textarea_field").value = "";
	OKInputNotice();
}
function OKInputNotice()
{
	//newInfoItemToWrite['version_comment'] = document.forms.inputNoticeForm.notice.value;
	newInfoItemToWrite['version_comment'] = $("create_window_textarea_field").value;
	closeInputNoticeDialog();	
    doStoreInfoItem();
}
function CancelInputNotice()
{
	savePending = false;
	document.forms.inputNoticeForm.notice.value = "";
    closeInputNoticeDialog();
	doStoreInfoItem();
}

// modal dialog
function setModalBusy (state) {
    if (state === true) {
        ox.api.setModal(true);
        jQuery("#modal-dialog-decorator").addClass("busy");
    } else {
        ox.api.setModal(false);
        jQuery("#modal-dialog-decorator").removeClass("busy");
    }
}

function doStoreInfoItem()
{
	if(oMailInfo || oAttachModule)
	{
		if (!newInfoItemToWrite.folder_id) {
			savePending = false;
			alert(_('Please set valid folder!'));
			return;
		}
		var callback_attach = function (arg) {
			if (arg.error) {
				savePending = false;
				setModalBusy(false);
				newServerError(arg);
			} else {
			    setTimeout(function () {
			        ctrl.close(true);
			    }, 50);
			}
		};
		// save file
		setModalBusy(true);
		if(oAttachModule)
			doAjaxRequestAttachInfoMail(oAttachModule,clickedItem,callback_attach);
		else			
			doAjaxRequestAttachInfoMail(oMailInfo,clickedItem,callback_attach);
	}
	else if(bEditId != -1)
	{
		function cb_detach_files(arg)
		{	
			if(arg && arg.error)
			{
				savePending = false;
				setModalBusy(false);
				newServerError(arg);				
			}
			else
			{
			    setModalBusy(true);
				document.forms.newInfoForm2.action = AjaxRoot + "/infostore?action=update&id="+ bEditId.id +"&timestamp="+arg.timestamp+"&session=" + session;		
				document.forms.newInfoForm2.json.value = JSON.serialize(newInfoItemToWrite);			
				document.forms.newInfoForm2.submit();
			}
		}
		if(bDetachFile)
		{
			bDetachFile = false;
			doAjaxDetachInfoFile(bEditId, nObjectTimeStamp, cb_detach_files);
		}
		else
		{
			var obj = new Object();
			obj['timestamp'] = nObjectTimeStamp;
			cb_detach_files(obj);
		}
	}
	else
	{
	    // delay this, since the Popup-Manager will revoke modal mode too late otherwise
        setModalBusy(true);
        var form = document.forms.newInfoForm2;
        form.action = AjaxRoot + '/infostore?action=new'+"&timestamp="+nObjectTimeStamp+"&session=" + session;
        form.json.value = JSON.serialize(newInfoItemToWrite);		
        form.submit();
	}	
}

function doAjaxDetachInfoFile(oObj, nTimeStamp, callback) {
	var sAjaxRequest = AjaxRoot + "/infostore?action=revert&id="+oObj.id+"&folder="+oObj.folder+"&timestamp="+nTimeStamp+"&session=" + session;
	newInfoJson.get(sAjaxRequest, null,callback);			
}

function doAjaxRequestAttachInfoMail(mailinfo,folder,callback) {
	delete newInfoItemToWrite.filename;	
	var sAjaxRequest;	
	if (mailinfo.mailid != undefined)	{
		sAjaxRequest = AjaxRoot + "/mail?action=attachment"
		      + "&id=" + mailinfo.mailid
		      + "&folder=" + mailinfo.mailfolder 
		      + "&dest_folder=" + folder
		      + "&attachment=" + mailinfo.attachmail
		      + "&session=" + session;
	} else {						
		sAjaxRequest = AjaxRoot + "/infostore?action=saveAs"
		      + "&attached=" + mailinfo.objid
		      + "&folder=" + mailinfo.objfolder
		      + "&attachment=" + mailinfo.attach
		      + "&module=" + mailinfo.module
		      + "&session=" + session;
	}	
	var error = function () {
	    setModalBusy(false);
	};
	newInfoJson.put(sAjaxRequest, newInfoItemToWrite, null, callback, error);
}

/*
function doAjaxRequestCreateNewInfo(newInfoItem,callback)
{
	var sAjaxRequest = AjaxRoot + "/infostore?action=new&session=" + session;
	newInfoJson.put(sAjaxRequest, newInfoItem, null,callback);		
}
*/
function getFormDataAsObject(currForm,oParamObj)  
{
	for(var nIndex=0;nIndex < currForm.elements.length;nIndex++)
	{
		var currElement = currForm.elements[nIndex];
		var aTMP = currElement.id.split('_');
		var sId = currElement.id;
		//disable buttons, folderpath;
		if(aTMP[0] == 'but' || sId == 'folderpath' || sId == 'document_type'
							|| sId == 'displfile' || sId == 'json' || sId == 'file' || sId == 'cancelNewAppointmentTreeButton')
			continue;	
		var sValue = currElement.value;
		if(sId == 'folder')
		{
			sId = 'folder_id';
			// please check the conditions! if you uncomment this, you can't move
			// the object to any other folder at the new window as it's always true!?
			//if(clickedItem == -1 || (!setEditedFolder && bEditId != -1))
			//	continue;
			sValue = clickedItem;
		}
		if(sId == 'filepath')
		{
			sId = 'filename';	
			sValue = separateFilenameFromPath(sValue);
		}		
		if(sValue && sValue.length == 0)
			continue;
		oParamObj[sId] = sValue;	
	}
	return oParamObj;
}

// init window controller

var ctrl = windowController = new WindowController();

ctrl.set("beforeunload", function () {
    if (messageOnCancel) {
        return messageCloseWindow + "";
    }
});