
/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/modules/alerts/Popup_Alerts.js
*/
var AlertsPopup_class = function() {
	this.delayDeleteWarning = {};
}

AlertsPopup_class.Extend(Popup);

AlertsPopup_class.prototype.BUFFER_CONTENT_TYPE = 'text/javascript';
AlertsPopup_class.prototype.BUFFER_URL_DELIVERY_SUSPENDED = SiteRules.getURL('/resources/buffer/alerts/DeliverySuspended.asp');

AlertsPopup_class.prototype.CSS_ALERT_POPUP = "alertsPopup";
AlertsPopup_class.prototype.CSS_COMPANY_ALERT_POPUP = "AlertsPopup";

AlertsPopup_class.prototype.ERROR_MESSAGE_DEFAULT = 'There was a problem saving your alert settings, please try again.';

AlertsPopup_class.prototype.KEY_CODE_ENTER = 13;

AlertsPopup_class.prototype.PATH_ALERTS_POPUP = SiteRules.getURL("/resources/buffer/alerts/AlertsPopup.asp");
AlertsPopup_class.prototype.PATH_UPDATE_ALERTS = SiteRules.getURL("/resources/buffer/alerts/UpdateAlerts.asp");
AlertsPopup_class.prototype.PATH_ALERTS_TABLES = SiteRules.getURL("/resources/buffer/alerts/AlertsTables.asp");
AlertsPopup_class.prototype.PATH_ALERTS_QUOTE_DATA = SiteRules.getURL("/resources/buffer/alerts/CompanyAlertsData.asp");

AlertsPopup_class.prototype.UNSUPPORTED_DELIVERY_ITEMS = {
	'Twitter': {
		'453': true,
		'454': true
	}
/*
	// Possible addition for Phase 3 ???
	,'iPhone': {
		'453': true,
		'454': true
	}
*/
}

AlertsPopup_class.prototype.POPUP_TITLE_MAP = {
	'AddKeyword':'Create a new keyword alert',
	'EditKeyword':'Edit a keyword alert',
	'AddCompany':'Set a company alert',
	'EditCompany':'Edit a company alert',
	'AddIndex':'Set an index alert',
	'EditIndex':'Edit an index alert',
	'AddPortfolio':'Add a portfolio alert',
	'EditPortfolio':'Edit a portfolio alert',
	'SubscriptionLevel':'Your subscription level has changed'
};

AlertsPopup_class.prototype.URL_MAP = {
	'Keyword':'keyword.asp',
	'Company':'company-News-And-Price.asp',
	'Index':'portfolio-And-Index.asp',
	'Portfolio':'portfolio-And-Index.asp'
}

AlertsPopup_class.prototype.ERROR_CODES = {
	 '7929861': 'The alert can\'t be saved. Please edit your Preferences and try again.'
	,'-1001':   'You have reached the limit for your account for this type of alert.'
	,'-1002':   'You do not currently have an email address configured. Please edit your Preferences and try again.'
	,'-10001':  'You cannot set an alert for "Price drops below" that is above the current trading price of a security.'
	,'-10002':  'You cannot set an alert for "Price rises above" that is below the current trading price of a security.'
	,'-10003':  'The symbol appears to be invalid.'
	,'-10004':  'There is an identical alert already saved. Please change your settings and try again.'
}

AlertsPopup_class.prototype.TIMEFRAME_DISCLAIMERS = {
	'p16':'Weekly alerts are sent at 7pm BST on Friday.',
	'p8':'Monthly alerts are sent at 7pm BST on the last day of the month.'
}

AlertsPopup_class.prototype.dragStart = function() {
	return false;
}

AlertsPopup_class.prototype.isHistory = function() { this.setType('History'); }
AlertsPopup_class.prototype.isKeyword = function() { this.setType('Keyword');}
AlertsPopup_class.prototype.isCompany = function() { this.setType('Company');}
AlertsPopup_class.prototype.isPortfolio = function() { this.setType('Portfolio');}
AlertsPopup_class.prototype.isIndex = function() { this.setType('Index');}

AlertsPopup_class.prototype.getErrorMessage = function(oResult) {
	oResult = oResult || {};

	var sStatus = oResult.status || false
		,sErrorMessage = (sStatus && this.ERROR_CODES[sStatus]) ? this.ERROR_CODES[sStatus] : this.ERROR_MESSAGE_DEFAULT;

	return sErrorMessage;
}

AlertsPopup_class.prototype.getType = function() { return "Company"; }
AlertsPopup_class.prototype.setType = function(sType) {
	this.getType = function() { return sType; }
}

AlertsPopup_class.prototype.getDrawInPopup = function() { return false; }
AlertsPopup_class.prototype.isDrawInPopup = function() {
	this.getDrawInPopup = function() {
		return true;
	}
}

AlertsPopup_class.prototype.getContainer = function() { return WSDOM.Element.get("wsod"); }
AlertsPopup_class.prototype.setContainer = function(elContainer) {
	if (!elContainer) { return; }

	this.getContainer = function() { return elContainer; }
}

AlertsPopup_class.prototype.init = function() {
	this.setContainer(WSDOM.Element.parseSelector("div.alertsTables"+this.getType(), "wsod", "first"));

	Events.add(WSDOM.Element.parseSelector("div.buttonSet"+this.getType()+"Alert", "wsod"), "click", this.initAddEditPopup, this, {});
	Events.add(WSDOM.Element.get("setAlert"), "click", this.initAddEditPopup, this, {});
	
	this.attachTableEvents();
}

