var Global = {};
    Global.cme = {};
    Global.cbot = {};
    Global.nymex = {};
    Global.g = {};
    Global.cme.overRide = [];
    Global.quotes = {};

var newTypes = null;
var GLOB_UpdateColumn = null;/*Mike Amara to control when time stamp is updated*/

function clearList(elementId){
	var list = document.getElementById(elementId);
	// clear the country list 
	if ( list != null ){
		for (var count = list.options.length-1; count > -1; count--)
			list.options[count] = null;
	}
} 

function populateDropTownList(elementId,array,selectThis){
	clearList(elementId);
	var list 		= document.getElementById(elementId);
	var optionItem;
	if ( array != null){
		var len = array.length;
		for ( i = 0; i < len; ++i){
			var selected = false;
			if ( selectThis != null && array[i] == selectThis )
				selected = true;
			optionItem = new Option( array[i],array[i],  false, selected); 
			list.options[list.length] = optionItem;
		}
	} 
}

function populateDropTownListWithIndex(elementId,arrayNdx,arrayDisplay,selectThis){
	clearList(elementId);
	var list 		= document.getElementById(elementId);
	var optionItem;
	if ( arrayDisplay != null ){
		if ( arrayNdx == null )
			arrayDisplay = arrayNdx;
		for ( i = 0; i < arrayDisplay.length; ++i){
			var selected = false;
			if ( selectThis != null && arrayNdx[i] == selectThis )
				selected = true;
			optionItem = new Option( arrayDisplay[i],arrayNdx[i],  false, selected);
			list.options[list.length] = optionItem;
		}
	}
}

function changecolor(cell,x){
	cell.style.color = x;
}

function changeIfNeeded2(elementId, tmp){
	var cell = document.getElementById(elementId);
	if ( cell != null && cell.innerHTML != tmp ){
		cell.innerHTML = tmp;
	}
}

function changeIfNeeded(celle, tmp, value){
	var cell = $j(celle);
	var cellHTML = cell.html();//.replace(/\,/g, '');//Updated 20100105 by James Owens
	cell.html( cellHTML != tmp ? tmp : cellHTML );
	if(typeof value != 'undefined'){
		GLOB_UpdateColumn = 1;
		if( value.value == 'last' && cellHTML != tmp){
			cell.css({'color':'#ffffff','background-color':'#e78a01'});
		}
	}
}

