
//pre onReady global settings.

// reference local blank image
Ext.BLANK_IMAGE_URL = '/lib/ext-2.0/resources/images/default/s.gif'; 

// common variables

var xg = Ext.grid;

var tipsoff = "true";

var strikes = []; //create,populate array of strikes for comboBox
var j = 0;
for (var i = 1; i < 25; i = i + 1) {
	strikes[j] = [j,i];
	j++;
}
for (var i = 5; i < 35; i = i + 2.5) {
	strikes[j] = [j,i];
	j++;
}
for (i = 35; i < 200; i = i + 5) {
	strikes[j] = [j,i];
	j++;
}
for (i = 200; i < 1000; i = i + 10) {
	strikes[j] = [j,i];
	j++;
}

var reader = new Ext.data.JsonReader({
    idProperty:'taskId',
    fields: [
        {name: 'projectId', type: 'int'},
        {name: 'project', type: 'string'},
        {name: 'taskId', type: 'int'},
		{name: 'leg', type: 'string'},			// short or long
		{name: 'option', type: 'string'},		// call or put
        {name: 'description', type: 'string'},
        {name: 'callstk', type: 'auto'},
		{name: 'putstk', type: 'auto'},
        {name: 'rate', type: 'auto'},			// opening bid-ask 
		{name: 'toclose', type: 'auto'},		// closing bid-ask
		{name: 'space', type: 'auto'},
		{name: 'delta', type: 'auto'},			// delta per leg
		{name: 'fees', type: 'auto'},			// broker charge
        {name: 'maxr', type: 'float'},			// Max Reward
        {name: 'shortratio', type: 'float'},	// Short/Long ratio (Calendars)
		{name: 'retratio', type: 'float'},		// Return to risk ratio
		{name: 'roi', type: 'float'},			// Current return on investment
		{name: 'movet', type: 'float'},			// Stock Move to reach Target ROI
		{name: 'moveb', type: 'float'},			// Stock Move to reach breakeven
		{name: 'movel', type: 'float'},			// Stock Move to reach 50% loss
		{name: 'price', type: 'auto'},			// Stock price, used to calc best
		{name: 'brkeven', type: 'float'},		// Closing to cover expenses
		{name: 'target', type: 'float'},		// Closing to reach target ROI %
		{name: 'profit', type: 'float'},		// Max Profit per contract
        {name: 'due', type: 'date', dateFormat:'m/d/Y'}
    ]
});

var traderecord = Ext.data.Record.create([
    	{name: 'projectId', type: 'int'},
    	{name: 'project', type: 'string'},
        {name: 'taskId', type: 'int'},
		{name: 'leg', type: 'string'},
		{name: 'option', type: 'string'},
        {name: 'description', type: 'string'},
		{name: 'callstk', type: 'auto'},
        {name: 'putstk', type: 'auto'},
        {name: 'rate', type: 'auto'},
		{name: 'toclose', type: 'auto'},
		{name: 'space', type: 'auto'},
		{name: 'delta', type: 'auto'},
		{name: 'fees', type: 'auto'},
        {name: 'maxr', type: 'float'},
		{name: 'shortratio', type: 'float'},
		{name: 'retratio', type: 'float'},
		{name: 'roi', type: 'float'},
		{name: 'movet', type: 'float'},
		{name: 'moveb', type: 'float'},
		{name: 'movel', type: 'float'},
		{name: 'price', type: 'auto'},
		{name: 'brkeven', type: 'float'},
		{name: 'target', type: 'float'},
		{name: 'profit', type: 'float'},
        {name: 'due', type: 'date', dateFormat:'m/d/Y'}
]);

// common functions

function tipjunk(mytip) {  //render happens upon initialization, show happens each time displayed
	//return false;      //Always return false and
						 // start-tips,stop-tips adds and removes this listener
						 // tips accidentally on, just stay on and are caught here constantly
		 
	if (tipsoff === "true"){  //One listener always on that, that disables tips again if triggered
		Ext.QuickTips.getQuickTip().disable();	//The indiv instance
		Ext.QuickTips.disable();      			//Globaly from the mgr level, 
		return false;		  //checks the flag and redisables everything
	}
}

