/**
 * 
 * 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 Suphi Basdemir <suphi.basdemir@open-xchange.com>
 * 
 */
 
registerView("contact_new",
	function() {
	 	register("OX_Picture_Add",myNewContactFunctions.addPicutre);
	 	register("OX_Picture_Remove",myNewContactFunctions.deletePicture);
	 	var menu = new ContextMenu();
        var item = new MenuItem(_("Add"),
            function() { triggerEvent('OX_Picture_Add'); });
        item.setIcon("img/menu/add_picture.gif", "img/menu/add_picture_d.gif");
        menu.addItem(item);
        item = new MenuItem(_("Remove"),
            function() { triggerEvent('OX_Picture_Remove'); });
        item.setIcon("img/menu/remove_picture.gif",
                     "img/menu/remove_picture_d.gif");
        menu.addItem(item);
        addDOMEvent($("imageContactTd"), "contextmenu", function(e) {
            menu.display(e.clientX, e.clientY);
        });
        //#. The address format for input fields.
        //#. 
        //#. DO NOT TRANSLATE THE FIELD NAMES!
        //#. 
        //#. Only change the order.
        //#. Comma (,) separates lines, slash (/) separates fields in a line.
        var def = String(_("street,postal_code/city,country,state")).split(",");
        for (var i = 0; i < def.length; i++) def[i] = def[i].split("/");
        reorderFields(16, "_business");
        reorderFields(60, "_other");
        function getField(name) { return document.getElementsByName(name)[0]; }
        function getTR(name) { return getField(name).parentNode.parentNode; }
        function reorderFields(tabIndex, suffix) {
            var lineNames = ["street", "postal_code", "country", "state"];
            var trs = [];
            for (var i = 0; i < lineNames.length; i++) {
                trs.push(getTR(lineNames[i] + suffix));
            }
            var labels = { street: _("Street"), postal_code: _("ZIP"),
                city: _("City"), country: _("Country"), state: _("State") };
            for (var i = 0; i < def.length; i++) {
                var tr = trs[i];
                var label = [];
                var td = tr.getElementsByTagName("td")[1];
                removeChildNodes(td);
                for (var j = 0; j < def[i].length; j++) {
                    label.push(expectI18n(labels[def[i][j]]));
                    if (j) td.appendChild(newtext("\xa0"));
                    td.appendChild(newnode("input", 0, {
                        type: "text",
                        name: def[i][j] + suffix,
                        className: def[i].length == 1 ? "leftLong" :
                                   def[i][j] == "postal_code" ? "leftZip" :
                                   "leftShort",
                        onkeydown: "editContact(this)",
                        tabIndex: tabIndex++
                    }));
                }
                tr.getElementsByTagName("td")[0].firstChild.data =
                    label.join(" / ");
            }
        }
        // fill newly added fields
        if (url.module == "new") {
            fillFields(url);
            autofillDN();
        }
        if (configGetKey("language") == "ja_JP") {
            getTR("yomiFirstName").style.display = "";
            getTR("yomiLastName").style.display = "";
            getTR("yomiCompany").style.display = "";
            watchKana("first_name", "yomiFirstName");
            watchKana("last_name", "yomiLastName");
            watchKana("company", "yomiCompany");
            jQuery("#furigana").click(editFurigana);
        }
        function watchKana(name, yomiName) {
            var interval;
            var field = getField(name);
            jQuery(field).focus(function() {
                interval = setInterval(intervalHandler, 10);
            }).blur(function() {
                if (interval !== undefined) {
                    clearInterval(interval);
                    interval = undefined;
                }
            });
            var lastValue = field.value;
            var yomiField = getField(yomiName);
            function intervalHandler() {
                var value = field.value;
                if (value == lastValue) return;
                lastValue = value;
                var kana = [];
                for (var i = 0; i < value.length; i++) {
                    var c = value.charCodeAt(i);
                    
                    // Convert Hiragana to Katakana
                    if (c >= 0x3041 && c <= 0x309e) c += 0x60;
                    
                    // Copy only Katakana (and Hiragana "yori")
                    if (   c >= 0x309f && c <= 0x30ff  // Katakana
                        || c >= 0x31f0 && c <= 0x31ff  // Katakana phonetic extensions
                        || c >= 0xff61 && c <= 0xff9f) // halfwidth Katakana
                    {
                        kana.push(c);
                    }
                }
                var newYomi = String.fromCharCode.apply(String, kana);
                if (newYomi.length == value.length) yomiField.value = newYomi;
            }
        }
        function editFurigana() {
            var table = jQuery(
                '<table style="width: 20em"><tbody>' +
                    '<tr>' +
                        '<td></td>' +
                        '<td>' +
                            '<input type="text" disabled="disabled"></input>' +
                        '</td>' +
                    '</tr><tr>' +
                        '<td></td>' +
                        '<td><input type="text"></input></td>' +
                    '</tr><tr>' +
                        '<td></td>' +
                        '<td>' +
                            '<input type="text" disabled="disabled"></input>' +
                        '</td>' +
                    '</tr><tr>' +
                        '<td></td>' +
                        '<td><input type="text"></input></td>' +
                    '</tr><tr>' +
                        '<td></td>' +
                        '<td>' +
                            '<input type="text" disabled="disabled"></input>' +
                        '</td>' +
                    '</tr><tr>' +
                        '<td></td>' +
                        '<td><input type="text"></input></td>' +
                    '</tr>' +
                '</tbody></table>');
            var tds = table.find("td");
            tds[0].appendChild(newtext(String(_("Last name"))));
            tds[4].appendChild(newtext(String(_("First name"))));
            tds[8].appendChild(newtext(String(_("Company"))));
            var inputs = table.find("input");
            inputs[0].value = getField("last_name").value;
            inputs[1].value = getField("yomiLastName").value;
            inputs[2].value = getField("first_name").value;
            inputs[3].value = getField("yomiFirstName").value;
            inputs[4].value = getField("company").value;
            inputs[5].value = getField("yomiCompany").value;
            newConfirm(String(_("Edit Furigana")), null, AlertPopup.OK +
                AlertPopup.CANCEL, ok, 0, 0, 0, 0, 0, 0, 0, 0, table[0]);
            setTimeout(function() { inputs[1].focus(); }, 0);
            function ok() {
                getField("yomiLastName").value = inputs[1].value;
                getField("yomiFirstName").value = inputs[3].value;
                getField("yomiCompany").value = inputs[5].value;
            }
        }
	},
	null, 
	null,
	null
);