AlertsPopup_class.prototype.attachTableEvents = function() {
	Events.add(WSDOM.Element.parseSelector("div.buttonSet"+this.getType()+"Alert", this.getContainer()), "click", this.initAddEditPopup, this, {});

	if ('Portfolio' != this.getType()) {
		Events.add(WSDOM.Element.parseSelector("div[buttonSymbol],a[buttonSymbol]", this.getContainer()), "click", this.initAddEditPopup, this, {});
	} else {
		Events.add(WSDOM.Element.parseSelector("div[buttonPortfolioID],a[buttonPortfolioID]", this.getContainer()), "click", this.initAddEditPopup, this, {});
	}
	
	Events.add(WSDOM.Element.parseSelector("a.icon-edit", this.getContainer()), "click", this.initAddEditPopup, this, {isEdit: true});
	Events.add(WSDOM.Element.parseSelector("a.icon-delete-close", this.getContainer()), "click", this.initDeletePopup, this);
	
	Events.add(WSDOM.Element.parseSelector(".alertsTableContainer select[name='Timeframe']", this.getContainer()), "change", this.changeTimeframe, this);
	Events.add(WSDOM.Element.parseSelector(".alertsTableContainer input[type='checkbox'][checked=.`false`]", this.getContainer()), "click", this.toggleDeliveryOption, this);
	Events.add(WSDOM.Element.parseSelector(".alertsTableContainer input[type='checkbox'][checked=.`true`]", this.getContainer()), "click", this.toggleDeliveryOption, this);
}

AlertsPopup_class.prototype.resetPopup = function() {
	this.setTitleText("");
	WSDOM.Element.addClass(this.getContent(), "contain");
	this.clearContent();
	
	sCSSPopup = 'keywordAlertsPopup';
	
	if ('Company' == this.getType() || 'Index' == this.getType()) {
		sCSSPopup = 'addCompany'+this.CSS_COMPANY_ALERT_POPUP;
	}
		
	WSDOM.Element.addClass(this.getFrame(), this.CSS_ALERT_POPUP);
	WSDOM.Element.addClass(this.getFrame(), sCSSPopup);
	
	WSDOM.Element.removeClass(this.getFrame(), "addCompanyAlertsPopup");
	WSDOM.Element.removeClass(this.getFrame(), "editCompanyAlertsPopup");
	WSDOM.Element.removeClass(this.getFrame(), "deleteCompanyAlertsPopup");
}

AlertsPopup_class.prototype.initPopup = function(action, params, symbol) {
	var callback = "draw" + action.substr(0,1).toUpperCase() + action.substr(1, action.length-1) + "Popup";

	this.getContentBuffer().abortRequests();
	this.getContentBuffer().load({
		debug: true,
		url: this.PATH_ALERTS_POPUP,
		method: "post",
		contentType: "text/html",
		context:this,
		data: {
			type: this.getType(),
			action: action,
			symbol: symbol || '',
			params: Common.getSerializer().serialize(params)
		},
		onload: this[callback]
	});
}

AlertsPopup_class.prototype.initAddEditPopup = function(e, el, data) {
	e.cancel();

	var oTableOuterContainer = WSDOM.Element.parseSelector('DIV.alertsTablesModule', 'wsod', 'first'),
		oTableInnerContainer = WSDOM.Element.parseSelector('DIV.innerContainer', oTableOuterContainer, 'first'),
		tm = oTableInnerContainer ? oTableInnerContainer.getAttribute('tm') : '';  // 'tm' stands for "Too Many" (alerts) in cases where FT has downgraded a user's subscription level

	if (tm) {
		this.initPopup('tm', { 'value':tm });
	}
	else {
		var oParams = {},
			sSymbol = el.getAttribute('buttonSymbol') || '';

		if (data.isEdit) {
			var elParent = WSDOM.Element.getParentBySelector(el, "tr"),
				aActiveItems = WSDOM.Element.parseSelector("input[type='checkbox'][checked=.`true`]", elParent),
				sItemID = elParent.getAttribute("itemID"),
				sQueryName = elParent.getAttribute("queryName"),
				sDeliveryType;

			oParams = Common.getSerializer().deserialize(elParent.getAttribute("params"));
			oParams.item = elParent.getAttribute("item");
			oParams.deliveryType = [];

			if (sItemID) { oParams.itemID = sItemID; }
			if (sQueryName) { oParams.queryName = sQueryName; }

			for (var i = 0; i < aActiveItems.length; i++) {
				oParams.deliveryType.push(aActiveItems[i].getAttribute("deliveryType"));
			}
		}

		this.initPopup(data.isEdit?'edit':'add', oParams, sSymbol);
	}
}

AlertsPopup_class.prototype.initDeletePopup = function(e, el, data) {
	e.cancel();

	var elParent = WSDOM.Element.getParentBySelector(el, "tr"),
		sItemID = elParent.getAttribute("itemID"),
		sQueryName = elParent.getAttribute("queryName"),
		oParams = {};
		
	if (sItemID) { oParams.itemID = sItemID; }
	if (sQueryName) { oParams.queryName = sQueryName; }
		
	this.initPopup('delete', oParams);
}

AlertsPopup_class.prototype.drawDeletePopup = function(cb) {
	var result = cb.getResult(),
		elPopupBody;

	this.resetPopup();
	
	this.setTitleText("Delete this alert?");
	WSDOM.Element.addClass(this.getFrame(), "deleteCompanyAlertsPopup");
	
	elPopupBody = WSDOM.Element.create("div", {"class":"popupBody"}, result, this.getContent());

	this.getEventManagerCompanyAlerts().add(WSDOM.Element.parseSelector("div.buttonSubmit", elPopupBody), "click", this.saveAlerts, this);
	this.getEventManagerCompanyAlerts().add(WSDOM.Element.parseSelector("div.buttonDelete", elPopupBody), "click", this.close, this);
	
	this.draw();
	this.sizeShim();

	this.position();
}

