
/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/modules/alerts/DeliveryPreferences.js
*/
var DeliveryPreferences = function() {
	DeliveryPreferences.Super(this);
}

DeliveryPreferences.Extend(Popup);

DeliveryPreferences.prototype.ACTION_MAP = {
	 'retrieve':           'retrieve'
	,'save':               'save'
};

DeliveryPreferences.prototype.BUFFER_CONTENT_TYPE = 'text/javascript';
DeliveryPreferences.prototype.BUFFER_URL = SiteRules.getURL('/resources/buffer/alerts/DeliveryPreferences.asp');

DeliveryPreferences.prototype.CLASS_NAME_FOR_ALERT_POPUP = 'alertsPopup';
DeliveryPreferences.prototype.CLASS_NAME_FOR_DELIVERY_PREFERENCES_POPUP = 'deliveryPreferencesPopup';

DeliveryPreferences.prototype.DELIVERY_METHOD = {
	 'COMPANY':   'CompanyNewsAndPriceEmail'
	,'KEYWORD':   'KeywordEmail'
	,'PORTFOLIO': 'PortfolioAndIndexEmail'
}
DeliveryPreferences.prototype.DELIVERY_STATUS = 'deliveryStatus';

DeliveryPreferences.prototype.EMAIL_ADDRESS_1 = 'emailAddress1';
DeliveryPreferences.prototype.EMAIL_ADDRESS_2 = 'emailAddress2';
DeliveryPreferences.prototype.EMAIL_FORMAT = {
	M: 'M',  // HTML (Multi-part)
	T: 'T'
};
DeliveryPreferences.prototype.EMAIL_SELECTED = 'emailSelected';

DeliveryPreferences.prototype.HREF_DEFAULT = 'javascript:void(0)';

DeliveryPreferences.prototype.TITLE_TEXT = 'Alert delivery preferences';

DeliveryPreferences.prototype.VACATION = 'vacation';

DeliveryPreferences.prototype.PREVIEW_WIDTH = 775;
DeliveryPreferences.prototype.PREVIEW_HEIGHT = 750;


DeliveryPreferences.prototype.getEventManagerForDeliveryPreferences = function() {
	// This method has been locally named getEventManagerForDeliveryPreferences() to avoid any conflicts with Popup's getEventManager().

	var em = new EventManager();

	this.getEventManager = function() {
		return em;
	}

	return this.getEventManager();
};

DeliveryPreferences.prototype.getPreferences = function() {
	var data = {
		'action': this.ACTION_MAP.retrieve
	};

	this.loadContentBuffer(data);
}

DeliveryPreferences.prototype.init = function() {
	this.wsod = WSDOM.Element.get('wsod');
	this.wsodPop = WSDOM.Element.get('wsodPop');

	Events.add(WSDOM.Element.parseSelector('A.deliveryPreferencesLink', this.wsod), 'click', this.showPopup, this);
}


DeliveryPreferences.prototype.loadContentBuffer = function(data) {
	data = data || {};

	var serializedData = Common.getSerializer().serialize(data);
	var methodForOnLoad;

	if (this.ACTION_MAP.save == data.action) {
		methodForOnLoad = this.onLoadForSavePreferences;
	} else {
		methodForOnLoad = this.onLoad;
	}

	var contentBuffer = new ContentBuffer();
		contentBuffer.abortRequests();
		contentBuffer.load(
			{
				 contentType: this.BUFFER_CONTENT_TYPE
				,context:     this
				,data:        { serializedData:serializedData }
				,onload:      methodForOnLoad
				,onerror:     this.onError
				,preventEval: true
				,url:         this.BUFFER_URL
			}
		);
}

