$(document).ready(function(){
	$('#notification_alert_screen_window').dialog({autoOpen:false,width:450,height:'auto', modal: true, resizable: false, close: onDialogClose, open: onDialogOpen});	
});


function CriteriaDataToState(data) {
	var state = '';

	for (var i = 0; i< data.length; i++) {
		state += data[i].cid + ':' + data[i].op + ':' + data[i].values.join(':');
		for (var j = 0; j< data[i].refine.length; j++) {
			state += ','+ data[i].refine[j].parameter + ':' + data[i].refine[j].op + ':' + data[i].refine[j].values.join(':');
		}

		if (i != (data.length - 1)) {
			state += '|';
		}
	}

	return state;
	
}

function CriteriaDataToApi(data) {
	var api = '';

	for (var i = 0; i< data.length; i++) {
		api += '&crt=' + data[i].cid + ':' + data[i].op + ':' + data[i].values.join(':');
		for (var j = 0; j< data[i].refine.length; j++) {
			api += ','+ data[i].refine[j].parameter + ':' + data[i].refine[j].op + ':' + data[i].refine[j].values.join(':');
		}
	}

	return api;
}

function dialogAlert(html) {
	$('#notification_alert_screen_window_msg').html(html);
	$('#notification_alert_screen_window_ok_btn').unbind('click').click(function() {$('#notification_alert_screen_window').dialog('close')});
	$('#notification_alert_screen_window').dialog('open');
}

//IE fixes to remove combo boxes when dialogs is open
function onDialogOpen()  {
	if (jQuery.browser.msie) {
		var opener_id = $(this).attr('id');
		$('select').each(function() {
			if ($(this).parents('#'+opener_id).length == 0) {
				$(this).css('visibility', 'hidden');
			}
		});
	}
}
	
function onDialogClose()  {
	if (jQuery.browser.msie) {
		var opener_id = $(this).attr('id');
		$('select').each(function() {
			if ($(this).parents('#'+opener_id).length == 0) {
				$(this).css('visibility', 'visible');
			}
		});
	}
}

function ajaxFail () {
	alert(GetTranslation('GenericError'))
};

function trim(str) {
        return str.replace(/^\s+|\s+$/g,"");
}

var UrlState = new function() {

	var history_length = -1;
	var type = 'url';


	var replace = function(replace_with) {
		if (type == 'dom') {
			$('#recognia_page_state').val(replace_with);
		} else {
			location.replace(replace_with);
			if (jQuery.browser.safari) {
				history_length = history.length;
			}
		}
	}

	var getLocal = function() {
		if (type == 'dom') {
			return $('#recognia_page_state').val();
		} else {
			return location.href.toString();
		}
	}

	var getState = function() {

		if (type == 'dom') {
			return $('#recognia_page_state').val();
		} else {
			if (location.hash) {
				return location.hash;
			} else {
				var local = location.href.toString();
				local = local.split('#');
				if (typeof local[1] != 'undefined') {
					local = local.splice(1);
					local = local.join('');
					return local;
				}
			}
		}
		return;
	}

	var getMatch = function(id) {
		var regex = new RegExp(id+'\\[(.*?)\\]');
		return regex.exec(getState());
	}

	this.Get = function(id) {
		var match = getMatch(id);
		if (match && match[1]) {
			return match[1];
		}

		return false;
	}

	this.Set = function(id,val) {
		var local = getLocal();
		var match = getMatch(id);
		if (match && match[1]) {
			local = local.replace(match[0],id+'['+val+']');
		} else {
			if (!getState() && (type == 'url')) {
				local += '#';
			}
			local += id+'['+val+']';
		}

		replace(local);
	}

	this.SetStateType = function(type_in) {
		if (type_in == 'dom') {
			type = 'dom';
		} else {
			type = 'url';
		}
	}

	this.Clear = function(id) {
		var match = getMatch(id);
		if (match && match[0]) {
			var local = getLocal();
			replace(local.replace(match[0],''));
		}
	}

	this.StartHistoryPolling = function(callback) {
		if (history_length == -1) {
			history_length = history.length;
		}
		
		if (history.length != history_length) {
			history_length = history.length;
			callback();
		}

		setTimeout(function() {UrlState.StartHistoryPolling(callback)},50);
	}

}

function GetTranslation(ID) {
    return RECOGNIA_TEXT[ID];
}

function GetImageSource(ID) {
    return RECOGNIA_IMAGES[ID];
}

function LoadChartPage(EVENT_ID, QUERYSTATE, NEW_WINDOW) {
	var ChartLink = './serve.shtml?page=chart_eid&eid=' + EVENT_ID + GetProgrammingFieldValue('QueryStringParameters');
	
	// Add Query State if it exists
	if (QUERYSTATE && QUERYSTATE != '') {
		ChartLink += QUERYSTATE;
	}
	
	// Add Technical Insight state parameters if they exists
	if (window.document.event_lookup_state) {
		ChartLink += '&ti_cst=' + window.document.event_lookup_state.chart_style.value;
		ChartLink += '&ti_thz=' + window.document.event_lookup_state.trading_horizon.value;
		ChartLink += '&ti_list=' + window.document.event_lookup_state.result_list.value;
		
		// Needed for Fidelity screens
		ChartLink += '&symbol=' + window.document.event_lookup_state.symbol.value;
	}
	
	if (NEW_WINDOW == 1) {
		newWindow(ChartLink);
	} else {
		window.location = ChartLink;
	}
}

function LoadChartSupportResistance(NEW_WINDOW) {
	var ChartLink = './serve.shtml?page=chart&page_type=supportresistance' + GetProgrammingFieldValue('QueryStringParameters');
	
	// Add Technical Insight state parameters if they exists
	if (window.document.event_lookup_state) {
		ChartLink += '&ti_cst=' + window.document.event_lookup_state.chart_style.value;
		ChartLink += '&ti_thz=' + window.document.event_lookup_state.trading_horizon.value;
		ChartLink += '&ti_list=' + window.document.event_lookup_state.result_list.value;
		
		ChartLink += '&symbol=' + window.document.event_lookup_state.symbol.value;
		ChartLink += '&exchange=' + window.document.event_lookup_state.exchange.value;
		ChartLink += '&instrument_type=' + window.document.event_lookup_state.instrument_type.value;
	}
	
	if (NEW_WINDOW == 1) {
		newWindow(ChartLink);
	} else {
		window.location = ChartLink;
	}
}


