Ext.BLANK_IMAGE_URL = '/images/default/s.gif';

Ext.form.Field.prototype.msgTarget = 'side';
Ext.form.TextField.prototype.width = 200;
Ext.form.Action.Submit.prototype.clientValidation = true;

Ext.form.FormPanel.prototype.labelWidth = 100;
Ext.form.FormPanel.prototype.frame = true;
Ext.form.FormPanel.prototype.bodyStyle = 'padding: 5px 5px 0';
Ext.form.FormPanel.prototype.width = 350;
Ext.form.FormPanel.prototype.monitorValid = false;
Ext.form.FormPanel.prototype.removeField = function(id) {
	field = this.form.findField(id);
	fitem = field.getEl().up('.x-form-item');
	field.destroy();
	fitem.remove();
};
Ext.form.Action.Load.prototype.waitMsg = 'Loading...';

Ext.Window.prototype.autoHeight = true;
Ext.Window.prototype.width = 362;
Ext.Window.prototype.modal = true;
Ext.Window.prototype.collapsible = false;
Ext.Window.prototype.resizable = false;
Ext.Window.prototype.border = false;
Ext.Window.prototype.plain = true;
Ext.Window.prototype.closable = false;

Ext.grid.GridPanel.prototype.frame = false;
Ext.grid.GridView.prototype.forceFit = true;

Ext.Ajax.timeout = 600000;

Ext.onReady(function(){	Ext.QuickTips.init(); });

Ext.namespace('TSM', 'TSM.data', 'TSM.meta', 'TSM.store');

TSM.DEFAULT_PAGE_SIZE = 50;
TSM.DATE_POST_FORMAT = 'Y-m-d';
TSM.DATE_POST_FORMAT_LONG = 'Y-m-d H:i:s';

TSM.data.paymentType = [
	['VISA','Visa'],
	['MC','Mastercard'],
	['AMEX','American Express'],
	['DISC','Discover']
];

TSM.data.paymentMonth = [
	[1,'Jan (1)'],
	[2,'Feb (2)'],
	[3,'Mar (3)'],
	[4,'Apr (4)'],
	[5,'May (5)'],
	[6,'Jun (6)'],
	[7,'Jul (7)'],
	[8,'Aug (8)'],
	[9,'Sep (9)'],
	[10,'Oct (10)'],
	[11,'Nov (11)'],
	[12,'Dec (12)']
];

var currentTime = new Date();
var start_year = currentTime.getFullYear();
TSM.data.paymentYear = [
	start_year,
	start_year + 1,
	start_year + 2,
	start_year + 3,
	start_year + 4,
	start_year + 5,
	start_year + 6
];

TSM.ReportStore = function(c) {
	c.root = !c.root ? 'rows' : undefined;
	c.totalProperty = !c.totalProperty ? 'totalCount' : undefined;
	c.remoteSort = !c.remoteSort ? true : undefined;
    TSM.ReportStore.superclass.constructor.call(this, Ext.apply(c, {
        proxy: !c.data ? new Ext.data.HttpProxy({url: c.url}) : undefined,
        reader: new Ext.data.JsonReader(c, c.fields),
		baseParams: {limit: TSM.DEFAULT_PAGE_SIZE},
		toCSV: function() {
			if(!Ext.get('csv-form')) Ext.DomHelper.append('content', '<form id="csv-form"></form>');
			var csvParams = this.baseParams;
			if(csvParams.limit == TSM.DEFAULT_PAGE_SIZE) csvParams.limit = null;
			Ext.Ajax.request({
				form: 'csv-form',
				url: this.url + '/csv',
				params: this.baseParams,
				isUpload: true
			});
		}
    }));
};
Ext.extend(TSM.ReportStore, Ext.data.Store);

Ext.PagingToolbar.prototype.onRender = Ext.PagingToolbar.prototype.onRender.createSequence(function(ct,position) {
    this.add('-', {
			icon: '/images/icons/page_white_excel.png',
			cls: 'x-btn-icon',
			tooltip: 'Download report as CSV',
			handler: this.store.toCSV,
			scope: this.store
		}, {
			icon: '/images/icons/help.png',
			cls: 'x-btn-icon',
			tooltip: 'Report Help',
			handler: function() {
				TSM.Util.popupHelp();
			}
		}
	);
});

TSM.getRowClass = function (row, index) { 
	var cls = ''; 
	var data = row.data;
	if(data.advertiser_url)
	{
		if(TSM.store.campaignWebsites.find('url', data.advertiser_url) >= 0)
		{
			cls = 'competitor-me';
		}
		else if(TSM.store.hotCompetitors.find('url', data.advertiser_url) >= 0)
		{
			cls = 'competitor-hot';
		}
	}
	return cls; 
};