AlertsPopup_class.prototype.drawTmPopup = function(cb) {
	var result = cb.getResult();
	// console.log(result);

	this.resetPopup();

	WSDOM.Element.addClass(this.getFrame(), 'subscriptionAlertsPopup');
	this.setTitleText(this.POPUP_TITLE_MAP['SubscriptionLevel'] || '');

	elPopupBody = WSDOM.Element.create('DIV', { 'class':'popupBody' }, result, this.getContent());

	this.getEventManagerCompanyAlerts().add(WSDOM.Element.parseSelector('DIV.buttonSaveSubscriptions', elPopupBody), 'click', this.saveSubscriptions, this);

    this.draw();
    this.sizeShim();
}

AlertsPopup_class.prototype.drawAddPopup = function(cb, sType) {
    sType = sType || 'Add';

    var result = cb.getResult(),
		elPopupBody,
		elSymbolLookup,
		ref = this;

    this.resetPopup();

    this.setTitleText(this.POPUP_TITLE_MAP[sType + this.getType()] || "");
        
    if ('Company' == this.getType() || 'Index' == this.getType()) {
        WSDOM.Element.addClass(this.getFrame(), sType.toLowerCase() + "CompanyAlertsPopup");
    }

    elPopupBody = WSDOM.Element.create("div", { "class": "popupBody" }, result, this.getContent());

    elSymbolLookup = WSDOM.Element.parseSelector("div.alertsSymbolInput input", elPopupBody, "first");
    elDeliverySelect = WSDOM.Element.get("deliveryControl");
    elTimeframeSelect = WSDOM.Element.parseSelector("select[name='Timeframe']", elPopupBody, "first");

    this.getEventManagerCompanyAlerts().add(elSymbolLookup, "focus", Common.focusText, Common);
    this.getEventManagerCompanyAlerts().add(elSymbolLookup, "blur", Common.blurText, Common);
    //this.getEventManagerCompanyAlerts().add(elDeliverySelect, "change", this.togglePopupTimeframe, this);
    this.getEventManagerCompanyAlerts().add(WSDOM.Element.parseSelector("div.buttonSubmit", elPopupBody), "click", this.saveAlerts, this);
    this.getEventManagerCompanyAlerts().add(WSDOM.Element.parseSelector("div.buttonCancel", elPopupBody), 'click', this.close, this);

    this.getEventManagerCompanyAlerts().add(WSDOM.Element.get('keywordsInput'), 'keypress', this.handleTheKeypress, this);

    this.getEventManagerCompanyAlerts().add(WSDOM.Element.parseSelector("div.editSymbolButton", elPopupBody), "click", this.editSymbol, this);

    if (elTimeframeSelect) {
        this.getEventManagerCompanyAlerts().add(elTimeframeSelect, "change", this.displayTimeframeDisclaimer, this);
    }

    if (elSymbolLookup) {
        var elForm = WSDOM.Element.parseSelector("form[name='addEditAlertItem']", elPopupBody, "first");

        var s = new SymbolSearch();

        if ('Index' == this.getType()) {
            s.setIssueType('IN');
        } else {
            s.setIssueType('EQ');
        }

        s.moreResultsPopupMode(true);
        s.moreResultsHandlerCallback(
				function(popup, parent) {
				    var elLinks = WSDOM.Element.parseSelector('.interactiveChartLink', parent || WSDOM.Element.get('wsod'));

				    WSDOM.Events.add(elLinks, 'click', function(e, el) {
				        e.cancel();

				        var symbol = el.getAttribute('intchartsymbol');

				        this.go(symbol);

				        popup.close();
				    } .Context(s));
				}
			);
        s.setForm(elForm);
        s.setRequestor(new ContentBuffer());

        s.go = function(symbol) {
            this.clearResults();

            this.query = symbol;

            WSDOM.Element.get("alertsSymbol").value = symbol;

            ref.getQuoteData();
        };

        s.setSymbolDisplay = function(cb) {
            var result = Common.getSerializer().deserialize(cb.getResult()),
					elParent = WSDOM.Element.getParentBySelector(this.elInput, "form.addEditAlertItem"),
					elInputContainer = WSDOM.Element.parseSelector("div.alertsSymbolInput", elParent, "first"),
					elDisplayContainer = WSDOM.Element.parseSelector("div.alertsSymbolDisplay", elParent, "first"),
					dynamicQuoteValues = WSDOM.Element.parseSelector("span.dynamicQuoteValue", elParent);

            WSDOM.Element.get("alertsSymbol").value = result['Bridge'];

            WSDOM.Element.setHTML(WSDOM.Element.parseSelector("div", elDisplayContainer, "first"), result['Name'] + '<span>' + result['FTStandard'] + '</span>');

            for (var i = 0; i < dynamicQuoteValues.length; i++) {
                WSDOM.Element.setHTML(dynamicQuoteValues[i], result['Quote'][dynamicQuoteValues[i].getAttribute("key")]);
            }

            WSDOM.Element.addClass(elInputContainer, "wsodHidden");
            WSDOM.Element.removeClass(elDisplayContainer, "wsodHidden");
        }
        s.eventManager.add(s.elForm, "submit", function(e) {
            e.cancel();
            this.go(this.elInput.value);
        } .Context(s), this);
    }

    if (WSDOM.Element.get("alertsSymbol") && WSDOM.Element.get("alertsSymbol").value) {
        this.getQuoteData('Bridge');
    }

    this.draw();
    this.sizeShim();
}

AlertsPopup_class.prototype.drawEditPopup = function(cb) {
	this.drawAddPopup(cb, 'Edit');
}

AlertsPopup_class.prototype.displayTimeframeDisclaimer = function(e, el) {
	if (this.elDisclaimer) {
		WSDOM.Element.remove(this.elDisclaimer);
		this.elDisclaimer = null;
	}

	if (this.TIMEFRAME_DISCLAIMERS[el.value]) {
		this.elDisclaimer = WSDOM.Element.create("div", {"class":"disclaimerText"}, this.TIMEFRAME_DISCLAIMERS[el.value]);
		WSDOM.Element.insertBefore(this.elDisclaimer, WSDOM.Element.parseSelector("div.buttonSubmit", this.getContent(), "first"));
	}
	
	this.sizeShim();
}

