// for jquery, not set in stone, but starting the swim plugins off with this
// to add plugins use something like the $.swim.sortTypes example 
// in jquery.swim.indicators.js
$.swim = {};
// diagnostics plugin, to add a test use $.swim.diagnostics.addTest(testMethod);
// the method should return it's results, wich will in turn be sent to console.
$.swim.diagnostics = {
	testResults:new Array(),
	testMethods:new Array(),
	status:"notset",
	addTest:function(testMethod){ 
		testMethods.push(testMethod);
	},
	runTests:function(){
		$.swim.diagnostics.testMethods.each(function(index, test){
			$.swim.diagnostics.log("test "+index+":"+test());
		});
	},
	log:function(message){
		if (typeof console != "undefined" && typeof console.debug != "undefined") {
			console.log(message);
		} else { 
			alert(message);
		}
	},
	setTestResult:function(name, value){
		$.swim.diagnostics.testResults[name] = value;
	},
	getTestResult:function(name){
		return $.swim.diagnostics.testResults[name];
	},
	getIntTestResult:function(name){
		var result = $.swim.diagnostics.getTestResult(name);
		try{
			return parseInt(result);
		}catch(e){doNTG();}
		return null;
	},
	getResultStatus:function(){
		return $.swim.diagnostics.status;
	},
	setResultStatus:function(status){
		$.swim.diagnostics.status = status;
	},
	toString:function(){
		var out = new StringBuffer();
		out.append("Status: ").append($.swim.diagnostics.getResultStatus()+"\n");
		out.append("Page: ").append(document.location+"\n");
		for(var key in $.swim.diagnostics.testResults){
			out.append(key + ": "+ $.swim.diagnostics.testResults[key]+"\n");
		}
		return out;
	}
};
//Securities plugin
$.swim.securityTypes={
	types:new Array({id:1, name:"Stocks"},{id:13, name:"Options"},{id:102, name:"Industries"}),
	getSecurityType:function(id){
		for(var i = 0; i < this.types.length; i++){
			if(this.types[i].id == id)
				return this.types[i];
		}
	}
};
// urls and images
$.swim.uris={
	urls:new Array(),
	imgs:new Array(),
	addUrl:function(key,url){
		$.swim.uris.urls[key] = url;
		return $.swim.uris;
	},
	addImg:function(key,url){
		$.swim.uris.imgs[key] = new Image();
		$.swim.uris.imgs[key].src = url;
		return $.swim.uris;
	},
	getUrl:function(key){
		return $.swim.uris.urls[key];
	},
	getImg:function(key){
		var img = $.swim.uris.imgs[key];
		if(img == null) return "";
		return $.swim.uris.imgs[key].src;
	},
	userPrefLink:function(key, name, params){
		if(("" + ajaxTables_sameWindow) == "true")
			$.swim.uris.go(key, params);
		else{	
			$.swim.uris.pop(key, name, params);
		}
	},
	go:function(key, params){
		if(params == null){
			params = "";
		}
		//TODO [kr] trim - dont know if the global trim is available here
		//this could be cleaned up
		params.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		if(params.length > 0 && params.indexOf('?') != 0){
			params = "?"+params;
		}
		var loc = $.swim.uris.urls[key]+params;
		window.location = loc;
	},
	pop:function(key, name, params, windowPrefs){
		if(params == null){
			params = "";
		}else if(params.indexOf('?') != 0){
			params = "?"+params;
		}
		if(windowPrefs == null) windowPrefs = 'scrollbars=1,menubar=0,resizable=1,toolbar=1,location=0,status=0';
		if(name == null) name = "DataWindow";
		var loc = $.swim.uris.urls[key]+params;
		window.open(loc, name, windowPrefs);
	},
	openTab:function(key,params){
		if (params == null){
			params = null;
		}else if (params.indexOf('?') != 0){
			params = "?" + params;
		}
		var loc ;
		if ( params != null)
			loc = $.swim.uris.urls[key]+params;
		else
			loc = $.swim.uris.urls[key];
		var newWindow = window.open(loc,'_blank');
		newWindow.focus();
	}
};
var userPrefs = new Array();
function getContextHint(){
	return 'This icon: <img src='+$.swim.uris.getImg("ctxhint")+'></img> indicates that the following item has a right click menu.';
}
var ui = 0;
function doNTG(){}// less obvious then javascript:void();
function getUniqueId(prefix){
	if(prefix == null) prefix = "UI_";
	return prefix+(ui++);
}
var prefURL = contextPath + '/ajaxbridge/preferences.iedu';
// element sets
function getElementSet(cls, tag){// this can be relplaced by using the jquery methods.
	var ret;					// leaving for now so nothing will break.
	if(tag == null)
		ret = $(tag);
	else ret = $(tag+"."+cls);
	return ret;
}
function clearElementSet(){return;}// not needed leaving so nothing will break.
function clearCache(){return;}// not needed leaving so nothing will break.