function LoadChartStops(NEW_WINDOW) {
	var ChartLink = './serve.shtml?page=chart&page_type=stops' + GetProgrammingFieldValue('QueryStringParameters');
	
	// Add Technical Insight state parameters if they exists
	if (window.document.event_lookup_state) {
		ChartLink += '&ti_cst=' + window.document.event_lookup_state.chart_style.value;
		ChartLink += '&ti_thz=' + window.document.event_lookup_state.trading_horizon.value;
		ChartLink += '&ti_list=' + window.document.event_lookup_state.result_list.value;
		
		ChartLink += '&symbol=' + window.document.event_lookup_state.symbol.value;
		ChartLink += '&exchange=' + window.document.event_lookup_state.exchange.value;
		ChartLink += '&instrument_type=' + window.document.event_lookup_state.instrument_type.value;
	}
	
	if (NEW_WINDOW == 1) {
		newWindow(ChartLink);
	} else {
		window.location = ChartLink;
	}
}


function HidePrintOptions() {
	if (document.getElementById('RecogniaPrintSection')) {
		document.getElementById('RecogniaPrintSection').style.display = "none";
	}
}

function HideSaveRestoreOptions() {
	if (document.getElementById('RecogniaSaveSettingsSection')) {
		document.getElementById('RecogniaSaveSettingsSection').style.display = "none";
	}
}

function ShowPrintOptions() {
	if (document.getElementById('RecogniaPrintSection')) {
		document.getElementById('RecogniaPrintSection').style.display = "inline";
	}
}

function ShowSaveRestoreOptions() {
	if (document.getElementById('RecogniaSaveSettingsSection')) {
		document.getElementById('RecogniaSaveSettingsSection').style.display = "";
	}
}

// javascript version of 'GetPreferenceValue' method in HostedWebsites::WebUser
function getPreferenceValues(TYPE, NAME) {
  return new AjaxRequest({async:false}).comp('/components/ajax_user_preferences.mason:GetPreferenceValue',
				      {params: {preference_type: TYPE, preference_name: NAME}});
	
}

// javascript version of 'SetPreferenceValues' method in HostedWebsites::WebUser
function setPreferenceValues(TYPE, DATA) {
	var Querystring = '';
	for (var i in DATA) {
		Querystring += '&' + i + '=' + DATA[i];
	}
	
	var Error = new AjaxRequest({async:false}).comp('/components/ajax_user_preferences.mason:SetPreferenceValues',{params: {preference_type : TYPE + Querystring}});
	
	if (Error == 0) {
		alert(GetTranslation('SettingsSaved'));
	} else {
		alert(GetTranslation('SettingsSavedFailed'));
	}
}

// javascript version of deprecated 'GetPersistentSessionValue' method in HostedWebsites::WebUser
function getPersistentSessionValue(NAME) {
	var cookie_name = 'P' + GetProgrammingFieldValue('SessionId');
	var cookie_value = getCookie(cookie_name);

	if (cookie_value != null) {
		var values = cookie_value.split('|');

		for (i in values) {
			if (values[i].indexOf(NAME + '=') != -1) {
				var index = values[i].indexOf('=');
				return values[i].substring(index + 1);
			}
		}
	}

	return null;
}

// javascript version of deprecated 'SetPersistentSessionValue' method in HostedWebsites::WebUser
function setPersistentSessionValue(NAME, VALUE) {
	var cookie_name = 'P' + GetProgrammingFieldValue('SessionId');
	var cookie_value = getCookie(cookie_name);
	var expire_date = 'Wed, 01-Jan-2020 05:00:00 GMT';
	    
	var date = new Date(); 
	var year = date.getFullYear();
	var month = ((date.getMonth() + 1) < 10) ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
	var date = ((date.getDate()) < 10) ? '0' + (date.getDate()) : (date.getDate());
	var dateCreated =  year + '-' + month + '-' + date;
	
	if (cookie_value == null) {
		setCookie(cookie_name, 'DateCreated=' + dateCreated + '|' + NAME + '=' + VALUE, expire_date);    
	
	} else if (cookie_value.indexOf(NAME + '=') == -1) {
		setCookie(cookie_name, cookie_value + '|' + NAME + '=' + VALUE, expire_date);
	
	} else {
		var values = cookie_value.split('|');
		
		for (index = 0; index < values.length; index++) {
			if (values[index].indexOf(NAME + '=') != -1) {
				values[index] = NAME + '=' + VALUE;
			}	
		}
		
		setCookie(cookie_name, values.join('|'), expire_date);
	}
}

// save cookie
function setCookie(COOKIE_NAME, COOKIE_VALUE, EXPIRES) {
	var cookie = COOKIE_NAME + "=" + escape(COOKIE_VALUE) + ((EXPIRES) ? "; expires=" + EXPIRES : "");
	document.cookie = cookie;
}

// get cookie
function getCookie(COOKIE_NAME) {
	var dc = document.cookie;
	var prefix = COOKIE_NAME + "=";
	var begin = dc.indexOf("; " + prefix);
	
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
	
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	
	return unescape(dc.substring(begin + prefix.length, end));
}

//opens a new window to print
function printPage(URL) {
	
	var url = window.location.toString();
	if (URL && URL.toString() != '')
		url = URL.toString();
	
	//remove the anchor in the URL if there is one
	var start = url.indexOf('#');
	if (start > -1) {
		end = url.lastIndexOf('&');
		
		if (end > start)
			url = url.substring(0, start) + url.substring(end);
		else
			url = url.substring(0, start);
	}
	
	window.open(url + '&output=print','','toolbar=no,scrollbars=yes,resizable=yes,menubar=no,status=no,directories=no,location=no,top=200,left=200,width=640,height=400');
}