AlertsPopup_class.prototype.displayUnavailableDisclaimer = function() {
	if (!this._unavailableItemID) { return; }

	var elUnavailableRow = WSDOM.Element.parseSelector("table.alertsTable tr[itemId='" + this._unavailableItemID + "'],table.alertsTable tr[queryName='" + this._unavailableItemID + "']", "wsod", "first"),
		iNumTDs = elUnavailableRow ? WSDOM.Element.parseSelector("td", elUnavailableRow).length : 0,
		elClose;
	
	WSDOM.Element.insertAfter(
		WSDOM.Element.create("tr", {"class":"unavailableDisclaimer"}, [
			WSDOM.Element.create("td", {"colspan":iNumTDs}, [
				Element.create("div", {"class":"contain"}, [
					Element.create("div", {"class":"message"}, "Twitter alerts are not available for the delivery frequency you have selected."),
					elClose = Element.create("a", {"class":"icon action icon-delete-close control"})
				])
			])
		]), elUnavailableRow
	);
	
	WSDOM.Events.add(elClose, "click", this.closeUnavailableDisclaimer, this);
	
	this._unavailableItemID = null;
}

AlertsPopup_class.prototype.closeUnavailableDisclaimer = function(e, el) {
	var elParent = Element.getParentBySelector(el, "tr");
	
	Element.remove(elParent);
}

AlertsPopup_class.prototype.toggleDeliveryOption = function(e, el) {
	var elParent = WSDOM.Element.getParentBySelector(el, "tr"),
		elTableContainer = WSDOM.Element.getParentBySelector(elParent, "div.alertsTableContainer"),
		aActiveItems = WSDOM.Element.parseSelector("input[type='checkbox'][checked=.`true`]", elParent),
		sItem = elParent.getAttribute("item"),
		sItemID = elParent.getAttribute("itemID"),
		sQueryName = elParent.getAttribute("queryName"),
		oParams = {},
		oParam = {},
		sParam = elParent.getAttribute("params"),
		sLabel = elTableContainer.getAttribute("label");
		
	if (sItemID || sQueryName) {
		if (!aActiveItems.length) {
			oParam = Common.getSerializer().deserialize(sParam);
			oParam.item = sItem;
			oParam.deliveryType = [];
		
			if (sItemID) { oParam.itemID = sItemID; }
			if (sQueryName) { oParam.queryName = sQueryName; }
			
			oParams["edit"] = [oParam];
			
//			if (this.delayDeleteWarning[sLabel+sParam]) { clearTimeout(this.delayDeleteWarning[sLabel+sParam]); }
//			this.delayDeleteWarning[sLabel+sParam] = setTimeout(function() {
//				WSDOM.Element.addClass(elParent, "deleted");
//				WSDOM.Element.removeClass(WSDOM.Element.parseSelector("div.deleteWarning", elTableContainer, "first"), "wsodHidden");
//			}.Context(this), 1000);
		} else {
			oParam = Common.getSerializer().deserialize(sParam);
			oParam.item = sItem;
			oParam.deliveryType = [];
			
			for (var i = 0; i < aActiveItems.length; i++) {
				oParam.deliveryType.push(aActiveItems[i].getAttribute("deliveryType"));
			}
			
			if (sItemID) { oParam.itemID = sItemID; }
			if (sQueryName) { oParam.queryName = sQueryName; }
		
			oParams["edit"] = [oParam];
		}
	} else {
		oParam = Common.getSerializer().deserialize(sParam);
		oParam.item = sItem;
		oParam.deliveryType = [];
		
		for (var i = 0; i < aActiveItems.length; i++) {
			oParam.deliveryType.push(aActiveItems[i].getAttribute("deliveryType"));
		}
		
		oParams["add"] = [oParam];
	}
	
	this.elActiveRow = elParent;
	
	this.submitAlerts(oParams, 'updateAlertsNoRedraw');
}

AlertsPopup_class.prototype.changeTimeframe = function(e, el) {
	var elParent = WSDOM.Element.getParentBySelector(el, "tr"),
		aActiveItems = WSDOM.Element.parseSelector("input[type='checkbox'][checked=.`true`]", elParent),
		oExistingParams = Common.getSerializer().deserialize(elParent.getAttribute("params")),
		sItemID = elParent.getAttribute("itemID"),
		sQueryName = elParent.getAttribute("queryName"),
		oParams = {},
		oParam = {},
		aDeliveries = [],
		sKey = el.getAttribute('name');
	
	for (var i = 0; i < aActiveItems.length; i++) {
		aDeliveries.push(aActiveItems[i].getAttribute("deliveryType"));
	}
	
	if (!el.value) {
		sKey = "";
	} else if (el.value.match(/^p/gi)) {
		sKey = "Period";
	}
		
	oParam = CopyObj(oExistingParams);
	
	if (oParam['Timeframe']) { delete oParam['Timeframe']; }
	if (oParam['Period']) { delete oParam['Period']; }
	
	oParam.item = sKey ? elParent.getAttribute("item"+sKey) : elParent.getAttribute("item");
	oParam.deliveryType = aDeliveries;
	
	if (sItemID) { oParam.itemID = sItemID; }
	if (sQueryName) { oParam.queryName = sQueryName; }
	if (sKey) { oParam[sKey] = Number(el.value.replace(/p/gi, '')); }
		
	if (aDeliveries.length) {
		oParams["edit"] = [oParam];
		
		for (var i = 0; i < aDeliveries.length; i++) {
			if (this.UNSUPPORTED_DELIVERY_ITEMS[aDeliveries[i]] && this.UNSUPPORTED_DELIVERY_ITEMS[aDeliveries[i]][oParam.item]) {
				this._unavailableItemID = sItemID ? sItemID : null;
				this._unavailableItemID = sQueryName ? sQueryName : this._unavailableItemID;
				break;
			}
		}
		
		this.submitAlerts(oParams, 'updateAlertsRedraw');
	}
}