function colorTransitionWidget(ajaxDisplay, tmp){
	var cell = $j(ajaxDisplay);
	if ( cell.html() != tmp ){
		var newClass = 'font_black';
		if(tmp.match(/^-/)){
			newClass = 'font_red';
		}
		else 
		if(!tmp.match(/^([+]*[0]{1}[\.|\']?[^1-9]*)$/gi)){
			/*NOT any of these: "0" or "+0" or "0.0" or "+0'0" or "0.00" or "0'00" or "0.000" or "0'000" or "0.0000" or "0'0000" or "0.0" or "0'0"*/
			newClass = 'font_green';
			tmp = '+'+tmp;
		} 
		cell.removeClass('font_green').removeClass('font_black').removeClass('font_red').html(tmp).addClass(newClass);
		
		ajaxDisplay.style.backgroundColor = "#e78a01";
		ajaxDisplay.innerHTML = tmp;
	}
}

function colorTransition(celle, tmp){
	var cell = $j(celle);
	if ( cell.html() != tmp ){
		var newClass = 'font_black';
		if(tmp.match(/^-/)){
			newClass = 'font_red';
		}
		else 
		if(!tmp.match(/^([+]*[0]{1}[\.|\']?[^1-9]*)$/gi)){
			/*NOT any of these: "0" or "+0" or "0.0" or "+0'0" or "0.00" or "0'00" or "0.000" or "0'000" or "0.0000" or "0'0000" or "0.0" or "0'0"*/
			newClass = 'font_green';
			tmp = '+'+tmp;
		} 
		cell.removeClass('font_green').removeClass('font_black').removeClass('font_red').html(tmp).addClass(newClass);
	}
}

//helper method that resets the values of table to default value = '-'
function clearTable(maxRowsPerPage, maxColumns, rowPrefix, emptyChar){
	for ( i = 0; i < maxRowsPerPage; ++i){
		var row = document.getElementById(rowPrefix+i);	
		for ( j = 0; row!=null && j < maxColumns; ++j)
			row.cells[j].innerHTML = emptyChar;
	}
}

//Helper method to extract values from drop downs	
function getSelectedValue(elementId){
	var ndx         = document.getElementById(elementId).selectedIndex;
	return document.getElementById(elementId).options[ndx].text;
}

function getSelectedValueNdx(elementId){
	var ndx         = document.getElementById(elementId).selectedIndex;
	return document.getElementById(elementId).options[ndx].value;
} 

function formatHighLowLimi(message){
	var formatedHiLow = "-";
	var br = "";
	var hasNoLimit = false;

	if ( message.highLimitPrice != null && message.highLimitPrice != "-" ){
		hasNoLimit = isNoLimit(message.highLimitPrice);

		if ( !hasNoLimit )
			formatedHiLow = message.highLimitPrice;
		else
			formatedHiLow = "No Limit";
		br = "<br/>";
	}
	if ( message.lowLimitPrice != null && message.lowLimitPrice != "-" ){
		if ( !isNoLimit(message.lowLimitPrice) )
			formatedHiLow += br + message.lowLimitPrice;
		else
			if ( !hasNoLimit )
				formatedHiLow += br + "No Limit";
	}
	return formatedHiLow;
}

var noLimitArray = new Array("0", "00","000","0000","00000", "000000", "0000000","99999", "999999", "9999999", "9999900", "9999999000",  "99999000", "99999990", "09999999", "99999999998");
function isNoLimit(value){
	var len 				= noLimitArray.length;
	var noDotsOrDashValue 	= value.replace(/\.|\'/, "");
	noDotsOrDashValue 		= noDotsOrDashValue.replace(/-/, "");
	noDotsOrDashValue 		= noDotsOrDashValue.replace(/'/, "");
	for (var i = 0; i < len; ++i){
		if ( noDotsOrDashValue == noLimitArray[i] )
			return true;
	}

	return false;
}
var GLOB_tmp = null;
var GLOB_visited = [];


var GLOB_hash_ticker = [];

function GetObjArr(val){
	return GLOB_hash_ticker[val] ? GLOB_hash_ticker[val] : null;
}

function CreateTickerHash(messages){
	var len = messages.length;
	for(var e=0;e<len;e++){
		GLOB_hash_ticker[messages[e].ticker] = e;
	}
}

function HighLowMgr(HighInd,LowInd,message){
	var HighIndRes = '';
	var LowIndRes = '';
	if(venue.match(/g/i)){
		if(HighInd == 'a')
			HighIndRes = 'b';

		if(LowInd == 'a')
			LowIndRes = 'b';
	
		if(HighInd == 'v')
			HighIndRes = 'a';

		if(LowInd == 'v')
			LowIndRes = 'a';
	}
	else{
		if(HighInd == 'a')
			HighIndRes = 'a';

		if(LowInd == 'a')
			LowIndRes = 'a';
	
		if(HighInd == 'b')
			HighIndRes = 'b';

		if(LowInd == 'b')
			LowIndRes = 'b';
	}
	if(HighIndRes == 'a' || HighIndRes == 'b')
		HighIndRes = " " + HighIndRes;

	if(LowIndRes == 'a' || LowIndRes == 'b')
		LowIndRes = " " + LowIndRes;
	return [message.highPrice + HighIndRes,message.lowPrice + LowIndRes];
}

function FixAllInd(message){
	if(venue.match(/g/i)){
		var bidRegExpVs = new RegExp("a","i");
		if(message.lastAskBidIndicator.match(bidRegExpVs)){
			message.lastAskBidIndicator = 'b';
		}					
		var bidRegExpVs = new RegExp("v","i");
		if(message.lastAskBidIndicator.match(bidRegExpVs)){
			message.lastAskBidIndicator = 'a';
		}
		var bidRegExpVs = new RegExp("m","i");
		if(message.lastAskBidIndicator.match(bidRegExpVs)){
			message.lastAskBidIndicator = 's';
		}
	}					
	return message;
}

//Process the response that we extract from the server's RESTful call
function processMDResponse(tmp){
	if ( tmp.marketDataInfoAsStringList != null && tmp.marketDataInfoAsStringList.responseHeader.RCode >= 0 ){
		var messages 	 = tmp.marketDataInfoAsStringList.message;
		if(GLOB_hash_ticker.length == 0) CreateTickerHash(messages);

		$j('tr.RowToPopulate').each( function(i){
		//jQuery.each(messages, function(i, val) {
			//var ticker = messages[i].ticker.replace(' ','');
			var row = $j(this);//$j('tr#'+ticker);

			if( GetObjArr(row.attr('id')) ){//if(row){
				var message = FixAllInd(messages[GetObjArr(row.attr('id'))]);//messages[i];				

				var tradePrice = message.tradePrice;
				var bidRegExpall = new RegExp("[ab]","i");//Temp hack  - was [abis]
				if ( message.lastAskBidIndicator.match(bidRegExpall) )//Mike - if a or be found add them to trade price
					tradePrice += " " + message.lastAskBidIndicator;
				
				colorTransition(row.find('td.netChange'),message.netChange);

				changeIfNeeded(row.find('td.settlePrice'),message.settlePrice);
			
				changeIfNeeded(row.find('td.priorSettlePrice'),message.priorSettlePrice);

				if ( Global.quotes.hideOpen != null && Global.quotes.hideOpen != "Y" )
					changeIfNeeded(row.find('td.openPrice'),message.openPrice);

				changeIfNeeded(row.find('td.HighInd'),HighLowMgr(message.highPriceBidAskIndicator,message.lowPriceBidAskIndicator,message)[0],{'value':'high'});//Mike Amara - Added value high, to control when time stamp is updated

				changeIfNeeded(row.find('td.LowInd'),HighLowMgr(message.highPriceBidAskIndicator,message.lowPriceBidAskIndicator,message)[1],{'value':'low'});//Mike Amara - Added value low, to control when time stamp is updated

				if ( Global.quotes.hideClose != null && Global.quotes.hideClose != "Y" )
					changeIfNeeded(row.find('td.closePrice'),message.closePrice,{'value':'close'});//Mike Amara - Added value close, to control when time stamp is updated

				if ( tmp.marketDataInfoAsStringList.searchCriteria.venue != 'F' ) {
					changeIfNeeded(row.find('td.cumulativeVolume'),message.cumulativeVolume); 
					row.find('td.cumulativeVolume').html( formatCurrency( row.find('td.cumulativeVolume').html() ) ); // added 2010-01-05 by James Owens, details at formatCurrency function definition.
				}

				if ( Global.quotes.hideHiLoLimit != null && Global.quotes.hideHiLoLimit != "Y" )
					changeIfNeeded(row.find('td.formatHighLowLimi'),formatHighLowLimi(message));

				if(GLOB_UpdateColumn){
					changeIfNeeded(row.find('td.tradeDate'),message.tradeDate);}//Mike Amara - Added to control when time stampe is updated
				
				GLOB_UpdateColumn = null;
				
				bidRegExpall = new RegExp("[is]","i");
				if(!message.lastAskBidIndicator.match(bidRegExpall))
					changeIfNeeded(row.find('td.tradePrice'),tradePrice,{'value':'last'});//Last
			}
		}); 
		setTimeout(function(){$j('tr.RowToPopulate').find('td.tradePrice').css({'color':'#ffffff','background-color':'#e78a01'}).filter(function (index) {
			$j(this).css({'color':'#000000','background-color':'#ffffff'});
			})},1000);
	}

}

function cmeExecJSONPost(restful,methodToExecute,postAjaxMethod){

	var posturl = [];
	posturl = restful.split('?');

	new Ajax(posturl[0],{method: 'post', headers: {'accept': 'application/json'},postBody: posturl[1],  onComplete: 
		function(jsText){ 
			var js = Json.evaluate(jsText); 
			methodToExecute(js);
			if ( postAjaxMethod != null )
			postAjaxMethod();
		},
		onFailure:function(xhr){
			if(xhr){
			//alert('Failure-cmeExecJSON-\nready state: '+xhr.readState+'\nstatus: '+xhr.status+'\nresponse text: '+xhr.responseText);
			}
			else{
			//alert('Failure-cmeExecJSON- ... ');
			}
		},
		onException:function(headerName, value){
			//alert('Exception-cmeExecJSON-\n'+headerName+'\n'+value);
		}

	}).request();
}

function cmeExecJSON(restful,methodToExecute,postAjaxMethod){ 
	new Ajax(restful,{method: 'get', headers: {'accept': 'application/json'}, onComplete: 
	function(jsText){ 
		var js = Json.evaluate(jsText);
//Widget calls - processProdGroupResponse()
		methodToExecute(js);
		if ( typeof postAjaxMethod != 'undefined' && postAjaxMethod != null )
			postAjaxMethod();
	},
	onFailure:function(xhr){
//alert('Fail');
		if(xhr){
			//alert('Failure-cmeExecJSON-\nready state: '+xhr.readState+'\nstatus: '+xhr.status+'\nresponse text: '+xhr.responseText);
		}
		else{
			//alert('Failure-cmeExecJSON- ... ');
		}
	},
	onException:function(headerName, value){
//alert('Exception');
		//alert('Exception-cmeExecJSON-\n'+headerName+'\n'+value);
	}

	}).request();
} 

function cmeAJAX(restful,elementID,preAjaxMethod,postAjaxMethod){ 

	if ( preAjaxMethod != null ){
		preAjaxMethod(elementID);
	}
	try{
		new Ajax(restful,{method: 'get', 
			onSuccess: function(html){
				$j('#'+elementID).html(html).ready(function(){
					if ( typeof postAjaxMethod != 'undefined' && postAjaxMethod != null ){
						postAjaxMethod();
					}
				});
			},
			onFailure:function(xhr){
				//alert('Failure-cmeAJAX-\n'+xhr+'\nPlease Refresh the page.');
			},
			onException:function(headerName, value){
				//alert('Exception-cmeAJAX-\n'+headerName+'\n'+value);
			}
		}).request();
	}
	catch(e){
		//alert('JS Error-cmeAJAX-\n'+e.description);
	}
}

//Process the response for product group like asset class
function processProdGroupResponse(tmp){//called to display widget data
	var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	if ( tmp.marketDataInfoAsStringList != null && tmp.marketDataInfoAsStringList.responseHeader.RCode >= 0 ){
		var messages 	 = tmp.marketDataInfoAsStringList.message;
		var lastesttime = new Date();
		//lastesttime.format("mm/dd/yyyy");
		lastesttime="as of " + monthNames[lastesttime.getMonth()] +" " + lastesttime.getDate()+", "+lastesttime.getFullYear();	
		for ( i = 0; i < messages.length; ++i){
			var message = messages[i];

			//Iterate over the cells for each row
			var row = document.getElementById(message.ticker);	
			if(row!=null){
				var j =2;
				if ( message.ticker.indexOf(" ") > 0 )
				j +=1;
				changeIfNeeded(row.cells[j++],message.tradePrice);
				colorTransitionWidget(row.cells[j++],message.netChange);
				$j('#'+message.ticker).find('td.colorFlicker').animate({
						fontSize: '11px'
				}, 1000, function() {
						$j(this).css({'border-top':'1px solid #ccc','background-color':'#fff'});
				});
			}
		}
		var timestampfield = document.getElementById("prgptimestamp");
		timestampfield.innerHTML = lastesttime;		
	}
}

function DropDownInfo(elementId,arrayName,fieldName,fieldNdxName){ 
	this.elementId=elementId;
	this.arrayName=arrayName;
	this.fieldName=fieldName;
	this.fieldNdxName=fieldNdxName;
} 

function CmeGetJSON(dropDownInfo){ 
	this.dropDownInfo=dropDownInfo;
}

function populateDropDown(){
	var obj = this;
	cmeExecJSON(obj.dropDownInfo.buildRESTful(),
		function(data){
		obj.populateList(data);
		if ( obj.dropDownInfo.postAjaxFuction != null )
			obj.dropDownInfo.postAjaxFuction();
	});
}
 
function populateList(tmp){
	var messages 	 = eval("tmp."+this.dropDownInfo.arrayName);

	if ( messages != null ){
		clearList(this.dropDownInfo.elementId);
		var list 		= document.getElementById(this.dropDownInfo.elementId);
		var optionItem;

		if ( messages.length != null ){
			for ( i = 0; i < messages.length ; ++i){
			var value = eval("tmp."+this.dropDownInfo.arrayName+"[i]."+this.dropDownInfo.fieldName);

			var ndx   = value;
			if ( this.dropDownInfo.fieldNdxName != null )
			ndx = eval("tmp."+this.dropDownInfo.arrayName+"[i]."+this.dropDownInfo.fieldNdxName);

			optionItem = new Option( value, ndx,  false, false);
			list.options[list.length] = optionItem;
			}
		}
		else{
			var value = eval("tmp."+this.dropDownInfo.arrayName+"."+this.dropDownInfo.fieldName);
			var ndx   = value;
			if ( this.dropDownInfo.fieldNdxName != null )
			ndx = eval("tmp."+this.dropDownInfo.arrayName+"."+this.dropDownInfo.fieldNdxName);
			optionItem = new Option( value, ndx,  false, false);
			list.options[list.length] = optionItem;
		}
	}
}  

CmeGetJSON.prototype.populateDropDown=populateDropDown;
CmeGetJSON.prototype.populateList=populateList; 

var cachedDropDown = new Object(); 
function createDropDown(id){
	var myDropDown = cachedDropDown[id];

	if (   myDropDown == null ){
		var dropDownURL = "/CmeWS/da/DropDownInfo/V1/DropDown/"+id;

		cmeExecJSON(dropDownURL,function(dropDownFromServer){
			var dropDown = new DropDownInfo(dropDownFromServer.dropDownInfo.elementId,
			dropDownFromServer.dropDownInfo.arrayName,
			dropDownFromServer.dropDownInfo.valueField,
			dropDownFromServer.dropDownInfo.ndxField);
			dropDown.buildRESTful = eval(dropDownFromServer.dropDownInfo.buildUrlFuction);
			if ( dropDownFromServer.dropDownInfo.postAjaxFuction != null )
			dropDown.postAjaxFuction = eval(dropDownFromServer.dropDownInfo.postAjaxFuction);
			myDropDown = new CmeGetJSON(dropDown);

			myDropDown.populateDropDown();
			cachedDropDown[id] = myDropDown;
		});
	}
	else{
		myDropDown.populateDropDown();
	}

	return;
}

function cmeLoading(id){
	ajaxLoader = new Element('img', {'src':'/images/ajax-loader.gif'}).injectTop($(id));
}

function addDOMLoadEvent(event){
	//DOMReady.onDOMReadyHandler = event;
	//DOMReady.listenDOMReady();
	/*
	This function should be removed after recoding datafeed.do file.
	*/
} 

//=========================================================================================================================
// non-american style options Functions
//=========================================================================================================================
//==================================================================
// Functions to execute when pages is fully loaded in browser
//==================================================================
//window.onload = function(){
$j(document).ready(function(){
	DoBlockElement();

	var EWR12 = new ExecuteWhenReady({
		Execute : function(){
			if(!location.pathname.match(/_futures.html/gi)){
				processURLonload();//will populate dropdown
			} 
		},
		When : function(){
			return $j('#productTypeSelect').length > 0;
		},
		onfailure: function(){

		},
		CheckEvery : 500,	
		NumofAttempts : 14	
	}); 
	CheckURLhash();
	if(location.pathname.match(/_options.html/gi) && location.pathname.match(/_quotes_/gi)){
		OptionQuotePageFix();
	}
});
//==================================================================

//==================================================================
// -populate non-american type dropdown
// -set logic to be executed when dropdown selection change
//==================================================================
function processURLonload(){
	PopulateDropDownbyAjax();
}

function ProductTypeOnChange(){//This function is called in other pages "Time&Sales, Settlements, Contract Specs, Product Calendar".	
	//var val = $j('#productTypeSelect').val();
	//populateqouteTable(val);
}

function SetonChange(){
	var val = $j('#productTypeSelect').val();
	$j('a.dynaLink_Href').each(function(){	
		UpdateLinkHref(this,"prodType",val);
	});	
	UpdateURLHash("prodType",val);
}


function HideTypeOnFutureSettelmentPage(){
	var path = location.pathname;
	var res = 'not_future_settlemtn_page';
	if(path.match(/_settlements_futures.html/gi)){
		$j('#destroy_on_future_settelemt_page').remove();
		res = 'it_is_future_settlemtn_page';
	}
	return res;
}

//populate the Option Type Dropdown
function PopulateDropDownbyAjax(){
	var p = Global.cme.productCd;//values from open cms
	var f = Global.cme.f;
		//When page is OPTION: 
		//Global.cme.f = OPT   -> ProductType service call to populate dropdown is expecting this value
		//Global.cme.foi = OOF -> most of the other service calls expecting this value
	var e = Global.cme.exchangeCd;//values from open cms
	var v = Global.cme.venue;//values from open cms
	
	var xmlpath = '/da/Products/V1/ProductMap/'+f+'/Venue/'+v+'/Exchange/'+e+'/Product/'+p;
	var xsltpath = '/XSLT/md/nonAmericanDropDown.xsl';

	if(typeof Global.PageName !== 'undefined' && f === 'OPT'){
		var SpecialProducts = new RegExp('CL|BZ|HO|BH|RB|NG|QLD','gi');
		if(Global.cme.productCd.match(SpecialProducts) && (Global.PageName === 'ContractSpecsPage' || Global.PageName === 'Settlement' || Global.PageName === 'ProductCalendar')){
			xmlpath = '/da/Products/V1/ProductMap/ALL/'+f+'/Venue/'+v+'/Exchange/'+e+'/Product/'+p;
		}
	}

	var uri = '/CmeWS/mvc/xsltTransformer.do?xlstDoc='+xsltpath+'&url='+xmlpath;

	$j.ajax({
		url: uri,
		type:'get',
		date: 'html',
		success: function(html){
			var def = null;
			var NewCPCOptionTypes = GetNewCPCOptionTypes();
			
			//Add opencms over rides
			if(NewCPCOptionTypes !== ''){
				if(jQuery.trim(html) !== ''){//append to end ajax results
					var regexpe = new RegExp('</select>','gmi');
					html = html.replace(regexpe,NewCPCOptionTypes+'</select>');
				}
				else{//add to ajax results
					html = NewCPCOptionTypes;
				}
			}

			//find value to use as selected value
			def = guphash('prodType') !== null ? guphash('prodType') : Global.cme.defaultType;

			//if def is a valid value set it as the selected option in the dro down
			if(def !== null){
				var regexpe = new RegExp('value="'+def+'"','gmi');
				html = html.replace(regexpe,'selected="selected" value="'+def+'"');
			}
			
			//insert product type options in to the span
			$j('#productTypeSpan').html( html );
			//FIX_xcme_xcbt_TypeDropDown();
		},
		error: function(){
			//$j('div.error').remove();
			//$j('#loaderholder').before('<div style="padding-top:20px;" class="error">This page is currently experiencing technical difficulties. To report this problem, please contact us via the feedback link.<div style="display:none;">Failed:PopulateDropDownbyAjax in CmeUtil.js</div></div>');
			var params = {
				"id":"loaderholder",
				"functionName":"PopulateDropDownbyAjax()",
				"fileName":"cmeUtil.js"
			}
			GlobalErrorMsg(params);
		}		
	});
}

function FIX_xcme_xcbt_TypeDropDown(){
	if( (location.pathname.match(/_contract_specifications.html/gi) && Global.cme.f === "OPT") || (location.pathname.match(/_contractSpecs_options.html/gi) && Global.cme.f === "OPT") ){
		return;
	}
	else{
		var exc = Global.cme.exchangeCd;
		if(exc.match(/XCBT/gi) || exc.match(/XCME/gi)){
			removenonAmerican();
		}
	}
}

function removenonAmerican(){
	var def = Global.cme.defaultType;
	var dd = document.getElementById("productTypeSelect");
	var start = 0;
	var end = dd.length;
	while(start !== end){
		if(dd.options[start].value !== def){
			dd.remove(start);
			removenonAmerican();
		}
		else{
			start++;
		}
	}	
}

function GetNewCPCOptionTypes(){
	var result = '';
	if(typeof Global.cme.addedTypesId !== 'undefined'){
		result = $j('#'+Global.cme.addedTypesId).html();
	}
	return result;
}
//==================================================================

//==================================================================
//
//==================================================================
function ContractSpecsHTML(html){
	if(html === null){
		$j('#cspecOverride').html('<div id="cspecOverride"><table class="ProductTable"><tbody><tr><td style="vertical-align: top;" class="LeftFutureDiv"><table class="ProductTableSmall"><tbody><tr><td style="width: 82px;" class="font_red">Contract Specifications N/A.</td></tr></tbody></table></td><td class="RightFutureDiv"></td></tr></tbody></table></div>');
		setTimeout("PopulateRightNav()",500);
	}
	else{
		$j('#cspecOverride').html(html);
		setTimeout("PopulateRightNav()",500);
	}
}
//==================================================================
//==================================================================
// -When page loads do the following:
//  if -> "Globex Options | Open Outcry Options" links on page
//     -FIRST : Update all links on page to have expMonth value
//     -SECOND: Add the hash key and value to all links
//  ELSE
//     -Add the hash key and value to all links
//==================================================================
function CheckURLhash(){
	if(guphash('prodType') !== null){//check if hash param prodType is in url
		if($j('#optionsLink').length > 0){//optionLink which is "Globex Options | Open Outcry Options" links will wait for expMonth to be added to it
			var EWR12 = new ExecuteWhenReady({
				Execute : function(){	
					$j('a.dynaLink_Href').each(function(){	
						UpdateLinkHref(this,"prodType",guphash('prodType'));
					});						
				},
				When : function(){
					//expMonth - special case for link with id optionLink - waits for expMonth value to be added to link first then add hash
					return $j('#optionsLink').attr('href').match('expMonth='+gup('expMonth'));
				},
				onfailure: function(){
					
				},
				CheckEvery : 1000,	
				NumofAttempts : 5	
			}); 
		}
		else{//then we do not have to wait for expmonth to be added to element with id optionLink
			$j('a.dynaLink_Href').each(function(){	
				UpdateLinkHref(this,"prodType",guphash('prodType'));
			});				
		}
	}
}
//==================================================================

//==================================================================
// will change the href attribute in a url
//==================================================================
function UpdateLinkHref(thsi,key,val){
	var href = $j(thsi).attr('href');
	var toLookfor = new RegExp("prodType=","gi");
	$j(thsi).attr('href',ClearHrefHash(href)+'#prodType='+val);
}
//==================================================================

//==================================================================
// will strip the hash value from a link, and return the original url without the hash value
//==================================================================
function ClearHrefHash(href){
	var toLookfor = new RegExp("#(.)*$","gi");
	href = href.replace(toLookfor,'');
	return href;
}
//==================================================================

//==================================================================
// will change the hash value in the browser url address bar #key=val
//==================================================================
function UpdateURLHash(key,val){
	var urlhash = location.hash;
	var hashregexp = new RegExp(key+"="+guphash(key),"gi");
	urlhash = urlhash.replace("#","");
	
	if(urlhash.match(hashregexp)){
		urlhash = urlhash.replace(hashregexp,key+"="+val);
		location.hash = urlhash;
	}
	else{
		var divider = location.hash === '' ? '' : '&';
		location.hash = urlhash +divider+ key+'='+val;
	}
}
//==================================================================

//==================================================================
// cache right-nav in Global.RightNavHTML - ONLY for option page
//==================================================================
function PopulateRightNav(){
	if($j('#RightFutureDiv_ID').length > 0 && typeof Global.RightNavHTML !== 'undefined')
		$j('#RightFutureDiv_ID').html(Global.RightNavHTML);
}
//==================================================================


//=========================================================================================================================
// Util Functions
//=========================================================================================================================
//==================================================================
// Used for debuging javascript objects
//==================================================================
function alertObj(obj){
	var name;
	var res = "";
	for(name in obj) {
		if (typeof obj[name] !== 'function') {
       		res += name + ': ' + obj[name] + '\n';
		}
	}
	alert(res);
}
//==================================================================

//==================================================================
// INPUT -> url hash key name , OUTPUT -> url hash key value
//==================================================================
function gup(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}
//#sortKey=7&sortOrder=descending&SortType=number&FilterOn=1&PageStart=1
function guphash(param){
	var result = null;
	var URLhash = location.hash;
	URLhash = URLhash.replace("#",'');
	hashsp = [];
	hashsp = URLhash.split('&');//[sortKey=7,sortOrder=descending,SortType=number,FilterOn=1,PageStart=1]
	var spl = hashsp.length;
	var hashtemp = [];
	for(var i=0;i<spl;i++){
		hashtemp[0] = null;
		hashtemp[1] = null;
		h = hashsp[i];
		hashtemp = h.split('=');
		//hashtemp[0] = sortKey
		//hashtemp[1] = 7
		if(param === hashtemp[0]){
			result = hashtemp[1];
			break;
		}
	}
	return result;
}

function gupLink(name,str){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\#&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( str );
	if( results == null )
		return "";
	else
		return results[1];
}

function gupString(name,str){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( str );
  if( results == null )
    return "";
  else
    return results[1];
}
//==================================================================

//==================================================================
// Used to Execute a function when a condition is valid
// Example:
//
// var EWR1 = new ExecuteWhenReady({
//	Execute : function(){	
//		TO BE EXECUTED
//	},
//	When : function(){
//		return CONDITION !== null;
//	},
//  onfailure: function(){
//      onfailure is OPTIONAL
//  },
//	CheckEvery : 1000,	Time interval to check for condition
//	NumofAttempts : 3	Number of times to do the checking
// });
//
//==================================================================
var ExecuteWhenReady = function(vars) {
	var f = vars.Execute;
	var fail = vars.onfailure || null;
	var cond = vars.When;
	var delay = vars.CheckEvery || 500;
	var limit = vars.NumofAttempts || 30;
	var init = 0;
	var t = null;
	var obj = this; 
	
	var loop = function(){
		var c = cond();
		if(init === limit || c){
			if(c){
				f();
			}
			else if(fail !== null){
				fail();
			} 
			clearTimeout(t);
			obj = null;
		}
		else{
			init++;
			loopd();
		}
	}
	var loopd = function(){
		t = setTimeout(loop, delay);
	}
	loopd();
}
//==================================================================

//==================================================================
//
//==================================================================
function GetEBI(id){
	return document.getElementById(id);
}
//==================================================================

//==================================================================
// Block element by 'add' a transaprent element on top or 'remove' the blocking element
//==================================================================
function BlockElement(elmid,how){
	if($j('#'+elmid).length > 0){
		var elm = $j('#'+elmid);
		var id = $j('#'+elmid+'_white');
		if(how == 'add'){
			if(id.length > 0){
				var h = elm.height() + 7;
				var w = elm.width();
				id.height(h+'px');
				id.width(w+'px');
				id.css('display','block');
			}
			else{
				var h = elm.height() + 7;
				var w = elm.width();
				var t = elm.position().top;
				//var l = elm.position().left; this why not to use jquery for everything
				var telm = document.getElementById(elmid); 
				var l = getAbsX(telm);
				var himg = (h/2)-15;
				var html = '<div id="'+elmid+'_white" style="opacity: .8;filter: alpha(opacity=80);background:#ffffff;display:block;position:absolute;z-index:199;height:'+h+'px;width:'+w+'px;top:'+t+'px;left:'+l+'px;"><div style="padding-top:'+himg+'px;font:bold 14px arial;white-space:nowrap;">Processing..<img style="vertical-align:middle;" src="/images/ajax-loader.gif"/></div></div>';
				elm.before(html);				
			}
		}
		if(how == 'remove'){
			if(id.length > 0){
				id.css('display','none');
			}
		}
	}
}

function getAbsX(elt) { return (elt.x) ? elt.x : getAbsPos(elt, 'offsetLeft'); }
function getAbsY(elt) { return (elt.y) ? elt.y : getAbsPos(elt, 'offsetTop'); }
function getAbsPos(elt, which) {
	var iPos = 0;
	while (elt != null) {
	iPos += elt[which];
	elt = elt.offsetParent;
	}
	return iPos;
} 
//==================================================================

//==================================================================
// creates a <select [style,class,js event function,id,formate_function]>
//==================================================================
function CreateDropDownFromXml(vars){
	var xmlobj = vars.xmlobj;
	var nodename = vars.nodename;
	var elm_style = vars.cssstyle || '';	//example: 'style="width:200px;"'
	var elm_class = vars.elmclass || '';	//example: 'class="classname"'
	var elm_js = vars.elmjsEvent || '';	//example: 'onchange="processevent()"'
	var elm_id = vars.elm_id || '';		//example: 'id="elmid"'
	var do_formate = vars.formate || null;	//example: 'formate_TradeDate($j(this).text())'
	var option_value = vars.optionValue || '$j(this).text()';
	var option_descr = vars.optionDescr || '$j(this).text()';
	var option_rel = vars.rel_vars || '';

	var t = '<select '+ elm_id + elm_style + elm_class + elm_js +'>';
	if($j(xmlobj).find(nodename).length > 0){
		$j(xmlobj).find(nodename).each(function(){
			var rd = eval(option_value);
			var fd = do_formate !== null ? eval(do_formate) : eval(option_descr);
			var clearingCode = '';
			var floorCode = '';
			var exchange = ''; 

			if(option_rel === 'SaveAsArray'){
				clearingCode = $j(this).find("clearingCode").text() !== '' ? 'clearingCode='+$j(this).find("clearingCode").text()+'&' : '';
				clearingCode = '?' + clearingCode;
				floorCode = $j(this).find("floorCode").text() !== '' ? 'floorCode='+$j(this).find("floorCode").text()+'&' : '';
				exchange = $j(this).find("exchange").text() !== '' ? 'exchange='+$j(this).find("exchange").text() : '';
			}
			else{
				clearingCode = eval(option_rel);
			}
			t += '<option value="'+rd+'" rel="'+ clearingCode+floorCode+exchange +'">'+fd+'</option>';
		});
	}
	else{
		//t +='<option value="" class="xml node not found">Select...</option>';
	}
	t += '</select>';
	return t;
}
//==================================================================

//==================================================================
//
//==================================================================
function Ajaxslt(vars){
	var uri = vars.url;
	var id = vars.elementId;
	var alrt = vars.alert;
	$j.ajax({
		url: uri,
		type:'get',
		date: 'html',
		success: function(html){
			if(typeof alrt !== 'undefined')
				alert(html);
			$j('#'+id).html( html );
		},
		error: function(){
			//$j('#container').html('<div style="padding-top:20px;" class="error">This page is currently experiencing technical difficulties. To report this problem, please contact us via the feedback link.</div>');
			var params = {
				"id":"container",
				"functionName":"Ajaxslt()",
				"fileName":"cmeUtil.js"
			}
			GlobalErrorMsg(params);
		}		
	});
}
//==================================================================

//==================================================================
//This page is currently experiencing technical difficulties. It should be available shortly.
//==================================================================
function isArray(my_value){
	return (my_value && typeof my_value === 'object' && my_value.constructor === Array) ? true : false;
}
//==================================================================

//==================================================================
//This function is used for printing rules in Rulebook.
//==================================================================
function printPage(){
	window.print();
}
//==================================================================

//==================================================================
//
//==================================================================
function DoBlockElement(){
	if($j('#futureunderlier').length === 0){return;}
	var EWR12 = new ExecuteWhenReady({
		Execute : function(){
			BlockElement('table_under_bluebar','remove');
		},
		When : function(){
			return ( $j('#productTypeSelect').length > 0 && $j('#dstradedate').find('option').length > 1 && $j('#dscontractmon').find('option').length > 1 );
		},
		onfailure: function(){
			BlockElement('table_under_bluebar','remove');
		},
		CheckEvery : 500,	
		NumofAttempts : 5	
	}); 

	$j('#table_under_bluebar').css({"visibility":"visible"});
	BlockElement('table_under_bluebar','add');
	
	//added to fix the position of the processing block in the option vew BY Mike Amara 02/19/2010
	var EWR12 = new ExecuteWhenReady({
		Execute : function(){
			var cssObj = {
			  'top' : Number($j('#table_under_bluebar').position().top + 5)+'px',
			  'left' : $j('#table_under_bluebar').position().left+'px',
			  'width' : $j('#table_under_bluebar').width()+'px',
			  'height' : $j('#table_under_bluebar').height()+'px',
			  'padding' : '0px',
			  'margin' : '0px'
			};
			$j('#table_under_bluebar_white').css(cssObj);
		},
		When : function(){
			return ( $j('#futureunderlier').length > 0 && jQuery.trim($j('#futureunderlier').html()) !== '');
		},
		onfailure: function(){
			var cssObj = {
			  'top' : Number($j('#table_under_bluebar').position().top + 5)+'px',
			  'left' : $j('#table_under_bluebar').position().left+'px',
			  'width' : $j('#table_under_bluebar').width()+'px',
			  'height' : $j('#table_under_bluebar').height()+'px',
			  'padding' : '0px',
			  'margin' : '0px'
			};
			$j('#table_under_bluebar_white').css(cssObj);
		},
		CheckEvery : 100,	
		NumofAttempts : 15	
	}); 	
}
//==================================================================

//==================================================================
//
//==================================================================
function OptionQuotePageFix(){
	var e = Global.cme.exchangeCd;
	var f = Global.cme.f;
	var v = Global.cme.venue;
//	var pcd = Global.cme.
//	var ucd = Global.cme.
//	var fcd = Global.cme.
//	var exp = Global.cme.
//	var qa = exchange='+e+'&foi='+f+'&venue='+v+'&productCd='+pcd+'&underlyingContract='+ucd+'&floorContractCd='+fcd+'&expMonth='+exp;

	$j('body').append('<span id="XXX" style="display:none;">'+$j('#optionsLink').attr('href')+'</span>');
}
//==================================================================

//==================================================================
//
//==================================================================
function GlobalErrorMsg(vars){
	var id = vars.id;
	var functionName = vars.functionName || '';
	var fileName = vars.fileName || '';
	var msg = '<div class="newerrormsg"><br/><div class="ProductIden">No Data Available, due to one of the following reasons:</div><br/><div><b>The market for this product is not open.</b></div><div><ul><li>Refer to our trading hours for an official list of times that this product trades, or</li></ul></div><br/><div><b>The market is open, but no trades have occurred for this session.</b></div><div><ul><li>Certain illiquid products do not trade immediately at the open. Delayed quotes will be available once trades have occurred, or</li></ul></div><br/><div><b>This is a new product that has yet not begun trading.</b></div><div><ul><li>View our latest press releases for official dates and times of product launches.</li></ul></div><br/><div>Still have questions? Please <a href="/tools-information/contacts-list.html">Contact Us</a>!</div><br/><div style="display:none;">Failed in '+fileName+'.js using '+functionName+' function.</div></div>';

	if ($j('#'+id).length === 0) return;
	ClearGlobalErrorMsg();
	$j('#'+id).html(msg);//09/22/2009 modified by James Owens to correct simultaneous display of error message and data table. Prior line $j('#'+id).before(msg);

}

function ClearGlobalErrorMsg(){
	$j('div.newerrormsg').remove();
}
//==================================================================


function absoluteOrRelativeURI(url) {//10/26/2009 Added by James Owens to handle for dropdowns with mixed urls (ie /trading/energy/index.html)

	if (url.indexOf("http:") > -1) {
		return url;
	} else {
		return 'http://' + window.location.host + url;
	}

}


/********************************************************
Format Currency util added 2010/01/05 by James Owens to fulfill SharePoint request 1726 for matching price formatting between Quotes and Settlements pages. Commented out content may help in the future.
Based on http://www.selfcontained.us/2008/04/22/format-currency-in-javascript-simplified/
*********************************************************/

function formatCurrency(num) {
	num = num.toString(); //.replace(/\$|\,/g, '');
	if (isNaN(num)) num = '0';
	//sign = (num == (num = Math.abs(num)));
	//num = Math.floor(num * 100 + 0.50000000001);
	//cents = num % 100;
	//num = Math.floor(num / 100).toString();
	//if (cents < 10) { cents = '0' + cents; }
	for (var i = 0; i < Math.floor((num.length - (1 + i))/3); i++) {
		num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
	}
	//return (((sign) ? '' : '-') + '$' + num + '.' + cents);
	return num;
}