var ModalNotifyHeight = 270;
var ModalNotifyWidth = 350;

var NewsDetailHeight = 400;
var NewsDetailWidth = 693;

var LastOrderId = '-1';
var numPositions = -1;
var Positions = [];
var Orders = [];  //

function wsIcons(state, ws){
	if(state == 'open'){
		var rmClass = 'ui-icon-arrowthick-1-ne';
		var newClass = 'ui-icon-arrowthick-1-sw';
		var shLable = 'Hide';
	} else {
		var rmClass = 'ui-icon-arrowthick-1-sw';
		var newClass = 'ui-icon-arrowthick-1-ne';
		var shLable = 'Show';
	}
	if('AccountInfo' == ws){
		var ico = jQuery('#HideAccountIcon');
		var shLableId = 'HideAccountInfo';
	 }
	 else {
		var ico = jQuery('#HideQuotesIcon');
		var shLableId = 'HideQuotes';
	 }
	ico.removeClass(rmClass);
	ico.addClass(newClass);
	jQuery('#'+shLableId).attr('title', shLable);
}
function repositionWS(){ 
      var ws = "";
      var curTop = 0;
      var sib = '';
      var myH = 0;
      var ext = 0;
      var padding = 7;
      var idRoot = '';
      for (var i = 0; i < WorkSpaceOrder.length; i++){ 
         ws = WorkSpaceOrder[i];
         
         if(ws == 'AccountInfo'){
        	 sib = 'Quote';
        	 jQuery("#AccountInfo").css('top', '' + curTop + 'px');
        	 idRoot = "#HideAccount";
         } else {
        	 sib = 'AccountInfo';
        	 jQuery("#QuoteView").css('top', '' + curTop + 'px');
        	 idRoot = "#HideQuotes";
         }
         if(WorkSpace[ws]['State'] == 'open'){
        	 myH = WorkSpace[ws]['HideHeight'];
        	 ext = 0;
        	 
        	 if(WorkSpace[sib]['State'] == 'closed'){
        		 myH = myH + WorkSpace[sib]['HideHeight'];
        	 }
        	 
        	 if('AccountInfo' == ws){
        		 var hmm = 'wtf';
        		 jQuery('#AccountInfoHide').css('display', '');
        		 jQuery('.AccountInfoNormal').each(function() {
  					jQuery(this).height(myH-17);
  				  });
  				  
        	 }
        	 else {
      					
     			jQuery('#QuoteHide').css('display', '');
     			jQuery('#QuoteHide').height(myH);
     			jQuery('#QuoteViewTable').height(myH - 55); 
     			var foo = 123;
     			var ccc;
        	 }
        
        	 
         } else {
        	 myH = 0;
        	 if(ws == 'AccountInfo'){
        		 jQuery('#AccountInfoHide').css('display', 'none');
        	 } else {
       					
        		 jQuery('#QuoteHide').css('display', 'none');
        	 }
         }
         curTop = curTop + myH + WorkSpace[ws]['ClosedHeight'] + ext + padding;
         wsIcons(WorkSpace[ws]['State'], ws);
      } 
      return; 
    } 

