﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="jquery.cookie.js" />

/*  WS Code
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.IO
Imports System.Net
	<WebMethod()> _
	Public Function getStockQuote(ByVal Symbols As String) As String

		Dim lURL As String = String.Format("http://finance.yahoo.com/d/Data.csv?s={0}&f=snl9c6p4&e=.csv", _
										  Symbols)

		Dim lRequest As WebRequest = WebRequest.Create(lURL)

		Dim lStream As StreamReader = New StreamReader(lRequest.GetResponse().GetResponseStream())
		Dim lData As String = String.Empty

		While (Not lStream.EndOfStream)
			lData += lStream.ReadLine().Replace("""", "") + "~"
		End While

		lData = lData.Substring(0, lData.Length - 1)
		Return lData

	End Function
*/

/* WebMethod (in the aspx or asmx in the client project)
Imports USAFinStockQuote.StockDataoapClient

	<WebMethod()> _
	Public Shared Function getStockQuote(ByVal Symbols As String) As String
		'By placing the call to the web service here, this bypasses the security 
		'limitation of Javascript accessing remote servers.  
		Try
			Return (New USAFinStockQuote.StockDataoapClient()).getStockQuote(Symbols)
		Catch ex As Exception
			Return ex.Message
		End Try

	End Function

	<WebMethod()> _
	Public Shared Sub cacheStockSymbols(ByVal Symbols As String)

		Try
			HttpContext.Current.Cache.Insert("StockSymbols", Symbols)
		Catch ex As Exception

		End Try

	End Sub

	<WebMethod()> _
	Public Shared Function getStockSymbols(ByVal Symbols As String) As String

		Try
			Return TryCast(HttpContext.Current.Cache.Get("StockSymbols"), String)
		Catch ex As Exception
			Return String.Empty
		End Try

	End Function
*/

/* PHP Web Service proxy code
<?php
	session_start();

	//Web Service Proxy
	class USAStockQuotes
	{
		public function getStockInfo($Symbols)
		{			
			$URL = "http://www.usafinancial.net/services/StockQuote.asmx/getStockQuote";

			//open connection
			$ch = curl_init();
		
			//set the url, number of POST vars, POST data
			curl_setopt($ch,CURLOPT_URL,$URL);
			curl_setopt($ch,CURLOPT_POST,1);
			curl_setopt($ch,CURLOPT_POSTFIELDS,'Symbols='.$Symbols);
		
			//execute post
			$result = curl_exec($ch);
			return $result;
		}

	}

	$SessionVar = 'Symbols';
	$Action = $_GET['Action'];

	if ($Action == 'getStockInfo')
	{
		$USAStocks = new USAStockQuotes();
		print $USAStocks->getStockInfo($_GET[$SessionVar]);
	}
	elseif ($Action == 'cacheStockSymbols')
	{
		$_SESSION[$SessionVar] = $_GET[$SessionVar];
	}
	else
	{
		if (isset($_SESSION[$SessionVar]))
		{
			print $_SESSION[$SessionVar];
		}
		else
		{
			print '';
		}
	}
?>
*/


//////Configuration Variables
var mDefaultSymbols = 'INDU,^IXIC,^SPX,^RUT'; //Dow(^DJI), NASDAQ, S&P 500, Russel 2000 by default - everytime
var mUsePHPProxy = true;
var mPHPPage = '/home/ticker_new/js/StockQuote.php';
var mASPXPage = 'default.aspx';
var mUp = '/home/ticker_new/style/images/up.gif';
var mDown = '/home/ticker_new/style/images/down.gif';
var mNc = '/home/ticker_new/style/images/no-change.gif';
//////

var mUserSymbols;	// This variable will store user entered symbols while on the page
var mDisplayChars = 16;
var mCookieName = 'pnrUserStockSymbols';

$(document).ready(function () {

	$.ajaxSetup({
		type: "post",
		contentType: "application/json; chrset-utf-8",
		dataType: "json"
	});

	$(document).ajaxError(function (e, xhr, settings, exception) {
		alert('Error in: ' + settings.url + '\nError: ' + exception);
	});

	$("#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
		$.cookie('pnrCookieTest', 'Checking to see it cookies are enabled');

		//Attempt to read the cookie.  If successful, then cookies are enabled.
		if ($.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 = $("#symbol").val();

	if (cookiesEnabled()) {
		$.cookie(mCookieName, mUserSymbols, { expires: 365 });
		getStockSymbols();
	}
	else {
		if (mUsePHPProxy) {
			lParam = { Action: 'cacheStockSymbols', Symbols: mUserSymbols };
			$.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 };
			$.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 = $.cookie(mCookieName);
	
	if (mUserSymbols == null || mUserSymbols.length == 0) {
		if (mUsePHPProxy) {
			var lParam = { Action: 'getStockSymbols' };
			$.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 {
			$.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 };
		$.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 };
		$.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 = $('#market-data').empty();

	for (i = 0; i < linesOfData.length; i++) {
		var lineOfData = linesOfData[i].split(',');
		tr = $('<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) + '...';
			}
			$('<td>', { html: val }).appendTo(tr);
		}
		$('<td>', { html: $('<img>', { id: 'ChangeType' + i })	}).appendTo(tr);
		tr.appendTo(lStocks);
	}

	lStocks.children().children('tr').each(function (i) {
		var val = $(this).children(':last').prev().text().toString().substring(0, 1);
		var lImg = val == '+' ? mUp : (val == '-' ? mDown : mNc);
		$('#ChangeType' + i).attr('src', lImg);
		$('#ChangeType' + i).addClass('Market-Update');
	});
}