function doSavePreference(distributed, preference, value, onsaved) {
	var requestName = (distributed)? 'savePreference' : 'saveNonDistributedPreference';
	if(onsaved == null) onsaved = doNTG;
	var xml = "<request name='"+requestName+"'><preference name='"+preference+"' value='"+value+"' /></request>";
	var requestMaker = new CATS.RequestMaker(prefURL, onsaved, null, xml);
	requestMaker.loadXMLDoc();
	return requestMaker;
}
function savePreference(preference, value, onsaved) {
	doSavePreference(true, preference, value, onsaved);
}
function saveNonDistributedPreference(preference, value, onsaved) {
	doSavePreference(false, preference, value, onsaved);
}
function saveSiteAlertRecord(siteAlertIDs) {
    var xml = "<request name='saveSiteAlertRecord'>";
    var alerts = siteAlertIDs.split(',');
    if (alerts.length <= 0)  return;
    for (var i = 0; i < alerts.length; i++) {
        xml += "<preference name='" + alerts[i] + "' value='dismissed' />";
    }
    xml += "</request>";
    var requestMaker = new CATS.RequestMaker(prefURL, doNTG, null, xml);
    requestMaker.loadXMLDoc();
    return requestMaker;
}
function doGetPreference(distributed, preference, onPreference){
	var requestName = (distributed)? 'getPreference' : 'getNonDistributedPreference';
	preferencesUpdated = onPreference;
	var xml = "<request name='"+requestName+"'><preference name='"+preference+"' /></request>";
	var requestMaker = new CATS.RequestMaker(prefURL, _recievePreferences, null, xml);
	requestMaker.prefcallback = onPreference;
	var xmlDoc = requestMaker.loadXMLDoc();
	return requestMaker;
}
function getPreference(preference, onPreference) {
	doGetPreference(true, preference, onPreference);
}
function getNonDistributedPreference(preference, onPreference) {
	doGetPreference(false, preference, onPreference);
}
function _recievePreferences(){
	var xml = this.req.responseXML;
	var mainresponse = xml.getElementsByTagName("response");
	var preferenceList = xml.getElementsByTagName("preference");
	for (var i = 0; i < preferenceList.length; i++){
		var attbs = preferenceList[i].attributes;
		var attr = attbs.getNamedItem('name');
		if(attr == null) continue;
		attr = attr.value;
		var val = attbs.getNamedItem('value');
		if (val == null) continue;
		val = val.value;
		userPrefs[attr] = val;
	}
	if(this.prefcallback != null) 
		preferencesUpdated = this.prefcallback;
	preferencesUpdated.call(this);
}
function focusInput(inputId, bool){
	var input = document.getElementById(inputId);
	if(input == null) return;
	if (bool == true){
		input.select();
		bool = false;
	}
}
function addOnce(symbol, array){
	for(var i = 0; i < array.length; i++){
		if(array[i] == symbol) return;
	}
	array.push(symbol);
}
function removeDuplicates(array){
	var ret = new Array();
	for(var i = 0; i<array.length; i++){
		addOnce(array[i], ret);
	}
	return ret;
}
function arrayContains(theArray, theValue){
	for (var i = 0;  i < theArray.length; i++){
		if(theArray[i] == theValue)
			return true;
	}
	return false;
}
function replaceAll(string, val, rep){
    if(val == null) return "";
	while(string.indexOf(val) > -1)
		string = string.replace(val, rep);
	return string;
}
var StoredValue;
function noteValue(value){
	if(value == null || value == 'undefined' || value == 'null')
		value = '';
	StoredValue = value;
}