function updateJwebWorkspace(){
		
	jQuery.getJtJSON('/quotes/updateJwebWorkspace?QuoteOrder='
		+ WorkSpace['Quote']['Order'] + "&QuoteStatus=" + WorkSpace['Quote']['State'] 
		+ "&AccInfoOrder=" + WorkSpace['AccountInfo']['Order'] + "&AccInfoStatus="
		+ WorkSpace['AccountInfo']['State'],
			function(data){
				if(data != ''){
					var foo = 1;
				}
			});
}
function jtIconClick(obj, event){
	var padding = 5;
	var id = obj.attr('id');
	if(obj.hasClass('ChangeOrder')){
		if(id == 'MoveQuotes'){
			if(WorkSpace['Quote']['Order'] ==0){
				WorkSpace['Quote']['Order'] = 1;
				WorkSpace['AccountInfo']['Order'] = 0;
			} else {
				WorkSpace['Quote']['Order'] = 0;
				WorkSpace['AccountInfo']['Order'] = 1;
			}
		} else {
			if(WorkSpace['AccountInfo']['Order'] ==0){
				WorkSpace['Quote']['Order'] = 0;
				WorkSpace['AccountInfo']['Order'] = 1;
			} else {
				WorkSpace['Quote']['Order'] = 1;
				WorkSpace['AccountInfo']['Order'] = 0;
			}
		}
		WorkSpaceOrder[WorkSpace['Quote']['Order']] = 'Quote';
		WorkSpaceOrder[WorkSpace['AccountInfo']['Order']] = 'AccountInfo';
		repositionWS();
	} else if(obj.hasClass('HidePanel')) {
		if(id == 'HideAccountInfo'){
			var wsKey = 'AccountInfo';
		} else {
			var wsKey = 'Quote';
		}
		if(WorkSpace[wsKey]['State'] == 'closed'){
			WorkSpace[wsKey]['State'] = 'open';
		} else {
			WorkSpace[wsKey]['State'] = 'closed';
		}
		repositionWS();
	}
	if(event != null){
		updateJwebWorkspace();
	}
}
function updateH2(){
	if(mOverView == ''){
		return;
	}
	jQuery.getJtJSON(pathRoot+'/updateMov.php?id='+mOverView+'&ipath='+pathRoot,
		function(data){
			if(data.html != ''){
				jQuery('#'+mOverView).html(data.html);
			}
		});
}
function changeAccountInfoTabs(event, ui){
	if(ui.index == 2){
		jQuery("#LoadingMsg").html('Loading History');
		jQuery("#ModalLoading").dialog('open');
		var tan = '?tan=' + jQuery("#TradingAccounts").val();
		jQuery.getJtJSON('/quotes/getOsHistory' + tan,
			function(data){
				if(data.html != ''){
					jQuery("#HistoryValue").html(data.html);
					jQuery("#HistoryRange").html(data.StartDate +
							' - ' + data.EndDate);
					
				}
				jQuery("#ModalLoading").dialog('close');	
				});
	} else if(ui.index == 3){
		jQuery("#LoadingMsg").html('Loading History');
		jQuery("#ModalLoading").dialog('open');
		jQuery.getJtJSON('/quotes/getMessages',
			function(data){
				if(data.html != ''){
					jQuery("#SecMsgs").html(data.html);
					
				}
				jQuery("#ModalLoading").dialog('close');	
				});
	}
}
function changeChart(event, ui){
	//var selected = jQuery('#tabs').tabs('option', 'selected');
	var params = "&ct=i";
	if(ui.index > 0){
		params = chartValues[ ui.index];
	} 
	var chartUrl = PageProto + '://www.junotrade.com/Charts/ChartServer/juno1.php?s=' +currentDetailSym + params;
	jQuery("#DetailChart" + ui.index).attr('src', chartUrl);
	return true;
}
function str_replace(haystack, needle, replacement) {
	var temp = haystack.split(needle);
	return temp.join(replacement);
}
function findPosition(hId){
	var oId = hId.replace('Row', '');
	oId = str_replace(oId, 'Pi', '');
	oId = str_replace(oId, '-', '');
	return Positions[oId];
}
function positionBeforeDisplay( el){
	var oId = el.attr('id').replace('Row', '');
	oId = str_replace(oId, 'Pi', '');
	oId = str_replace(oId, '-', '');
	setActiveRow(el, activePosnInfoRow);
	activePosnInfoRow = el;
	var pInfo = Positions[oId];
	if (pInfo === undefined){
		return;
	}
	jQuery("#positionMenuHeader").html(pInfo['Symbol'] + ' ' + pInfo['Quantity'] +
			' ' + pInfo['Type']);
}
function processPositionRightClick(action, el, pos) {
	/*var oId = el.attr('id').replace('Row', '');
	oId = str_replace(oId, '_', '.');
	*/
	if(action.indexOf("#") >= 0){ //ie7 passes the full url
		var parts = action.split("#");
		if(parts.length = 2){
			action = parts[1];
		}
	}
	//
	setChildbg(el, normRowBg);
	var cPositions = [];
	var pInfo;
	var lMsg = '';
	var oSide = '';
	if(action == "ClosePosition"){
		pInfo = findPosition(el.attr('id'));
		if (pInfo === undefined){
			return;
		} else {
			cPositions[0] = pInfo;
			lMsg = "Closing " + pInfo['Symbol'] + ' ' + pInfo['Quantity'] +
			' ' + pInfo['Type'];
			if(pInfo['Type'] == 'Long'){
				oSide = 'Sell';
			} else {
				oSide = 'Buy';
			}
			setOrderRow('OrderHolder', pInfo['Symbol'], pInfo['Quantity'], 
					oSide, '', '','Pending','Market');
		}
	} else if(action == 'CloseAllPosition') {
		for (i in Positions) {
			if(typeof(Positions[i]) == "undefined" ||
					typeof(Positions[i]) != "object"){
				continue;
			}
			cPositions.push(Positions[i]);
		}
		//cPositions = Positions;
		lMsg = "Closing All Postions";
	} else {
		return;
	}
	/*
	jQuery("#LoadingMsg").html(lMsg);
	jQuery("#ModalLoading").dialog('open');
	*/
	clearTimeout(UpdateOsTimer);
	jQuery(el.children()[6]).html('<img alt="" src="/images/ajax-loader-10.gif" /><div style="text-align:left; padding-top:0px; color:#ffffff;">Pending</div>');
	jQuery.getJtJSON('/quotes/closePositions', {
		Positions : JSON.stringify(cPositions)
		},
		function(data){
			//jQuery("#ModalLoading").dialog('close');
			processOsInfo(data);
			});
			
}