//creates a pdf
function pdfPage(URL) {
	
	var url = window.location.toString();
	if (URL && URL.toString() != '')
		url = URL.toString();
	
	//remove the anchor in the URL if there is one
	var start = url.indexOf('#');
	if (start > -1) {
		end = url.lastIndexOf('&');
		
		if (end > start)
			url = url.substring(0, start) + url.substring(end);
		else
			url = url.substring(0, start);
	}
	
	//change serve.shtml to pdf.shtml
	start = url.indexOf('serve.shtml');
	end = url.indexOf('?');
	url = url.substring(0, start) + 'pdf.shtml' + url.substring(end);
	
	window.location = url + '&output=pdf';
}

//creates a pdf and email it to the user
function emailPage(URL) {
	
	var url = window.location.toString();
	if (URL && URL.toString() != '')
		url = URL.toString();
	
	//remove the anchor in the URL if there is one
	var start = url.indexOf('#');
	if (start > -1) {
		end = url.lastIndexOf('&');
		
		if (end > start)
			url = url.substring(0, start) + url.substring(end);
		else
			url = url.substring(0, start);
	}
	
	//change serve.shtml to email.shtml
	start = url.indexOf('serve.shtml');
	end = url.indexOf('?');
	url = url.substring(0, start) + 'email.shtml' + url.substring(end);
	
	window.open(url + '&email=1','','toolbar=no,scrollbars=yes,resizable=yes,menubar=no,status=no,directories=no,location=no,top=100,left=200,width=500,height=600');
}

//opens a new window
function newWindow(URL, TOOLBAR, WIDTH, HEIGHT, TARGET) {
	
	var toolbar = (TOOLBAR) ? 'yes' : 'no';
	var width = (WIDTH) ? WIDTH : '640';
	var height = (HEIGHT) ? HEIGHT : '400';
	var target = (TARGET) ? TARGET : '';
		
	window.open(URL, target, 'toolbar=' + toolbar + ',scrollbars=yes,resizable=yes,menubar=no,status=no,directories=no,location=no,top=200,left=200,width=' + width + ',height=' + height);
}

//changes the page content using DHTML
function ChangePage(PAGE_NUMBER, LAST_PAGE_NUMBER) {
	
	for (index = 1; index <= LAST_PAGE_NUMBER; index++) {
		document.getElementById('Page' + index).style.display = 'none';
		document.getElementById('TopPageLink' + index).className = 'RecogniaNormalText';	
		document.getElementById('BottomPageLink' + index).className = 'RecogniaNormalText';	
	}
	document.getElementById('Page' + PAGE_NUMBER).style.display = 'inline';
	document.getElementById('TopPageLink' + PAGE_NUMBER).className = 'RecogniaFeaturedText';
	document.getElementById('BottomPageLink' + PAGE_NUMBER).className = 'RecogniaFeaturedText';
}

// changes the result list using DHTML
// SELECTED=standard|detailed|chart
function ChangeResultList(SELECTED, LIST) {
	
	if (document.getElementById(SELECTED + '_list_button')) {
		document.getElementById('standard_list_button').className = 'RecogniaResultsListUnselected';	
		document.getElementById('detailed_list_button').className = 'RecogniaResultsListUnselected';	
		document.getElementById('chart_list_button').className = 'RecogniaResultsListUnselected';	

		document.getElementById(SELECTED + '_list_button').className = 'RecogniaResultsListSelected';	
	}
	
	RecogniaResults(LIST, SELECTED);
}

// changes the result list using DHTML
// SELECTED=standard|detailed|chart
function ChangePrebuiltResultList(SELECTED, LIST) {
	
	if (document.getElementById(SELECTED + '_' + LIST)) {
		document.getElementById('standard_' + LIST).style.display = 'none';
		document.getElementById('standard_' + LIST + '_button').className = 'RecogniaResultsListUnselected';	
		document.getElementById('detailed_' + LIST).style.display = 'none';
		document.getElementById('detailed_' + LIST + '_button').className = 'RecogniaResultsListUnselected';	
		document.getElementById('chart_' + LIST).style.display = 'none';
		document.getElementById('chart_' + LIST + '_button').className = 'RecogniaResultsListUnselected';	
			
		document.getElementById(SELECTED + '_' + LIST).style.display = 'inline';
		document.getElementById(SELECTED + '_' + LIST + '_button').className = 'RecogniaResultsListSelected';	
	}
}

function isSymbolFieldBlank(FIELD, MESSAGE) {
	if (FIELD.value != '') {   
		document.MM_returnValue = true;
	} else {
		AlertAboutFormErrors(MESSAGE);
		document.MM_returnValue = false;
	}
}

//get checked value of a radio button group
function GetRadioValue(RADIO) {
	for (var index=0; index < RADIO.length; index++) {
		if (RADIO[index].checked) {
			return RADIO[index].value;
		}
	}
}

//return the value of a field that might be a select, but might also be hidden
function GetValue(ELEMENT) {
	if (ELEMENT.options) {
		return ELEMENT.options[ELEMENT.options.selectedIndex].value;
	} else {
		return ELEMENT.value;
	}
}

/*
 * Append a clone of cloneId element to parentId, removing the id.
 *
 * [in] parentId - id of the parent element
 * [in] childId  - id of the element to clone and add.
 */
function appendClone(parentId, childId) {
	var parentNode = document.getElementById(parentId);
	var childNodes = parentNode.childNodes;
	
	var uniqueId = 0;
	var found = false;
	
	while (!found) {
		uniqueId++;
		found = true;
		
		for (i=0; i < childNodes.length; i++)
		{
			if (childNodes[i].id == childId + uniqueId) {
				found = false;
			}
		}
	}
	
	var childNode = document.getElementById(childId).cloneNode(true);
	childNode.id = childId + uniqueId;

	parentNode.appendChild(childNode);
}

/*
 * Remove element from ancestor levels higher up the DOM.
 *
 * [in] startNode - node at which to start
 * [in] levels    - number of levels up tree to remove
 */