AlertsPopup_class.prototype.editSymbol = function(ev, el) {
	var wsodPop = WSDOM.Element.get('wsodPop');
	var alertsSymbolInputContainer = WSDOM.Element.parseSelector('div.alertsSymbolInput', wsodPop, 'first');
	var alertsSymbolInput = WSDOM.Element.parseSelector('INPUT[name="query"]', alertsSymbolInputContainer, 'first');
	var alertsSymbolDisplayContainer = WSDOM.Element.parseSelector('div.alertsSymbolDisplay', wsodPop, 'first');
	var alertsDisplaySymbol = WSDOM.Element.parseSelector('div.alertsDisplaySymbol', alertsSymbolDisplayContainer, 'first');
	var previousSymbol = WSDOM.Element.parseSelector('SPAN', alertsDisplaySymbol, 'first');

	alertsSymbolInput.value = previousSymbol.innerHTML;

	WSDOM.Element.addClass(alertsSymbolDisplayContainer, 'wsodHidden');
	WSDOM.Element.removeClass(alertsSymbolInputContainer, 'wsodHidden');

	alertsSymbolInput.focus();
}

AlertsPopup_class.prototype.handleTheKeypress = function(ev, el) {
	if (this.KEY_CODE_ENTER == ev.nativeEvent.keyCode) {
		// var el = ev.nativeEvent.target || ev.nativeEvent.srcElement;

		ev.cancel();

		this.saveAlerts(ev, el);
	}
}

AlertsPopup_class.prototype.saveAlerts = function(e, el, data) {
	data = data || {};

    var elForm = WSDOM.Element.getParentBySelector(el, "form"),
		sAction = data.action || WSDOM.Element.parseSelector("input[name='action']", elForm, "first").value,
		bIsIndex = WSDOM.Element.parseSelector("input[name='isIndex']", elForm, "first") ? WSDOM.Element.parseSelector("input[name='isIndex']", elForm, "first").value : false,
		aItemIDs = [],
		aQueryNames = [],
		aDeliveryType = WSDOM.Element.parseSelector("input[name='deliveryType']", elForm),
		aActiveItems = WSDOM.Element.parseSelector("fieldset input[type='checkbox'][checked=.`true`]", elForm),
		aItemsToBeDeleted = data.aItemsToBeDeleted || false,
		oParams = {},
		aParams = [],
		aDeliveries = [],
		oCurrentItemID = {},
		oCurrentQueryName = {};

	// console.log('aItemsToBeDeleted', aItemsToBeDeleted);

	if (aItemsToBeDeleted) {
		for (var i = 0; i < aItemsToBeDeleted.length; i++) {
			oCurrentItem = aItemsToBeDeleted[i];
			oCurrentParent = WSDOM.Element.getParentBySelector(oCurrentItem, 'DIV');

			oCurrentItemID = WSDOM.Element.parseSelector("INPUT[name='itemID']", oCurrentParent, 'first') || {};
			oCurrentQueryName = WSDOM.Element.parseSelector("INPUT[name='queryName']", oCurrentParent, 'first') || {};

			aItemIDs.push(oCurrentItemID);
			aQueryNames.push(oCurrentQueryName);
		}

		// console.log('aItemIDs', aItemIDs);
		// console.log('aQueryNames', aQueryNames);
	}
	else {
		aItemIDs = WSDOM.Element.parseSelector("input[name='itemID']", elForm);
		aQueryNames = WSDOM.Element.parseSelector("input[name='queryName']", elForm);
	}

    var elInput,
		sValue,
		sName;

    for (var i = 0; i < aDeliveryType.length; i++) {
        aDeliveries.push(aDeliveryType[i].value);
    }

    switch (sAction) {
        case "add": case "edit":
            for (var i = 0, parent, inputs, item, sAction; i < aActiveItems.length; i++) {
                parent = WSDOM.Element.getParentBySelector(aActiveItems[i], "fieldset");
                inputs = WSDOM.Element.parseSelector("input[type!='checkbox'],select", parent);
                item = parent.getAttribute("item"),
                isHidden = false,
                isSelect = false;

                aParams.push({
                    'item': item,
                    'isIndex': bIsIndex
                });

                if (WSDOM.Element.get("alertsSymbol")) {
                    aParams[aParams.length - 1]['Symbols.Symbol'] = WSDOM.Element.get("alertsSymbol").value;
                }

                for (var j = 0; j < inputs.length; j++) {
                    if (!WSDOM.Element.hasClass(inputs[j], "inactive")) {
                        sName = inputs[j].name;
                        sValue = inputs[j].value;

                        if ('Timeframe' == sName) {
                            if (!sValue) {
                                continue;
                            } else if (sValue.match(/^p/i)) {
                                sValue = sValue.replace(/^p/i, '');
                                sName = 'Period';

                                aParams[aParams.length - 1]['item'] = parent.getAttribute('itemPeriod');
                            } else {
                                aParams[aParams.length - 1]['item'] = parent.getAttribute('itemTimeframe');
                            }
                        }

						isSelect = ("SELECT" == inputs[j].tagName.toUpperCase()) ? true : false;
						isHidden = (!isSelect && ("hidden" == inputs[j].type)) ? true : false;

                        if (sValue) {
                        	if (!isSelect && !isHidden && isNaN(sValue) && WSDOM.Element.hasClass(inputs[j], 'price')) {
                        		alert('Please enter a number.');
                        		return false;
                        	}

                            aParams[aParams.length - 1][sName] = sValue;
                        } else if (!isSelect) {
                            alert('Please enter a value.');
                            return false;
                        }
                    }
                }

            }
            break;
        case "delete":
            aParams.push({});
            break;
        default:
            break;
    }

    oParams[sAction] = [];

    if (!aQueryNames.length) {
        for (var i = 0; i < aItemIDs.length; i++) {
            for (var j = 0; j < aParams.length; j++) {
                oParams[sAction].push(CopyObj(aParams[j]));
                oParams[sAction][oParams[sAction].length - 1]['itemID'] = aItemIDs[i].value;
                oParams[sAction][oParams[sAction].length - 1]['deliveryType'] = aDeliveries;
            }
        }
    } else {
        for (var i = 0; i < aQueryNames.length; i++) {
            for (var j = 0; j < aParams.length; j++) {
                oParams[sAction].push(CopyObj(aParams[j]));
                oParams[sAction][oParams[sAction].length - 1]['queryName'] = aQueryNames[i].value;
                oParams[sAction][oParams[sAction].length - 1]['deliveryType'] = aDeliveries;

                if (aItemIDs.length && i < aItemIDs.length) {
                    oParams[sAction][oParams[sAction].length - 1]['itemID'] = aItemIDs[i].value;
                }
            }
        }
    }

    if (!oParams[sAction].length) {
        for (var i = 0; i < aParams.length; i++) {
            oParams[sAction].push(CopyObj(aParams[i]));
        }
    }

    if (!oParams[sAction] || !oParams[sAction].length) {
        alert('Please select an alert.');
        return;
    }

	// console.log('oParams', oParams);

	this.submitAlerts(oParams, 'updateAlertsRedraw', el);
}

