var storage = new Array()
var req	= false;
var reqLog = ''

function setOffset(amount, formName)
{
	offsetInput = document.getElementById('offset')
	offsetInput.value = Number(Number(offsetInput.value) + Number(amount))
	document.getElementById(formName).submit()	
}

function sortSearch(sortby,formName)
{	
	sortInput = document.getElementById('sortOn')
	sortOrderInput = document.getElementById('sortOrder')
	
	// check for intent to reverse sort
	if( sortInput.value == sortby || sortInput.value == '')
	{
		//alert(sortOrderInput.value)
		if( sortOrderInput.value == 'ASC' || sortOrderInput.value == '' )
			sortOrderInput.value = 'DESC'
		else
			sortOrderInput.value = 'ASC'
	} else {
		sortOrderInput.value = 'ASC'
	}
	
	sortInput.value=sortby
	//alert(sortOrderInput.value)
	document.getElementById(formName).submit()
}

function resetForm(formName)
{
	for(i=0;i < document.forms[formName].elements.length; i++)
	{
		if(document.forms[formName].elements[i].type)
		{
			if(document.forms[formName].elements[i].type == 'text')
			{
				document.forms[formName].elements[i].value = ''
			}
			
			if (document.forms[formName].elements[i].type == 'select-one' && document.forms[formName].elements[i].id != 'stockTypeSelect')
			{
				document.forms[formName].elements[i].selectedIndex='0'
			}
		}
	}
}


// Sets cookie values. Expiration date is optional
function setCookieNew(name, value, days, path, domain, secured)
{      
  var expire = new Date();
  if(!days){
     var days = 1;
  }
  expire.setTime(expire.getTime() + days*24*60*60*1000);
  cookie = name + "=" + escape(value) +
  "; expires=" + expire.toUTCString() +
  ((path) ? "; path=" + path : "") +
  ((domain) ? "; domain=" + domain : "") +
  ((secured) ? "; secure" : "");
  document.cookie = cookie
}

function getCookie(Name) {
	var search = Name + "="
	if (document.cookie.length > 0) { // if there are any cookies                    
		offset = document.cookie.indexOf(search)                     
		if (offset != -1) { // if cookie exists                               
			offset += search.length                               
		
			// set index of beginning of value                              
			end = document.cookie.indexOf(";", offset)                               
		
			// set index of end of cookie value                              
			if (end == -1)                                         
				end = document.cookie.length                              
			return unescape(document.cookie.substring(offset, end))                    
		}
	}
	
	return false
}

function printArray(array)
{
	str = new String()
	for(i=0; i < array.length; i++)
	{
		str = str + "\n[" + i + "] => [" + array[i] + "]"
	}
	alert(str)
}

function cleanArray(array, value)
{
	for(i=0; i < array.length; i++)
	{
		if(array[i] == value)
			array.splice(i,1)
	}
	return array
}

function clearAllStocks(formName)
{
	response = confirm("Are you sure you wish to clear your watched stocks?")
	
	if(response)
	{
    form = document.createElement('form')

    form.action = '/lib/folio/call/removeAllStock'
    form.method = 'post'
    document.body.appendChild(form)
    form.submit()
	}
	return
}