function getOrderById(oId){
	for( var i = -1, order;  order = Orders[++i]; ){
		if(order['OrderID'] == oId) {
			return order;
		}
	}
	return null;
}
function processOrderRightClick(action, el, pos) {
	var oId = el.attr('id').replace('Row', '');
	oId = str_replace(oId, '_', '.');
	
	if(action.indexOf("#") >= 0){ //ie7 passes the full url
		var parts = action.split("#");
		if(parts.length = 2){
			action = parts[1];
		}
	}
	var orderInfo = getOrderById(oId);
	if(orderInfo){
		jQuery("#LoadingMsg").html("Canceling " + orderInfo['Side'] + ' ' +
				orderInfo['Symbol'] + ' ' + orderInfo['Type'] + ' order');
		//jQuery("#ModalLoading").dialog('open');
		jQuery(el.children()[9]).html('<img alt="" src="/images/ajax-loader-10.gif" /><div style="padding-top:0px; color:#ffffff;">Pending cancel</div>');
		//jQuery(el.children()[9]).html('<img alt="" src="/images/ajax-loader.gif" />Pending cancel');
		setChildbg(el, normRowBg);
		TradeActionCount = 0;
		jQuery.getJtJSON('/quotes/cancelOrder', {
			OrderID : orderInfo['OrderID'],
			ClOrdID : orderInfo['ClOrdID'],
			Side : orderInfo['Side'],
			Symbol : orderInfo['Symbol']
			},
			function(data){
				//jQuery("#ModalLoading").dialog('close');
				clearTimeout(UpdateOsTimer);
				processOsInfo(data);
				});
	}
}
var activeRowBgS = 'url("/quotes/images/ActiveRow.png") repeat-x scroll 70% 60%';
var activeRowBgB = 'url("/quotes/images/ActiveRow.png") repeat-x scroll 70% 70%';
var normRowBg = 'url("/quotes/images/quoteValueBg.jpg") repeat scroll center top transparent';
var activeOrderInfoRow = null;
var activePosnInfoRow = null;
var activeQuoteInfoRow = null;

function setChildbg(par, tag){
	jQuery(par).children().each(
	    function(){
		jQuery(this).css('background', tag);
		
	});
}
function setActiveRow(actRow, curRow){
	if(curRow != null && actRow != curRow){
		setChildbg(curRow, normRowBg);
	}
	if(actRow.html().indexOf('<br') > 0){
		setChildbg(actRow, activeRowBgB);
	} else {
		setChildbg(actRow, activeRowBgS);
	}
}
function ordersBeforeDisplay( el){
	var oId = el.attr('id').replace('Row', '');
	var found = false;
	
	oId = str_replace(oId, '_', '.');
	for( var i = -1, order;  order = Orders[++i]; ){
		if(order['OrderID'] == oId) {
			jQuery("#orderMenuHeader").html(order['Side'] + ' ' +
					order['Symbol'] + ' ' + order['Type']);
			found = true;
			break;
		}
	}
	if(found == true){
		setActiveRow(el, activeOrderInfoRow);
		activeOrderInfoRow = el;
	}
	return found;
}
/* 'Total Value' column which is 
 * quantity times bid for long positions and 
 * quantity times ask for short positions
*/
var plLastData = [];

function calculatePL(value, sym, tdId, vType){
	var pType = '';
	if(tdId.indexOf('Long') > 0 ){
		pType = 'Long';
	} else {
		pType = 'Short';
	}
	var pInfo = Positions[sym+pType];
	if (pInfo === undefined){
		return;
	}
	var plVal;
	var plTotVal;
	var update = false;
	//if(plData[sym] === undefined) {
	//plLastData[sym] = [];
	//}
	if(pType == 'Long'){
		if(vType == 'Bid'){
			//plLastData[sym]['Bid'] = value;
			plLastData[sym+'Bid'] = value;

		plVal = (value - pInfo.AveragePrice.Amount) * pInfo.Quantity;
		plTotVal = (value) * pInfo.Quantity;
		update = true;
		}
	} else {
		if(vType == 'Ask'){
			plLastData[sym+'Ask'] = value;
			plVal = (pInfo.AveragePrice.Amount - value) * pInfo.Quantity;
			plTotVal = (value) * pInfo.Quantity;
			update = true;
		}
	}
	if(update == true){
		jQuery("#" + tdId).html(plVal.toFixed(2));
		jQuery("#" + tdId.replace('PiPl', 'PiPlT')).html(plTotVal.toFixed(2));
	}
}
function processPositions(data){
	var positions = data.Positions;
	
	if(data.posHtml != ''){
		jQuery("#PositionsValue").html(data.posHtml);
	}
	if(typeof(positions) == "undefined"){
		numPositions = 0;
		return;
	}
	numPositions = positions.length;
	var error = false;
	var positionData = [];
	var symTag = '';
	var qStr = '';
	var avgAmount = 0.0;
	for( var i = -1, position;  position = positions[++i]; ){
		symTag = position['Symbol'].replace('.', '_');
		if(jQuery('#' + symTag  + '-' + position['Type'] + 'PiRow').length == 0){
			error = true;
			numPositions = -1;
			continue;
		}

		positionData[position['Symbol']+ position['Type']] = position;
		//symTag = position['Symbol'].replace('.', '_') + '-' + position['Type'] + 'PiTime'
		jQuery('#' + symTag + '-' + position['Type'] + 'PiTime').html(position['TransactTimestamp']);
		avgAmount = parseFloat(position['AveragePrice']['Amount']);
		qStr = '' + position['Quantity'] + ' (' +  avgAmount.toFixed(2) + ')';
		jQuery('#' + symTag + '-' + position['Type'] + 'PiQuantity').html(qStr);
		if(data.posHtml != ''){
			if(position['Type'] == 'Long' && plLastData[symTag+'Bid'] !== undefined){
				calculatePL(plLastData[symTag+'Bid'], symTag, symTag + '-LongPiPl', 'Bid');
			} else {
				if(updateQuotesTimer != null){
					clearTimeout(updateQuotesTimer);
				}
				window.setTimeout(function() {
					updateQuotesTimer = updateQuotes();
					}, 100);
			}
			if(position['Type'] == 'Short' && plLastData[symTag+'Ask'] !== undefined){
				calculatePL(plLastData[symTag+'Ask'], symTag, symTag + '-ShortPiPl', 'Ask');
			}
		}
		/*
		 * >>> value
22.44
>>> sym
"CAL"
>>> tdId
"CAL-LongPiPl"
>>> vType
"Bid"
		 */
	}
	Positions = positionData;
	jQuery("#PositionsValue tr").contextMenu({
		menu: 'positionMenu',
		container: jQuery('#PositionsValue'),
		enableClick: true,
		BeforeDisplay: function(el){
		positionBeforeDisplay(el);
			}
	}, function(action, el, pos) {
		processPositionRightClick(action, el, pos);
	});
}