AlertsPopup_class.prototype.saveSubscriptions = function(ev, el) {
	var oData = {}
		,elForm = WSDOM.Element.get('subscriptionForm')
		,aItemsToBeDeleted = WSDOM.Element.parseSelector("input[type='checkbox'][checked=.`false`]", elForm);

	if (aItemsToBeDeleted.length) {
		var deleteConfirm = confirm('Are you sure you want to delete the unchecked alerts?');

		if (deleteConfirm) {
			oData.action = 'delete';
			oData.aItemsToBeDeleted = aItemsToBeDeleted;

			this.saveAlerts(ev, el, oData);
		}
	}
	else {
		this.close();
	}
}

AlertsPopup_class.prototype.submitAlerts = function(oParams, sCallback, el) {
	sCallback = sCallback || 'updateAlertsRedraw';
	el = el || false;
	
	if (this.getDrawInPopup()) {
		sCallback = 'updateAlertsInPopup'
	}
	
	var elParentSize = WSDOM.Element.getSize(this.getContainer());
	
	if (!this.getDrawInPopup()) {
		var elLoadingDiv = WSDOM.Element.create("div", {"class":"loadDiv", "style":""}, null, this.getContainer());
		WSDOM.Element.setSize(elLoadingDiv, elParentSize.width, elParentSize.height);
	}
	
	var elAlertsSymbol = WSDOM.Element.get("alertsSymbol"),
		elKeywordsInput = WSDOM.Element.get("keywordsInput");
	
	if (elAlertsSymbol && !elAlertsSymbol.value) {
		alert('Please enter a symbol.');
		return;
	}
	
	if (oParams) {
		var elSaveAlertButton = WSDOM.Element.parseSelector('DIV.buttonSubmit', this.getContent(), 'first') || false
			,elSaveSubscriptionsButton = WSDOM.Element.parseSelector('DIV.buttonSaveSubscriptions', this.getContent(), 'first') || false;

		if ((elSaveAlertButton == el) || (elSaveSubscriptionsButton == el)) {
			var elLoadingDivForPopup = WSDOM.Element.parseSelector('DIV.loadDiv', this.getFrame(), 'first') || WSDOM.Element.create('DIV', { 'class':'loadDiv', 'style':'' }, null, this.getFrame());
			var elFrameSize = WSDOM.Element.getSize(this.getFrame());
			WSDOM.Element.setSize(elLoadingDivForPopup, elFrameSize.width, elFrameSize.height);
		}

		this.getContentBuffer().abortRequests();
		this.getContentBuffer().load({
			debug: true,
			url: this.PATH_UPDATE_ALERTS,
			method: "post",
			contentType: "text/javascript",
			context:this,
			preventEval: true,
			data: {
				params: Common.getSerializer().serialize(oParams)
			},
			onload: this[sCallback]
		});
	} else {
		this.close();
	}
}

AlertsPopup_class.prototype.updateAlertsRedraw = function(cb, type) {
	var result = cb ? Common.getSerializer().deserialize(cb.getResult()) : null;

	if (type) {
		this.setType(type);
		
		result = {
			status: 1
		}
		
		var elParentSize = WSDOM.Element.getSize(this.getContainer());
		var elLoadingDiv = WSDOM.Element.create("div", {"class":"loadDiv", "style":""}, null, this.getContainer());
		WSDOM.Element.setSize(elLoadingDiv, elParentSize.width, elParentSize.height);
	}
	
	if (result && (1 == result.status)) {
		this.getContentBuffer().abortRequests();
		this.getContentBuffer().load({
			debug: true,
			url: this.PATH_ALERTS_TABLES,
			method: "post",
			contentType: "text/html",
			context:this,
			data: {
				type: type || this.getType()
			},
			onload: this.renderAlertsTables
		});
	} else {
		alert(this.getErrorMessage(result));

		WSDOM.Element.remove(WSDOM.Element.parseSelector("div.loadDiv", this.getContainer(), "first"));  // table
		WSDOM.Element.remove(WSDOM.Element.parseSelector('DIV.loadDiv', this.getFrame(), 'first'));  // popup
	}
}

AlertsPopup_class.prototype.renderAlertsTables = function(cb) {
	var result = cb.getResult();
	
	WSDOM.Element.setHTML(this.getContainer(), result);
	
	this.attachTableEvents();
	this.close();
	WSDOM.Element.remove(WSDOM.Element.parseSelector('DIV.loadDiv', this.getFrame(), 'first'));
	
	this.displayUnavailableDisclaimer();
}