function turnontips () {  //Initialize, but dont show tips to start with
	Ext.QuickTips.init();				/* Most reliable if you start enabled */
	Ext.apply(Ext.QuickTips.getQuickTip(), {   
			//mouseOffset: [-5000,0],		/* CANT SEE THEM, but IE flickers, other cond apply */
			//x: 40,  //down and to the side
			//y: 60,
			//mouseOffset:[-3000,-3000],//[30,40],  force to top-left corner
			mouseOffset: [50,20],  //centered underneath
			animCollapse: false,
			border: 'true',
			bodyBorder: 'true',
			bodyStyle: 'padding:5px; font-size:13px; font-weight:normal;',
			baseCls: 'qtip',
			dismissDelay: 0,
			frame: 'true',
			hideDelay: 0,
			autoWidth: 'true',
	    	minWidth: 100,
	    	showDelay: 0,
	    	trackMouse: true   //true allows large mouseoffset to show offscreen on firefox
	});
	Ext.QuickTips.getQuickTip().addListener('beforeshow',tipjunk,this);
	Ext.QuickTips.getQuickTip().disable();	//The indiv instance
	Ext.QuickTips.disable();      			//Globaly from the mgr level, 
}

function stoptips(g) {
	tipsoff = "true";
	//g.getColumnModel().defaultSortable = false;  //used for highlights, cannot be quoted
	//Ext.apply(Ext.QuickTips.getQuickTip(), {    /* IS Persistent */
		//mouseOffset: [-5000,0]    /* Show it clear off the monitor so noone sees it. */
		//showDelay: 120000,       /* wait LONG time to show the tip, breaks the mouseOffset */
		//trackMouse: false       /* reduce the cycles, breaks mouseOffset */
		//dismissDelay: 1
	//});
	//Ext.QuickTips.getQuickTip().destroy();  //Very very persistant
	///Ext.QuickTips.getQuickTip().addListener('beforeshow',tipjunk,this);
	Ext.QuickTips.disable();      //Globaly from the mgr level, 
	Ext.QuickTips.getQuickTip().disable(); //The indiv instance
}
	
function starttips(g) {
	tipsoff = "false";
	//g.getColumnModel().defaultSortable = true;  //used for highlights, cannot be quoted,makes it sort
	//Ext.QuickTips.init();         /* Cause tips off by default to save cycles */
	Ext.QuickTips.enable();       //The manager,  In case we have disabled them once 
	Ext.QuickTips.getQuickTip().enable();  //This instance
	///Ext.QuickTips.getQuickTip().removeListener('beforeshow',tipjunk,this);
	/*Ext.apply(Ext.QuickTips.getQuickTip(), {
		animCollapse: false,
		border: 'true',
		bodyBorder: 'true',
		bodyStyle: 'padding:5px; font-size:13px; font-weight:normal;',
		baseCls: 'qtip',
		dismissDelay: 0,
		frame: 'true',
		hideDelay: 0,
		autoWidth: 'true',
    	minWidth: 100,
		mouseOffset: [-130,25],
    	showDelay: 0,
    	trackMouse: true
	});*/
}

/* almost works, passes string but not grid variable
function isvalid(form,options) {
	var togrid = options.fromgrid;
	//alert(togrid);
	//togrid.view.refresh();
	//collpapsed = 'false';
}	

function opennumber(form,options) {
	var togrid = options.fromgrid;
	////var me = stuff.Answer1;
	////alert(me);
	form.reset();  //apparently calls a gratuitous valid, ignored
	//var foo = options.args.foo;
	
	form.addListener('valid',this.isvalid.createDelegate(this, {fromgrid:togrid},true), {
		single:true,
		buffer: 100
	});
}

function getneteditor(g) {
	var neteditor = new Ext.form.NumberField({
					allowBlank: false,
                    allowNegative: false,
					maxLength: 10,
					minValue: '.01',
					selectOnFocus: false,
					style: "font-size:13px;",
					validationDelay: 1500,
					validateOnBlur: true,  //always validates on blur
					listeners: {
						'focus'		: {
							fn: this.opennumber.createDelegate(this, {fromgrid: g}, true)
						}
						//'specialkey': {fn: enterkey},
						//'blur' 		: {fn: myblur}
					},
					style: 'text-align:left'
	});
	return neteditor;
} */