/*
**	report view toggle js
*/
	function toggleView(tableId,which)
	{
		rangeA = new Array(4,5,6,7,8)
		rangeB = new Array(9,10,11,12,13)
		
		table = document.getElementById(tableId)
		tbody = table.getElementsByTagName('TBODY')
		tbody = tbody[0]
		
		//alert(tbody.nodeName)
		//printArray(tbody.childNodes)
		
		// loop through tr nodes

		for(i=0;i < tbody.childNodes.length;i++)
		{
			if(tbody.childNodes[i].nodeName == 'TR')
			{
				// this gives us an array of each td in this row
				tdNodes = tbody.childNodes[i].getElementsByTagName('TD')
				
				// now we want to set the td's to display:none or display OR display: table-cell:
				if(which == 'showEval')
				{
					rangeADisplayVal = 'none'
					rangeBDisplayVal = ''
					
					displayMng = 'none'
					displayEval = ''
				} else {
					rangeADisplayVal = ''
					rangeBDisplayVal = 'none'
					
					displayMng = ''
					displayEval = 'none'
				}
				
				rangeA.each(function(a){
				  tdNodes[a].style.display = rangeADisplayVal
				})
				
				rangeB.each(function(b){
				  tdNodes[b].style.display = rangeBDisplayVal
				})
				
				// set which date value to show
				node = document.getElementById('lastUpdatedMng')
				node.style.display = displayMng
				
				node = document.getElementById('lastUpdatedEval')
				node.style.display = displayEval
			}
		}
		setCookieNew('HDGFView', which, '','/')
	}
	
	function onLoadSetView()
	{
		// if they're coming here clean from no previous search - reset view
		if( document.URL.search('call/doSearch') == -1)
		{
			setCookieNew('HDGFView', '','','/')
			return
		}
		
		if(which = getCookie('HDGFView'))
		{
			if(node = document.getElementById('viewSelect'))
			{
				node.value = which
				toggleView('resultsTable', which)
			}
		}
	}
	
	function stockTypeChange(self)
	{
		elementsArray	= new Array('size','income')
		optionsArray		= new Array('HIGH VALUE','MID VALUE','LOW VALUE','VALUE BLEND','GROWTH BLEND','LOW GROWTH','MID GROWTH','HIGH GROWTH')
		
		if(self.value != 'STK') // ETF something or other
		{
			styleETFSelect = document.getElementById('styleETFSelect')
			styleSelect = document.getElementById('styleSelect')

			// restore backed up node
			if(styleETFSelect == undefined)
			{
				styleSelect.parentNode.appendChild(storage)
				styleETFSelect = document.getElementById('styleETFSelect')
				styleETFSelect.selectedIndex=0
			}

			// backup style select
			storage = styleSelect.cloneNode(true)
				
			// remove style select
			styleSelect.parentNode.removeChild(styleSelect)

			return
		}
		
		if(self.value == 'STK')
		{
			styleETFSelect = document.getElementById('styleETFSelect')
			styleSelect = document.getElementById('styleSelect')

			// restore backed up node
			if(styleSelect == undefined)
			{
				styleETFSelect.parentNode.appendChild(storage)
				styleSelect = document.getElementById('styleSelect')
				styleSelect.selectedIndex = 0
			}

			// backup styleETF select
			storage = styleETFSelect.cloneNode(true)

			// remove styleETF select
			styleETFSelect.parentNode.removeChild(styleETFSelect)

			return
		}
	}
	
	function onLoadSetStockType()
	{
		stockTypeChange(document.getElementById('stockTypeSelect'))
	}
	
	function onLoadCursor()
	{
		if(document.getElementById('cname').value.length)
		{
			document.getElementById('cname').select()
		}
		else
		{
			document.getElementById('symbol').select()
		}
	}
	
	
	function hotkeyCheck(event)
	{
		// keyboard shortcuts for results lists only
		if( event.target.nodeName != 'input' && (viewSelect = document.getElementById('viewSelect')) )
		{
			if(event.charCode == 118)
			{
				if(viewSelect.selectedIndex == 1)
					viewSelect.selectedIndex = 0
				if(viewSelect.selectedIndex == 0)
					viewSelect.selectedIndex = 1
			}
		}	
	}

  /*
  * Handle toggling stocks to be watched
  */

  function toggleFolioFlag(id,myfolioFlag)
  {
  	checkbox = document.getElementById(id)
  	
  	// confirm the user wants to uncheck this
  	if(! checkbox.checked) {
  	  if(!confirm('Remove this stock from your folio?'))
  	  {
  	    checkbox.checked = true;
  	    return;
  	  }
  	}
  	
  	var pars = 'stock=' + checkbox.value + '&rowId=' + id + '&cState='+ !checkbox.checked
  	
  	// handle if being checked on
  	if(checkbox.checked) {
  	  var ajxReq = new Ajax.Request('/lib/folio/call/ajaxAdd',{method: 'get', parameters: pars, onComplete: toggleFolioAjaxResponse})
  	} else { // handle if being checked off
  	  if(myfolioFlag) {
  	    window.location = '/lib/folio/call/removeStock?' + pars
  	  } else {
  	    var ajxReq = new Ajax.Request('/lib/folio/call/ajaxRemove',{method: 'get', parameters: pars, onComplete: toggleFolioAjaxResponse})
  	  }
  	}
  }

  function toggleFolioAjaxResponse(request,r)
  {
    if(r['err']) {

      // display error if any
      if(r['eTxt'].length) {
        alert(r['eTxt'])
      }
      
      // put checkbox back to original state
      if(r['cState'] == 'false')
        $(r['rowId']).checked = false
        
      if(r['cState'] == 'true')
        $(r['rowId']).checked = true
    }
  }
  
  // set a test 'old skool' cookie that was once used for storing myfolio values
  // NOVL%2CYHOO%2CAAPL%2CMSFT
  function setTestCookie()
  {
    stockArray = Array('NOVL','YHOO','AAPL','MSFT')
    setCookieNew('HDGFSTOCKS', stockArray.toString(),90,'/')
  }