JSON = YAHOO.lang.JSON;

SUGAR.quickCompose= {};

SUGAR.quickCompose = function() {
	return {
		
		parentPanel : null,
		options: null,
		loadingMessgPanl : null,
		frameLoaded : false,
		resourcesLoaded: false,
		cachedComposedResponses: {}, //Cached objects.
		
		/**
		 * Get the required compose package in an ajax call required for 
		 * the quick compose.
		 * @method initComposePackage
		 * @param {Array} c Options containing compose package and full return url.
		 * @return {} none
		 **/
		initComposePackage: function(c)
		{
		    //Init fix for YUI 2.7.0 datatable sort.
	        SUGAR.email2.addressBook.initFixForDatatableSort();
	        
		    //JS resources must have been loaded if we reach this step.
		    SUGAR.quickCompose.resourcesLoaded = true;
            var callback = 
	        { 
	           success: function(o) 
	           {
	               var responseData = JSON.parse(o.responseText);
	               //Create and insert the necessary script tag
	               var scriptTag = document.createElement('script');
	               scriptTag.id = 'quickComposeScript';
                   scriptTag.setAttribute('type','text/javascript');
                   
                   if(YAHOO.env.ua.ie > 0) //IE hack
                   		scriptTag.text = responseData.jsData;
                   else  //Everybody else
                   		scriptTag.appendChild(document.createTextNode(responseData.jsData));
                   
                   document.getElementsByTagName("head")[0].appendChild(scriptTag);
                   
                   //Create and insert the necessary div elements and html markup
	               var divTag = document.createElement("div");
	               divTag.innerHTML = responseData.divData;
	               divTag.id = 'quickCompose';
	               YAHOO.util.Dom.insertBefore(divTag, 'footer');  
	               
	               //Set the flag that we loaded the compose package.
	               SUGAR.quickCompose.frameLoaded = true;
	               //Init the UI
                   SUGAR.quickCompose.initUI(c.data);
	           }
	       } 
	       
	       if(!SUGAR.quickCompose.frameLoaded)
		      YAHOO.util.Connect.asyncRequest('GET', 'index.php?entryPoint=GenerateQuickComposeFrame', callback, null);   
		   else
		      SUGAR.quickCompose.initUI(c.data);
		       
		},
		/**
		 * Initalize the UI for the quick compose
		 * the quick compose.
		 * @method initComposePackage
		 * @param {Array} options Options containing compose package and full return url.
		 * @return {} none
		 **/
		initUI: function(options)
		{
			var SQ = SUGAR.quickCompose;
			this.options = options;
		     
			//Hide the loading div
			loadingMessgPanl.hide();
			
			//Construct the main pannel if necessary.	
			if(SQ.parentPanel == null)
			{
				theme = SUGAR.themes.theme_name;
		
				//The quick compose utalizes the EmailUI compose functionality which allows for multiple compose
				//tabs.  Quick compose always has only one compose screen with an index of 0.
				var idx = 0;  
	
			    //Get template engine with template
        		if (!SE.composeLayout.composeTemplate) 
        			SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
       	 	
        
	        	SQ.parentPanel = new YAHOO.widget.Panel("container1", {
	                modal:true,
					visible:true,
	            	constraintoviewport: true,
	                width	: '880px',
	                height : '400px',
	                shadow	: true,
	                draggable : true,
					resize: true
	            });
			
	            SQ.parentPanel.setHeader( SUGAR.language.get('app_strings','LBL_EMAIL_QUICK_COMPOSE')) ;
            	SQ.parentPanel.setBody("<div id='htmleditordiv" + idx + "'></div>");
        	
				var composePanel = SE.composeLayout.getQuickComposeLayout(SQ.parentPanel,this.options);

				var resize = new YAHOO.util.Resize('container1', { 
                    handles: ['br'], 
                    autoRatio: false, 
                    minWidth: 400, 
                    minHeight: 350, 
                    status: false
                });
                
                resize.on('resize', function(args) { 
                    var panelHeight = args.height; 
                    this.cfg.setProperty("height", panelHeight + "px");
					var layout = SE.composeLayout[SE.composeLayout.currentInstanceId];
					layout.set("height", panelHeight - 50);
					layout.resize(true);
					SE.composeLayout.resizeEditor(SE.composeLayout.currentInstanceId);
                }, SQ.parentPanel, true);
				
				YAHOO.util.Dom.setStyle("container1", "z-index", 1);
				
				//TinyMCE bug, since we are loading the js file dynamically we need to let tiny know that the
				//dom event has fired.  
				tinymce.dom.Event.domLoaded = true;

				tinyMCE.init({
			 		 convert_urls : false,
			         theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
			         width: tinyConfig.width,
			         theme: tinyConfig.theme,
			         theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
			         theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
			         theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
			         theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
			         plugins : tinyConfig.plugins,
			         elements : tinyConfig.elements,
			         language : tinyConfig.language,
			         extended_valid_elements : tinyConfig.extended_valid_elements,
			         mode: tinyConfig.mode,
			         strict_loading_mode : true
		    	 });
				
				
				//Re-declare the close function to handle appropriattely.
				SUGAR.email2.composeLayout.forceCloseCompose = function(o){SUGAR.quickCompose.parentPanel.hide(); }
				
			}
			else
			{
			    //Clear body and subject
			    this.options.composePackage.subject = ' ';
			    //The following options are needed to clear tiny content
			    this.options.composePackage.currentInstanceId = 0;
			    this.options.composePackage.clearBody = true;
			    //Set body to not empty otherwise composePackage function will ignore
			    this.options.composePackage.body = ' ';
			    //Clear CC, BCC addresses and hide them if displayed.
			    document.getElementById("addressCC0").value = "";
			    document.getElementById("addressBCC0").value = "";
			    SE.composeLayout.hideHiddenAddresses('0');
			    //Re-populate compose options (User clicked a different email addr on same page).
			    SE.composeLayout.quickCreateComposePackage(this.options);
				SQ.parentPanel.show();
			}
			SQ.parentPanel.center();
		},
		/**
		 * Display a loading pannel and start retrieving the quick compose requirements.
		 * @method init
		 * @param {Array} o Options containing compose package and full return url.
		 * @return {} none
		 **/
		init: function(o) {

             loadingMessgPanl = new YAHOO.widget.SimpleDialog('loading', {
        			width: '200px',
        			close: true,
        			modal: true,
        			visible: true,
        			fixedcenter: true,
        	        constraintoviewport: true,
        	        draggable: false
		      });

              loadingMessgPanl.setHeader(SUGAR.language.get('app_strings','LBL_EMAIL_PERFORMING_TASK'));
		      loadingMessgPanl.setBody(SUGAR.language.get('app_strings','LBL_EMAIL_ONE_MOMENT'));
		      loadingMessgPanl.render(document.body);
		      loadingMessgPanl.show();
		      
		      SUGAR.quickCompose.loadComposePackage(o);
		},
		/**
		 * Dynamically loads the compose package
		 * @method loadComposePackage
		 * @param {Array} o Options containing compose package or url to gather package details from.
		 * @return {} none
		 **/
		loadComposePackage: function (o) {
            
		    //Generate the composePackage if the link is passed in.
		    if(typeof(o.composeOptionsLink) != 'undefined')
            {
		        var cacheMan = SUGAR.quickCompose.cachedComposedResponses;
		        //Check for a cache hit.
                if(typeof(o.id) != 'undefined' && typeof(cacheMan[o.id] ) != 'undefined')
                    SUGAR.quickCompose.afterComposePackageLoad(cacheMan[o.id]); 
		        else
		        {
                    var baseUrl = 'index.php?module=Emails&action=Compose&to_pdf=true&ajaxCall=true';
                    var fullUrl = baseUrl + '&' + o.composeOptionsLink;
                    var callback = {  success: function(o) 
                     {
                         var resp = JSON.parse(o.responseText);
                         var composePackage = {'composePackage': resp};
                         //Add the response to the cache object.
                         if( typeof(resp.parent_id) != 'undefined' )
                             SUGAR.quickCompose.cachedComposedResponses[resp.parent_id] = composePackage;
    
                         SUGAR.quickCompose.afterComposePackageLoad(composePackage);
                     }};
                    YAHOO.util.Connect.asyncRequest('GET', fullUrl, callback,null);
		        }
            }
            //Compose package already passed in (from listview calls).
            else
		      SUGAR.quickCompose.afterComposePackageLoad(o); 
		},
		
		/**
		 * Fired after the compose package has been loaded (or already passed in from lv calls)
		 * @method afterComposePackageLoad
		 * @param {Array} o Options containing compose package and full return url.
		 * @return {} none
		 **/
		afterComposePackageLoad: function (o) {
		    //If JS files havn't been loaded, perform the load.
		      if(! SUGAR.quickCompose.resourcesLoaded )
		          this.loadResources(o);
		      else
		          this.initUI(o);
		},
		/**
		 * Pull in all the required js files.
		 * @method loadResources
		 * @param {Array} o Options containing compose package and full return url.
		 * @return {} none
		 **/
		loadResources: function(o)
		{
			//IE Bug fix for TinyMCE when pulling in the js file dynamically.
		   	window.skipTinyMCEInitPhase = true;
		   
			var loader = new YAHOO.util.YUILoader({
				    require : ["layout", "element", "tabview", "menu","cookie","tinymce","securejson","sugarwidgets","sugarquickcompose","sugarquickcomposecss"],
				    loadOptional: true,
				    skin: { base: 'blank', defaultSkin: '' },
				    data: o,
				    onSuccess: this.initComposePackage,
				    allowRollup: true,
				    base: "include/javascript/yui/build/"
				});
				
				//TiinyMCE cannot be added into the sugar_grp_quickcomp file as it breaks the build, needs to be loaded 
				//seperately.
				loader.addModule({
				    name :"tinymce",
				    type : "js",
				    fullpath: "include/javascript/tiny_mce/tiny_mce.js"
				});
				
				loader.addModule({
				    name :"securejson",
				    type : "js",
				    fullpath: "include/JSON.js"
				});
				
				//Load the Sugar widgets with dependancies on the yui library.
				loader.addModule({
				    name :"sugarwidgets",
				    type : "js",
				    fullpath: "include/javascript/sugarwidgets/SugarYUIWidgets.js",
				    varName: "YAHOO.SUGAR",
				    requires: ["datatable", "dragdrop", "treeview", "tabview"]
				});
			
				//Load the main components for the quick create compose screen.
				loader.addModule({
				    name :"sugarquickcompose",
				    type : "js",
				    fullpath: "include/javascript/sugar_grp_quickcomp.js"
				});
				
				//Load the css needed for the quickCompose.
				loader.addModule({
				    name :"sugarquickcomposecss",
				    type : "css",
				    fullpath: "modules/Emails/EmailUI.css"
				});
				
				loader.insert();
	    }	
	};
}();