AlertsPopup_class.prototype.renderSuspendedDetails = function(cb) {
	var deserializedResults = Common.getSerializer().deserialize(cb.getResult()) || {};
	// console.log(deserializedResults);

	var updatedMessage = deserializedResults.message || '';

	WSDOM.Element.setHTML(this.getContainer(), updatedMessage);
}

AlertsPopup_class.prototype.updateAlertsNoRedraw = function(cb) {
	var result = Common.getSerializer().deserialize(cb.getResult());
	
	if (result && 1 == result.status) {
		if (!this.getDrawInPopup()) {
			if (this.elActiveRow) {
				if (result.itemID || result.queryName) {
					if (result.itemID) {
						this.elActiveRow.setAttribute("itemID", result.itemID);
					}
					
					if (result.queryName) {
						this.elActiveRow.setAttribute("queryName", result.queryName);
					}
					
					WSDOM.Element.removeClass(this.elActiveRow, "deleted");
				}
				
				var elTableContainer = WSDOM.Element.getParentBySelector(this.elActiveRow, "div.alertsTableContainer"),
					sParam = this.elActiveRow.getAttribute("params"),
					sLabel = elTableContainer.getAttribute("label");
				
				if (this.delayDeleteWarning[sLabel+sParam] && WSDOM.Element.parseSelector("input[type='checkbox'][checked=.`true`]", this.elActiveRow).length) { clearTimeout(this.delayDeleteWarning[sLabel+sParam]); }
				
				if (!WSDOM.Element.parseSelector("tr.deleted", elTableContainer).length) {
					WSDOM.Element.addClass(WSDOM.Element.parseSelector("div.deleteWarning", elTableContainer, "first"), "wsodHidden");
				}
			}
			
			this.elActiveRow = null;
		}
	} else {
		alert(this.getErrorMessage(result));
	}
	
	if (!this.getDrawInPopup()) {
		WSDOM.Element.remove(WSDOM.Element.parseSelector("div.loadDiv", this.getContainer(), "first"));
	}
}

AlertsPopup_class.prototype.updateAlertsInPopup = function(cb) {
	var result = Common.getSerializer().deserialize(cb.getResult());
	
	var elButton = WSDOM.Element.parseSelector("div.buttonSubmit", this.getContent(), "first");
	var elUpdateResults = WSDOM.Element.create("div", {"class":"updateResults contain"});
	
	if (result && 1 == result.status) {
		WSDOM.Element.addChild(elUpdateResults,
			WSDOM.Element.create("div", {"class":"visitAlerts"}, [
				"To change delivery preferences, visit the ",
				WSDOM.Element.create("a", {"href":SiteRules.getURL("/alerts/"+this.URL_MAP[this.getType()])}, SiteRules.isInvestorsChronicle() ? "IC Alerts Hub" : "FT Alerts Hub")
			])
		);
		
		WSDOM.Element.addChild(elUpdateResults,
			WSDOM.Element.create("div", {"class":"alertsResult alertsSuccess"}, "Your alerts have been set")
		);
	}
	else {
		WSDOM.Element.addChild(elUpdateResults,
			WSDOM.Element.create("div", {"class":"visitAlerts"})
		);

		var alertFailureDetails = this.getErrorMessage(result);

		WSDOM.Element.addChild(elUpdateResults,
			WSDOM.Element.create("div", {"class":"alertsResult alertsFailure"}, alertFailureDetails)
		);
	}
	
	WSDOM.Element.addChild(WSDOM.Element.parseSelector("div.popupBody", this.getContent(), "first"), elUpdateResults);
	WSDOM.Element.remove(elButton);
	
	this.sizeShim();

	WSDOM.Element.remove(WSDOM.Element.parseSelector('DIV.loadDiv', this.getFrame(), 'first'));
}

AlertsPopup_class.prototype.updateSuspendedDetails = function() {
	var serializedData = Common.getSerializer().serialize({ 'type':'suspendedAddress' });

	var contentBuffer = new ContentBuffer();
		contentBuffer.abortRequests();
		contentBuffer.load(
			{
				 contentType: this.BUFFER_CONTENT_TYPE
				,context:     this
				,data:        { 'data':serializedData }
				,debug:       true
				,onload:      this.renderSuspendedDetails
				,preventEval: true
				,url:         this.BUFFER_URL_DELIVERY_SUSPENDED
			}
		);
}

AlertsPopup_class.prototype.getQuoteData = function(symbolSet) {
	var elAlertsSymbol = WSDOM.Element.get("alertsSymbol"),
		elParent = WSDOM.Element.getParentBySelector(elAlertsSymbol, "form.addEditAlertItem"),
		dynamicQuoteValues = WSDOM.Element.parseSelector("span.dynamicQuoteValue", elParent),
		params = [];
		
	for (var i = 0; i < dynamicQuoteValues.length; i++) {
		params.push(dynamicQuoteValues[i].getAttribute("key"));
	}

	this.getContentBuffer().abortRequests();
	this.getContentBuffer().load({
		debug: true,
		url: this.PATH_ALERTS_QUOTE_DATA,
		method: "post",
		contentType: "text/javascript",
		context:this,
		preventEval: true,
		data: {
			symbol: elAlertsSymbol.value,
			symbolSet: symbolSet,
			params: Common.getSerializer().serialize(params)
		},
		onload: this.showQuoteData
	});
}