DeliveryPreferences.prototype.onLoad = function(cb) {
	var deserializedResults = Common.getSerializer().deserialize(cb.getResult()) || false;
	// console.log(deserializedResults);

	if (!this.isVisible()) {
		this.resetPopup();

		WSDOM.Element.addClass(this.getFrame(), this.CLASS_NAME_FOR_ALERT_POPUP);
		WSDOM.Element.addClass(this.getFrame(), this.CLASS_NAME_FOR_DELIVERY_PREFERENCES_POPUP);

		this.setTitleText(this.TITLE_TEXT);

		var renderEmail,
			renderEmailFormat;

		if (deserializedResults.ShowDestinations) {
			renderEmail = this.renderDestinations(deserializedResults);
			renderEmailFormat = '';
		}
		else {
			renderEmail = this.renderEmail(deserializedResults);
			renderEmailFormat = this.renderEmailFormat(deserializedResults.Destinations);
		}

		WSDOM.Element.create('form', { 'name':'formDeliveryPreferences', 'className':'contain' }, [
			 renderEmail
			,renderEmailFormat
			,this.renderDeliveryStatus(deserializedResults)
			,this.renderActionButtons()
		], this.getContent());

		this.renderVacationStopSelectMenus(deserializedResults.Vacation);

		this.draw();
		this.sizeShim();

		this.initExampleAlerts();
	}
}

DeliveryPreferences.prototype.initExampleAlerts = function() {
    ref = this;
    
    function displayExample(ev, el) {
        if (ev) { ev.cancel(); }

        el.blur();

        var type = (el.getAttribute("exampletype"));
        var image;

        switch (type) {
            case "htmlExampleCompany":
                image = new Image(); image.src = SiteRules.getURL('/resources/image/alerts/priceHTML.png')
                break;
            case "textExampleCompany":
                image = new Image(); image.src = SiteRules.getURL('/resources/image/alerts/priceTXT.png')
                break;
            case "htmlExampleKeyword":
                image = new Image(); image.src = SiteRules.getURL('/resources/image/alerts/keywordHTML.png')
                break;
            case "textExampleKeyword":
                image = new Image(); image.src = SiteRules.getURL('/resources/image/alerts/keywordTXT.png')
                break;
            case "htmlExamplePortfolio":
                image = new Image(); image.src = SiteRules.getURL('/resources/image/alerts/portfolioHTML.png')
                break;
            case "textExamplePortfolio":
                image = new Image(); image.src = SiteRules.getURL('/resources/image/alerts/portfolioTXT.png')
                break;
        }

        if (this.showExampleWindow) {
            this.showExampleWindow.close();
        }
        
        var example = image;
        this.showExampleWindow = window.open(
                '/ft/resources/server/alerts/AlertsTemplateExample.asp?img=' + example.src,
                'alertExample',
                'width=' + (ref.PREVIEW_WIDTH) + ',height=' + (ref.PREVIEW_HEIGHT) + ',status=no,toolbar=no,resizable=yes,location=no,menubar=no,scrollbars=yes');
    }

    var templateExample = WSDOM.Element.parseSelector('A.templateExample', this.getContent());
    
    if (templateExample) {
        this.getEventManagerForDeliveryPreferences().add(templateExample, 'click', displayExample, this);
    }
}

DeliveryPreferences.prototype.onLoadForSavePreferences = function(cb) {
	var deserializedResults = Common.getSerializer().deserialize(cb.getResult()) || false;

	var statusMessage = WSDOM.Element.get('deliveryPreferencesStatusMessage');

	WSDOM.Element.setHTML(statusMessage, '');

	if (deserializedResults) {
		if (deserializedResults.errorMessage) {
			alert(deserializedResults.errorMessage);
		}
		else {
			WSDOM.Element.setHTML(statusMessage, 'Delivery preferences have been updated');

			var suspendedInformationContainer = WSDOM.Element.parseSelector('DIV.errorModuleContainer', 'wsod', 'first');

			if (suspendedInformationContainer) {
				var apForSuspend = new AlertsPopup_class();
					apForSuspend.setContainer(suspendedInformationContainer);
					apForSuspend.updateSuspendedDetails();
			}

			var aContainers = WSDOM.Element.parseSelector('DIV.alertsTablesKeyword, DIV.alertsTablesCompany, DIV.alertsTablesPortfolio, DIV.alertsTablesIndex', 'wsod');
			// console.log('aContainers', aContainers);

			for (var i = 0; i < aContainers.length; i++) {
				var ap = new AlertsPopup_class();
					ap.setContainer(aContainers[i]);
					ap.updateAlertsRedraw(null, aContainers[i].getAttribute('type'));
			}
		}
	}
	
	this.sizeShim();
}