function processOsInfo(data){
	var orders = data.Orders;
	var pending = false;
	Orders = data.Orders;
	if(data.New != '') {
		jQuery("#OrdersValue").html(data.New);
	}
	if(data.Subscriber != null){
		setSubscribers(data.Subscriber);
	}
	if(typeof(orders) != "undefined"){
		if(orders.length > 0) {
			for( var i = -1, order;  order = orders[++i]; ){
				if(i == 0){
					LastOrderId = order.ClOrdID;
				}
				if(order.Status.indexOf('Pending') >= 0){
					pending = true;
					LastOrderId = '-1';
				}
				j = order;
			} 
		
			
			jQuery("#OrdersValue tr").contextMenu({
				menu: 'orderMenu',
				container: jQuery('#OrdersValue'),
				enableClick: true,
				BeforeDisplay: function(el){
				return ordersBeforeDisplay(el);
					}
			}, function(action, el, pos) {
				processOrderRightClick(action, el, pos);
			});
		} else {
			LastOrderId = '0';
		}
	}
	var status = processPositions(data);
	var timerInt = 5000;
	if(pending == true){
		timerInt = 100;
	}
//console.log('setTimeout ' + timerInt);
	UpdateOsTimer = window.setTimeout(function() {
		updateOsInfo();
		}, timerInt);
	return pending;
}
var TradeActionCount = 0;
function updateOsInfo(){
	// XXX DISABLE
	//return;
  if(TradeActionCount < 3){
    LastOrderId = -1;
    numPositions = -1;
    TradeActionCount += 1;
  }

	var tan = '&tan=' + jQuery("#TradingAccounts").val();
	jQuery.getJtJSON('/quotes/getOsInfo?last=' + LastOrderId + "&cp=" + numPositions + tan, 
      function(data){
		var pending = processOsInfo(data);		
      });
}
function changeTradingAcc() {
  //'&tan=' + jQuery("#TradingAccounts").val();
  LastOrderId = -1;
  numPositions = -1;
  
  var orderR = '<tr class="QuoteRow"><td colspan="10" class="OrderValue" style="text-align:left;">Loading, pleas wait...</td></tr>';
  jQuery("#OrdersValue").html(orderR);
  var posR = '<tr class="QuoteRow"><td colspan="6" class="OrderValue" style="text-align:left;">Loading, please wait...</td></tr>';
  jQuery("#PositionsValue").html(posR);
  jQuery("#HistoryValue").html(posR);
  

  clearTimeout(UpdateOsTimer);
  updateOsInfo();
}
function displayNewsDetail(link, title){
	jQuery("#ModalNotifyText").html('<iframe src ="' + link + '" width="100%" height="300"></ifarme>');
	jQuery("#ModalNotify").dialog('option', 'width', NewsDetailWidth);
	jQuery("#ModalNotify").dialog('option', 'height', NewsDetailHeight);
	jQuery("#ModalNotify").dialog('option', 'title', title);
	jQuery("#ModalNotify").dialog("open");
}
function displayModalNotify(title, text) {
	jQuery("#ModalNotifyText").html(text);
	jQuery("#ModalNotify").dialog('option', 'width', ModalNotifyWidth);
	jQuery("#ModalNotify").dialog('option', 'height', ModalNotifyHeight);
	jQuery("#ModalNotify").dialog('option', 'title', title);
	jQuery("#ModalNotify").dialog("open");
}

function getNewsFeed(sym) {
	jQuery("#NewsRow").parent().children().each(
	    function(){
		if(jQuery(this).attr('id') == '') {
			jQuery(this).remove();
		}
	});
		
	jQuery.getJtJSON('/quotes/getNews?sym=' + sym, 
      function(data){
		var newsRow = jQuery("#NewsRow");
		var newsColumn = jQuery("#NewsColumn");
		var newsTable = jQuery("#NewsTable");
		
		for(var i = 0; i < data.items.length && i < 5; i++) {
			var item = data.items[i];
			/*
			var aLink = '<a onClick="displayNewsDetail(\'' + item.link + "','" + item.title +
				'\');return false;"> ';
			*/
			var aLink = ' <a href="' + item.link + '" target="_blank">';
			newsColumn.html(item.title + ' ' + item.pubDate + aLink +  'more...</a>');
			
			//newsColumn.html(item.title + ' ' + item.pubDate);
			var newHeight = newsTable.height() + newsRow.height();

			if(newHeight < 125) {
				var newRow = newsRow.clone();
				if(i == 0){
					newRow.find("td").attr('style', 'border:none')
				}
				newsRow.before('<tr>' + newRow.html() + '</tr>');

			} else {
				break;
			}
	}
      });
}

var validateSym;