function removeElement(startNode, levels) {
	var node = startNode;
	
	for (i = 0; i < levels; i++) {
		node = node.parentNode;
	}

	node.parentNode.removeChild(node);
}


//change the css class for an object on a page with id=ID
function ChangeClass(ID,CLASS) { 
	if (document.layers) {
		document.layers[ID].className = CLASS; 
	} else if (document.all) {
		window.document.all[ID].className = CLASS; 
	} else {
		document.getElementById(ID).className = CLASS;
	}
}

// Check that the values entered in LOW and HIGH are numbers, and that LOW is less than HIGH.
function CheckEnteredFloatRange (LOW, LOW_NAME, HIGH, HIGH_NAME, ALLOW_NEGATIVE_VALUES) {
	var errors = '';
	if ((LOW.value != '') && (!isFloat(LOW.value, ALLOW_NEGATIVE_VALUES))) {
		errors += '- ' + LOW_NAME + " " + GetTranslation('MustBeNumber') + "\n";
	}
	if ((HIGH.value != '') && (!isFloat(HIGH.value, ALLOW_NEGATIVE_VALUES))) {
		errors += '- ' + HIGH_NAME + " " + GetTranslation('MustBeNumber') + "\n";
	}
	if (errors == '') {
		var low = parseFloat(LOW.value);
		var high = parseFloat(HIGH.value);
		if (low > high) {
			errors += '- ' + LOW_NAME + " " + GetTranslation('MustBeLess') + " " + HIGH_NAME + '.\n';
		}
	}
	return errors;
}

// Check that the values entered in LOW and HIGH are numbers in
// the range [MINIMUM, MAXIMUM], and that LOW is less than HIGH.
function CheckEnteredFloatRangeInRange (LOW, LOW_NAME, HIGH, HIGH_NAME, MINIMUM, MAXIMUM) {
	var errors = '';
	if ((LOW.value != '') && (!isFloatInRange(LOW.value, MINIMUM, MAXIMUM, true))) {
		errors += '- ' + LOW_NAME + " " + GetTranslation('MustBeNumberBetween') + " " + MINIMUM + " " + GetTranslation('And') + " " + MAXIMUM + '.\n';
	}
	if ((HIGH.value != '') && (!isFloatInRange(HIGH.value, MINIMUM, MAXIMUM, true))) {
		errors += '- ' + HIGH_NAME + " " + GetTranslation('MustBeNumberBetween') + " " + MINIMUM + " " + GetTranslation('And') + " " + MAXIMUM + '.\n';
	}
	if (errors == '') {
		var low = parseFloat(LOW.value);
		var high = parseFloat(HIGH.value);
		if (low > high) {
			errors += '- ' + LOW_NAME + " " + GetTranslation('MustBeLess') + " " + HIGH_NAME + '.\n';
		}
	}
	return errors;
}

// Check that the values entered in LOW and HIGH are integers in
// the range [MINIMUM, MAXIMUM], and that LOW is less than HIGH.
function CheckEnteredIntegerRangeInRange (LOW, LOW_NAME, HIGH, HIGH_NAME, MINIMUM, MAXIMUM) {
	var errors = '';
	if ((LOW.value != '') && (!isIntegerInRange(LOW.value, MINIMUM, MAXIMUM))) {
		errors += '- ' + LOW_NAME + " " + GetTranslation('MustBeIntBetween') + " " + MINIMUM + " " + GetTranslation('And') + " " + MAXIMUM + '.\n';
	}
	if ((HIGH.value != '') && (!isIntegerInRange(HIGH.value, MINIMUM, MAXIMUM))) {
		errors += '- ' + HIGH_NAME + " " + GetTranslation('MustBeIntBetween') + " " + MINIMUM + " " + GetTranslation('And') + " " + MAXIMUM + '.\n';
	}
	if (errors == '') {
		var low = parseFloat(LOW.value);
		var high = parseFloat(HIGH.value);
		if (low > high) {
			errors += '- ' + LOW_NAME + " " + GetTranslation('MustBeLess') + " " + HIGH_NAME + '.\n';
		}
	}
	return errors;
}

// Sample Date Format (e.g. YYYY-MM-DD)
function SampleDateFormat() {
	
	var SampleFormat = '';
	var DateLocale = GetProgrammingFieldValue('DateLocale');
	var Language = GetProgrammingFieldValue('Language');

	var Day = GetTranslation('DateFormatDay');
	var Month = GetTranslation('DateFormatMonth');
	var Year = GetTranslation('DateFormatYear');
	
	if (Language == 'fr' || DateLocale == 'europe') {
		SampleFormat = Day + '-' + Month + '-' + Year;
	} else if (DateLocale == 'us') {
		SampleFormat = Month + '-' + Day + '-' + Year;
	} else {
		SampleFormat = Year + '-' + Month + '-' + Day;
	}
	
	return "("+SampleFormat+")";
}


// Check that the date (API format) is formatted correctly
function CheckDate(TEXTBOX, NAME) {
	
	var message = '';
	var year = TEXTBOX.value.substring(0,4);
	var month = TEXTBOX.value.substring(5,7);
	var day = TEXTBOX.value.substring(8,10);
		
	if (isDigit(year) && isDigit(month) && isDigit(day) && TEXTBOX.value.length == 10 && IsValidDate(year, month, day)) {
	} else {
	  message +=  "- " + NAME + " " + GetTranslation('ValidDate') + " " + SampleDateFormat() + ".\n";
	}

	return message;
}

// Checks that the date is valid
function IsValidDate (YEAR, MONTH, DAY) {
	
	MONTH--;  
	var objTempDate = new Date(YEAR, MONTH, DAY);
	return ((objTempDate.getFullYear() == YEAR) && (objTempDate.getMonth() == MONTH) && (objTempDate.getDate() == DAY));
}