DeliveryPreferences.prototype.onError = function(cb) {
	var deserializedResults = Common.getSerializer().deserialize(cb.getResult()) || {};
	// console.log('error', deserializedResults);

	var statusMessage = WSDOM.Element.get('deliveryPreferencesStatusMessage');

	WSDOM.Element.setHTML(statusMessage, 'This feature is not currently available.');
}

DeliveryPreferences.prototype.removeEvents = function() {
	// Remove DateSelector events
	// Events.remove(WSDOM.Element.parseSelector('*', this.getContent()));
	Events.remove(WSDOM.Element.parseSelector('*', this.getFrame()));

	// Remove global popup events
	this.getEventManager().removeAll();

	// Remove local popup events
	this.getEventManagerForDeliveryPreferences().removeAll();

	// this.getEventManager().profileEvents();
	// this.getEventManagerForDeliveryPreferences().profileEvents();

	DeliveryPreferences.Super(this, 'close');
}

DeliveryPreferences.prototype.renderActionButtons = function(oArgs) {
	oArgs = oArgs || {};

	var statusMessagePlaceholder = WSDOM.Element.create('div', { 'id':'deliveryPreferencesStatusMessage', 'className':'statusMessage alertsResult alertsSuccess' }, null);

	var cancelButton = WSDOM.Element.create('div', { 'className':'basicButtonSmall' }, WSDOM.Element.create('div', {}, 'Cancel'));
	// this.getCloseEvent().addElement(cancelButton);
	this.getEventManagerForDeliveryPreferences().add(cancelButton, 'click', this.removeEvents, this);

	var savePreferencesInnerButton = WSDOM.Element.create('div', {}, 'Save preferences');
	var savePreferencesOuterButton = WSDOM.Element.create('div', { 'className':'basicButtonSmall' }, savePreferencesInnerButton);

	this.getEventManagerForDeliveryPreferences().add(savePreferencesInnerButton, 'click', this.savePreferences, this);

	var actionButtonsContainer = WSDOM.Element.create('div', { 'className':'actionButtonsContainer contain' }, [
		WSDOM.Element.create('div', { 'className':'rightSide' }, [
			 statusMessagePlaceholder
			,cancelButton
			,savePreferencesOuterButton
		])
	]);

	return actionButtonsContainer;
}

DeliveryPreferences.prototype.renderDeliveryStatus = function(oArgs) {
	oArgs = oArgs || {};
	// console.log(oArgs);

	var oDelivery = oArgs.Destinations || {},
		companyDelivery = oDelivery[this.DELIVERY_METHOD.COMPANY] || {},
		isInactive = (companyDelivery) ? companyDelivery.isInactive : false,
		isVacation =  oArgs.Vacation.vacationOn || false;

	var elRadioStatusActive,
		elRadioStatusInactive,
		elRadioStatusVacation;

	// IE 6 hack
	try {
		elRadioStatusActive =    document.createElement('<input type="radio" class="radio" name="deliveryStatus" value="active" />');
		elRadioStatusInactive = document.createElement('<input type="radio" class="radio" name="deliveryStatus" value="inactive" />');
		elRadioStatusVacation =  document.createElement('<input type="radio" class="radio" name="deliveryStatus" value="vacation" />');
	}
	catch(e) {
		elRadioStatusActive =    WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':this.DELIVERY_STATUS, 'value':'active' });
		elRadioStatusInactive = WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':this.DELIVERY_STATUS, 'value':'inactive' });
		elRadioStatusVacation =  WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':this.DELIVERY_STATUS, 'value':this.VACATION });
	}

	if (isInactive) {
		elRadioStatusInactive.checked = 'checked';
		elRadioStatusInactive.defaultChecked = 'true';
	}
	else if (isVacation) {
		elRadioStatusVacation.checked = 'checked';
		elRadioStatusVacation.defaultChecked = 'true';
	}
	else {
		elRadioStatusActive.checked = 'checked';
		elRadioStatusActive.defaultChecked = 'true';
	}

	var vacationStopContainer = WSDOM.Element.create('div', { 'className':'controlGroup deliveryStatusGroup' }, [
			 WSDOM.Element.create('h2', {}, 'Delivery Status')
			,WSDOM.Element.create('div', { 'className':'radioGroup' }, [
				WSDOM.Element.create('label', {}, [
					 elRadioStatusActive
					,WSDOM.Element.create('span', {}, 'Active')
					,WSDOM.Element.create('span', { 'className':'details' }, ' - Alerts will be delivered as scheduled.')
				])
			])
			,WSDOM.Element.create('div', { 'className':'radioGroup' }, [
				WSDOM.Element.create('label', {}, [
					 elRadioStatusInactive
					,WSDOM.Element.create('span', {}, 'Inactive')
					,WSDOM.Element.create('span', { 'className':'details' }, ' - You may temporarily stop alerts delivery without affecting your current subscriptions.')
				])
			])
			,WSDOM.Element.create('div', { 'className':'radioGroup' }, [
				WSDOM.Element.create('label', {}, [
					 elRadioStatusVacation
					,WSDOM.Element.create('span', {}, 'Vacation')
					,WSDOM.Element.create('span', { 'className':'details' }, ' - Stop delivery of all alerts between these dates.')
				])
			])
			,WSDOM.Element.create('div', { 'className':'vacationStopForm indent' }, [
				 WSDOM.Element.create('span', { 'className':'details' }, 'Stop sending')
				,WSDOM.Element.create('span', { 'id':'vacationStopDatesContainer_1' }, null)
				,WSDOM.Element.create('span', { 'className':'details' }, 'Resume sending')
				,WSDOM.Element.create('span', { 'id':'vacationStopDatesContainer_2' }, null)
			])
		]
	);

	return vacationStopContainer;
}