registerView("contact_new/business",
	function() { 
		$("tabContact1").style.display="block";
		$("panelContact1").className="tabPanelFirstHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
	},
    function() {
        try {
            setTimeout(function() {
                if ($("last_name")) $("last_name").focus();
            },0);
        } catch (e) {
            
        }
    }, 
    null,
	function() {
		$("tabContact1").style.display="none";
		$("panelContact1").className="tabPanelFirst tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	},
	function() {
		try {
			setTimeout(function() {
				if ($("last_name")) $("last_name").focus();
			},0);
		} catch (e) {
			
		}
	}
);

registerView("contact_new/personal",
	function() { 
		$("tabContact2").style.display="block";
		$("panelContact2").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";
		try {
            setTimeout(function() {	
            	$("contactForm").profession.focus();
            },0);
        } catch (e) {
            
        }     	
		if(!birthdayCalendar && !anniversaryCalendar)
			createMiniCalendar();
		enableBirthdayAppointment();
	},
	null, 
	 null,
	function() {
		$("tabContact2").style.display="none";
		$("panelContact2").className="tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";	
	}
);

registerView("contact_new/additional",
	function() { 
		$("tabContact3").style.display="block";
		$("panelContact3").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
        try {
            setTimeout(function() { 		
            	$("contactForm").street_other.focus();
            },0);
        } catch (e) {
            
        }             	
	},
	null, 
	 null,
	function() {
		$("tabContact3").style.display="none";
		$("panelContact3").className="tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	}
);
registerView("contact_new/attachment",
	function() { 
		$("tabContact5").style.display="block";
		$("panelContact5").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";	
	},
	function() {
		
		if(!bAttachmentGridCreated)
		{
			initAttachmentsGrid();
			bAttachmentGridCreated = true;
			tmp_attachment.getAttachments();
		}
		else		{

			tmp_attachment.enableGrid();			
		}
		register("OX_Attachments_Changed_InGrid",setContactsNewNumberOfAtt);
		register("OX_Timestamp_Changed_By_Attach",setContactsNewTimeStampByAtt);
		
	}, 
	 function() {
	 	unregister("OX_Attachments_Changed_InGrid",setContactsNewNumberOfAtt);
		register("OX_Timestamp_Changed_By_Attach",setContactsNewTimeStampByAtt);
		if(bAttachmentGridCreated)
			tmp_attachment.disableGrid();
	 },
	function() {
		$("tabContact5").style.display="none";
		$("panelContact5").className="tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";		
	}
);

var json = new JSON();
var contactDetailId = 0;
var activefolderLocal = "";
var session = null;
var lastTimestamp = 0;
var modulPopup = "new";
var contact_object = {};
var contact_categories = "";
var dataFromDb = null;
var dateAction = new Array();
var myNewContactFunctions = null;
var clickedItemForSave = "";
var contactTreeLoaded = false;
var tmp_attachment = null;
var treeVisible = false;
var miniBirthdayVisible = false;
var miniAnniversaryVisible = false;
var configGetKey = corewindow.configGetKey;
var configSetKey = corewindow.configSetKey;
var configContainsKey = corewindow.configContainsKey;
var optFolderState = corewindow.optFolderState;
var bAttachmentGridCreated = false;
var newContactId = 0;
var messageOnCancel = false;
var birthdayCalendar = null;
var anniversaryCalendar = null;
var savePending = false;
var newContactFolderTree = null;
var triggerReady = jQuery.noop;

var tmp_attachmentDialog = null;
var messageCloseWindow = _("Do you really want to discard your changes and close the window?");


// 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 setContactsNewTimeStampByAtt(arg)
{
	lastTimestamp = arg;
}

/********************************** Init *****************************************************************/
function initAttachmentsGrid() {
	tmp_attachment = new attachmentGrid("attachmentsNewContactGrid", (url.id || false),
			 clickedItemForSave , 7, tmp_attachmentDialog);	
}

function NewContactFunctions() {
	this.salutationComboBox = null;
	this.cardColumns = (Math.min(Math.ceil(corewindow.countContactCards / 4)));
	this.imageExist = false;
	this.deleteImageOnServer = false;
	this.searchPath = "";
	this.searchAlreadyActivated = false;
}

NewContactFunctions.prototype = {
	deletePicture: function() {		
		if(myNewContactFunctions.imageExist) {
			removeChildNodes($('imageContactTd'));	
			$('imageContactTd').appendChild(newnode("div", 0, {className : "contactDummyImage border-color-design"}, [newnode("img", 0, { src : getFullImgSrc("img/contacts/dummypicture.gif")})]));
			contact_object.image1 = "";
			this.deleteImageOnServer = true;
		} else {
			$("contactUploadImage").reset();
		}
	},	
	applyUploadImage: function() {		
		$('contact_upload_image').style.display = "none";
		ox.api.setModal(false);
//		hideNode("modal-dialog");
//        $("modal-dialog").style.display="none"; 
		if(document.getElementById("image1").value != "" && document.getElementById("image1").value != myNewContactFunctions.searchPath) 
			triggerEvent("OX_New_Info",4,_("Your selected picture will be displayed after saving"));
	},	
	cancelUploadImage: function() {
		if(document.getElementById("image1").value != "" && document.getElementById("image1").value != myNewContactFunctions.searchPath) {
			document.getElementById("image1").value = "";
			$("contactUploadImage").reset();
		}
		$('contact_upload_image').style.display = "none";
		ox.api.setModal(false);
//		hideNode("modal-dialog");
//        $("modal-dialog").style.display="none";
	},
	addPicutre: function() {
	    ox.api.setModal(true);
//		showNode("modal-dialog");
//		$('modal-dialog').style.display = "block";        
		centerPopupWindow($('contact_upload_image'));
		$('contact_upload_image').style.display = "block";
		if(document.getElementById("image1").value != "") {
			myNewContactFunctions.searchPath = document.getElementById("image1").value;
			myNewContactFunctions.searchAlreadyActivated = true;
		} else {
			myNewContactFunctions.searchAlreadyActivated = false;
		}
	},	
	closeWindow : function() {
		function cbyes() {
		    ctrl.close(true);
		}
		if (messageOnCancel) {
			newConfirm(_("Close Window"), messageCloseWindow, AlertPopup.YESNO,
			    null, null, cbyes, null);	
		} else {
			cbyes();
		}
	},
	initCategories: function() {		
		// add click on categories button
		addDOMEvent($("newcontact_categories_button"), "click", function(e) {
			myNewContactFunctions.openCategoriesDialog();
		});
		
		// handle dbl click which attachs an inplace input field to div
		addDOMEvent($("newcontact_categories_list"), "dblclick", function(e) {
			ox.categories.ui.attachInplaceInput($("newcontact_categories_list"),
				function(value) {				
					// handle value
					var list = clone(ox.categories.getByString(contact_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);
						contact_categories = ox.categories.utils.paramToString(list, "name");				
					}
					ox.categories.ui.drawCategoriesList(
							ox.categories.getByString(contact_categories), 
							$("newcontact_categories_list"));
				}
			);		
		});		
	},
	openCategoriesDialog: function() {
		ox.categories.ui.open((contact_categories || ""), function(list, str) {
			contact_categories = str;
			ox.categories.ui.drawCategoriesList(ox.categories.getByString(contact_categories), 
					$("newcontact_categories_list"));
		});
	},
	folderPath : function() {
		if(!clickedItemForSave || clickedItemForSave=="null")
				clickedItemForSave = corewindow.configGetKey("folder.contacts");
		ox.api.folder.get({
		    folder: clickedItemForSave,
		    success: function (data) {
    			if(data.type != 1){
    				$("newcontact_personal_tr").style.visibility = "hidden";
    			} else {
    				$("newcontact_personal_tr").style.visibility = "visible";
    			}
    			
    			var nPermission = ox.api.folder.derive("permissions", data, 0).bit;
    			
    			ox.api.folder.getPathString({
    			    folder: clickedItemForSave,
    			    success: cb_getpath
    			});
    			var folderViewSettingsNewContact = new Object();
    			var folderViewSettingsNewContactById = new Object();
    			//Disable Email... 
    			// folder.popup
    			folderViewSettingsNewContact["mail"] = 4;
    			folderViewSettingsNewContactById["default"] = 4;
    			folderViewSettingsNewContact["contacts"] = 8;
    			folderViewSettingsNewContact["calendar"] = 4;
    			folderViewSettingsNewContact["tasks"] = 4;
    			folderViewSettingsNewContact["infostore"] = 4;
    			if(!contactTreeLoaded){
    				ox.api.ui.selectFolder({
    			    	type: "contacts",
    			    	id: "select-folder-popup-contacts",
    			    	callback: folderAction,
    			    	node: $('folder_tree_info')
    			    });
    				contactTreeLoaded = true;
    			}
		    }
		});
	}
}

function cb_getpath(sPath) {
	document.getElementsByName('newcontact_folder')[0].value = sPath;
}	

function folderAction(data) {
	toggleTree();
	clickedItemForSave = data.id;
	ox.api.folder.getPathString({
	    folder: clickedItemForSave,
	    success: cb_getpath
	});
}

function showTree(){
	centerPopupWindow($("treeDialogNewContact"));
	$("treeDialogNewContact").style.display = "block";
	$("treeDialogNewContact").style.top = "120px";
	$("treeDialogNewContact").style.left = "170px";
}
function hideTree(){
	$("treeDialogNewContact").style.display = "none";	
}

function toggleTree(){
	if(newContactFolderTree == null)
	{
		myNewContactFunctions.folderPath();
	}
	if(!treeVisible){
		centerPopupWindow($("treeDialogNewContact"));
		$("treeDialogNewContact").style.display = "block";
		$("treeDialogNewContact").style.top = "120px";
		$("treeDialogNewContact").style.left = "170px";
		treeVisible = true;

	}
	else{
		$("treeDialogNewContact").style.display = "none";
		treeVisible = false;
	}
}

/**
 * init() onLoad
 */
function newContactOnload() {
    
    // add default theme (should be in browser cache)
    var themeStyle = corewindow.oxThemeStyle || { name: "Default", path: "default" };
    ox.gui.themePath = getFullImgSrc("");
    removeCSSFilesForNewWindow(themeStyle.path);
    
	activemodule="contact_new";	
	initContents("contact_new");
	initAll();
	
	window.setTimeout(function() {
		initContactContent();
	}, 0);
}

//register("Loaded",initContactContent);
var internalCache = corewindow.internalCache;
var configContainsKey = corewindow.configContainsKey;
var	configGetKey = corewindow.configGetKey;
var	configSetKey = corewindow.configSetKey;

function initContactContent() {
	// extend url object
	url = jQuery.extend((url || {}), ox.api.window.getData(url.guid));
	
	// fixed extended fu.ck3l, don't use german vars
	url.module = url.modul || "new";
	
	// instance is required now
	myNewContactFunctions = new NewContactFunctions();
	
	clickedItemForSave = url.folder || configGetKey("folder.contacts");
	session = corewindow.session;
	activemoduleLocal = corewindow.activemodule;
	activefolderLocal =	url.folder;
	
    triggerReady = function () {
        
        // init new menu for contacts
        ox.gui.initToolBarNewWindowContact();
        
        triggerEvent("OX_menu_Change_Height",true);
        
        var metaData = {
            module: "contacts",
            activemodule: activemodule,
            handle: url.guid,
            id: (url.id != undefined) ? url.id : null,
            folder_id: url.folder ? url.folder : null,
            title: window.document.title
        };
        
        ox.api.window.core.triggerEvent("OX_Window_Ready", metaData, window);
    };
	
	setModulPopup();
	
	addOnClose($("contact_upload_image"), myNewContactFunctions.cancelUploadImage);
		
	register("OX_SAVE_OBJECT", saveContact);	
	register("OX_Cancel_Object", function() {
		myNewContactFunctions.closeWindow();
	});	
		
	loadingComplete();
	
	function callMeOnOK(parameter) {
		tmp_attachment.updateGrid(parameter);
	}
	tmp_attachmentDialog = new attachmentDialog(0,callMeOnOK); 
	
	// register keydown and mouseover for the autfill of the display name
	addDOMEvent($("last_name"), "keyup", autofillDN);
	addDOMEvent($("first_name"), "keyup", autofillDN);			
	addDOMEvent($("last_name"), "mouseout", autofillDN);
	addDOMEvent($("first_name"), "mouseout", autofillDN);
	
	if (clickedItemForSave == 6) {
		$("email1").disabled = true;
		$("email1").removeAttribute("onkeydown");
	}
	
	myNewContactFunctions.initCategories();
	
	window.setTimeout(function() {
		ox.api.folder.getPathString({
		    folder: clickedItemForSave,
		    success: cb_getpath
		});
	   }, 10);
    setTabLists(tabsList, panelsList, eventList);
    window.setTimeout(function() {
            triggerEvent("OX_Switch_View","contact_new/business");
        },0);
}

function callback_new(arg) {
	if(savePending) savePending = false;
	if(arg.error)
	{
		document.getElementById("contactUploadImage").reset();
		newServerError(arg);
	}
	else
	{
		newContactId = arg.data.id;
		if(document.getElementById('image1')) {
            myNewContactFunctions.new_contains_image1 = $("image1").value ? 1 : 0;
            document.getElementById('image1').value = "";
        }
		if (tmp_attachmentDialog.attach_changed()) 
		{
			var obj = new Object();
			obj['attached'] = newContactId;
			obj['module'] = 7; 				
			obj['folder'] = clickedItemForSave;
			tmp_attachmentDialog.do_post(obj,finalFunction);
		} else
			finalFunction();
	}	
}

function callback_update(arg)
{
	if(savePending) savePending = false;
	if(arg.error)
	{
		document.getElementById("contactUploadImage").reset();
		newServerError(arg);
	}
	else
	{
		if(document.getElementById('image1')) {
            myNewContactFunctions.new_contains_image1 = $("image1").value ? 1 : 0;
			document.getElementById('image1').value = "";
        }
		if (tmp_attachmentDialog.attach_changed()) 
		{
			var obj = new Object();
			obj['attached'] = contactDetailId;
			obj['module'] = 7; 				
			obj['folder'] = clickedItemForSave;
			tmp_attachmentDialog.do_post(obj,finalFunction);
		} else
			finalFunction();
	}
}

/********************************** Datepicker *****************************************************************/

function createMiniCalendar(){
	birthdayCalendar = new cMiniCalendar(	$("birthday_header"), 
										$("birthday_container"), 
										setBirthday,
										false,
										"id_birthday",
										$("birthday_header_month"),
										$("birthday_header_year"));
										
	anniversaryCalendar = new cMiniCalendar(	$("anniversary_header"), 
										$("anniversary_container"), 
										setAnniversary,
										false,
										"id_anniversary",
										$("anniversary_header_month"),
										$("anniversary_header_year"));
}

function setBirthday() {
	var tmp = $("contactForm");
	birthdayCalendar.setSelected(this.id);
	tmp.birthday.value = formatDate(birthdayCalendar.selectedTime, "date");
	$("mini_birthday").style.display = "none";
	miniBirthdayVisible = false;
	enableBirthdayAppointment();
}

function showMiniBirthday(){
	var tmp = $("mini_birthday");
	tmp.style.display = "block";
	tmp.left = 0;
	tmp.top = "1.6em";	
}

function toggleMiniBirthday(){
	var tmp = $("mini_birthday");
	tmp.left = 0;
	tmp.top = "1.6em";	
	if(!miniBirthdayVisible){
		if(miniAnniversaryVisible){
			$("mini_anniversary").style.display = "none";
			miniAnniversaryVisible = false;
		}
		var birthday_date = parseDateString($("birthday").value, "date");
		if(birthday_date) {
			birthdayCalendar.setSelectedByDate(birthday_date.getUTCFullYear(),
											birthday_date.getUTCMonth(),
											birthday_date.getUTCDate());
		} else {
			birthdayCalendar.setUnselected();
		}
		tmp.style.display = "block";
		miniBirthdayVisible = true;
	} else {
		tmp.style.display = "none";
		miniBirthdayVisible = false;
	}
}

var bDayObj = new Object();
var bDaySubmit = false;
/**
 * checks if we have all information and enables/disables the create birthday
 * appointment button/image
 */
function enableBirthdayAppointment() {
	var img = getFullImgSrc("img/menu/add_appointment_d.gif");
	var cursor = "default";
	if (parseDateString($("birthday").value, "date") != null
	    && trimStr($("display_name").value).length != 0) {
	   img=getFullImgSrc("img/menu/add_appointment.gif");
	   cursor = "pointer";
	}
	if ($("mini_calender_add_appointment_img").src != img) {
		$("mini_calender_add_appointment_img").src=img;
		$("mini_calender_add_appointment_img").style.cursor=cursor;
	}
}

/**
 * handles the birthday appointment dialog
 */
function createBirthdayAppointment() {
	var bday = parseDateString($("birthday").value, "date");
	if (!bday || bDaySubmit) return;
	bday.setUTCFullYear(new Date().getFullYear());
	bday.setUTCHours(bday.getUTCHours());
    bday.setUTCMinutes(bday.getUTCMinutes());    
	
    var jparam = "?action=new";
	if (bDayObj["id"]) {
		jparam = "?action=update";
		jparam += "&id=" + bDayObj["id"];		
		jparam += "&timestamp=" + bDayObj["timestamp"];		
	}
	jparam+="&folder=" + configGetKey("folder.calendar");

    bDayObj["folder_id"] = configGetKey("folder.calendar");
	bDayObj["start_date"] = Date.UTC(bday.getUTCFullYear(), bday.getUTCMonth(), bday.getUTCDate(), 0, 0, 0);
	bDayObj["end_date"] = Date.UTC(bday.getUTCFullYear(), bday.getUTCMonth(), bday.getUTCDate(), 0, 0, 0);
	//#. New contact window: Used to create a pre-filled title at the new birthday appointment dialog  
	//#. %s will be replaced with the display name of the contact
	//#, c-format
	bDayObj["title"] = format(_("Birthday of %s."), $("display_name").value);
	bDayObj["full_time"] = true;
	if (bDayObj["private_flag"] == undefined) bDayObj["private_flag"] = true;
	bDayObj["shown_as"] = 4;
	bDayObj["alarm"] = 1440;
	bDayObj["recurrence_type"] = 4;
	bDayObj["day_in_month"] = bday.getDate();
	bDayObj["month"] = bday.getMonth();
	bDayObj["interval"] = 1;
	
	var ap_titleInp = newnode("input", { width:"75%" }, { type:"text", value:bDayObj["title"] });
	var ap_privCbk  = newnode("input", { paddingRight:"15px" }, { type:"checkbox", checked:bDayObj["private_flag"], className:"noborder" });
		
	var myDiv = newnode("div", { lineHeight:"1.8em", verticalAlign:"middle" }, null,
           [ newnode("span", null, null, [ 
                    document.createTextNode(_("Would you like to create the following birthday series appointment?"))]),
             newnode("div", { width:"98%"  }, null, [ 
                    newnode("span", { paddingRight:"15px" }, null, [ document.createTextNode(pgettext("description", "Title:")) ]),
                    ap_titleInp]), 
             newnode("div", { width:"98%" }, null, [ ap_privCbk, 
                    newnode("span", { paddingLeft:"10px" }, null, [ document.createTextNode(_("Private appointment")) ])
                    ])           
           ]);
	
	function cb_Ok() {
		bDayObj["title"] = ap_titleInp.value;
		bDayObj["private_flag"] = ap_privCbk.checked;
	    bDaySubmit = true;
	    setModalBusy(true);
	    new JSON().put(AjaxRoot + "/calendar" + jparam + "&session=" + session, bDayObj, null, function(cb) {     
	        if (cb.data && !cb.error) {
	            var resp = _("Birthday appointment has been created."); /*i18n*/
	            if (bDayObj["id"])
	                 resp = _("Birthday appointment has been changed."); /*i18n*/
	            bDayObj["id"]=cb.data.id;
	            bDayObj["timestamp"]=cb.timestamp;
	            triggerEvent("OX_New_Info",4,resp);         
	        }
	        bDaySubmit = false;
	        setModalBusy();
	    },setModalBusy); 
	}
	
	newConfirm(_("Birthday Appointment") /*i18n*/, null, AlertPopup.OKCANCEL, 
	       cb_Ok, function() { return; }, null, null, null, null, null, 
	       null, null, myDiv);

	if (IE6) setTimeout(function() { ap_privCbk.checked=bDayObj["private_flag"]; }, 0);
	
}

function setAnniversary(){
	var tmp = $("contactForm");
	anniversaryCalendar.setSelected(this.id);

	tmp.anniversary.value = formatDate(anniversaryCalendar.selectedTime, "date");
	$("mini_anniversary").style.display = "none";
	miniAnniversaryVisible = false;
}

function showMiniAnniversary(){
	var tmp = $("mini_anniversary");
	tmp.style.display = "block";
	tmp.left = 0;
	tmp.top = "1.6em";	
}

function toggleMiniAnniversary(){
	var tmp = $("mini_anniversary");
	tmp.left = 0;
	tmp.top = "1.6em";	
	if(!miniAnniversaryVisible){
		if(miniBirthdayVisible){
			$("mini_birthday").style.display = "none";
			miniBirthdayVisible = false;
		}
		var anniversary_date = parseDateString($("anniversary").value, "date");
		if(anniversary_date) {
			anniversaryCalendar.setSelectedByDate(anniversary_date.getUTCFullYear(),
											anniversary_date.getUTCMonth(),
											anniversary_date.getUTCDate());
		} else {
			anniversaryCalendar.setUnselected();
		}
		tmp.style.display = "block";
		miniAnniversaryVisible = true;
	} else {
		tmp.style.display = "none";
		miniAnniversaryVisible = false;
	}
}

var autofillmatch = true;
function autofillDN() {
	var dn = $("display_name");
	var ln = $("last_name").value;
	var fn = $("first_name").value;
	if (dn.value == "" || autofillmatch) {
		dn.value = ln + (fn && ln ? ", " : "") + fn;
	}
}

function autofillDN_turn_off(e) {
	if (!e) e = window.event;
	// turn off autocomplete only if characters are entered
	// ignores control, alt, shift, tab, etc.
	if (e.keyCode >= 32) autofillmatch = false;
}

function setTitle (data) {
    var title = "";
    if (data) {
        // display name set?
        if (data.display_name) {
            title = data.display_name;
        } else {
            // get new display name
            title = data.last_name + (data.first_name && data.last_name ? ", " : "") + data.first_name;
        }
        // set document title
        document.title = _("Contact") + ": " + title;
    }
}

/********************************** Save Contact *****************************************************************/
/**
 * triggerEvent -> save Button
 * switch: new, edit, dublicate, newmember
 */
function saveContact()
{
	if(savePending) return;
	else savePending = true;
	
	if(modulPopup == "new" || modulPopup == "duplicate") {
		writeNewContact();
	} else if(modulPopup == "edit") {
        /********************************** update Contact ********************************************************/	
		var ct = $("contactForm");
		//check if Birthday changed
		if(!checkDateFormat("birthday") || !checkDateFormat("anniversary")) {
			savePending = false;
			return;
		}
			
		var date = $("birthday").value;
		if (date) {
		    var d = parseDateString(date);
		    if (d) contact_object.birthday = d.getTime();
		} else if (dataFromDb.data.birthday != null) {
		    contact_object.birthday = null;
		}

		//check if anniversary changed
		date = $("anniversary").value;
		if (date) {
            var d = parseDateString(date);
            if (d) contact_object.anniversary = d.getTime();
        } else if (dataFromDb.data.anniversary != null) {
            contact_object.anniversary = null;
        }
		
		for (i=0; i<ct.elements.length; i++) {
			if(ct.elements[i].value != "" && ct.elements[i].name != "")	{
				if(ct.elements[i].name != "anniversary" && ct.elements[i].name != "birthday" && ct.elements[i].name.indexOf("newcontact_") == -1)
					contact_object[ct.elements[i].name] = ct.elements[i].value;
			}				
		}
		
		if (typeof(contact_categories) != "undefined") {
			contact_object.categories = contact_categories;
		}
				
		if (activefolderLocal != clickedItemForSave) {
			contact_object.folder_id = clickedItemForSave;
		}
		
		if($('newcontact_personal').checked && ($("newcontact_personal_tr").style.visibility == "visible" || $("newcontact_personal_tr").style.visibility == "")) 
		{
			contact_object.private_flag = true;
		} else {
			contact_object.private_flag = false;
		}
		
		checkModified(dataFromDb.data, contact_object)
		
		if($("image1").value != "" || myNewContactFunctions.deleteImageOnServer) {
				with 	($('contactUploadImage')) 
				{					
						action = AjaxRoot + "/contacts?action=update&session=" + session + "&id="+contactDetailId+"&folder="+activefolderLocal+"&timestamp="+lastTimestamp+ "&time=" + new Date().getTime();		
						json.value = JSON.serialize(contact_object);		
						submit();
				}
			}
		else {
		    setModalBusy(true);
			json.put(AjaxRoot + "/contacts?action=update&session=" + session + "&id="+contactDetailId+"&folder="+activefolderLocal+"&timestamp="+lastTimestamp, 
				contact_object, 
				null, 
				function(updatedFields)
				{	
					if(updatedFields) {
						if(updatedFields.error) {
							//error
						} else {
                            
                            ox.api.window.core.triggerEvent("OX_NEW_CONTACT_SAVE_SUCCESS", {data:{id: contactDetailId}}, url.guid);
							if (tmp_attachmentDialog.attach_changed()) 
							{
								var obj = new Object();
								obj['attached'] = contactDetailId;
								obj['module'] = 7; 				
								obj['folder'] = clickedItemForSave;
								tmp_attachmentDialog.do_post(obj,finalFunction);
							}
							else {
								finalFunction();
							}
						}
					}
				},setModalBusy
			);
		}
		
	}
}


/*
 * use the global function to get a Date Object
 * returns the long from this dateobject
 * */

function formatDateToUTC(formDate) {
	var longTime = parseDateString(formDate);
	if(longTime == null)
		return longTime
	else
		return longTime.getTime();
}


/**
 * Help function for compare two Dates in m/d/y 
 * @param {string} Date in m/d/y  
 * @param {string} Date in m/d/y  
 * @param {string} name of the field  
 */
function compareDate(formDate, dbDate, labelDate)
{
	dateAction[0] = "";
	dateAction[1] = "";
	
	if(formDate != "") {
		
		var UTCformated = formatDateToUTC(formDate);
		if (UTCformated == 0) UTCformated = 1; // 0 -> fix for 01.01.1970
		dateAction[1] = UTCformated;	
		if(!UTCformated || UTCformated == "") { 
			dateAction[0] = "error";
		}
		else if(UTCformated != dbDate) {
			dateAction[0] = "save";
		} 
		else if(contact_object[labelDate]) {
			dateAction[0] = "save";
		}
	} 
	else if(dbDate != "") {
		dateAction[0] = "clear";
	}
	return dateAction;
}

/********************************** Contact Obj for Update *****************************************************************/
/**
 * If Modus is 'edit', the json objekt (contact_object) will be created for Update DB, whith changed fields
 */
var myKeyTimeout = null;
function editContact(field) {	
	if(myKeyTimeout) {
		clearTimeout(myKeyTimeout);
	}
	myKeyTimeout = setTimeout(
		function() {
			switch(modulPopup) {
			
				case "edit" 		:		if(dataFromDb && document.getElementsByName(field.name)[0] && document.getElementsByName(field.name)[0].value != dataFromDb.data[field.name]) {	
												contact_object[field.name] = document.getElementsByName(field.name)[0].value || "";
												setBeforeUnload(true);
											}
											break;
							
				case "duplicate" 	:		if(dataFromDb && document.getElementsByName(field.name)[0] && document.getElementsByName(field.name)[0].value != dataFromDb.data[field.name]) {	
												setBeforeUnload(true);
											}
											break;
											
				case "new" 	:		if(document.getElementsByName(field.name)[0] && document.getElementsByName(field.name)[0].value != "") {	
												setBeforeUnload(true);
											}
											break;
				
			}
		},200
	)
}

function checkDateFormat(field) {
	var valueDate = $(field).value;
	if(valueDate != "") {
		var checkedDate = formatDateToUTC(valueDate);
		if((!checkedDate || checkedDate == "") && checkedDate != 0) { // !=0 -> fix for 01.01.1970
			triggerEvent("OX_New_Error", 4, _("Invalid date format. The valid format is dd.mm.yyyy"));		
			$(field).className = $(field).className + "borderColorError"; 
			return checkedDate;
		} else {
			$(field).className = $(field).className + "border-color-default";
			return true;
		}
	} else {
		$(field).className = $(field).className + "border-color-default";
		return true;
	}
}

/********************************** set var Module *****************************************************************/
/**
 * Init Popup for setting the Modul
 * @param {String} parameters from the url 
 */
function setModulPopup(params) {
    
	clickedItemForSave= trimStr(url.folder) || configGetKey("folder.contacts");
	
	// new
	if (url.module == "new") {
	    // set document title
	    document.title = _("New contact") + "";
        // disable loading screen
        $("loading_data_bg").style.display="none";
        // ready
        triggerReady();
	} else {
		// edit or duplicate
		modulPopup = url.module;
		contactDetailId = url.id;
		activefolder = url.folder;
		session = url.session;
		currentView = url.currentView;
		fillFieldById();
	}
}

/********************************** get ContactById *****************************************************************/

/**
 * fill the Fields which comes from DB 
 * id is a Param in the url, see {@link setModulPopup}
 */
function fillFieldById()
{
	new JSON().get(AjaxRoot + "/contacts?action=get&session=" + session +"&id="+contactDetailId+"&folder="+clickedItemForSave+"&",
		null,
		function(reply) {
			dataFromDb = reply;
			fillFields(reply.data);
			setTitle(reply.data);
			lastTimestamp = reply.timestamp;
			// disable loading screen
            $("loading_data_bg").style.display="none";
            // ready
            triggerReady();
		}
	);
}

function fillFields(data) {
    for (field in data) {
        if(document.getElementsByName(field)[0] && data[field] != "") {
            document.getElementsByName(field)[0].value = data[field];
        }
        
        if(field=="birthday")
        {
            $("birthday").value = formatDate(data[field],"date");
        }
        if(field=="anniversary")
        {
            $("anniversary").value = formatDate(data[field],"date");
        }
        
        if(field=="number_of_attachments")
        {
            if (url.module == "duplicate")
                setContactsNewNumberOfAtt(0);
            else
                setContactsNewNumberOfAtt(data.number_of_attachments);
        }
        
        if(field=="private_flag" && data[field] == true) {
            $("newcontact_personal").checked = "checked";
        }
        
        if(field=="disribution_list")
        {
            if(data[field] && data[field].length > 0) {
                
                if(myDistrListAdressBook) {
                    
                    myDistrListAdressBook.findContactForDistrList       = {};
                    myDistrListAdressBook.findContactForDistrList.data  = new Array();
                    
                    for(i=0; i<data[field].length;i++){
                        myDistrListAdressBook.findContactForDistrList.data[i] =
                            [data[field][i].id, data[field][i].display_name,
                             data[field][i].mail];
                        myDistrListAdressBook.tmpIdsForSave[i] =
                            data[field][i].id; //ID
                    }
                }
            }
        }
        /* if an image is existing */
        if (field == "number_of_images" && data[field] > 0 && url.module != "duplicate") {
            myNewContactFunctions.imageExist = true;
            removeChildNodes($('imageContactTd'));
            $('imageContactTd').appendChild(newnode("img", 0, {src: data.image1_url + "&random=" + new Date().getTime(), alt: ""}));
        }
    }
    if (data["categories"]) {
        contact_categories = data["categories"];
        // draw list
        if ($("newcontact_categories_list")) {
            ox.categories.ui.drawCategoriesList(ox.categories.getByString(contact_categories),
                    $("newcontact_categories_list"));
        }
    }
    try {
        // dn autofill: check if the dn still matches                       
        var fn = data.first_name || "";
        var ln = data.last_name || "";
        var dn = data.display_name || "";
        autofillmatch = (dn == (ln + (fn && ln ? ", " : "") + fn));
    } catch (e) { }
}

function setContactsNewNumberOfAtt(nNumAttParam) {
	$('contact_number_of_attachments').firstChild.nodeValue = nNumAttParam;
}

/**
 * Validation email
 * @param {string} email for validation
 * @return {boolean} true if is valid
 */
function checkEmailAdr(feld) {
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported)
		return (feld.indexOf(".") > 2) && (feld.indexOf("@") > 0);
		
		var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
		var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		return (!r1.test(feld) && r2.test(feld));
}

/********************************** Write new Contact *****************************************************************/
/**
 * Write all filled fields in DB
 * json.put -> contact_object
 */
 
function writeNewContact()
{
	var ct = $("contactForm");	
	contact_object = {};
	//Convert Date to UTC
	var datepart = "";
	
	var birthdayData = $("birthday").value;
	
	var birthdayUTC = "";
	
	if(birthdayData != "") {
		birthdayUTC = formatDateToUTC(birthdayData);
		if(!birthdayUTC || birthdayUTC != "") {
			contact_object.birthday = birthdayUTC;
		}		
	}
	
	var anniversaryData = $("anniversary").value;
	var anniversaryUTC = "";
	if(anniversaryData != "") 
	{
		anniversaryUTC = formatDateToUTC(anniversaryData);
		
		if(!anniversaryUTC || anniversaryUTC != "") {
			contact_object.anniversary = anniversaryUTC;
		}		
	}
	
	var privatEmailData = ct.email1.value;
		
	for (i=0; i<ct.elements.length; i++) {
		if(ct.elements[i].value != "" && ct.elements[i].name != "")	{
			if(ct.elements[i].name != "anniversary" && ct.elements[i].name != "birthday" && ct.elements[i].name.indexOf("newcontact_") == -1)
				contact_object[ct.elements[i].name] = ct.elements[i].value;
		}				
	}
	contact_object.folder_id = activefolderLocal;

	if (contact_categories) {
		contact_object.categories = contact_categories;
	}
	
	if (activefolderLocal != clickedItemForSave) {
		contact_object.folder_id = clickedItemForSave;
	}
	
	if($('newcontact_personal').checked && ($("newcontact_personal_tr").style.visibility == "visible" || $("newcontact_personal_tr").style.visibility == "")) {
		contact_object.private_flag = true;
	} else {
		contact_object.private_flag = false;
	}
	
	if(document.getElementById("image1").value != "") {	
		with (document.getElementById('contactUploadImage')) {					
			action = AjaxRoot + "/contacts?action=new&session=" + session + "&folder="+clickedItemForSave+"&timestamp="+lastTimestamp;		
			json.value = JSON.serialize(contact_object);		
			submit();
		}				
	} else {
	    setModalBusy(true);
		json.put(AjaxRoot + "/contacts?action=new&session=" + session +"&folder="+clickedItemForSave+ "&" , contact_object, null, 
		function(idObj){
			if(idObj) {
                ox.api.window.core.triggerEvent("OX_NEW_CONTACT_SAVE_SUCCESS", idObj, url.guid);
				newContactId = idObj.data.id;
				if (tmp_attachmentDialog.attach_changed()) {
					var obj = new Object();
					obj['attached'] = idObj.data.id;
					obj['module'] = 7; 				
					obj['folder'] = clickedItemForSave;
					tmp_attachmentDialog.do_post(obj,finalFunction);
				} else finalFunction();
			}
		},setModalBusy);
	}

}


function finalFunction(myObject) {	
    if ("new_contains_image1" in myNewContactFunctions) {
        contact_object.contains_image1 =
            myNewContactFunctions.new_contains_image1;
    }
    if (tmp_attachmentDialog.attach_changed()) {
        contact_object.number_of_attachments =
            tmp_attachmentDialog.file_storage.ids.length;
        corewindow.triggerEvent("OX_Quota_Update");
    }
	if(modulPopup == "new" || modulPopup == "duplicate") {
       setBeforeUnload(false);
       corewindow.OXContactMapping.createObject(contact_object);
       corewindow.closeContactPopUp(window, clickedItemForSave);
    } else if(modulPopup = "edit") {
        setBeforeUnload(false);
        corewindow.OXCache.newRequest(null, "contacts", { columns: null,
            objects: [corewindow.OXContactMapping.createKeyFromObject({
                module: "contacts", folder_id: clickedItemForSave,
                id: contactDetailId
            })] }, null, emptyFunction, true);
        if (activefolderLocal != clickedItemForSave) {
            corewindow.OXContactMapping.deleteObjectsInternal(
                [corewindow.OXContactMapping.createKeyFromObject({
                    module: "contacts", folder_id: activefolderLocal,
                    id: contactDetailId
                })]);
        }
       corewindow.closeContactPopUp(window, clickedItemForSave);
    }
	setModalBusy();
}

/********************************** Tabs *****************************************************************/
register("OX_Contact_New_Switch",function(param) { menuswitchContactNew(param) });
/**
 * global vars for new Contact
 */
var tabsList   =	new Array('tabContact1','tabContact2', 'tabContact3', 'tabContact4', 'tabContact5', 'tabContact6' );
var panelsList = 	new Array('panelContact1','panelContact2', 'panelContact3', 'panelContact4', 'panelContact5', 'panelContact6' );
//var eventList  =	null;
var eventList =
		new Array(	['OX_Contact_New_Switch','business'],
					['OX_Contact_New_Switch','personal'],
					['OX_Contact_New_Switch','additional'],
					['OX_Contact_New_Switch','distributionlist'],
					['OX_Contact_New_Switch','attachment'],
					['OX_Contact_New_Switch','links']);
									

function setBeforeUnload(on) {
    messageOnCancel = on;
}

// init window controller

var ctrl = windowController = new WindowController();

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