/*
 * 117337 | Add templates to submissions, notes, calendars and tasks 
 * 
 */
 

function MessageTemplateOnSelect (commentsObjName, messageTemplateID, templateType, contentMergeBehavior, thisComponent, privateLabelID, encryptedAPIKey, userID) { 
    
	switch (messageTemplateID) {

		case '-10':		
			thisComponent.defaultFilter = /personal/;
			thisComponent.applyFilter();		
			updateUserSetting(privateLabelID, encryptedAPIKey, userID, 'messageTemplateFilter_' + templateType, 'personal');				
			break;
			
		case '-20':		
			thisComponent.defaultFilter = /(personal|group)/;
			thisComponent.applyFilter();						
			updateUserSetting(privateLabelID, encryptedAPIKey, userID, 'messageTemplateFilter_' + templateType, '(personal|group)');
			break;
			
		case '-30':		
			thisComponent.defaultFilter = /(personal|group|all|delegate)/;
			thisComponent.applyFilter();	
			updateUserSetting(privateLabelID, encryptedAPIKey, userID, 'messageTemplateFilter_' + templateType, '(personal|group|all)');					
			break;
			
		case '-40':		
			thisComponent.defaultFilter = /delegate/;
			thisComponent.applyFilter();	
			updateUserSetting(privateLabelID, encryptedAPIKey, userID, 'messageTemplateFilter_' + templateType, 'delegate');					
			break;			
		
		// seperator 
		case '-2':					
			break;
			
		// new template	
		case '-1':
		
	        if (bhsWindowManagerObj != null) {
	            wndHdl = bhWindowOpen('/BullhornStaffing/Portfolio/Forms/EditMessageTemplate.cfm?noLogo=TRUE&reloadOpener=FALSE&closeOnFinish=TRUE&templateType=' + templateType, 'MessageTemplateWnd', 'resizable,scrollbars'); 
	            wndHdl.focus();	        	
	        } else {
	            wndHdl = bhWindowOpen('/BullhornStaffing/Portfolio/Forms/EditMessageTemplate.cfm?noLogo=TRUE&reloadOpener=FALSE&closeOnFinish=TRUE&templateType=' + templateType, 'MessageTemplateWnd', 'resizable,scrollbars'); 
	            wndHdl.focus();
	        }		
	        
			break;
		
		// organize templates	
		case '0':
		
	        if (bhsWindowManagerObj != null) {
	            wndHdl = bhWindowOpen('/BullhornStaffing/Portfolio/MessageTemplates.cfm?noLogo=TRUE&closeOnFinish=FALSE&reloadOpener=FALSE&templateType=' + templateType, 'MessageTemplateWnd', 'resizable,scrollbars'); 
	            wndHdl.focus();                        
	        } else {
	            wndHdl = bhWindowOpen('/BullhornStaffing/Portfolio/MessageTemplates.cfm?noLogo=TRUE&templateType=' + templateType, 'MessageTemplateWnd', 'resizable,scrollbars'); 
	            wndHdl.focus();
	        }		
	        
			break;
		
		// actual message template selected, populate the form field	
		default:			
		
		    // make an Ajax call to get the content
		    var content = GetTemplateContent(messageTemplateID,templateType);
		    
		    // set the content in a templateType specific fashion		    		   
		    var commentsObj = getCommentsObj(commentsObjName);		    
		    switch (templateType) {
		    	
		    	case "SIGNATURE":
		    		SetSignature(commentsObj, content);
		    		break;

		    	case "TEMPLATE":
			    	SetTemplate(commentsObj, content, contentMergeBehavior);
		    		break;

				default: 
					SetTemplate(commentsObj, content, null);
					break;		    				    		
		    	
		    }
    		
			break;			
	}         
	
    document.body.style.cursor = "default";	                   
}

/**
 * Handles both the DHTML and textarea methods of passing the input box reference
 */
function getCommentsObj(commentsObjName) {

	var commentsObj = null;
	try {
		// document.all does NOT work
		commentsObj = document[commentsObjName];
	}
	catch (ex) {}	
	
	if (typeof(commentsObj) == "undefined")
		commentsObj = eval(commentsObjName);	
	
	return commentsObj;
}