DeliveryPreferences.prototype.renderDestinations = function(oArgs) {
	oArgs = oArgs || {};
	// console.log(oArgs);

	var oDelivery = oArgs.Destinations || {},
		companyDelivery = oDelivery[this.DELIVERY_METHOD.COMPANY] || {},
		keywordDelivery = oDelivery[this.DELIVERY_METHOD.KEYWORD] || {},
		portfolioDelivery = oDelivery[this.DELIVERY_METHOD.PORTFOLIO] || {},
		elEmailContainer,
		elInputEmailCompany,
		elInputEmailKeyword,
		elInputEmailPortfolio,
		elRadioHTML_Keyword,
		elRadioHTML_Company,
		elRadioHTML_Portfolio,
		elRadioText_Keyword,
		elRadioText_Company,
		elRadioText_Portfolio,
		valueForElInputEmailCompany = companyDelivery.email || oDelivery.FTDestination.email,
		valueForElInputEmailKeyword = keywordDelivery.email || oDelivery.FTDestination.email,
		valueForElInputEmailPortfolio = portfolioDelivery.email || oDelivery.FTDestination.email;

	// IE 6 hack
	try {
		elRadioHTML_Keyword =   document.createElement('<input type="radio" class="radio" name="emailFormatKeyword" value="' + this.EMAIL_FORMAT.M + '" />');
		elRadioHTML_Company =   document.createElement('<input type="radio" class="radio" name="emailFormatCompany" value="' + this.EMAIL_FORMAT.M + '" />');
		elRadioHTML_Portfolio = document.createElement('<input type="radio" class="radio" name="emailFormatPortfolio" value="' + this.EMAIL_FORMAT.M + '" />');
		elRadioText_Keyword =   document.createElement('<input type="radio" class="radio" name="emailFormatKeyword" value="' + this.EMAIL_FORMAT.T + '" />');
		elRadioText_Company =   document.createElement('<input type="radio" class="radio" name="emailFormatCompany" value="' + this.EMAIL_FORMAT.T + '" />');
		elRadioText_Portfolio = document.createElement('<input type="radio" class="radio" name="emailFormatPortfolio" value="' + this.EMAIL_FORMAT.T + '" />');
	} catch(e) {
		elRadioHTML_Keyword =   WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormatKeyword', 'value':this.EMAIL_FORMAT.M });
		elRadioHTML_Company =   WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormatCompany', 'value':this.EMAIL_FORMAT.M });
		elRadioHTML_Portfolio = WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormatPortfolio', 'value':this.EMAIL_FORMAT.M });
		elRadioText_Keyword =   WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormatKeyword', 'value':this.EMAIL_FORMAT.T });
		elRadioText_Company =   WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormatCompany', 'value':this.EMAIL_FORMAT.T });
		elRadioText_Portfolio = WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormatPortfolio', 'value':this.EMAIL_FORMAT.T });
	}

	if (this.EMAIL_FORMAT.T == companyDelivery.format) {
		elRadioText_Company.checked = 'checked';
		elRadioText_Company.defaultChecked = 'true';
	} else {
		elRadioHTML_Company.checked = 'checked';
		elRadioHTML_Company.defaultChecked = 'true';
	}

	if (this.EMAIL_FORMAT.T == keywordDelivery.format) {
		elRadioText_Keyword.checked = 'checked';
		elRadioText_Keyword.defaultChecked = 'true';
	} else {
		elRadioHTML_Keyword.checked = 'checked';
		elRadioHTML_Keyword.defaultChecked = 'true';
	}

	if (this.EMAIL_FORMAT.T == portfolioDelivery.format) {
		elRadioText_Portfolio.checked = 'checked';
		elRadioText_Portfolio.defaultChecked = 'true';
	} else {
		elRadioHTML_Portfolio.checked = 'checked';
		elRadioHTML_Portfolio.defaultChecked = 'true';
	}

	var elEmailContainer = WSDOM.Element.create('div', { 'className':'controlGroup destinationGroup' }, [
		WSDOM.Element.create('H2', {}, 'Alert Destinations &amp; Format'),
		WSDOM.Element.create('DIV', { 'className':'deliveryTypeContainer contain' }, [
			 WSDOM.Element.create('DIV', { 'className':'deliveryType' }, 'Keyword Alerts')
			,WSDOM.Element.create('DIV', { 'className':'emailAddressAndFormat' }, [
				 WSDOM.Element.create('INPUT', { 'name':'emailAddressKeyword', 'emailName':'emailAddressKeyword', 'type':'text', 'value':valueForElInputEmailKeyword, 'className':'emailAddress' })
				,WSDOM.Element.create('DIV', { 'className':'radioGroup' }, [
					WSDOM.Element.create('LABEL', {}, [
						 elRadioHTML_Keyword
						,WSDOM.Element.create('SPAN', {}, 'HTML')
					])
					, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'htmlExampleKeyword' }, 'example')
				])
				,WSDOM.Element.create('DIV', { 'className':'radioGroup last' }, [
					WSDOM.Element.create('LABEL', {}, [
						 elRadioText_Keyword
						,WSDOM.Element.create('SPAN', {}, 'Text only')
					])
					, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'textExampleKeyword' }, 'example')
				])
			])
		])
		,WSDOM.Element.create('DIV', { 'className':'deliveryTypeContainer contain' }, [
			 WSDOM.Element.create('DIV', { 'className':'deliveryType' }, 'Company News &amp; Price Alerts')
			,WSDOM.Element.create('DIV', { 'className':'emailAddressAndFormat' }, [
				 WSDOM.Element.create('INPUT', { 'name':'emailAddressCompany', 'emailName':'emailAddressCompany', 'type':'text', 'value':valueForElInputEmailCompany, 'className':'emailAddress' })
				,WSDOM.Element.create('DIV', { 'className':'radioGroup' }, [
					WSDOM.Element.create('LABEL', {}, [
						 elRadioHTML_Company
						,WSDOM.Element.create('SPAN', {}, 'HTML')
					])
					, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'htmlExampleCompany' }, 'example')
				])
				,WSDOM.Element.create('DIV', { 'className':'radioGroup last' }, [
					WSDOM.Element.create('LABEL', {}, [
						 elRadioText_Company
						,WSDOM.Element.create('SPAN', {}, 'Text only')
					])
					, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'textExampleCompany' }, 'example')
				])
			])
		])
		,WSDOM.Element.create('DIV', { 'className':'deliveryTypeContainer contain' }, [
			 WSDOM.Element.create('DIV', { 'className':'deliveryType' }, 'Portfolio &amp; Index Alerts')
			,WSDOM.Element.create('DIV', { 'className':'emailAddressAndFormat' }, [
				 WSDOM.Element.create('INPUT', { 'name':'emailAddressPortfolio', 'emailName':'emailAddressPortfolio', 'type':'text', 'value':valueForElInputEmailPortfolio, 'className':'emailAddress' })
				,WSDOM.Element.create('DIV', { 'className':'radioGroup' }, [
					WSDOM.Element.create('LABEL', {}, [
						 elRadioHTML_Portfolio
						,WSDOM.Element.create('SPAN', {}, 'HTML')
					])
					, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'htmlExamplePortfolio' }, 'example')
				])
				,WSDOM.Element.create('DIV', { 'className':'radioGroup last' }, [
					WSDOM.Element.create('LABEL', {}, [
						 elRadioText_Portfolio
						,WSDOM.Element.create('SPAN', {}, 'Text only')
					])
					, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'textExamplePortfolio' }, 'example')
				])
			])
		])
	]);

	return elEmailContainer;
}

