////////////////////////////////////////////////////////////////////
// CICFunc class
CICFunc.CLASS_NAME = 'CICFunc';
CICFunc.ACTION_AJAX_SEARCH = 'Ajax Search';
CICFunc.BASE_URL = 'index.php';
CICFunc.AJAX_SEARCH_RESULTS_PER_PAGE = 50;
CICFunc.AJAX_SEARCH_START = 0;
CICFunc.DEFAULT_WIDTH = 775;
CICFunc.DEFAULT_HEIGHT = 600;

// Static vars/objs
CICFunc.disableFormSubmit = true;
CICFunc.htHideDetails = new Hashtable();
CICFunc.htHideMain = new Hashtable();
CICFunc.prevAjaxId = "";
CICFunc.prevUnderlyingId = null;

// Constructor
function CICFunc() {
}


CICFunc.htHideDetails.put("contractCalendar", "contractCalendar");
CICFunc.htHideDetails.put("contractNews", "contractNews");
CICFunc.htHideDetails.put("contractSpecs", "contractSpecs");

CICFunc.htHideMain.put("advancedSearch", "advancedSearch");
CICFunc.htHideMain.put("bondBillSearch", "bondBillSearch");
CICFunc.htHideMain.put("cfdSearch", "cfdSearch");
CICFunc.htHideMain.put("componentSearch", "componentSearch");
CICFunc.htHideMain.put("forexSearch", "forexSearch");
CICFunc.htHideMain.put("futuresSearch", "futuresSearch");
CICFunc.htHideMain.put("help", "help")
CICFunc.htHideMain.put("indexSearch", "indexSearch");
CICFunc.htHideMain.put("mutualFundSearch", "mutualFundSearch");
CICFunc.htHideMain.put("optionSearch", "optionSsearch");
CICFunc.htHideMain.put("simpleSearch", "simpleSearch");
CICFunc.htHideMain.put("stockSearch", "stockSearch");
CICFunc.htHideMain.put("warrantSearch", "warrantSearch");

CICFunc.doAlert = function(str) {
  var d = document.createElement("div");
  d.innerHTML = str;
  alert(d.innerHTML);
}

// Static method to save the preferences
CICFunc.savePreferences = function() {
  var lang = $getRBVal('langSelect');
  if (lang == null || lang == "") {
    CICFunc.doAlert("You must select a preferred language!");
    return;
  }
  opener.CICFunc.updatePreferences(lang);
  CICFunc.doAlert("Preferences Saved!");
  window.close();
}

// Static method to show the preferences
CICFunc.showPreferences = function() {
  var lang = $('lang').value;
  var wlId = $('wlId').value;
  var url = 'preferences.php?action=Edit Preferences&lang='+lang+"&wlId="+wlId;
  IBCSUtils.openWin(url,'cicpref','600','400','center','front');
}

// Update preferences
CICFunc.updatePreferences = function(lang) {
  $('lang').value = lang;
  CICFunc.changeLangMain();
}

// Static method to show options for a specific underlying
CICFunc.showOptionsForUnderlying = function(id) {
  var rows = document.getElementsByTagName("tr");
  var numRows = rows.length;

  // Hide the previously displayed underlying
  if (CICFunc.prevUnderlyingId != null) {
    var pattern = new RegExp('\\b'+CICFunc.prevUnderlyingId+'\\b');
    for (var i=0; i<numRows; i++) {
      var row = rows[i];
      if (pattern.test(row.className)) {
        row.style.display = 'none';
      } 
    }
  }

  var pattern = new RegExp('\\b'+id+'\\b');
  for (var i=0; i<numRows; i++) {
    var row = rows[i];
    if (pattern.test(row.className)) {
      row.style.display = '';
    }

  }
  CICFunc.prevUnderlyingId = id;
}

// Hide all the details tabs
function hideAllDetails(source) {
  for (var i=0; i<CICFunc.htHideDetails.keys.length; i++) {
    var k = CICFunc.htHideDetails.keys[i];
    if (k == source) {
      $shElm(k);
      continue;
    }
    $hdElm(k);
  }
}