function symbolBlur(obj, event){
	var newSym = jQuery(obj).val().toUpperCase();
	var lastSym = jQuery(obj);
	oldSym = currentSymbol;
	if(newSym == validateSym) {
		return;
	}
	if(newSym == '' && currentSymbol.indexOf("NEWItem") == 0){
		return; // blur on currently blank (add stubs)
	}
	if(currentSymbol != jQuery(obj).val()){
		// dup check
		if(currentWatchListObj != null){
			for (property in currentWatchListObj.Items) {
				if(property == newSym){
					displayModalNotify('Invalid Symbol ', newSym + ' is already in this Watch List');
					jQuery(obj).val(oldSym);
					return;
				}
			}
		}
	
		if(newSym == '') {
			//validateSym = oldSym;
			jQuery("#LoadingMsg").html("Updating Watch List ");
			jQuery("#ModalLoading").dialog('open');
			//validateSym = newSym;
			jQuery.getJtJSON('/quotes/removeWatchListItem?sym=' + oldSym + '&wlId=' + currentWatchListObj['Index'], 
				function(data){
				jQuery("#ModalLoading").dialog('close');
				if(data){
					var obj = jQuery('#' + data.sym);
					obj.parent().parent().remove()
					currentWatchListObj = JSON.parse(data.watchListData); 
				}
			});
			return;
		}
		
		var url = '/quotes/changeWatchListItem?symNew=' + newSym;
		var curIndex;
		var oldItemId;
		if(currentWatchListObj == null){
			curIndex = -1;
			var wlName = jQuery("#CurrentName").val();
			if(wlName == ''){
				wlName = 'New Watch List';
				jQuery("#CurrentName").val(wlName);
			}
			url = url + "&wlName=" + wlName;
			oldItemId = '-1';
		} else {
			curIndex = currentWatchListObj['Index'];
			try {
				oldItemId = currentWatchListObj['Items'][oldSym];
			}
			catch(err) {
				oldItemId = '-1';
			}
		}
		url = url + '&symOld=' + oldSym + '&wlId=' + curIndex +'&itemId=';
		if(oldSym.indexOf('NEWItem') == 0){
			url = url + '-1';
		} else {
		// update wli
			url = url + oldItemId;
		}
		jQuery("#LoadingMsg").html("Validating " + newSym);
		jQuery("#ModalLoading").dialog('open');
		validateSym = newSym;
		jQuery.getJtJSON(url, function(data){
			jQuery("#ModalLoading").dialog('close');
			if(data){
				var dataObj = data;
				var obj = jQuery('#' + dataObj.symOld);
				if(parseFloat(dataObj.Status) > 0){
					var newSym = dataObj.symNew;
					var changeOldSymbol = dataObj.symOld;
					
					var curId = jQuery(obj).attr('id');
					jQuery(obj).attr('id', curId.replace(changeOldSymbol, newSym));
					// change name id
					var nameId = jQuery('#' + changeOldSymbol + 'Name').attr('id');
					jQuery('#' + oldSym + 'Name').attr('id', nameId.replace(changeOldSymbol, newSym));
					changeItemIds(jQuery(obj).parent().parent(), changeOldSymbol, newSym);
					curId = jQuery(obj).parent().parent().attr('id');
					jQuery(obj).parent().parent().attr('id', curId.replace(changeOldSymbol, newSym));
					
					parseData(dataObj.newSymData);
					jQuery(obj).val(newSym);
					currentWatchListObj = dataObj.watchListData;
					currentWatchList =  currentWatchListObj.Index;
				} else if(parseFloat(dataObj.Status) < 0){
					displayModalNotify('Invalid Symbol ', dataObj.symNew + ' is not a valid Symbol');
					if(dataObj.symOld.indexOf("NEWItem") < 0){
						jQuery(obj).val(dataObj.symOld);
					} else {
						jQuery(obj).val('');
					}
					
					return;
				}
				//currentWatchListObj = JSON.parse(data);
			}
		});
		return;
	}
}

var currentWlName;
function wlNameFocus(obj){
	currentWlName = jQuery(obj).val();
}
function updateWlName(newName){
	jQuery("#LoadingMsg").html("Updating Watch List Name");
	jQuery("#ModalLoading").dialog('open');
	jQuery.getJtJSON('/quotes/changeWatchListName?newName=' + newName + '&wlId=' + currentWatchListObj.Index,
		function(data){
			jQuery("#ModalLoading").dialog('close');
			if(data){
				//var data  = JSON.parse(dataRaw);
				currentWatchListObj = data.wlData;
				jQuery("#CurrentWLName").val(data.newName);
				jQuery("#WatchLists").html(data.wlOptions);
				}
			});
	
}
function deleteWl(name){
	jQuery("#LoadingMsg").html("Deleting Watch List - " + name);
	jQuery("#ModalLoading").dialog('open');
	jQuery.getJt('/quotes/removeWatchList?watdhListId=' + currentWatchListObj.Index,
		function(data){
			jQuery("#ModalLoading").dialog('close');
			if(data){
				jQuery("#QuoteView").html(data);
				}
			});
	
}
function wlNameBlur(obj){
	var newName = jQuery(obj).val();
	if(currentWlName != newName && currentWatchListObj != null) {
		// update or delete
		if(newName != '') {
			updateWlName(newName);
		} else {
			deleteWl(currentWlName);
		}
		/*
		jQuery("#LoadingMsg").html("Updating Watch List Name");
		jQuery("#ModalLoading").dialog('open');
		jQuery.getJtJSON('/quotes/changeWatchListName?newName=' + newName + '&wlId=' + currentWatchListObj.Index,
			function(data){
				jQuery("#ModalLoading").dialog('close');
				if(data){
					//var data  = JSON.parse(dataRaw);
					currentWatchListObj = data.wlData;
					jQuery("#CurrentWLName").val(data.newName);
					jQuery("#WatchLists").html(data.wlOptions);
					}
				});
		*/		
	}
}