TSM.maskForm = function(form, comp, message) {
	if(!message) message = 'Processing...';
	form.on('beforeaction', function() { comp.getEl().mask(message) });
	form.on('actioncomplete', function() { comp.getEl().unmask() });
	form.on('actionfailed', function() { comp.getEl().unmask() });
}
			

TSM.PortletGrid = Ext.extend(Ext.grid.GridPanel, {
	autoHeight: true,
	loadMask: true,
	stripeRows: true,
	enableHdMenu: false,
	enableColumnMove: false,
	viewConfig: {scrollOffset: 0},
	initComponent: function() {
    	TSM.PortletGrid.superclass.initComponent.apply(this, arguments);
		this.getSelectionModel().lock();
	}
});

TSM.ReportGrid = Ext.extend(Ext.grid.GridPanel, {
	autoHeight: true,
	loadMask: true,
	stripeRows: true,
	enableHdMenu: false,
	enableColumnMove: false,
	viewConfig: {scrollOffset: 0},
	initComponent: function() {
        Ext.apply(this, {
	        tbar: new Ext.PagingToolbar({
				store: this.store,
				pageSize: TSM.DEFAULT_PAGE_SIZE,
				displayInfo: true,
				displayMsg: 'Displaying results {0} - {1} of {2}',
				emptyMsg: "No results to display"
			})
	    });
	    TSM.ReportGrid.superclass.initComponent.apply(this, arguments);
		this.getColumnModel().defaultSortable = true;
		this.getSelectionModel().lock();
		this.getView().getRowClass = TSM.getRowClass;
	}
});

TSM.ReportForm = Ext.extend(Ext.form.FormPanel, {
	width: 'auto',
	labelAlign: 'top',
	initComponent: function() {
        Ext.apply(this, {			
			buttons: [{
				text: 'Refresh Report',
				handler: function() {
					TSM.Reporting.refreshReport();
				}
			}]
        });
        TSM.ReportForm.superclass.initComponent.apply(this, arguments);
	},
	getValues: function() {
		var numFields = this.form.items.length;
		var values = {};
		var field = null;
		var name = null;
		for(var idx = 0; idx < numFields; idx++)
		{
			field = this.form.findField(idx);
			name = field.getName();
			if(name.search(/_date/) >= 0)
				values[name] = field.getValue().format(TSM.DATE_POST_FORMAT);
			else
				values[name] = field.getValue();
		}
		return values;
	}
});

TSM.Util = new function() {

	return {
		popupHelp: function() {
			if (!(hw = Ext.WindowMgr.get('popup-help-window'))) {
				hw = new Ext.Window({
					title: 'Help',
					id: 'popup-help-window',
					closable: true,
					closeAction: 'hide',
					items: [
						new Ext.Panel({
							contentEl: 'popup-help',
							height: 300,
							autoScroll: true,
							bodyStyle: 'padding: 10px'
						})
					]
				});
			}
			hw.show();
		}
	};

}();