/*
function removeAlpha(value){
	var ret = "";
    for(var i = 0; i < value.length; i++){
		try{
			var next = '';
			if(value[i] != '.'){
                next = parseInt(value[i]);  // value[i] is undefined in IE 7
                if(""+next == "NaN") continue;
			}else 
				next = '.';
			ret += next;
		}catch(e){
			continue;
		}
	}
	return ret;
}*/

function removeAlpha(value){
    if(!value) return value;
    return value.replace(/[^0-9.]/g, '');
}
// TextBox Methods
function validateMinMaxNumerical(property, settingMax){
    if(property == null) return;
	if (settingMax == null) settingMax = true;
	var minS = getTextValue(property+"Min");
    var minSC = removeAlpha(minS);
    var maxS = getTextValue(property+"Max");
    var maxSC = removeAlpha(maxS);
    var min = minSC.length>0? parseInt(minSC):"";
	var max = maxSC.length>0? parseInt(maxSC):"";
     
    if(min.length != 0 && max.length != 0){
        if(min > max){
			if(settingMax)
				min = max;
			else
				max = min;
		}
	}
    setTextValue(property+"Min", (""+min).replace("NaN", ""));
    setTextValue(property+"Max", (""+max).replace("NaN", ""));
}
function toNumerical(val, defaultVal){
	if(defaultVal == "\0") defaultVal = null;
	else if(defaultVal == null) defaultVal = '0';
	var val = LTrim(RTrim(replaceAll(""+val, ",", "")));
	if(val.indexOf("-.") == 0)
		val = val.replace("-.", "-0.");
	else if(val.indexOf(".") == 0)
		val = "0"+val;
	if(val != ''){
		try{val = parseFloat(val);
		}catch(err){ 
		return defaultVal;}
		if(""+val == "NaN") return defaultVal;
		return val;
	}
	return defaultVal;
}
function toBoolean(val, defaultVal){
	if(defaultVal == null) defaultVal = false;
	var val = ""+LTrim(RTrim(val));
	if(val.indexOf("f") == 0 || val.indexOf("F") == 0){
		return false;
	}
	if(val.indexOf("t") == 0 || val.indexOf("T") == 0){
		return true;
	}
	return defaultVal;
}
function getNumericalInputValue(textId, defaultVal){
	return toNumerical(getTextValue(textId, defaultVal));
}
function getBoolValue(textId, defaultVal){
	if(defaultVal == null) defaultVal = false;
	return toBoolean(getTextValue(textId, defaultVal));
}
function getTextValue(textId, defaultVal){
	var ret = $('#'+textId).val();
	if(defaultVal == null) defaultVal = '';
	if(ret == null) ret = defaultVal;
	return ret;
}
function setTextValue(textId, val){
	$('#'+textId).val(val);
}
// Select Methods
function validateMinMaxSelect(property, settingMax){
	if(property == null) return;
	if (max == null) max = true;
	var minS = getSelectedValue(property+"Min");
	var maxS = getSelectedValue(property+"Max");
	var min = parseInt(minS);
	var max = parseInt(maxS);
	if(min <= max) return;
	if(settingMax)
		setSelectedValue(property+"Min", max);
	else
		setSelectedValue(property+"Max", min);
}
function getNumericalSelectedValue(selectId, defaultVal){
	return toNumerical(getSelectedValue(selectId, defaultVal));
}
function setSelectedValue(selectId, value){
	var select = document.getElementById(selectId);
	if(select == null) return null;
	var vals = select.options;
	if(vals.length == 0){
		return true;
	}
	vals[0].selected = true;
	set = false;
	for (var i=0; i < vals.length; i++){
		if("" + vals[i].value == "" + value){
			vals[i].selected = true;
			set = true;
		}else
			vals[i].selected = false;
	}
	return set;
}
function getSelectedValue(selectId, defaultVal){
	var select = $("#"+selectId).get(0);//document.getElementById(selectId);
	if(select == null) return defaultVal;
	var vals = select.options;
	for(var i = 0; i < vals.length; i++)
		if(vals[i].selected)
			return vals[i].value;
	return defaultVal;
}
function getSelectedName(selectId, defaultName){
	var select = $('select#'+selectId);
	if(select.length == 0) return defaultName;
	var vals = select.get(0).options;
	for(var i = 0; i < vals.length; i++)
		if(vals[i].selected)
			return $(vals[i]).html();
	return defaultName;
}
function getSelectedIndex(selectId, defaultIndex){
	if(defaultIndex == null) defaultIndex = -1;
	var select = $('select#'+selectId);
	if(select.length == 0) return defaultIndex;
	var vals = select.get(0).options;
	for(var i = 0; i < vals.length; i++)
		if(vals[i].selected)
			return i;
	return defaultIndex;
}
function setSelectedIndex(selectId, index){
	if(index == null) index = 0;
	var select = $('select#'+selectId);
	if(select.lenght == 0) return;
	var vals = select.get(0).options;
	if(index > vals.length) return;
	vals[index].selected = "selected";
}
// DOM methods .... These are all handled by jquery, but
// I don't want to break any existing code.
function setInnerHTML(elementId, value){
	$('#'+elementId).html(value);
	return $('#'+elementId).get(0) != null;
}
function setElementValue(elementId, value){
	$('#'+elementId).val(value);
	return $('#'+elementId).get(0) != null;
}
function hideElement(elementId){
	$('#'+elementId).hide();
	return $('#'+elementId).get(0) != null;
}
function showElement(elementId){
	$('#'+elementId).show();
	return $('#'+elementId).get(0) != null;
}
function clearSelect(select, emptytext){
	select.options.length = 0;
	if(emptytext != null){
    	select.options[select.options.length] = new Option(emptytext, null);
    }
}
// sorting --
function optionCompare(resultItemA, resultItemB) {
    var valueA = resultItemA[0];
    var valueB = resultItemB[0];
    if(valueB.indexOf("All") > -1)
    	return 1;
    if(valueA.indexOf("All") > -1)
    	return -1;
    if (valueA > valueB) {
        return 1;
    } else if (valueA < valueB) {
        return -1;
    } else {
        return 0;
    }
}
function namedItemCompare(itemA, itemB) {
    var valueA = itemA.name;
    var valueB = itemB.name;
    if(itemB.id != null && itemB.id == "ALL")
    	return 1;
    if(itemA.id != null && itemA.id == "ALL")
    	return -1;
    if (valueA > valueB) {
        return 1;
    } else if (valueA < valueB) {
        return -1;
    } else {
        return 0;
    }
}