DeliveryPreferences.prototype.renderEmail = function(oArgs) {
	oArgs = oArgs || {};

	var oDelivery = oArgs.Destinations || {},
		companyDelivery = oDelivery[this.DELIVERY_METHOD.COMPANY] || {},
		elEmailContainer,
		elInputEmail,
		elInputEmailAlternate,
		elRadioEmailDefault,
		elRadioEmailAlternate,
		emailAddresses = oArgs.EmailAddresses || {},
		selectedEmail,
		valueForElInputEmail = emailAddresses.emailAddress1 || companyDelivery.email || oDelivery.FTDestination.email,
		valueForElInputEmailAlternate = emailAddresses.emailAddress2 || '';

	if (companyDelivery.email) {
		selectedEmail = companyDelivery.email;
	}

	// IE 6 hack
	try {
		elRadioEmailDefault =   document.createElement('<input type="radio" class="radio" name="emailSelected" value="emailSelected1" />');
		elRadioEmailAlternate = document.createElement('<input type="radio" class="radio" name="emailSelected" value="emailSelected2" />');
	} catch(e) {
		elRadioEmailDefault =   WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':this.EMAIL_SELECTED, 'value':'emailSelected1' });
		elRadioEmailAlternate = WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':this.EMAIL_SELECTED, 'value':'emailSelected2' });
	}

	var elEmailContainer = WSDOM.Element.create('div', { 'className':'controlGroup emailGroup' }, [
		WSDOM.Element.create('h2', {}, 'Email'),
		WSDOM.Element.create('div', { 'className':'contain' }, [
			WSDOM.Element.create('div', { 'className':'radioGroup' }, [
				WSDOM.Element.create('label', {}, [
					 elRadioEmailDefault
					,WSDOM.Element.create('span', {}, 'Alerts will be sent to')
				]),
				elInputEmail = WSDOM.Element.create("input", { "name":this.EMAIL_ADDRESS_1, "type":"text", "value":valueForElInputEmail, 'className':'emailAddress indent' })
			]),
			WSDOM.Element.create('div', { 'className':'radioGroup last' }, [
				WSDOM.Element.create("label", {}, [
					 elRadioEmailAlternate
					,WSDOM.Element.create('span', {}, 'Send to an alternate email address')
				]),
				elInputEmailAlternate = WSDOM.Element.create("input", { "name":this.EMAIL_ADDRESS_2, "type":"text", "value":valueForElInputEmailAlternate, 'className':'emailAddress indent' })
			])
		])
	]);

	if (valueForElInputEmailAlternate.length && (valueForElInputEmailAlternate == selectedEmail)) {
		elRadioEmailAlternate.checked = 'checked';
		elRadioEmailAlternate.defaultChecked = 'true';
	} else {
		elRadioEmailDefault.checked = 'checked';
		elRadioEmailDefault.defaultChecked = 'true';
	}

	return elEmailContainer;
}