function myask(v) {
	if (v > 99.99) {
		return '<span style=\'padding-left:0px;\'>' + Ext.util.Format.usMoney(v) + '</span>' + word;
	}else{
		if (v > 9.99) {
			return '<span style=\'padding-left:7px;\'>' + Ext.util.Format.usMoney(v) + '</span>' + word;
		}else{
			return ( (v > 0|| v===0 ) ? ('<span style=\'padding-left:14px;\'>' + Ext.util.Format.usMoney(v) + '</span>' + word) : (v));
		}
	}
}

    // define custom summary functions that generally dont loop
	// looping summary functions are generally in GroupSummary.js
	
	/* looping example, unused
    Ext.grid.GroupSummary.Calculations.totalCost = function(v, record, field){
        return v + (record.data.callstk * record.data.rate);
    };*/
	
	Ext.grid.GroupSummary.Calculations.entertext = function(v, record, field){
		return;
		//future enhancement
        //return '<span class=positive>Ticker: &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span>';
    };
	
	Ext.grid.GroupSummary.Calculations.totalRisk = function(v, record, field){
		/*alt method to calculate*/
		/*netrisk = (( v===0 ) ? (record.data.putstk - record.data.rate): (v -(record.data.putstk - record.data.rate) ) );*/

		/*Textbook method to calculate*/
		netrisk= netstrike - bidask;  /*bidask is netcredit OR Cost_Basis*/
        return netrisk;				/* or maxreward for some trades */
    };
	
	// For Calendar trades Short/Long ratio
	Ext.grid.GroupSummary.Calculations.bidaskRatio = function(v, record, field){
        return baratio;
    };	
	// For Calendar trades Ret/Risk ratio
	Ext.grid.GroupSummary.Calculations.CreditRatio = function(v, record, field){
        //return (shortbid / bidask * 100);  /* or reward / cost_basis */
		return crratio;
    };

	// For Credit trades the Short Strike price is the target ROI stock price limit
	Ext.grid.GroupSummary.Calculations.roitarget = function(v, record, field){
		return shortstk;
    };

	// For BullPut and BearCall Ret/Risk ratio
    Ext.grid.GroupSummary.Calculations.Ratio = function(v, record, field){
        return (bidask / netrisk * 100);
    };

	// For BullCall and BearPut Ret/Risk ratio
	Ext.grid.GroupSummary.Calculations.MaxRatio = function(v, record, field){
        return (netrisk / bidask * 100);  /* or reward / cost_basis */
    };
	
	// For BullPut Break-Even Stock price
	Ext.grid.GroupSummary.Calculations.Brkevensub = function(v, record, field){
        return (shortstk - bidask + brokerfee);
    };
	
	// For BearCall Break-Even Stock price
	Ext.grid.GroupSummary.Calculations.Brkevenadd = function(v, record, field){
		var sstrike = shortstk - 0;   /* must cast this as number since autocasting */
		return (sstrike + bidask - brokerfee);
    };
	
	// For Debit Trades Expenses
	Ext.grid.GroupSummary.Calculations.Brkevenaddspread = function(v, record, field){
		// brokerfee is not same as saying mybroker = record.data.fees
		// cause this call is in a loop
		// scale by 1000 to avoid javascript rounding bug
		fakenumber = ((bidask * 1000) + (brokerfee * 1000));
		expenses = (fakenumber / 1000);
		expenses = Math.round(expenses * 100) / 100;
		return expenses;
    };
	
	// For Debit Trades ROI
	Ext.grid.GroupSummary.Calculations.ROI = function(v, record, field){
		roi = (askbid - expenses) / expenses * 100;
		roi = Math.round(roi * 100) / 100;
		return roi;
    };	
	
	// For BullPut and BearCall MaxProfit
	Ext.grid.GroupSummary.Calculations.Profit = function(v, record, field){
        return ( (bidask - brokerfee) * 100 );
    };
		
	// For Calendars: Max Profit is the credit recieved
	Ext.grid.GroupSummary.Calculations.MaxCProfit = function(v, record, field){
        return ( (shortbid - brokerfee) * 100 );
    };
	
	// For BullCall and BearPut Max Profit is Max Reward
	Ext.grid.GroupSummary.Calculations.MaxProfit = function(v, record, field){
        return ( (netrisk - brokerfee) * 100 );  //netrisk calculation is maxreward variable
    };

	// For Debit Trades: Stock move required for Target close
	Ext.grid.GroupSummary.Calculations.MOVE = function(v, record, field){
		if (netdelta === 0) {
			stkmovet = 'improper';
			return stkmovet;
		}
		fakemove = ( (roitarget) - (askbid) ) / (netdelta);
		//stkmove = (fakemove / 1000);
		stkmovet = Math.round(fakemove * 100) / 100;
		return stkmovet;
    };	

	// For Debit Trades: Stock move required for Break-Even
	Ext.grid.GroupSummary.Calculations.MOVEB = function(v, record, field){
		if (netdelta === 0) {
			stkmovbe = 'improper';
			return stkmovbe;
		}
		fakemovbe = ( (expenses) - (askbid) ) / (netdelta);
		//stkmove = (fakemovbe / 1000);
		stkmovbe = Math.round(fakemovbe * 100) / 100;
		return stkmovbe;
    };	

	// For Debit Trades: Stock move required for 50% loss
	Ext.grid.GroupSummary.Calculations.MOVEL = function(v, record, field){
		if (netdelta === 0) {
			stkmovel = 'improper';
			return stkmovel;
		}
		fakemovel = ( (expenses * 0.5) - (askbid) ) / (netdelta);
		//stkmove = (fakemovel / 1000);
		stkmovel = Math.round(fakemovel * 100) / 100;
		return stkmovel;
    };	
	