// Always in API Date format
function ValidDateSequence(EARLY_DATE, LATE_DATE) {
	
	var	dayPosition = 8;
	var	monthPosition = 5;
	var	yearPosition = 0;
	
	if (EARLY_DATE.substring(yearPosition, yearPosition+4) > LATE_DATE.substring(yearPosition, yearPosition+4)) {
		return 0;
	
	} else if (EARLY_DATE.substring(yearPosition, yearPosition+4) < LATE_DATE.substring(yearPosition, yearPosition+4)) {
		return 1;
	
	} else {
		if (EARLY_DATE.substring(monthPosition, monthPosition+2) > LATE_DATE.substring(monthPosition, monthPosition+2)) {
			return 0;
		
		} else if (EARLY_DATE.substring(monthPosition, monthPosition+2) < LATE_DATE.substring(monthPosition, monthPosition+2)) {
			return 1;
		
		} else {
			if (EARLY_DATE.substring(dayPosition, dayPosition+2) > LATE_DATE.substring(dayPosition, dayPosition+2)) 
				return 0;
		}
	}
	
	return 1;
}

function StartDateEdited(FORM) {
	DateEdited(FORM.date_range, FORM.start_date, FORM.start_date1, FORM.start_date2, FORM.start_date3)
}

function EndDateEdited(FORM) {
	DateEdited(FORM.date_range, FORM.end_date, FORM.end_date1, FORM.end_date2, FORM.end_date3)
}

// Update the Date and Date Range fields
function DateEdited(DATE_RANGE, DATE, DATE_PART1, DATE_PART2, DATE_PART3) {

	var ApiDate = '';
	var DateLocale = GetProgrammingFieldValue('DateLocale');
	var Language = GetProgrammingFieldValue('Language');
	
	removeTrailingSpaces(DATE_PART1);
	removeTrailingSpaces(DATE_PART2);
	removeTrailingSpaces(DATE_PART3);
	PadDate(DATE_PART1);
	PadDate(DATE_PART2);
	PadDate(DATE_PART3);
	
	if (Language == 'fr' || DateLocale == 'europe') {
		ApiDate = DATE_PART3.value + '-' + DATE_PART2.value + '-' + DATE_PART1.value;
	} else if (DateLocale == 'us') {
		ApiDate = DATE_PART3.value + '-' + DATE_PART1.value + '-' + DATE_PART2.value;
	} else {
		ApiDate = DATE_PART1.value + '-' + DATE_PART2.value + '-' + DATE_PART3.value;
	}
	
	DATE.value = ApiDate;
	
	if (DATE_RANGE) {
		DATE_RANGE.selectedIndex = 0;
	}
}

// Update the Date and Year/Month/Day fields using the Date Range/User Defined values.
function DateSelected(FORM) {
	if (FORM.date_range && FORM.date_range.selectedIndex != 0) {
		var Dates = FORM.date_range.options[FORM.date_range.selectedIndex].value.split(':');
		FORM.start_date.value = Dates[0];
		FORM.end_date.value = Dates[1];
	}
	
	if (FORM.start_date) {
		DateUpdate(FORM.start_date, FORM.start_date1, FORM.start_date2, FORM.start_date3)
	}
	
	if (FORM.end_date) {
		DateUpdate(FORM.end_date, FORM.end_date1, FORM.end_date2, FORM.end_date3)
	}
}

// Update the Year/Month/Day fields using the Date value
function DateUpdate(DATE, DATE_PART1, DATE_PART2, DATE_PART3) {
	
	var ApiDate = DATE.value.split('-');
	var DateLocale = GetProgrammingFieldValue('DateLocale');
	var Language = GetProgrammingFieldValue('Language');
	
	if (Language == 'fr' || DateLocale == 'europe') {
		DATE_PART1.value = ApiDate[2];
		DATE_PART1.size = 2;
		DATE_PART1.maxLength = 2;
		DATE_PART2.value = ApiDate[1];
		DATE_PART2.size = 2;
		DATE_PART2.maxLength = 2;
		DATE_PART3.value = ApiDate[0];
		DATE_PART3.size = 4;
		DATE_PART3.maxLength = 4;
		
	} else if (DateLocale == 'us') {
		DATE_PART1.value = ApiDate[1];
		DATE_PART1.size = 2;
		DATE_PART1.maxLength = 2;
		DATE_PART2.value = ApiDate[2];
		DATE_PART2.size = 2;
		DATE_PART2.maxLength = 2;
		DATE_PART3.value = ApiDate[0];
		DATE_PART3.size = 4;
		DATE_PART3.maxLength = 4;
		
	} else {
		DATE_PART1.value = ApiDate[0];
		DATE_PART1.size = 4;
		DATE_PART1.maxLength = 4;
		DATE_PART2.value = ApiDate[1];
		DATE_PART2.size = 2;
		DATE_PART2.maxLength = 2;
		DATE_PART3.value = ApiDate[2];
		DATE_PART3.size = 2;
		DATE_PART3.maxLength = 2;
	}
}

function PadDate(DATE) {
	if (DATE.value.length == 1 && isDigit(DATE.value)) {
		DATE.value = '0' + DATE.value;
	}
}

// Select the user specified consensus option
function ConsensusEdited(CONSENSUSBOX, LIST) {
	removeTrailingSpaces(CONSENSUSBOX);
	LIST.selectedIndex = 0;
}

// Update the Consensus textboxes.
function ConsensusSelected(LIST, MINBOX, MAXBOX) {
	if (LIST && LIST.selectedIndex != 0) {
		var consensus = LIST.options[LIST.selectedIndex].value.split(':');
		MINBOX.value = consensus[0];
		MAXBOX.value = consensus[1];
	}
}

// Checks that every character of STRING is an ALLOWED character.
function IsValid(STRING,ALLOWED) {
    for (var index=0; index < STRING.length; index++) {
       if (ALLOWED.indexOf(STRING.charAt(index)) == -1)
          return false;
    }
    return true;
}

// Set the form control to be enabled/disabled.
function SetEnabled(CONTROL, ENABLED) {
	if (CONTROL) {
		CONTROL.disabled = !ENABLED;
		if (!document.all && !document.getElementById) {
			CONTROL.onfocus = (ENABLED) ? "" : "if (!document.all && !document.getElementById) this.blur();";
		}
	}
}