// Hide all the main tabs
function hideAllMain(source) {
  for (var i=0; i<CICFunc.htHideMain.keys.length; i++) {
    var k = CICFunc.htHideMain.keys[i];
    if (k == source) {
      continue;
    }
    $hdElm(k);
  }
}

function chgParams(start) {
  $('start').value = start;
  $('refreshForm').submit();
}

function changeLang() {
  $('refreshForm').submit();
}

// Update the main form
CICFunc.changeLangMain = function() {
  $('action').value = "Search Form";
  $('refreshForm').target = null;
  $('refreshForm').submit();
}

function showConTypeFilters() {
  var type = $('contractType').value;

  switch(type) {
    case '':
      CICFunc.showAdvancedSearch();
      break;
    case 'BOND':
      CICFunc.showBondsBillsSearch();
      break;
    case 'CASH':
      CICFunc.showForexSearch();
      break;
    case 'CFD':
      CICFunc.showCFDSearch();
      break;
    case 'FUTGRP':
      CICFunc.showFuturesSearch();
      break;
    case 'FOP':
      CICFunc.showFuturesOptionsSearch();
      break;
    case 'FUND':
      CICFunc.showMutualFundsSearch();
      break;
    case 'IND':
      CICFunc.showIndexSearch();
      break;
    case 'OPT':
      CICFunc.showOptionsSearch();
      break;
    case 'STK':
      CICFunc.showStockSearch();
      break;
    case 'WAR':
      CICFunc.showWarrantsSearch();
      break;
    default:
      CICFunc.doAlert("unknown contract type: " + type);
  }

}

CICFunc.showAdvancedSearch = function() {
  $('action').value = 'Advanced Search';
  _showSearchDiv('advancedSearch', 'Advanced');
}

CICFunc.showBondsBillsSearch = function() {
  $('contractType').value = 'BOND';
  $('action').value = 'Bond Search';
  _showSearchDiv('bondBillSearch', 'Bonds/Bills');
}

CICFunc.showCFDSearch = function() {
  $('action').value = 'CFD Search';
  _showSearchDiv('cfdSearch', 'CFDs');
}

CICFunc.showComponentSearch = function() {
  $('contractType').selectedIndex = 0;
  _showSearchDiv('componentSearch', 'Components');
}

CICFunc.showForexSearch = function() {
  $('contractType').value = 'CASH';
  $('action').value = 'Forex Search';
  _showSearchDiv('forexSearch', 'Forex');
}

CICFunc.showFuturesSearch = function() {
  $('contractType').value = 'FUTGRP';
  $('action').value = 'Futures Search';
  _showSearchDiv('futuresSearch', 'Futures');
}

CICFunc.showFuturesOptionsSearch = function() {
  $('contractType').value = 'FOP';
  $('action').value = 'Futures Option Search';
  _showSearchDiv('optionSearch', 'Options');
}

CICFunc.showHelp = function() {
  _showSearchDiv('help', 'Help');
}

CICFunc.showIndexSearch = function() {
  $('contractType').value = 'IND';
  $('action').value = 'Index Search';
  _showSearchDiv('indexSearch', 'Indexes');
}

CICFunc.showMutualFundsSearch = function() {
  $('contractType').value = 'FUND';
  $('action').value = 'Mutual Fund Search';
  _showSearchDiv('mutualFundSearch', 'Mutual Funds');
}

CICFunc.showOptionsSearch = function() {
  $('contractType').value = 'OPT';
  $('action').value = 'Option Search';
  _showSearchDiv('optionSearch', 'Options');
}

CICFunc.showSimpleSearch = function() {
  $('action').value = 'Simple Search';
  _showSearchDiv('simpleSearch', 'Simple');
}

CICFunc.showStockSearch = function() {
  $('contractType').value = 'STK';
  $('action').value = 'Stock Search';
  _showSearchDiv('stockSearch', 'Stocks');
}

CICFunc.showWarrantsSearch = function() {
  $('contractType').value = 'WAR';
  $('action').value = 'Warrant Search';
  _showSearchDiv('warrantSearch', 'Warrants');
}