DeliveryPreferences.prototype.renderEmailFormat = function(oDelivery) {
	oDelivery = oDelivery || {};

	var companyDelivery = oDelivery[this.DELIVERY_METHOD.COMPANY] || {},
		elEmailFormat,
		elRadioHTML,
		elRadioText;

	// IE 6 hack
	try {
		elRadioHTML = document.createElement('<input type="radio" class="radio" name="emailFormat" value="' + this.EMAIL_FORMAT.M + '" />');
		elRadioText = document.createElement('<input type="radio" class="radio" name="emailFormat" value="' + this.EMAIL_FORMAT.T + '" />');
	} catch(e) {
		elRadioHTML = WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormat', 'value':this.EMAIL_FORMAT.M });
		elRadioText = WSDOM.Element.create('INPUT', { 'type':'radio', 'className':'radio', 'name':'emailFormat', 'value':this.EMAIL_FORMAT.T });
	}

	var elEmailFormat = WSDOM.Element.create('div', { 'className':'controlGroup emailFormatGroup' }, [
		WSDOM.Element.create('h2', {}, 'Email Format'),
		WSDOM.Element.create('div', { 'className':'contain' }, [
			WSDOM.Element.create('div', { 'className':'radioGroup' }, [
				WSDOM.Element.create('label', {}, [
					 elRadioHTML
					,WSDOM.Element.create('span', {}, 'HTML')
				])
				, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'htmlExampleCompany' }, 'example')
			]),
			WSDOM.Element.create('div', { 'className':'radioGroup last' }, [
				WSDOM.Element.create('label', {}, [
					 elRadioText
					,WSDOM.Element.create('span', {}, 'Text only')
				])
				, WSDOM.Element.create('A', { 'href': this.HREF_DEFAULT, 'className': 'templateExample', 'exampleType': 'textExampleCompany' }, 'example')
			])
		])
	]);

	if (this.EMAIL_FORMAT.T == companyDelivery.format) {
		elRadioText.checked = 'checked';
		elRadioText.defaultChecked = 'true';
	} else {
		elRadioHTML.checked = 'checked';
		elRadioHTML.defaultChecked = 'true';
	}

	return elEmailFormat;
}