function launchProphetChart(symbol){
	if(!isJCRunning()){
		launchTimeAndSales(symbol);
		pchartWindow = 
			window.open(contextPath+'/graphs/prophetChart/launcher.iedu?symbol='+symbol,'', 'height=150,width=350,scrollbars=no,resizable=no');
	}else{
		launchTimeAndSales(symbol);
	}
}
function trade(symbol){
	window.open(contextPath+'/graphs/thinkOrSwimRedirect.iedu?symbol='+symbol,'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
}
function popWindow(url, name){
	if(("" + ajaxTables_sameWindow) == "true")
		this.location = url;
	else{	
		if(name == null) name = "Data_Window";
		window.open(url, name, 
			'scrollbars=1,menubar=0,resizable=1,toolbar=1,location=0,status=0');
	}
}
function setSameWindow(on){
	savePreference("sameWindow", on);
	ajaxTables_sameWindow = on;
}
function snapshot(symbol){
	popWindow(contextPath+'/graphs/snapshot.iedu?symbol='+symbol);
}
function compNews(symbol){
	popWindow(contextPath+'/graphs/companynews.iedu?symbol='+symbol);
}
function optionLink(symbol){
	popWindow(contextPath+'/graphs/option/listed.iedu?symbol='+symbol);
}



function buttonOn(elem){//return;
	if($(elem).is('button_special')){
		$(elem)
			.removeClass('button_special')
			.addClass('button_special-hover');
	}else{
		$(elem)
			//.removeClass('button')
			.addClass('button-hover');
	}
	
	//elem.className=(elem.className.indexOf('special')<0)?'button-hover':'button_special-hover';
}
function buttonOff(elem){
	if($(elem).is('button_special-hover')){
		$(elem)
			.removeClass('button_special-hover')
			.addClass('button_special');
	}else{
		$(elem)
			.removeClass('button-hover')
			.addClass('button');
	}
	
	//elem.className=(elem.className.indexOf('special')<0)?'button':'button_special';
}
var XMLAMP = '--xmlAMP';
var XMLLT = '--xmlLT';
var XMLGT = '--xmlGT';
var XMLAPOS = '--xmlAPOS';
var XMLQUOT = '--xmlQUOT';
function xmlEncode(str) {
	return str.toString().replace('&',XMLAMP).replace('<',XMLLT).replace('>',XMLGT).replace('\'', XMLAPOS).replace('\"', XMLQUOT);
}
function xmlDecode(str) {
	return str.toString().replace('&lt;','<').replace('&gt;','>').replace('&amp;','&').replace('&apos;', '\'').replace('&quot', '\"');
}
// String buffer concating strings is costly for the client
StringBuffer = function(){
	this.buffer = new Array();
}
StringBuffer.prototype ={
	appendLine:function(val){
		this.append(val);
		this.append("\n");
		return this;
	},
	append:function(){
		for(var i = 0; i < arguments.length; i++){
			this.buffer.push(arguments[i]);
		}
		return this;
	},
	toString:function(){
		return this.buffer.join("");
	}
}
function setSymbolContexts(){
	$('span.qStock').not('span.done')
		.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' ></img>")
		.contextMenu('qStock', {
      bindings: {
        'Trade': function(t) {
			$.swim.thinkPod.realmoneyTradingPlatform($(t).attr('symbol'));	
			if(track) track('http://toolbox.investools.com/rightClickTradeNowClicked');		
			//window.open(contextPath+'/graphs/thinkOrSwimRedirect.iedu?symbol='+$(t).attr('symbol'),
				//'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},
        'PaperMoney': function(t) {
			$.swim.thinkPod.papermoneyTradingPlatform($(t).attr('symbol'));	
			if(track) track('http://toolbox.investools.com/rightClickPaperMoneyClicked');
			//window.open(contextPath+'/graphs/thinkOrSwimPaperRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},              
        'Snapshot': function(t) {
        	snapshot($(t).attr('symbol'));
        },
        'ProphetCharts': function(t) {
        	launchProphetChart($(t).attr('symbol'));
        },
        'AddtoPortfolio': function(t) {
        	var out = new StringBuffer();
        	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        },
        'AddtoWatchlist': function(t) {
        	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        }
      }
    }).addClass('done');
	$('span.qOptionableStock').not('span.done')
		.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' />")
		.contextMenu('qOptionableStock', {
      bindings: {
        'Trade': function(t) {
			$.swim.thinkPod.realmoneyTradingPlatform($(t).attr('symbol'));	
			if(track) track('http://toolbox.investools.com/rightClickTradeNowClicked');	
			//window.open(contextPath+'/graphs/thinkOrSwimRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},
        'PaperMoney': function(t) {
			$.swim.thinkPod.papermoneyTradingPlatform($(t).attr('symbol'));	
			if(track) track('http://toolbox.investools.com/rightClickPaperMoneyClicked');
			//window.open(contextPath+'/graphs/thinkOrSwimPaperRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},              
        'Snapshot': function(t) {
        	snapshot($(t).attr('symbol'));
        },
        'Options': function(t) {
        	optionLink($(t).attr('symbol'));
        },
        'ProphetCharts': function(t) {
        	launchProphetChart($(t).attr('symbol'));
        },
        'AddtoPortfolio': function(t) {
        	var out = new StringBuffer();
        	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        },
        'AddtoWatchlist': function(t) {
        	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        }
      }
    }).addClass('done');
	$('span.qForex').not('span.done')
	.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' />")
	.contextMenu('qForex', {
	  bindings: {
	    'Trade': function(t) {
			$.swim.thinkPod.realmoneyTradingPlatform($(t).attr('symbol'));	
			if(track) track('http://toolbox.investools.com/rightClickTradeNowClicked');	
			//window.open(contextPath+'/graphs/thinkOrSwimRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},
	    'PaperMoney': function(t) {
			$.swim.thinkPod.papermoneyTradingPlatform($(t).attr('symbol'));
			if(track) track('http://toolbox.investools.com/rightClickPaperMoneyClicked');
			//window.open(contextPath+'/graphs/thinkOrSwimPaperRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},
	    'Snapshot': function(t) {
	    	snapshot($(t).attr('symbol'));
	    },
	    'ProphetCharts': function(t) {
	    	launchProphetChart($(t).attr('symbol'));
	    },
	    'AddtoPortfolio': function(t) {
	    	var out = new StringBuffer();
	    	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
	    },
	    'AddtoWatchlist': function(t) {
	    	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
	    }
	  }
	}).addClass('done');
	$('span.qFuture').not('span.done')
	.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' />")
	.contextMenu('qFuture', {
	  bindings: {
	    'Snapshot': function(t) {
	    	snapshot($(t).attr('symbol'));
	    },
	    'ProphetCharts': function(t) {
	    	launchProphetChart($(t).attr('symbol'));
	    },
	    'AddtoPortfolio': function(t) {
	    	var out = new StringBuffer();
	    	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
	    },
	    'AddtoWatchlist': function(t) {
	    	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
	    }
	  }
	}).addClass('done');
	$('span.qOption').not('span.done')
		.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' />")
		.contextMenu('qOption', {
      bindings: {
        'Trade': function(t) {
			$.swim.thinkPod.realmoneyTradingPlatform($(t).attr('symbol'));	
			if(track) track('http://toolbox.investools.com/rightClickTradeNowClicked');	
			//window.open(contextPath+'/graphs/thinkOrSwimRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},
        'PaperMoney': function(t) {
			$.swim.thinkPod.papermoneyTradingPlatform($(t).attr('symbol'));
			if(track) track('http://toolbox.investools.com/rightClickPaperMoneyClicked');
			//window.open(contextPath+'/graphs/thinkOrSwimPaperRedirect.iedu?symbol='+$(t).attr('symbol'),
			//	'', 'left=20, top=20, height=800,width=1060,scrollbars=yes,resizable=yes');
		},
        'Snapshot': function(t) {
        	snapshot($(t).attr('symbol'));
        },
        'ProphetCharts': function(t) {
        	launchProphetChart($(t).attr('symbol'));
        },
        'AddtoPortfolio': function(t) {
        	var out = new StringBuffer();
        	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        },
        'AddtoWatchlist': function(t) {
        	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        }
      }
    }).addClass('done');
	$('span.qMutualFund').not('span.done')
		.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' />")
		.contextMenu('qMutualFund', {
      bindings: {
        'Snapshot': function(t) {
        	snapshot($(t).attr('symbol'));
        },
        'ProphetCharts': function(t) {
        	launchProphetChart($(t).attr('symbol'));
        },
        'AddtoPortfolio': function(t) {
        	var out = new StringBuffer();
        	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        },
        'AddtoWatchlist': function(t) {
        	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        }
      }
    }).addClass('done');
	$('span.qUnimplemented').not('span.done')
		.before("<img src='"+$.swim.uris.getImg('ctxhint')+"' />")
		.contextMenu('qMutualFund', {
      bindings: {
        'Snapshot': function(t) {
        	snapshot($(t).attr('symbol'));
        },
        'ProphetCharts': function(t) {
        	launchProphetChart($(t).attr('symbol'));
        },
        'AddtoPortfolio': function(t) {
        	var out = new StringBuffer();
        	out.append(contextPath,'/portfolio/addSymbols.iedu?symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        },
        'AddtoWatchlist': function(t) {
        	var out = new StringBuffer();
			out.append(contextPath,'/portfolio/addSymbols.iedu?addTo=watchlist&symbols=',$(t).attr('symbol'));
			window.open(out.toString(),'newwin',
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=250');
        }
      }
    }).addClass('done');
}
function futureToTOS(symbol){
	symbol = symbol.replace("@", "");
	return "/"+symbol;
}
function setContextTimeout(force){
	if(force || $('#jqContextMenu').attr('inUse') == 'true'){
		setTimeout(function(){
			setContextTimeout();}, 3000);
	}else{
		$('#jqContextMenu').hide();
	}
}
var shiftActive = false;
function doReuters(){
	var loc = window.location+"";
	loc = loc.replace("articleId", "aId");
	$('origin').each(function(){
		if($(this).attr('href') == 'StoryRef'){
			var val = $(this).html();
			$(this).html("<a href='"+loc+"&articleId="+val+"'>read story</a>");
		}
	});
}
$(document).ready(function(){// these will be set for every page.
	//To display Tooltip: hoverReady is the class set for an element and the attribute hoverText is where the tooltip is defined. 
	$(".hoverReady").hoverIntent({
		   sensitivity: 1,
		   interval: 250,
		   over: function(event){
		   	if(typeof(ddrivetip)!='undefined') 
		   		ddrivetip($(this).attr("hoverText"), 250);
		   		positiontip(event);
		   	},
		   timeout: 1,
		   out: typeof(hideddrivetip) == 'function' ? hideddrivetip : function() {}
		});
	
	
	$.ajax.complete = function(){
		alert('ajaxed');
	}
	//doReuters();
	// symbol context menu
	if(!$.contextMenu) return;
	var contexts = new StringBuffer();
	contexts.append(
	'<div style="display:none;" id="qStock">',
		'<ul><li id="Trade" ><img src="'+$.swim.uris.getImg('trade')+'"/>Trade</li>',
        '<li id="PaperMoney" ><img src="'+$.swim.uris.getImg('papermoney')+'"/>paperMoney&reg;</li>',
        '<li id="Snapshot" >Snapshot</li>',
		'<li id="ProphetCharts" >ProphetCharts&reg;</li>',
		'<li id="AddtoPortfolio" >Add&nbsp;to&nbsp;Portfolio</li>',
	    '<li id="AddtoWatchlist" >Add&nbsp;to&nbsp;Watchlist</li></ul>',
	'</div><div style="display:none;" id="qOption">',
		'<ul><li id="Trade" ><img src="'+$.swim.uris.getImg('trade')+'"/>Trade</li>',
        '<li id="PaperMoney" ><img src="'+$.swim.uris.getImg('papermoney')+'"/>paperMoney&reg;</li>',
        '<li id="Snapshot" >Snapshot</li>',
	    '<li id="ProphetCharts" >ProphetCharts&reg;</li>',
	    '<li id="AddtoPortfolio" >Add&nbsp;to&nbsp;Portfolio</li>',
	    '<li id="AddtoWatchlist" >Add&nbsp;to&nbsp;Watchlist</li></ul>',
	'</div><div style="display:none;" id="qForex">',
		'<ul><li id="Trade" ><img src="'+$.swim.uris.getImg('trade')+'"/>Trade</li>',
        '<li id="PaperMoney" ><img src="'+$.swim.uris.getImg('papermoney')+'"/>paperMoney&reg;</li>',
        '<li id="Snapshot" >Snapshot</li>',
	    '<li id="ProphetCharts" >ProphetCharts&reg;</li>',
	    '<li id="AddtoPortfolio" >Add&nbsp;to&nbsp;Portfolio</li>',
	    '<li id="AddtoWatchlist" >Add&nbsp;to&nbsp;Watchlist</li></ul>',
	'</div><div style="display:none;" id="qFuture">',
		'<ul><li id="Snapshot" >Snapshot</li>',
	    '<li id="ProphetCharts" >ProphetCharts</li>',
	    '<li id="AddtoPortfolio" >Add&nbsp;to&nbsp;Portfolio</li>',
	    '<li id="AddtoWatchlist" >Add&nbsp;to&nbsp;Watchlist</li></ul>',
	'</div><div style="display:none;" id="qOptionableStock">',
		'<ul><li id="Trade" ><img src="'+$.swim.uris.getImg('trade')+'"/>Trade</li>',
        '<li id="PaperMoney" ><img src="'+$.swim.uris.getImg('papermoney')+'"/>paperMoney&reg;</li>',
        '<li id="Snapshot" >Snapshot</li>',
	    '<li id="Options" >Options</li>',
	    '<li id="ProphetCharts" >ProphetCharts&reg;</li>',
	    '<li id="AddtoPortfolio" >Add&nbsp;to&nbsp;Portfolio</li>',
	    '<li id="AddtoWatchlist" >Add&nbsp;to&nbsp;Watchlist</li></ul>',
	'</div><div style="display:none;" id="qMutualFund">',
		'<ul><li id="Snapshot" >Snapshot</li>',
		'<li id="ProphetCharts" >ProphetCharts&reg;</li>',
		'<li id="AddtoPortfolio" >Add&nbsp;to&nbsp;Portfolio</li>',
	    '<li id="AddtoWatchlist" >Add&nbsp;to&nbsp;Watchlist</li></ul></div>');
	$(contexts.toString()).prependTo('body');
	
	$.contextMenu.defaults({
			menuStyle:{listStyle:'none',padding:'1px',margin:'0px',backgroundColor:'#fff',border:'1px solid #999',width:'150px'},
			shadow:false,
			onContextMenu: function(e) {
				$('#jqContextMenu').attr('inUse', 'false');
				$('#jqContextMenu').hover(
				function(){
					$('#jqContextMenu').attr('inUse', 'true');
			   	},function(){
			   		$('#jqContextMenu').attr('inUse', 'false');
			   	});
			    setContextTimeout(true);
			    return true;}
	});
	$(window).keydown(function(event){
				if(event.keyCode == 16) shiftActive = true;
			}).keyup(function(event){
				if(event.keyCode == 16) shiftActive = false;
			});
	setSymbolContexts();

	// new better buttons
		$('input.cool').bind('btnselect', function(){
				$(this).addClass('selected');
			}).bind('btndeselect', function(){
				$(this).removeClass('selected');
			}).bind('btndisable', function(){
				var hid = $(this).attr('hid');
				$(this).removeClass('disabled').attr('disabled', '');
				$('input#'+hid).attr('disabled', '');
				$('div#div_'+$(this).attr('id')).removeClass('disabled');
			}).bind('btnenable', function(){
				var hid = $(this).attr('hid');
				$(this).addClass('disabled').attr('disabled', 'disabled');
				$('div#div_'+$(this).attr('id')).addClass('disabled');
				$('input#'+hid).attr('disabled', 'disabled');
			});

    //setHovers();
// other stuff
});
//  this is a util function for formating dates in js. http://jacwright.com/projects/javascript/date_format   
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 13 && this.getDate() != 1 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};