function addWatchList(){
	var url = '/quotes/addWatchList';
	currentWatchList = '-1';
	/*
	jQuery.getJtJSON(url, function(dataRaw){
		if(dataRaw){
			var dataObj = dataRaw; //JSON.parse(dataRaw);
			if(parseFloat(dataObj.Status) > 0){
				currentWatchListObj = dataObj.data;
				var newId = currentWatchListObj.Index;

				jQuery("#LoadingMsg").html("Loading Watch List");
				*/
				jQuery("#ModalLoading").dialog('open');
				jQuery.getJt('/quotes/changeQuoteTable?watdhListId=-1',  // + newId 
			      function(data){
					if(data){
						jQuery("#QuoteView").html(data);
						jQuery("#ModalLoading").dialog('close');
					}
				});
				/*
			}
		}
	});*/
}

function changeWatchLists(){
	if(initDone == false){
		return;
	}
	var newId = jQuery("#WatchLists").val();
	if(currentWatchList != newId){
		currentWatchList = newId;
		
		jQuery("#LoadingMsg").html("Loading Watch List");
		jQuery("#ModalLoading").dialog('open');
		jQuery.getJt('/quotes/changeQuoteTable?watdhListId=' + newId, 
	      function(data){
			if(data){
				jQuery("#QuoteView").html(data);
				jQuery("#ModalLoading").dialog('close');
			}
		});
	}
}