TSM.Home = function() {
	
	return {

		showTryIt: function() {
			var fpTryIt = new Ext.form.FormPanel({
				url: '/main/tryit',
				items: [
					{tabIndex: 1, xtype: "textfield", fieldLabel: "Your Name", name: "name", allowBlank: false},
					{tabIndex: 2, xtype: "textfield", fieldLabel: "Email Address", name: "email", allowBlank: false, vtype: "email"},
					{tabIndex: 3, xtype: "textfield", fieldLabel: "Company Name", name: "company", allowBlank: false}
				],
				buttons: [{
					tabIndex: 4, 
					text: 'Submit Request',
					type: 'submit',
					handler: function() {
						if((typeof pageTracker) != 'undefined') pageTracker._trackPageview("/funnel_G3/step1.html");
						fpTryIt.form.submit({
							success: function(f) {
								if((typeof pageTracker) != 'undefined') pageTracker._trackPageview("/funnel_G3/complete.html");
								Ext.Msg.alert('Request Submitted', 'Thank You. Your request has been submitted. A monitoring executive will be in touch with you within 24 hours to schedule a demo with you. You can also call us at 321-206-9705.');
								winTryIt.close();
							}
						});
					}
				}]
			});
			var winTryIt = new Ext.Window({
				title: 'Request a Demo!',
				closable: true,
				items: [fpTryIt]
			});
			TSM.maskForm(fpTryIt.form, winTryIt);
			winTryIt.show();
		},

		showSignup: function(defaultPackageId) {
			if(!defaultPackageId) defaultPackageId = 1;
			var stCountries = new Ext.data.JsonStore({
				root: 'countries',
				fields: ['id','name','alpha2'],
				url: '/main/get_countries_json',
				autoLoad: true
			});
			var stStates = new Ext.data.JsonStore({
				root: 'regions',
				fields: ['id','name'],
				url: '/main/get_regions_json',
				listeners: {
					load: function() {
						fState = fpSignup.form.findField('mail_state');
						if(this.getTotalCount() > 0)
						{
							fState.forceSelection = true;
							fState.emptyText = "Choose State/Province";
						}
						else
						{
							fState.forceSelection = false;
							fState.el.dom.removeAttribute('readOnly');
							fState.removeClass('x-form-empty-field');
							fState.emptyText = "Type State/Province Here";
						}
						fState.reset();
					}
				}
			});
			var fpSignup = new Ext.form.FormPanel({
				url: '/main/signup',
				title: 'Enter Your Information Below',
				renderTo: 'form-signup',
				width: 'auto',
				items: [{
					xtype: "fieldset",
					autoHeight: true,
					autoWidth: true,
					title: 'Package Info',
					layout: 'form',
					items: [
						{xtype: 'radiogroup', hideLabel: true, value: defaultPackageId, items: [
							{xtype: "radio", name: "package_id", inputValue: 1, boxLabel: "Starter&nbsp;at&nbsp;$99&nbsp;per&nbsp;Month&nbsp;(50&nbsp;Keywords)", checked: (defaultPackageId == 1)},
							{xtype: "radio", name: "package_id", inputValue: 2, boxLabel: "Pro&nbsp;at&nbsp;$399&nbsp;per&nbsp;Month&nbsp;(200&nbsp;Keywords&nbsp;+&nbsp;Compliance)", checked: (defaultPackageId == 2)}]
						}
					]
				},{
					xtype: "fieldset",
					autoHeight: true,
					autoWidth: true,
					title: 'User and Login Info',
					layout: 'column',
					items: [
						{columnWidth: .5, layout: 'form', items: [
							{tabIndex: 1, xtype: "textfield", fieldLabel: "Your Name", name: "name", allowBlank: false},
							{tabIndex: 3, xtype: "textfield", fieldLabel: "Password", name: "password", inputType: "password", allowBlank: false}
						]},
						{columnWidth: .5, layout: 'form', items: [
							{tabIndex: 2, xtype: "textfield", fieldLabel: "Email Address", name: "email", allowBlank: false, vtype: "email"},
							{tabIndex: 4, xtype: "textfield", fieldLabel: "Confirm Password", name: "confirm_password", inputType: "password", allowBlank: false}
						]}
					]
				},{
					xtype: "fieldset",
					autoHeight: true,
					autoWidth: true,
					title: 'Company Info',
					layout: 'column',
					items: [
						{columnWidth: .5, layout: 'form', items: [
							{tabIndex: 5, xtype: "textfield", fieldLabel: "Company Name", name: "company", allowBlank: false},
							{tabIndex: 7, xtype: "textfield", fieldLabel: "Address 1", name: "mail_addr1", allowBlank: false},
							{tabIndex: 9, xtype: "combo", fieldLabel: "Country", name: "mail_country_code", hiddenName: "mail_country_code", allowBlank: false, typeAhead: true, forceSelection: true, displayField: "name", valueField: "alpha2", emptyText: "Select Country", store: stCountries, triggerAction: 'all', mode: 'local', listeners: {
								select: function(combo,rec) {
									stStates.baseParams.country_id = rec.get('id');
									stStates.load();
								}
							}},
							{tabIndex: 11, xtype: "textfield", fieldLabel: "City", name: "mail_city", allowBlank: false},
							{tabIndex: 13, xtype: "textfield", fieldLabel: "Fax", name: "fax"}
						]},
						{columnWidth: .5, layout: 'form', items: [
							{tabIndex: 6, xtype: "textfield", fieldLabel: "Phone", name: "phone", allowBlank: false},
							{tabIndex: 8, xtype: "textfield", fieldLabel: "Address 2", name: "mail_addr2"},
							{tabIndex: 10, xtype: "combo", fieldLabel: "State/Province", name: "mail_state_dummy", hiddenName: "mail_state", allowBlank: false, typeAhead: true, displayField: "name", valueField: "name", emptyText: "Choose Country First", store: stStates, triggerAction: 'all', mode: 'local'},
							{tabIndex: 12, xtype: "textfield", fieldLabel: "Postal/Zip Code", name: "mail_postal_code", allowBlank: false},
							{tabIndex: 14, xtype: "textfield", fieldLabel: "Website", name: "website", allowBlank: false}
						]}
					]
				},{
					xtype: "fieldset",
					autoHeight: true,
					autoWidth: true,
					title: 'Payment Info',
					layout: 'column',
					items: [
						{columnWidth: .5, layout: 'form', items: [
							{tabIndex: 15, xtype: "combo", fieldLabel: "Card Type", name: "payment_type", hiddenName: "payment_type", allowBlank: false, typeAhead: true, forceSelection: true, emptyText: "Select Card Type", store: TSM.data.paymentType, triggerAction: 'all'},
							{
								layout: 'column',
								items: [
									{columnWidth: .6, layout: 'form', items: [{tabIndex: 17, xtype: "combo", width: 75, fieldLabel: "Card Expiration", name: "payment_exp_month", hiddenName: "payment_exp_month", allowBlank: false, typeAhead: true, forceSelection: true, emptyText: "Month", store: TSM.data.paymentMonth, triggerAction: 'all'}]},
									{columnWidth: .4, layout: 'form', items: [{tabIndex: 18, xtype: "combo", width: 75, hideLabel: true, name: "payment_exp_year", allowBlank: false, typeAhead: true, forceSelection: true, emptyText: "Year", store: TSM.data.paymentYear, triggerAction: 'all'}]}
								]
							}
						]},
						{columnWidth: .5, layout: 'form', items: [
							{tabIndex: 16, xtype: "textfield", fieldLabel: "Card Number", name: "payment_num", allowBlank: false},
							{tabIndex: 19, xtype: "textfield", fieldLabel: "Card CVV", name: "payment_cvv", allowBlank: false, width: 50, maxLength: 4}
						]}
					]
				},{
					xtype: "fieldset",
					autoHeight: true,
					autoWidth: true,
					title: 'Terms',
					layout: 'form',
					items: [
						{tabIndex: 20, xtype: "checkbox", fieldLabel: 'By checking this box you agree to our <a href="/terms.pdf" target="_blank">Terms of Use</a>', name: "agree_terms", inputValue: 1, labelStyle: 'width: 300px', style: 'margin-top: 5px', markInvalid: function(msg){
							if(!this.rendered || this.preventMark){ // not rendered
								return;
					        }
							this.el.addClass(this.invalidClass);
							msg = msg || this.invalidText;
							if(!this.errorIcon){
								var elp = this.getErrorCt();
								this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
							}
							this.errorIcon.dom.qtip = msg;
							this.errorIcon.applyStyles('margin-left: 320px;');
							this.errorIcon.dom.qclass = 'x-form-invalid-tip';
							this.errorIcon.show();
							this.fireEvent('invalid', this, msg);
						}, clearInvalid: function(){
							if(!this.rendered || this.preventMark){ // not rendered
								return;
							}
							this.el.removeClass(this.invalidClass);
							if(this.errorIcon){
								this.errorIcon.dom.qtip = '';
								this.errorIcon.hide();
								this.un('resize', this.alignErrorIcon, this);
							}
							this.fireEvent('valid', this);
						}, validate: function(){
							this.clearInvalid();
							return true;
						}}
					]
				}],
				buttons: [{
					tabIndex: 20, 
					text: 'Signup',
					type: 'submit',
					handler: function() {
						if((typeof pageTracker) != 'undefined') pageTracker._trackPageview("/funnel_G1/step2.html");
						fState = fpSignup.form.findField('mail_state');
						if(!fState.forceSelection)
						{
							fState.setValue(fState.getRawValue());
						}
						fpSignup.form.submit({
							waitMsg: 'Creating Your Account...',
							success: function() {
								if((typeof pageTracker) != 'undefined') pageTracker._trackPageview("/funnel_G1/complete.html");
								window.location.replace('/account');
							}
						});
					}
				}]
			});
		}

	};

}();

TSM.Security = function() {
	
	var fp;

	var doLogin = function() {
		if((typeof pageTracker) != 'undefined') pageTracker._trackPageview("/funnel_G2/step2.html");
		fp.form.submit({
			waitMsg: 'Checking Credentials...',
			success: function(f, a) {
				if((typeof pageTracker) != 'undefined') pageTracker._trackPageview("/funnel_G2/complete.html");
				if(a.result.redirect)
					window.location.replace(a.result.redirect);
				else
					window.location.replace('/account');
			}
		});
	};

	return {

		showLogin: function() {
			fp = new Ext.form.FormPanel({
				url: '/login',
				title: 'Enter Your Login Credentials',
				renderTo: 'form-login',
				
				items: [
					new Ext.form.TextField({fieldLabel: 'Email', name: 'email', allowBlank: false, vtype: 'email'}),
					new Ext.form.TextField({fieldLabel: 'Password', name: 'password', inputType: 'password', allowBlank: false})
				],
				
				buttons: [{
					text: 'Login',
					type: 'submit',
					handler: doLogin,
					scope: this
				}],

				keys: [{
					key: Ext.EventObject.ENTER,
					fn: doLogin,
					scope: this
				}]
			});
		}

	};
}();
