﻿
//////Configuration Variables
var mDefaultSymbols = 'INDU,^IXIC,^SPX,^RUT'; //Dow(^DJI), NASDAQ, S&P 500, Russel 2000 by default - everytime
var mUsePHPProxy = false;
var mPHPPage = 'js/StockQuote.php';
var mASPXPage = '/stockquoteproxy.aspx';
var mUp = '/style/images/stockquote/up.gif';
var mDown = '/style/images/stockquote/down.gif';
var mNc = '/style/images/stockquote/no-change.gif';
//////

var mUserSymbols;	// This variable will store user entered symbols while on the page
var mDisplayChars = 12;
var mCookieName = 'UserStockSymbols';

$j = jQuery.noConflict();
$j(document).ready(function () {

	$j.ajaxSetup({
		type: "post",
		contentType: "application/json; chrset-utf-8",
		dataType: "json"
	});

	$j(document).ajaxError(function (e, xhr, settings, exception) {
		alert('Error in: ' + settings.url + '\nError: ' + exception);
	});

	$j("#get-data").click(function (e) {
		e.preventDefault();
		cacheStockSymbols(); //calls getStockSymbols which calls getStockInfo
	});

	getStockSymbols();

	window.setInterval('getStockSymbols()', 300000);  // 5-minute refresh setting.


});

function cookiesEnabled() {
	try {
		//try to create a cookie
		$j.cookie('pnrCookieTest', 'Checking to see it cookies are enabled');

		//Attempt to read the cookie.  If successful, then cookies are enabled.
		if ($j.cookie('pnrCookieTest'))
			return true;
		else
			return false;
	}
	catch (e) {
		return false;
	}
}

function cacheStockSymbols() {
	/*	1) Try to use a cookie
		2) Use a Session Variable as backup
	*/
	var lParam;
	mUserSymbols = $j("#symbol").val();

	if (cookiesEnabled()) {
		$j.cookie(mCookieName, mUserSymbols, { expires: 365 });
		getStockSymbols();
	}
	else {
		if (mUsePHPProxy) {
			lParam = { Action: 'cacheStockSymbols', Symbols: mUserSymbols };
			$j.ajax({ url: mPHPPage,
				data: lParam,
				dataType: 'text',
				type: 'get',
				success: function (result) {
					getStockSymbols(); 
				},
				error: function (xhr, status, exception) {
					alert('Error (cacheStockSymbols): ' + status + '\n' + 'Details: ' + exception);
				}
			});
		}
		else {
			lParam = { Symbols: mUserSymbols };
			$j.ajax({
				url: mASPXPage + "/cacheStockSymbols",
				data: JSON.stringify(lParam),
				success: function (response) {
					getStockSymbols();
				}
			});
		}
	}
}

function getStockSymbols() {
	//This function will get the user entered symbols either from a cookie or 
	//the Session State (in the event of returning to the page).
	
	mUserSymbols = $j.cookie(mCookieName);
	
	if (mUserSymbols == null || mUserSymbols.length == 0) {
		if (mUsePHPProxy) {
			var lParam = { Action: 'getStockSymbols' };
			$j.ajax({ url: mPHPPage,
				data: lParam,
				dataType: 'text',
				type: 'get',
				success: function (result) {
					mUserSymbols = result;
					if (mUserSymbols == null || mUserSymbols.length == 0) {
						getStockInfo(mDefaultSymbols);
					}
					else {
						getStockInfo(mDefaultSymbols + ',' + mUserSymbols);
					}
				},
				error: function (xhr, status, exception) {
					alert('Error (getStockSymbols): ' + status + '\n' + 'Details: ' + exception);
				}
			});
		}
		else {
			$j.ajax({
				url: mASPXPage + "/getStockSymbols",
				data: JSON.stringify({}),
				success: function (response) {
					mUserSymbols = response.d;
					if (mUserSymbols == null) {
						getStockInfo(mDefaultSymbols);
					}
					else {
						getStockInfo(mDefaultSymbols + ',' + mUserSymbols);
					}
				}
			});
		}
	}
	else {
		getStockInfo(mDefaultSymbols + ',' + mUserSymbols);
	}
}

function getStockInfo(Symbols) {
	var lParam;
	if (mUsePHPProxy) {
		lParam = { Action: 'getStockInfo', Symbols: Symbols };
		$j.ajax({ url: mPHPPage,
			data: lParam,
			dataType: 'text',
			type: 'get',
			success: function (result) {
				displayStockInfo(result.substring(result.indexOf('">') + 2, result.lastIndexOf('</')));
			},
			error: function (xhr, status, exception) {
				alert('Error (getStockInfo): ' + status + '\n' + 'Details: ' + exception);
			}
		});
	}
	else {
		lParam = { Symbols: Symbols };
		$j.ajax({
			url: mASPXPage + '/getStockInfo',
			data: JSON.stringify(lParam),
			success: function (response) {
				displayStockInfo(response.d);
			}
		});
	}
}

//Needs a table with id="market-data"
function displayStockInfo(data) {
	var linesOfData = data.split('~');

	var lStocks = $j('#market-data').empty();

	for (i = 0; i < linesOfData.length; i++) {
		var lineOfData = linesOfData[i].split(',');
		tr = $j('<tr>');
		for (r = 1; r < lineOfData.length; r++) {
			//We start at r = 1, becuase we don't want to show the symbol.
			if (lineOfData.length == 6 && r == 2) {
				r++; //Stocks like S&P 500 have a comma in the name, so skip the extra part
			}
			var val = lineOfData[r].replace('\'', '').replace('\'', '');
			if (val.length > mDisplayChars) {
				val = val.substring(0, mDisplayChars) + '...';
			}
			$j('<td>', { html: val }).appendTo(tr);
		}
		$j('<td>', { html: $j('<img>', { id: 'ChangeType' + i })	}).appendTo(tr);
		tr.appendTo(lStocks);
	}

	lStocks.children().children('tr').each(function (i) {
		var val = $j(this).children(':last').prev().text().toString().substring(0, 1);
		var lImg = val == '+' ? mUp : (val == '-' ? mDown : mNc);
		$j('#ChangeType' + i).attr('src', lImg);
		$j('#ChangeType' + i).addClass('Market-Update');
	});
}