function changeRowIds(rows,lastId, newId){
	rows.each(
	    function(){
			//changeItemIds(jQuery(this), lastDetail, sym);
			jQuery(this).children().each(
			    function(){
					var curId = jQuery(this).attr('id');
					jQuery(this).attr('id', curId.replace(lastId, newId));
	//	console.log(jQuery(this).attr('id'));
			    });
		});
}
var lastDetail = "Empty";
function showDetails(obj, event){
//console.log('ROWS ');
//return false;
	var pos = obj.offset();  
	var height = obj.height();
	var infoObj = obj.find(".CompanyNameLabel");
	var sym = obj.find(".CompanyNameLabel").attr('id').replace('Name', '');
	var qDialog = jQuery("#QuoteDetailDialog");
	
	currentDetailSym = sym;
	//var chartUrl = 'http://appserver1.junotrade.com/Charts/ChartServer/juno1.php?s=' +sym +'&ct=i';
	if(event != null){
		detailPinned = true;
	}
	//jQuery("#DetailChart0").attr('src', chartUrl);
	changeChart('event', {index:0});
	jQuery('#tabs').tabs('select', '#tabs-1');
//console.log('ROWS ');
	
	var rows = jQuery("#QuoteDetailTable tr");

//console.log('ROWS ' + rows);

	rows.each(
	    function(){
			//changeItemIds(jQuery(this), lastDetail, sym);
			jQuery(this).children().each(
			    function(){
					var curId = jQuery(this).attr('id');
					jQuery(this).attr('id', curId.replace(lastDetail, sym));
	//	console.log(jQuery(this).attr('id'));
			    });
		});
	
	
	//changeRowIds(jQuery("#QuoteDetailTable tr"),lastDetail, sym)
	lastDetail = sym;
	jQuery("#DetailTrade").html('Trade ' + sym );
	//jQuery("#DetailChart").attr('src', chartUrl);
	//jQuery("#DetailNews").html('News for ' + sym);
	jQuery("#DetailCharts").html('Charts for ' + sym);
	var scrollOff = jQuery(window).scrollTop();
	var winHeight = jQuery(window).height();
	//var dHeight = DetailDialogHeight; //qDialog.height() +40;
	var dHeight = jQuery("#QuoteDetailDialog").parent().height();
	var dTop;
	if((pos.top - scrollOff + dHeight) > winHeight) {
		dTop = winHeight - dHeight;
	} else {
		dTop = pos.top - scrollOff;
	}
	jQuery("#QuoteDetailDialog").dialog('option', 'position', [pos.left+50, dTop]);
	//jQuery("#QuoteDetailDialog").dialog('option', 'width', "655px");
	//jQuery("#QuoteDetailDialog").dialog('option', 'height', "250px");
	jQuery("#QuoteDetailDialog").dialog('option', 'title', infoObj.html());
	
	jQuery("#QuoteDetailDialog").dialog("open");
	getNewsFeed(sym);
	
	jQuery.getJt('/quotes/getSymbol?sym=' + sym + '&H1req=1', 
      function(data){
		if(data){
			var lines = data.split('\n');
		    for( var i = -1, line;  line = lines[++i]; ) {
				parseLine(line, 'Detail');
		    }
		}
		return false;
	});
	
	return false;
}
function tradeBeforeDisplay( el){
	var sym = el.attr('id').replace('Row', '');

	if(sym == 'TradeButton'){
		return;
	}
	setActiveRow(el, activeQuoteInfoRow);
	activeQuoteInfoRow = el;
	if(focusSybol == currentSymbol){
		focusSybol = '';
		return false;
	}
	var tmBuy = '';
	var tmSell = '';
	var tmShort = '';
	var pType = '';
	if(sym.indexOf("NEW")<0){
		if(Positions[sym + "Long"] !== undefined){
			tmShort = 'none';
			pType = ' ' + Positions[sym + "Long"].Quantity + ' Long';
		} else {
			tmSell = 'none';
		}
		if(Positions[sym + "Short"] !== undefined){
			pType = ' ' + Positions[sym + "Short"].Quantity + ' Short';
		}
		jQuery("#tradeMenuHeader").html(sym + pType);
	} else {
		jQuery("#tradeMenuHeader").html('');
	}
	
	jQuery("#tmShort").css('display', tmShort);
	jQuery("#tmSell").css('display', tmSell);
}
function processRightClick(action, el, pos) {
	
	var sym = el.attr('id').replace('Row', '');
	if(sym == 'TradeButton'){
		sym = '';
	}
	if(action.indexOf("#") >= 0){ //ie7 passes the full url
		var parts = action.split("#");
		if(parts.length = 2){
			action = parts[1];
		}
	}
	//jQuery("[name=Symbol]").val(sym);
	if(sym.indexOf("NEW")<0){
		jQuery("#TradeForm").find('[name=trSymbol]').val(sym);
	} else {
		jQuery("#TradeForm").find('[name=trSymbol]').val('');
	}
	jQuery("[name=OrderSide]").val(OrderSide[action]);
	changeOrderType(jQuery("[name=OrderType]"));
	var title = action;
	if(action == 'SellShort'){
		title = 'Short';
	}
	jQuery("#TradeForm").dialog('option', 'title', title);
	jQuery("#TradeForm").dialog('open');
	return;
// TODO remove following ????	
	if(action == 'Buy'){
		jQuery("[name=BuySymbol]").val(sym);
		changeOrderType(jQuery("[name=BuyOrderType]"));
		jQuery("#TradeBuyForm").dialog('open');
	} else 	if(action == 'Sell'){
		jQuery("[name=SellSymbol]").val(sym);
		changeOrderType(jQuery("[name=SellOrderType]"));
		jQuery("#TradeSellForm").dialog('open');
	} else 	if(action == 'Short'){
		jQuery("[name=ShortSymbol]").val(sym);
		changeOrderType(jQuery("[name=ShortOrderType]"));
		jQuery("#TradeShortForm").dialog('open');
	}
	//jQuery("#TradeDialog").dialog(resetOpts);
	//jQuery("#TradeDialog").dialog('open');
}
function setTradeDefaults(prefix){
/*
	Type - Market
	Quanty - 100
	Specials unchecked
	rest disabled
*/
}
var OrderRequired = [];
function changeOrderType(obj){
	var prefix = obj.attr('name').replace('OrderType', '');
	prefix = '';
	jQuery("[name=" + prefix + "AON]").attr('checked', '');
	jQuery("[name=" + prefix + "DNR]").attr('checked', '');
	jQuery("[name=" + prefix + "MinQCheck]").attr('checked', '');
	jQuery("[name=" + prefix + "MinQ]").val('');
	jQuery("[name=" + prefix + "TimeInForce]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "Price]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "Price]").css('background-color', '#CCCCCC');
	jQuery("[name=" + prefix + "StopPrice]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "StopPrice]").css('background-color', '#CCCCCC');
	jQuery("[name=" + prefix + "TrailingType]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "TrailingStopDelta]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "TrailingStopDelta]").css('background-color', '#CCCCCC');
	jQuery("[name=" + prefix + "MinQCheck]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "MinQ]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "MinQ]").css('background-color', '#CCCCCC');
	jQuery("[name=" + prefix + "DNR]").attr('disabled', 'true');
	jQuery("[name=" + prefix + "AON]").attr('disabled', 'true');
	var oType = obj.val();
	OrderRequired = [];
	OrderRequired.push('trSymbol');
	OrderRequired.push('OrderQty');
	var timeOpt = '<option value="' + TimeInForce['Day'] + '" selected="yes">Day</option>' +
		'<option value="' + TimeInForce['GTC'] + '" >GTC</option>';
	if(oType == OrderType['Limit']){
		OrderRequired.push('Price');
		jQuery("[name=" + prefix + "Price]").attr('disabled', '');
		jQuery("[name=" + prefix + "Price]").css('background-color', '#FFFFFF');
		jQuery("[name=" + prefix + "TimeInForce]").attr('disabled', '');
		timeOpt = timeOpt + '<option value="' + TimeInForce['FOK'] + '">FOK</option>';
	} else if(oType == OrderType['Stop']){
		OrderRequired.push('StopPrice');
		jQuery("[name=" + prefix + "TimeInForce]").attr('disabled', '');
		jQuery("[name=" + prefix + "StopPrice]").attr('disabled', '');
		jQuery("[name=" + prefix + "StopPrice]").css('background-color', '#FFFFFF');
	} else if(oType == OrderType['StopLimit']){
		OrderRequired.push('Price');
		OrderRequired.push('StopPrice');
		jQuery("[name=" + prefix + "Price]").attr('disabled', '');
		jQuery("[name=" + prefix + "Price]").css('background-color', '#FFFFFF');
		jQuery("[name=" + prefix + "TimeInForce]").attr('disabled', '');
		jQuery("[name=" + prefix + "StopPrice]").attr('disabled', '');
		jQuery("[name=" + prefix + "StopPrice]").css('background-color', '#FFFFFF');
	} else if(oType == OrderType['Trailing']){
		OrderRequired.push('TrailingStopDelta');
		jQuery("[name=" + prefix + "TimeInForce]").attr('disabled', '');
		jQuery("[name=" + prefix + "TrailingStopDelta]").attr('disabled', '');
		jQuery("[name=" + prefix + "TrailingStopDelta]").css('background-color', '#FFFFFF');
		jQuery("[name=" + prefix + "TrailingType]").attr('disabled', '');
		jQuery("[name=" + prefix + "StopPrice]").attr('disabled', '');
		jQuery("[name=" + prefix + "StopPrice]").css('background-color', '#FFFFFF');
	}
	jQuery("[name=" + prefix + "TimeInForce]").html(timeOpt);
}
function changeTimeInForce(obj){
	var prefix = obj.attr('name').replace('TimeInForce', '');
	prefix = '';
	var oType = jQuery("[name=" + prefix + "OrderType]").val();
	if(oType == 'Stop' || oType == 'StopLimit') {
		jQuery("[name=" + prefix + "DNR]").attr('disabled', '');
	} else {
		jQuery("[name=" + prefix + "DNR]").attr('disabled', 'true');
	}
}
function updateQuotes() {
	jQuery.getJt('/quotes/updateWL?wlId=' + currentWatchList, 
      function(data){
		parseData(data);
		
		if(pauseUpdates == false){
			updateQuotesTimer = window.setTimeout(function() {
				updateQuotes();
				}, 5000);
		}
		
      });	
}