AlertsPopup_class.prototype.showQuoteData = function(cb) {
	var result = Common.getSerializer().deserialize(cb.getResult()),
		elParent = WSDOM.Element.getParentBySelector("alertsSymbol", "form.addEditAlertItem"),
		elInputContainer = WSDOM.Element.parseSelector("div.alertsSymbolInput", elParent, "first"),
		elDisplayContainer = WSDOM.Element.parseSelector("div.alertsSymbolDisplay", elParent, "first"),
		dynamicQuoteValues = WSDOM.Element.parseSelector("span.dynamicQuoteValue", elParent);

	if (
			!result ||
			!result['Bridge'] ||
			!result['FTStandard'] ||
			('-32768' == result['Bridge']) ||
			('-32768' == result['FTStandard'])
		) {
		return false;
	}

	WSDOM.Element.get("alertsSymbol").value = result['Bridge'];

	WSDOM.Element.setHTML(WSDOM.Element.parseSelector("div", elDisplayContainer, "first"), result['Name']+'<span>'+result['FTStandard']+'</span>');

	for (var i = 0; i < dynamicQuoteValues.length; i++) {
		WSDOM.Element.setHTML(dynamicQuoteValues[i],
			('Low52WeekDate' == dynamicQuoteValues[i].getAttribute("key") ||
			'High52WeekDate' == dynamicQuoteValues[i].getAttribute("key")) ?
			'<span class="spacer">/</span>'+result['Quote'][dynamicQuoteValues[i].getAttribute("key")] :
			result['Quote'][dynamicQuoteValues[i].getAttribute("key")]
		);
	}
	
	WSDOM.Element.addClass(elInputContainer, "wsodHidden");
	WSDOM.Element.removeClass(elDisplayContainer, "wsodHidden");
}

AlertsPopup_class.prototype.close = function() {
	AlertsPopup_class.Super(this, "close");
	
	this.resetPopup();
}

AlertsPopup_class.prototype.getContentBuffer = function() {
	var cb = new ContentBuffer();
	
	this.getContentBuffer = function() {
		return cb;
	}
	
	return this.getContentBuffer();
}

AlertsPopup_class.prototype.getEventManagerCompanyAlerts = function() {
	var em = new EventManager();
	
	this.getEventManagerCompanyAlerts = function() {
		return em;
	}
	
	return this.getEventManagerCompanyAlerts();
}
/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/modules/glossary/Popup_PermanentLink.js
*/
var PermanentLink_class = function(){
	PermanentLink_class.Super(this);
}

PermanentLink_class.Extend(Popup);

PermanentLink_class.prototype.init = function() {
	// has to be onload to handle the module in the FT wrapper
	Events.add(window, "load", function() {
		var permanentLink = Element.parseSelector("a.permanentLink", document.body, "first");
	
		Events.add(permanentLink, "click", this.drawPermanentLinkPopup, this);
	}.Context(this));
}

PermanentLink_class.prototype.resetPopup = function() {
	this.setTitleText("");
	this.clearContent();
	
	Element.addClass(this.getFrame(), "glikiPopup");
}

PermanentLink_class.prototype.drawPermanentLinkPopup = function(e, el) {
	if (e) { e.cancel(); }

	var termInput;
	
	this.resetPopup();
	
	this.setTitleText("Permanent Link");
	Element.addClass(this.getFrame(), "permanentLinkPopup");
	
	Element.create("div", {"class":"popupBody"}, [
		Element.create("p", {"class":"termText"}, ["Use a permanent link to cite a specific version of a Lexicon entry. Copy and paste the url below into your blog or web page to link to this term."]),
		termInput = Element.create("input", {"value":location.href})
	], this.getContent());
	
	this.getEventManagerPermanentLink().add(termInput, "click", this.selectText, this);
	
	this.draw();
	this.sizeShim();
}

PermanentLink_class.prototype.close = function (e, el) {
	PermanentLink_class.Super(this, "close", [e, el]);
	
	if (el) {
		this.getEventManagerPermanentLink().removeAll();
	}
};

PermanentLink_class.prototype.selectText = function(e, el) {
	e.cancel();
	
	el.focus();
	el.select();
}

PermanentLink_class.prototype.getEventManagerPermanentLink = function() {
	var em = new EventManager();
	
	this.getEventManagerPermanentLink = function() {
		return em;
	}
	
	return this.getEventManagerPermanentLink();
}

var permanentLink = new PermanentLink_class();
	permanentLink.init();
/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/modules/Popup_Subscribe.js
*/
var Subscribe_class = function() {}

Subscribe_class.Extend(Popup);

Subscribe_class.prototype.init = function() {
	Events.add(Element.parseSelector("a[subscribeText]"), "click", this.drawLoginPopup, this);
}

Subscribe_class.prototype.resetPopup = function() {
	this.setTitleText("");
	this.clearContent();
	
	Element.addClass(this.getFrame(), "glikiPopup");
}

Subscribe_class.prototype.drawLoginPopup = function(e, el) {
	e.cancel();

	var elCancel,
		elRegister;

	this.resetPopup();
	
	this.setTitleText("Log in to Financial Times");
	Element.addClass(this.getFrame(), "registerPopup");
	
	Element.create("div", {"class":"popupBody"}, [
		Element.create("p", {}, el.getAttribute("subscribeText")+" If you are not currently registered for this site, these are some of the benefits of registration:"),
		Element.create("ul", {}, [
			Element.create("li", {}, "More articles per 30 days"),
			Element.create("li", {}, "Price and portfolio email alerts"),
			Element.create("li", {}, "Portfolio tool"),
			Element.create("li", {}, "News by email")
		])
	], this.getContent());
	
	Element.create("div", {"class":"popupControls contain"}, [
		elRegister = Element.create("div", {"class":"basicButton", "link":el.getAttribute("href")}, [
			Element.create("div", {}, "Register &amp; Log In")
		]),
		elCancel = Element.create("div", {"class":"basicButton"}, [
			Element.create("div", {}, "Cancel")
		])
	], this.getContent());

	this.getEventManager().add(elCancel, "click", this.close, this);
	this.getEventManager().add(elRegister, "click", this.gotoRegistrationPage, this);
	
	this.draw();
	this.sizeShim();
}

Subscribe_class.prototype.gotoRegistrationPage = function(e, el) {
	location.href = el.getAttribute("link");
}

var subscribeToFT = new Subscribe_class();
	subscribeToFT.init();