function GetTemplateContent(messageTemplateID,templateType) {
	
    	// print a debug message to the window manager console
        if (bhsWindowManagerObj != null){
    	    bhsWindowManagerObj.Debug("Request: MessageTemplate_MessageText.cfm?messageTemplateID=" + messageTemplateID); 	
        }
    	
    	var responseHolder = "";
        var messageID = "";
    	
    	// make the ajax request	
	    var ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
        
        /*if we are getting the template for an email, lookup the userMessageUUID*/
        if (templateType == "TEMPLATE")
        {
            messageID = document.all.userMessageUUID.value;
        }

        ajaxObj.open("GET", "/BullhornStaffing/Portfolio/GetMessageTemplate.cfm?messageTemplateID=" + messageTemplateID + "&userMessageUUID=" + messageID + "&nocachetoken=" + Math.round(1000*Math.random()), false);
        ajaxObj.onreadystatechange = function() { 	
		    if (ajaxObj.readyState == 4
			    && ajaxObj.status == 200) {
		    	
					//responseHolder = trim(ajaxObj.responseText);
                    responseHolder = eval("(" + ajaxObj.responseText + ")");
 
		        }
		}
	    ajaxObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	    ajaxObj.setRequestHeader("Connection", "close");
	    ajaxObj.send();
	    
	    return responseHolder;
}

function SetSignature(commentsObj, content) {

    if (commentsObj.getHTML().match(/(<BR>|&nbsp;)*<!-- Signature [A-Z0-9\-]+ -->[\w\W\n]*<!-- End_Signature [A-Z0-9\-]+ -->/) ) {    				
			    
        // matches, so replace
        commentsObj.setHTML(
                commentsObj.getHTML().replace(
                /(<BR>|&nbsp;)*<!-- Signature ([A-Z0-9\-]+) -->[\w\W\n]*?<!-- End_Signature [A-Z0-9\-]+ -->/,
                  "&nbsp;<!-- Signature $2 -->" 
                + content.messagetext 
                + "<!-- End_Signature $2 -->" 
            )
        );
            
    } else {
                    
        // does NOT match, so insert
        commentsObj.setHTML(
              MessageForm_commentsObj.getHTML()
            + "&nbsp;<!-- Signature 1 -->" 
            + content.messagetext 
            + "<!-- End_Signature 1 -->"                                     
            );
    }
    
}      

function SetTemplate(commentsObj, content, contentMergeBehavior) {	
       
	switch (contentMergeBehavior) {
		
		case 'APPEND':
			setComments(commentsObj, getComments(commentsObj) + content["messagetext"],content);
			break;

		case 'INSERT':
			setComments(commentsObj, content["messagetext"] + getComments(commentsObj), content);			        
			break;
						
		default:	
			setComments(commentsObj, content["messagetext"],content);		
			break;
	}		
}    

function getComments(commentsObj) {	

	if (typeof(commentsObj.getHTML) == 'undefined')
		return commentsObj.value;
		
	return commentsObj.getHTML();
}

function setComments(commentsObj, content, templateObj) {
    //fire event to attach files
    if (bhsWindowManagerObj != null) {
        try {            
            if (typeof(bhsWindowManagerObj.fireEvent) != "undefined" && typeof(templateObj["attachments"]) != "undefined" && templateObj["attachments"].length > 0) {                  
                var fileIndex = document.all.attachments.length;
                if (fileIndex == 1 && document.all.attachments[0].innerText.indexOf("No Files Attached") > 0){
                    document.all.attachments.remove(fileIndex); 
                }else{  
                    fileIndex = fileIndex + 1;
                }
                
                for (var i = 0; i < templateObj["attachments"].length;i++){          
                    bhsWindowManagerObj.fireEvent("onfileattach_"+document.all.userMessageUUID.value, fileIndex+i, templateObj["attachments"][i]);  
                }
            }
        } catch (e) {
            alert(e.description)
        }
    }
                
	if (typeof(commentsObj.setHTML) == 'undefined') {
		commentsObj.value = content;
		return;
	}
		
	commentsObj.setHTML(content);	
}

/**
 * Make an Ajax call to the UpdateUserSettingAPI.cfm to update the user setting representing this
 * user's last Instant Messenger state (ie, Online, Away or Offline). This will be used at next
 * login to resume their last state.
 */
function updateUserSetting (privateLabelID, encryptedAPIKey, userID, setting, value) {
	
    // post to the web-service to persist the values    
    var URL = '/BullhornStaffing/API/UpdateUserSettingAPI.cfm';

    var parameters = 'privateLabelID=' + encodeURIComponent(privateLabelID)
    	+ '&encryptedAPIKey=' + encodeURIComponent(encryptedAPIKey)
    	+ '&userID=' + encodeURIComponent(userID)    	
    	+ '&setting=' + encodeURIComponent(setting)
    	+ '&value=' + encodeURIComponent(value);    	    	    

    var ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
    ajaxObj.open("POST", URL, true);
    ajaxObj.onreadystatechange = function() { 	
	    if (ajaxObj.readyState == 4
		    && ajaxObj.status != 200) {
	    		// do nothing, does not need to read from the results		   		    		
	        }
	}
	
    ajaxObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxObj.setRequestHeader("Content-length", parameters.length);
    ajaxObj.setRequestHeader("Connection", "close");
    ajaxObj.send(parameters); 
}