// Encode DATA so it can safely be passed in a url.
function UrlEncode(DATA) {
	if (encodeURIComponent) {
		DATA = encodeURIComponent(DATA);
	} else {
		DATA = escape(DATA);
	}
	
	return DATA;
}

// Select the option in the list with the value, otherwise select first option
function SelectOptionValue(OPTION_VALUE, SELECT_LIST) {
	for (var count = SELECT_LIST.options.length - 1; count >= 0; count--) {
		if (SELECT_LIST.options[count].value == OPTION_VALUE) {
			SELECT_LIST.options.selectedIndex = count;
			return;
		} 
	}
}

// Select text value for select list value
function GetOptionText(OPTION_VALUE, SELECT_LIST) {
	for (var count = SELECT_LIST.options.length - 1; count >= 0; count--) {
		if (SELECT_LIST.options[count].value == OPTION_VALUE) {
		  return SELECT_LIST.options[count].text;
		} 
	}
}

// Redirect to URL provided in value of selected option
// Example: <select onchange="RedirectPage(this)">
function RedirectPage(SELECT, MESSAGE) {
	var index;
	for (index=0; index < SELECT.options.length; index++) {
		//if((SELECT.options[index].selected) && (SELECT.options[index].value != '')) {
		if (SELECT.options[index].selected) {
			if(SELECT.options[index].value!="") window.location.href=SELECT.options[index].value;
			else AlertAboutFormErrors(MESSAGE);
			break;
		}
	}
}

function InstrumentTypeChanged(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE, VOLUME_LIST, VOLUME_OPERATOR_LIST, INDUSTRY_LIST) {
	ResetExchangeList(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE);
	ResetIndustryDisabling(INSTRUMENT_TYPE, INDUSTRY_LIST);
	ResetExchangeDisabling(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE);
	ResetVolumeDisabling(INSTRUMENT_TYPE, VOLUME_LIST, VOLUME_OPERATOR_LIST);
}

function InstrumentTypeChangedWithoutVolume(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE, INDUSTRY_LIST) {
	ResetExchangeList(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE);
	ResetIndustryDisabling(INSTRUMENT_TYPE, INDUSTRY_LIST);
	ResetExchangeDisabling(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE);	
}

function ResetExchangeList(INSTRUMENT_TYPE, EXCHANGE_LIST, TYPE) {
	EXCHANGE_LIST.options.length = 0;
	
	var criteria = '[' + TYPE + ':' + INSTRUMENT_TYPE + ']';
	var options = GetProgrammingFieldValue('ExchangeOptions', criteria);

	if (options) {
		options = options.split('|');
	
		for(index = 0; index < options.length; index++) {
			var option = options[index].split('<>');
			EXCHANGE_LIST.options[index] = new Option('', option[1]);
		    	EXCHANGE_LIST.options[index].innerHTML = option[0];
		    	$(EXCHANGE_LIST.options[index]).attr('schedule',option[2]);

			if (typeof(option[3]) != 'undefined') {
				$(EXCHANGE_LIST.options[index]).attr('distribution',option[3]);
			}
		       
		}
	}
	
	if (document.getElementById('ExchangePulldown') && TYPE == 'symbol') {
		if (options.length > 1) {
			document.getElementById('ExchangePulldown').style.display = 'inline';
		} else {
			document.getElementById('ExchangePulldown').style.display = 'none';
		}
	}

    EXCHANGE_LIST.options[0].selected = true;
    $(EXCHANGE_LIST).attr('autocomplete','off');

    if (typeof(SetSchedule) != 'undefined') {
	var schedules = GetProgrammingFieldValue('Schedules').split('|');
    	SetSchedule(schedules[parseInt($(EXCHANGE_LIST.options[0]).attr('schedule'))]);
	
    }
}


function GetProgrammingFieldValue(FIELD, SEARCH_CRITERIA) {
		
    var value = RECOGNIA_PROGFIELDS[FIELD].toString();
	
	if (value) {
		// grabs the content between both search criteria strings
		// ex: [test] blah blah blah [test][test1] blah blah [test1]
		if (SEARCH_CRITERIA && value) {
			var start = value.indexOf(SEARCH_CRITERIA);
			var end = value.lastIndexOf(SEARCH_CRITERIA);
			
			if (start != -1 && end != -1)
				value = value.substring(start + SEARCH_CRITERIA.length, end);
		}
	}
	
	return value;
}

function ResetIndustryDisabling(INSTRUMENT_TYPE, INDUSTRY_LIST) {
	if (INSTRUMENT_TYPE == 'C') {
		
		//reset and disable/enable industry
		if (INDUSTRY_LIST != 0) {
			INDUSTRY_LIST.options[INDUSTRY_LIST.options.selectedIndex].selected = false;
			INDUSTRY_LIST.options[0].selected = true;
			INDUSTRY_LIST.disabled = true;
			if (!document.all && !document.getElementById) {
				INDUSTRY_LIST.onfocus = 'blur()';
			}
		}
		
	}
	if (INSTRUMENT_TYPE == 'I') {
		
		//reset and diable/enable industry
		if (INDUSTRY_LIST != 0) {
			INDUSTRY_LIST.options[INDUSTRY_LIST.options.selectedIndex].selected = false;
			INDUSTRY_LIST.options[0].selected = true;
			INDUSTRY_LIST.disabled = true;
			if (!document.all && !document.getElementById) {
				INDUSTRY_LIST.onfocus = "blur()";
			}
		}		
	}
	if ((INSTRUMENT_TYPE == 'S')||(INSTRUMENT_TYPE == 'any')) {
		
		if (INDUSTRY_LIST != 0) {
			INDUSTRY_LIST.disabled = false;
			if (!document.all && !document.getElementById) {
				INDUSTRY_LIST.onfocus = "";
			}
		}  
	}
}