/* idea pieces
for (i = 0; i < grid.store.getCount(); i++) {
	if (i > 0) {  // or i > 0
		var rcrd = grid.store.getAt(i);
		rcrd.commit();
	}
}

grid.store.commitChanges();
var record = grid.store.getAt(rowIndex);
grid.stopEditing();
grid.startEditing(0,3);
alert('huh??');   */	
	

// for horizontal scroll even if autoheight:true
/* Ext.override(Ext.grid.GridView, {
    layout : function(){
        if(!this.mainBody){
            return;
        }
        var g = this.grid;
        var c = g.getGridEl(), cm = this.cm,
                expandCol = g.autoExpandColumn,
                gv = this;
        var csize = c.getSize(true);
        var vw = csize.width;
        if(vw < 20 || csize.height < 20){
            return;
        }
        if(g.autoHeight){
	        csize.height = this.mainHd.getHeight() + this.mainBody.getHeight();
	        if (!this.forceFit) {
	        	csize.height += this.scrollOffset;
	        }
        }
        this.el.setSize(csize.width, csize.height);
        var hdHeight = this.mainHd.getHeight();
        var vh = csize.height - (hdHeight);
        this.scroller.setSize(vw, vh);
        if(this.innerHd){
            this.innerHd.style.width = (vw)+'px';
        }
        if(this.forceFit){
            if(this.lastViewWidth != vw){
                this.fitColumns(false, false);
                this.lastViewWidth = vw;
            }
        }else {
            this.autoExpand();
        }
        this.onLayout(vw, vh);
    }
}); */

Ext.onReady(function(){

});	