function _showSearchDiv(id, title) {
  hideAllMain(id);
  $elmInHtml('mainTitle', title);
  if (id != 'simpleSearch' && id != 'componentSearch') {
    $shElm('advancedSearch');
  }
  $shElm(id);
}

CICFunc.openPageForEntity = function(entityId, url) {
  var lang = $('lang').value;
  var wlId = $('wlId').value;

  var showEntities = "Y";
  try {
    var se = $('showEntities');
    if (se.type == 'hidden') {
      showEntities = se.value;
    } else if (se.type == 'checkbox') {
      var chk = $('showEntities').checked;
      if (!chk) {
        showEntities = "";
      }
    }
  } catch (e) {}

  var extraStuff = "&lang=" + lang + "&wlId=" + wlId + "&showEntities=" + showEntities;
  url += extraStuff;
  IBCSUtils.openWin(url,entityId,CICFunc.DEFAULT_WIDTH,CICFunc.DEFAULT_HEIGHT,'center','front');
}

// Allow submit
CICFunc.allowSubmit = function() {
  CICFunc.disableFormSubmit = false;
}

// Validate form
CICFunc.validateForm = function() {
  if (CICFunc.disableFormSubmit) {
    return false;
  }
  CICFunc.disableFormSubmit = true;
  IBCSUtils.openWin('blank.html','cicsearchres',CICFunc.DEFAULT_WIDTH,CICFunc.DEFAULT_HEIGHT,'center','front');
  return true;
}

// Show Details
function showDetails(conid) {
  var lang = $('lang').value;
  var wlId = $('wlId').value;
  var url = 'index.php?action=Conid Info&wlId='+wlId+'&conid='+conid+'&lang='+lang;
  IBCSUtils.openWin(url,conid,'700','600','center','front');
}

// Show Components
function showComponents(conid) {
  var lang = $('lang').value; 
  var wlId = $('wlId').value;
  var url = 'index.php?action=ShowComponents&showEntities=Y&wlId='+wlId+'&conid='+conid+'&lang='+lang; 
  IBCSUtils.openWin(url,conid,CICFunc.DEFAULT_WIDTH,CICFunc.DEFAULT_HEIGHT,'center','front');
}

// Show country selector
function showCountrySelector() {
  CICFunc.doAlert("show country selector");
  ActionMenu.show(SymSearchCountry, 'countrySelDiv');
}


/////////////////////////////////////////////////////////////////////////////////////////
// Functions for contract details start

// Show contract calendar tab
function showContractCalendarTab() {
  hideAllDetails('contractCalendar');
}

// Show contract news tab
function showContractNewsTab() {
  hideAllDetails('contractNews');
}

// Show contract specs tab
function showContractSpecsTab() {
  hideAllDetails('contractSpecs');
}

// Functions for contract details end
/////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////
// Functions for ajax search start

// Static function to cache the search results
CICFunc.cacheAjaxObjects = function(xmlDoc, vars) {
  var queryInfoXml = xmlDoc.documentElement.getElementsByTagName("qinfo");
  queryInfoXml = queryInfoXml[0];
  var totalRecords = $attr(queryInfoXml, 'tr');

  $setCls('ajaxSearch', 'ajaxSearch');

  var resultsDiv = $('ajaxSearchResults');

  var html = "No records found"; 
  if (totalRecords == 0) {
    resultsDiv.innerHTML = html;
    return;
  }

  var text = $('ajaxSearch').value;

  var start = parseInt(CICFunc.AJAX_SEARCH_START)+1;
  var end = Math.min(totalRecords, start + CICFunc.AJAX_SEARCH_RESULTS_PER_PAGE-1);
  var prevStart = CICFunc.AJAX_SEARCH_START-CICFunc.AJAX_SEARCH_RESULTS_PER_PAGE;
  var prev = "";
  if (CICFunc.AJAX_SEARCH_START != 0) {
    prev = '<a href="javascript:CICFunc.createAjaxQuery(\'' + prevStart + '\',\'' + text + '\')">Prev</a> &nbsp; ';
  } 

  var next = "";
  if (totalRecords>(end)) {
    next = ' &nbsp; <a href="javascript:CICFunc.createAjaxQuery(\'' + end + '\',\'' + text + '\')">Next</a>';
  } 

  html = '<table class="resultsTbl" style="margin-bottom:0px; width:100%;">' +
         '<tr class="white">' +
         '<td colspan=3>' + prev + '<b>' + start + '</b> to <b>' + end + '</b> out of <b>' + totalRecords + '</b>' + next + '</td></tr>' +
         '<tr class="colhead">' +
         '<th width="1%">&nbsp;</th>' +
         '<th width="49%">Description/Name</th>' +
         '<th width="48%">Products</th>' +
//         '<th width="1%">&nbsp;</th>' +
         '</tr>';

  var objXml = xmlDoc.documentElement.getElementsByTagName("obj");
  for (var i=0; i<objXml.length; i++) {
    var e = new CICEntity(objXml[i]);
    html += e.getRowText();
  }

  html += '</table>';

  resultsDiv.innerHTML = html;
}