var OrderRequiredLabels = [];
//OrderRequiredLabels[0] = {field:'trSymbol', label:'Symbol'};
OrderRequiredLabels['trSymbol'] = 'Symbol';
OrderRequiredLabels['OrderQty'] = 'Quantity';
OrderRequiredLabels['Price'] = 'Limit Price';
OrderRequiredLabels['StopPrice'] = 'Stop Price';
OrderRequiredLabels['TrailingStopDelta'] = 'Trailing Amount';

function setOrderRow(key, tSym, oQu, oSide, oPrice, oStop,oStatus,oType){
	jQuery("#"+key+"OiSymbol").html(tSym);
	jQuery("#"+key+"OiQuantity").html(oQu);
	jQuery("#"+key+"OiSide").html(oSide);
	jQuery("#"+key+"OiPrice").html(oPrice);
	jQuery("#"+key+"OiStopPrice").html(oStop);
	jQuery("#"+key+"OiStatus").html(oStatus);
	jQuery("#"+key+"OiOrderTye").html(oType);
	
	jQuery("#"+key+"Row").css('display', '');
}
function processSaveOrder(obj){
	var OrderSide = [];
	OrderSide['s49'] = 'Buy';
	OrderSide['s50'] = 'Sell';
	OrderSide['s53'] = 'SellShort';
	var OrderType = [];
	OrderType['t49'] = 'Market';
	OrderType['t50'] = 'Limit';
	OrderType['t51'] = 'Stop';
	OrderType['t52'] = 'StopLimit';
	
	var errors = '';
	var reqItem = '';
	var errorMsg = '';
	var errorCount = 0;
	for( var i = -1, field;  field = OrderRequired[++i]; ) {
		reqItem = jQuery("#TradeInfo").find("[name=" + field + "]").val();
		if(reqItem == ''){
			errorMsg += OrderRequiredLabels[field] + ' is required<br />';
			errorCount += 1;
		}
    }
	if(errorCount != 0){
		var title;
		if(errorCount == 1){
			title = 'Please correct the following Error:';
		} else {
			title = 'Please correct the following Errors:';
		}
		displayModalNotify(title, errorMsg);
		return -1;
	}
	
	// XXX loading and acc # jQuery('#TradingAccounts').val()
	var fData = jQuery("#TradeInfo").serialize();
	var tSym = jQuery("#TradeForm").find('[name=trSymbol]').val();
	setChildbg(jQuery('#'+tSym+'Row'), normRowBg);
	fData += '&Symbol=' + tSym;
	fData += '&tan=' + jQuery("#TradingAccounts").val();
	var oType = OrderType['t'+jQuery("#TradeForm").find('[name=OrderType]').val()];
	var oSide = OrderSide['s'+jQuery("#TradeForm").find('[name=OrderSide]').val()];
	var oQu = jQuery("#TradeForm").find('[name=OrderQty]').val();
	var oPrice = jQuery("#TradeForm").find('[name=Price]').val();
	var oStop = jQuery("#TradeForm").find('[name=StopPrice]').val();
	setOrderRow('OrderHolder', tSym, oQu, oSide, oPrice, oStop,'Pending',oType);
	
	jQuery("#LoadingMsg").html("Processing " + oSide + ' ' +
			oQu + ' ' + tSym + ' ' + oType + ' order');
	//jQuery("#ModalLoading").dialog('open');
	TradeActionCount = 0;
	jQuery.getJtJSON('/quotes/makeOrder', fData, 
	function(data){
		var j = 'kk';
		clearTimeout(UpdateOsTimer);
		processOsInfo(data);
		//jQuery("#ModalLoading").dialog('close');
	  });
	return 1;
}