function ResetExchangeDisabling(INSTRUMENT_TYPE, EXCHANGE_LIST, EXCHANGE_LIST_TYPE) {
	if (INSTRUMENT_TYPE == 'C') {
		EXCHANGE_LIST.disabled = false;
		if (!document.all && !document.getElementById) {
			EXCHANGE_LIST.onfocus = "";
		}
	}
	if (INSTRUMENT_TYPE == 'I') {		
		//disable/enable exchange		
		EXCHANGE_LIST.disabled = false;
		if (!document.all && !document.getElementById) {
			EXCHANGE_LIST.onfocus = "";
		}
	}
	if ((INSTRUMENT_TYPE == 'S')||(INSTRUMENT_TYPE == 'any')) {
		//enable/disable exchange		
		EXCHANGE_LIST.disabled = false;		
		if (!document.all && !document.getElementById) {
			EXCHANGE_LIST.onfocus = "";
		}	
	}
}

function ResetVolumeDisabling(INSTRUMENT_TYPE, VOLUME_LIST, VOLUME_OPERATOR_LIST) {
	if (INSTRUMENT_TYPE == 'C') {
		//reset volume
		VOLUME_OPERATOR_LIST.options[VOLUME_OPERATOR_LIST.options.selectedIndex].selected = false;
		VOLUME_OPERATOR_LIST.options[0].selected = true;
		VOLUME_LIST.options[VOLUME_LIST.options.selectedIndex].selected = false;
		VOLUME_LIST.options[0].selected = true;
		
		//disable/enable volume and exchange
		VOLUME_OPERATOR_LIST.disabled = true;
  		VOLUME_LIST.disabled = true;
  		
  		if (!document.all && !document.getElementById) {
			VOLUME_OPERATOR_LIST.onfocus = 'blur()';
			VOLUME_LIST.onfocus = 'blur()';			
  		}
	}
	if (INSTRUMENT_TYPE == 'I') {
		//reset volume
		VOLUME_OPERATOR_LIST.options[VOLUME_OPERATOR_LIST.options.selectedIndex].selected = false;
		VOLUME_OPERATOR_LIST.options[0].selected = true;
		VOLUME_LIST.options[VOLUME_LIST.options.selectedIndex].selected = false;
		VOLUME_LIST.options[0].selected = true;
		
		//disable/enable volume and exchange
		VOLUME_OPERATOR_LIST.disabled = true;
  		VOLUME_LIST.disabled = true;  		
  		if (!document.all && !document.getElementById) {
			VOLUME_OPERATOR_LIST.onfocus = "blur()";
			VOLUME_LIST.onfocus = "blur()";			
  		}
	}
	if ((INSTRUMENT_TYPE == 'S')||(INSTRUMENT_TYPE == 'any')) {
		//enable/disable volume and exchange and industry
		VOLUME_OPERATOR_LIST.disabled = false;
  		VOLUME_LIST.disabled = false;  		
		
  		if (!document.all && !document.getElementById) {
			VOLUME_OPERATOR_LIST.onfocus = "";
			VOLUME_LIST.onfocus = "";			
  		}	
	}
}

function removeTrailingSpaces(textbox) {
	while (''+textbox.value.charAt(0)==' ') {
		textbox.value=textbox.value.substring(1,textbox.value.length);
	}
	while (''+textbox.value.charAt(textbox.value.length-1) == ' ') 	{
		textbox.value=textbox.value.substring(0,textbox.value.length-1);
	}
}

// Returns true if character c is a digit 
// (0 .. 9).
function isDigit(c) {
	return ((c >= "0") && (c <= "9"));
}

function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++)
	{   
		// Check that current character is number.
		var c = s.charAt(i);

		if (!isDigit(c)) return false;
	}

	// All characters are numbers.
	return true;
}

// isIntegerInRange (STRING s, INTEGER a, INTEGER b)
function isIntegerInRange (s, a, b) {
	if (!isAnyInteger(s)) return false;
	var num = parseInt (s, 10);
	return ((num >= a) && (num <= b));
}

// isFloatInRange (STRING s, INTEGER a, INTEGER b, boolean ALLOW_NEGATIVE_VALUES)
function isFloatInRange (s, a, b, ALLOW_NEGATIVE_VALUES) {
	if (!isFloat(s, ALLOW_NEGATIVE_VALUES)) return false;
	var num = parseFloat (s);
	return ((num >= a) && (num <= b));
}

function isFloat(s, ALLOW_NEGATIVE_VALUES) {
	var i;
	var seenDecimalPoint = false;

	if (s == '.') return false;

	for (i = 0; i < s.length; i++)
	{   
		// Check that current character is number.
		var c = s.charAt(i);
		
		if ((c == '.') && !seenDecimalPoint) {
			seenDecimalPoint = true;
		} else if (ALLOW_NEGATIVE_VALUES) {
			if (!isAnyDigit(c)) {
				return false;
			}
		} else if (!isDigit(c)) {
			return false;
		}
	}

	// All characters are numbers.
	return true;
}

function isAnyDigit(c) {
	return((c == "-") || ((c >= "0") && (c <= "9")));
}

function isAnyInteger (s) {
	var i;

	for (i = 0; i < s.length; i++)
	{   
		// Check that current character is number.
		var c = s.charAt(i);

		if (!isAnyDigit(c)) return false;
	}

	// All characters are numbers.
	return true;
}

function AlertAboutFormErrors(ERRORS) {
  alert(GetTranslation('CorrectErrors')+":\n" + ERRORS);
}

function copyByEnum(object) {
  var copyObject = new Object();
  for(var property in object) {
    copyObject[property] = object[property];
  }
  return copyObject;
}

// this function determines whether the event is the equivalent of the microsoft 
// mouseleave or mouseenter events. (used to remove flicker in IE)
// http://www.dynamic-tools.net/toolbox/isMouseLeaveOrEnter/
function isMouseLeaveOrEnter(e, handler) { 
	if (e.type != 'mouseout' && e.type != 'mouseover') 
		return false; 
		
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement; 
	while (reltg && reltg != handler) 
		reltg = reltg.parentNode; 
		
	return (reltg != handler); 
}


////////////////////////// Number Formatting