// When we enter the search field change the text to a blank string
// if it is the default text
CICFunc.enterSearchField = function() {
  var div = $('ajaxSearch');
  if (div.value == 'Enter a product name or symbol here.') {
    div.value = '';
  }
}

CICFunc.exitSearchField = function() {
  var div = $('ajaxSearch');
  if (div.value == '') {
    div.value = 'Enter a product name or symbol here.';
  }
}

CICFunc.handleKeyPress = function(evt) {
  var keyCode = evt.keyCode;
  if (keyCode == 13 || keyCode == 18 || keyCode == 16 || keyCode == 27 || keyCode == 32 || keyCode == 17 || keyCode == 224) {
    return;
  }
  var text = $('ajaxSearch').value;

  // Cancel previous call
  AJAXConn.cancelAjaxRequestForID(CICFunc.prevAjaxId);

  if (text == "") {
    $setCls('ajaxSearch', 'ajaxSearch');
    var div = $('ajaxSearchResults');
    div.innerHTML = 'Enter a product name or symbol here.'; 
    return;
  }

  CICFunc.createAjaxQuery(0, text);
}

CICFunc.doAjaxSearch = function() {
  var text = $('ajaxSearch').value;
      
  // Cancel previous call
  AJAXConn.cancelAjaxRequestForID(CICFunc.prevAjaxId);

  if (text == 'Enter a product name or symbol here.') {
    return;
  }

  if (text == "") {
    $setCls('ajaxSearch', 'ajaxSearch');
    var div = $('ajaxSearchResults');
    div.innerHTML = 'Enter a product name or symbol here.';
    return;
  } 
    
  CICFunc.createAjaxQuery(0, text);
}

// Static function to send an xml query to the server
CICFunc.createAjaxQuery = function(start, text) {
  CICFunc.AJAX_SEARCH_START = start;

  $setCls('ajaxSearch', 'ajaxSearchWorking');

  var url = CICFunc.BASE_URL + "?action=" + CICFunc.ACTION_AJAX_SEARCH + "&start=" + start;
  url += AJAXConn.addAjaxQryFlt2(text, 'description');

  // Create and send xml call
  vars = new Array();
  vars.abortFunction = AJAXConn.abortedAjaxQuery;
  vars.desc = "CIC Ajax Search";
  vars.functionToCall = CICFunc.cacheAjaxObjects;
  vars.timeout = 60000;
  vars.url = url;

  var id = AJAXConn.getXML(vars);
  CICFunc.prevAjaxId = id;

/*

  vars = new Array();
  vars.abortFunction = CICFunc.abortAjaxQuery;
  vars.objType = CICFunc;
  vars.desc = "Ajax Search";
  vars.functionToCall = CICFunc.cacheAjaxObjects;
  vars.timeout = 60000;
  vars.url = CICFunc.BASE_URL + "?action=" + CICFunc.ACTION_AJAX_SEARCH + "&description=" + text + "&start=" + start;
*/
}

// Functions for ajax search end
/////////////////////////////////////////////////////////////////////////////////////////