DeliveryPreferences.prototype.renderVacationStopSelectMenus = function(oArgs) {
	oArgs = oArgs || false;

	var vacationStopContainers = [ WSDOM.Element.get('vacationStopDatesContainer_1'), WSDOM.Element.get('vacationStopDatesContainer_2') ];

	var today = new Date();
	var todayYear = today.getFullYear();
	var startOrEndDate;
	var startOrEndYear;
	var startYear = 0;
	var endYear = 1;

	this.dateSelects = {};

	for (var i = 0; i < vacationStopContainers.length; i++) {
		if (oArgs && !oArgs.vacationOn) {
			startOrEndDate = today;
		}
		else {
			if (0 == i) {
				startOrEndDate = (oArgs && oArgs.vacationStart) ? new Date(oArgs.vacationStart.replace(/(\d{4})(\d{2})(\d{2})/,'$1/$2/$3')) : today;
			}
			else {
				startOrEndDate = (oArgs && oArgs.vacationEnd) ? new Date(oArgs.vacationEnd.replace(/(\d{4})(\d{2})(\d{2})/,'$1/$2/$3')) : today;
			}
		}

		startOrEndYear = startOrEndDate.getFullYear();

		if (startOrEndYear != todayYear) {
			startYear = todayYear - startOrEndYear;
			endYear = 0;
		}

		this.dateSelects[i] = new DateSelector(		
			{
				 container:    vacationStopContainers[i]
				,date:         new Date(startOrEndDate)
				,debug:        0
				,endYear:      endYear
				,fieldName:    'vacation' + (i ? 'End' : 'Start')
				,monthFormat:  '!mmm'
				,startYear:    startYear
			}
		);
	}
}

DeliveryPreferences.prototype.resetPopup = function() {
	this.setTitleText('');
	this.clearContent();
}