// from mredkj.com
function addCommas(nStr,lang) {
	if (!lang) {
		lang = GetProgrammingFieldValue('Language');
	}
	var seperator =',';

	if (lang == 'fr') { seperator = ' ';}

	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + seperator + '$2');
	}
	return x1 + x2;
}


function RoundNumber(num,unit,type) {
	num = parseFloat(num);
	if (isNaN(num)) {
		return num;
	}

	var negative = false;

	if (num < 0) {
		negative = true;
		num = Math.abs(num);
	}

	if (num < 0.1) {
		if (type == 'real') {
			if (unit == 'CURRENCY') {
				num = num.toFixed(2);
			} else {
				num = num.toFixed(3);
			}
		} else {
			num = 0;
		}
	} else if (num < 1) {
		if (type == 'real') {
			num = num.toFixed(2);
		} else {
			num = 0;
		}
	} else if (num < 10 ) {
		if (type == 'real') {
			num = num.toFixed(2);
		} else {
			num = Math.round(num);
		}
	} else if (num < 100) {
		if (type == 'real') {
			if (unit == 'CURRENCY') {
				num = num.toFixed(2);
			} else {
				num = num.toFixed(1);
			}
		} else {
			num = Math.round(num);
		}
	} else {
		num = Math.round(num);
		var div = num;
		while (true) {
			if (div < 10) break;
			div *= 0.1;
		}
		var div = Math.round(num / ( div*100));
		num /= div;	
		num = Math.round(num);
		num *= div;
	}

	if (negative) num *= -1;
	return num;
}

function FormatBigNumber(num, num_unit) {
	var zeros;

	if (num_unit == 'M') {
		zeros = 6;
	} else if (num_unit == 'B') {
		zeros = 9;
	}

	num = num.toString();

	var pos = num.indexOf('.');
	if (pos == -1) {
		num = num.substring(0,num.length - zeros)+'.'+num.substring(num.length - zeros);
	} else {
		num = num.replace('.','');
		num = num.substring(0,pos - zeros) +'.'+ num.substring(pos - zeros);
	}

	return parseFloat(num).toString()+num_unit;

}

function FormatNumber(num,unit,type,lang) {
	if (!lang) {
		lang = GetProgrammingFieldValue('Language');
	}

	num = parseFloat(num);

	if (unit == 'PERCENT') {
		num = parseFloat(num) * 100;
		num = parseFloat(num.toFixed(5));
	}

	if (unit == 'CURRENCY') {
		if ((parseFloat(num) - Math.floor(num) == 0) && (Math.abs(parseFloat(num)) >= 100)) {
			num = Math.floor(num);
		} else {
			num = num.toFixed(2);
		}
	}

	if (Math.abs(parseFloat(num)) >= 1000000000) {
		num = FormatBigNumber(num,'B');
	}  else if (Math.abs(parseFloat(num)) >= 1000000)  {
		num = FormatBigNumber(num,'M');
	} else {
		num = addCommas(num,lang);
	}

	if (unit == 'PERCENT') {
		num += '%';
	} else if (unit == 'DAYS') {
		if (lang == 'fr') {
			num += 'jrs';
		} else {
			num +='dys';
		}
	} else if (unit == 'CURRENCY') {
		if (lang == 'fr') {
			num += '$';
		} else {
			num = '$' + num;
		}
	}

	if (lang == 'fr') {
		num = num.toString().replace('.',',');  
	}

	return num;
	
}


function DeformatNumber(num,unit,type,lang) {
	if (!lang) {
 		lang = GetProgrammingFieldValue('Language');
	}

	var deformat_num = num;
	
	if (lang == 'fr') {

		deformat_num = deformat_num.replace(',','.');  
		deformat_num = deformat_num.replace(/\s/g,'');
		if (unit == 'PERCENT') {
    			deformat_num = deformat_num.replace(/%$/,'');
		} else if (unit == 'DAYS') {
    			deformat_num = deformat_num.replace(/jrs$/,'');
		} else if (unit == 'CURRENCY') {
    			deformat_num = deformat_num.replace(/^\$/,'');
    			deformat_num = deformat_num.replace(/\$$/,'');
		}

		if (isNaN(deformat_num.toString().replace('B','').replace('M',''))) {
			return NaN;
		}

		if(num.toString().indexOf('B')>=0){
			deformat_num = parseFloat(deformat_num.toString().replace('B','')) * 1000000000;
		} 

		if(num.toString().indexOf('M')>=0) {
			deformat_num= parseFloat(deformat_num.toString().replace('M','')) * 1000000;
		}

		if (unit == 'PERCENT') {
			deformat_num = parseFloat(deformat_num) * 0.01;
			deformat_num = parseFloat(deformat_num.toFixed(8));
		}
	} else {

		deformat_num = deformat_num.replace(/,/g,'');  
		deformat_num = deformat_num.replace(/\s/g,'');
		if (unit == 'PERCENT') {
    			deformat_num = deformat_num.replace(/%$/,'');
		} else if (unit == 'DAYS') {
    			deformat_num = deformat_num.replace(/dys$/,'');
		} else if (unit == 'CURRENCY') {
    			deformat_num = deformat_num.replace(/^\$/,'');
    			deformat_num = deformat_num.replace(/\$$/,'');
		}

		if (isNaN(deformat_num.toString().replace('B','').replace('M',''))) {
			return NaN;
		}

		if(num.toString().indexOf('B')>=0){
			deformat_num = parseFloat(deformat_num.toString().replace('B','')) * 1000000000;
		} 

		if(num.toString().indexOf('M')>=0) {
			deformat_num= parseFloat(deformat_num.toString().replace('M','')) * 1000000;
		}

		if (unit == 'PERCENT') {
			deformat_num = parseFloat(deformat_num) * 0.01;
			deformat_num = parseFloat(deformat_num.toFixed(8));
		}

	}

	if (isNaN(deformat_num)) {
		return NaN;
	} else {
		if (type == 'real') {
			return parseFloat(deformat_num);
		} else {
			return parseInt(deformat_num);
		}
	}

}