DeliveryPreferences.prototype.savePreferences = function(ev, el) {
	if (ev) { ev.cancel(); }

	var aErrorMessages = [],
		currentEmail,
		currentEmailValue,
		currentInput,
		destinationGroup = WSDOM.Element.parseSelector('DIV.destinationGroup', elForm, 'first'),
		elForm = WSDOM.Element.parseSelector('FORM', this.getFrame(), 'first'),
		elChecked = WSDOM.Element.parseSelector('INPUT[checked=.`true`]', elForm),
		emailAddress,
		emailAddresses = WSDOM.Element.parseSelector('INPUT.emailAddress', elForm),
		emailAddressValue,
		emailPreferenceParent,
		isError = false,
		iTodaysDate,
		oParams = {},
		vacationEnd,
		vacationStart;

	for (var i = 0; i < elChecked.length; i++) {
		currentInput = elChecked[i];

		oParams[currentInput.getAttribute('name')] = currentInput.value;

		if (this.EMAIL_SELECTED == currentInput.name) {
			emailPreferenceParent = WSDOM.Element.getParent(currentInput, 'DIV');
			emailAddress = WSDOM.Element.parseSelector('INPUT.emailAddress', emailPreferenceParent, 'first');

			emailAddressValue = trim(emailAddress.value);

			if (!emailAddressValue.length) {
				aErrorMessages.push('The selected email address is missing.');
				isError = true;
			}
			else {
				oParams[currentInput.getAttribute('name')] = emailAddressValue;  // Select which email address to use
			}
		}
		else if ((this.DELIVERY_STATUS == currentInput.name) && (this.VACATION == currentInput.value)) {
			iTodaysDate = Math.floor(jsToMsDate(new Date()));

			vacationStart = WSDOM.Element.parseSelector('INPUT[name="vacationStart"]', elForm, 'first');
			vacationEnd =   WSDOM.Element.parseSelector('INPUT[name="vacationEnd"]', elForm, 'first');

			oParams.vacationStart = Math.floor(jsToMsDate(new Date(vacationStart.value)));
			oParams.vacationEnd =   Math.floor(jsToMsDate(new Date(vacationEnd.value)));

			if (iTodaysDate > oParams.vacationStart || iTodaysDate > oParams.vacationEnd) {
				aErrorMessages.push('Vacation dates must not be before today\'s date.');
				isError = true;
			}
			else if (oParams.vacationStart > oParams.vacationEnd) {
				aErrorMessages.push('The vacation "resume" date must not be before the "stop" date.');
				isError = true;
			}
			else if (oParams.vacationStart == oParams.vacationEnd) {
				aErrorMessages.push('The vacation "resume" date must not be the same as the "stop" date.');
				isError = true;
			}
		}
	}

	for (var i = 0; i < emailAddresses.length; i++) {
		currentEmail = emailAddresses[i];
		currentEmailValue = trim(currentEmail.value);

		if (currentEmailValue.length) {
			if (!Common.validateEmail(currentEmailValue)) {
				aErrorMessages.push('The email address "' + currentEmailValue + '" is not valid.');
				isError = true;
			}
			else {
				oParams[currentEmail.getAttribute('emailName')] = currentEmailValue;  // Set the email preference(s)
			}
		}
		else if (destinationGroup && !currentEmailValue.length) {
			aErrorMessages.push('Blank email addresses are not valid.');
			isError = true;			
		}
	}

	if (!isError) {
		// console.log(oParams);

		this.loadContentBuffer({
			 'action': this.ACTION_MAP.save
			,'inputs': oParams
		});
	}
	else {
		if (aErrorMessages.length) {
			alert('Correct the following errors:\n\n' + aErrorMessages.join('\n'));
		}
	}
}

DeliveryPreferences.prototype.showPopup = function(ev, el) {
	if (ev) { ev.cancel(); }

	el.blur();

	this.getPreferences();
}

/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/modules/glossary/InfernoDiscussion.js
*/
var InfernoDiscussion_class = function() {}

InfernoDiscussion_class.prototype.init = function() {
	Events.add(window, "load", function(){
		var commentScript = document.createElement("SCRIPT");
		commentScript.type = "text/javascript";
		commentScript.src = "http://inferno.wsodqa.com/commentlib2";
		document.getElementsByTagName("HEAD")[0].appendChild(commentScript);
	});
}

var infernoDiscussion = new InfernoDiscussion_class();
	infernoDiscussion.init();