// ****************************************************************************
// Networks In Motion, Inc.
//
// Copyright (c) 2008 Networks In Motion, Inc.
// All rights reserved.  This file and associated materials are the
// trade secrets, confidential information, and copyrighted works of
// Networks In Motion, Inc.
//
// This intellectual property is for the internal use only by Networks
// In Motion, Inc.  This source code contains proprietary information
// of Networks In Motion, Inc., and shall not be used, copied by, or
// disclosed to, anyone other than a Networks In Motion, Inc.,
// certified employee that has written authorization to view or modify
// said source code.
// ****************************************************************************

var _error          = null;
var loginProcess    = false;
var COOKIE_URL      = '/';
var TAB_SECTION_ID  = new Array("INTRO", "FEATURES", "DEVICES", "MAP_COVERAGE");
// ----------------------------------------------------------------------------
// Window Event Overloading
// ----------------------------------------------------------------------------

window.alert = function(txt) { customErrorDialog(txt); }

window.onload = function(event)
{
  onLoad(event);
}

//----------------------------------------------------------------------------
//Functions
//----------------------------------------------------------------------------

function forgotPass()
{
  var html = '';
  html += '<form id="ForgotPass" method="post">';
  html += '  <p>Please enter your User Name</p>';//TODO: i18n
  html += '  <div class="container">';
  html += '    <input id="IDToken4" name="IDToken4" tabindex="6" type="text" value=""/><br/>';//BR: Opera fix

  if (_browser.isIE6 || _browser.isIE7) {
	html += '<div id="iebutton" class="Button2" style="width: 1px;">';
  }

  html += '      <a id="FORGOT_PASS" class="Button2" tabindex="7" href="javascript:xmlForgotPass();">';
  html += '        <span>Submit</span>';
  html += '      </a>';

  if (_browser.isIE6 || _browser.isIE7) {
	html += '</div>';
  }

  html += '  </div>';
  html += '</form>';

  customDialog('DialogForgotPass', 'Forgot Password', html);
  document.getElementById('IDToken4').focus();
}

function forgotUser()
{
  var html = '';
  html += '<form id="ForgotUser" method="post">';
  html += '  <p>Please enter your email address:</p>';//TODO: i18n
  html += '  <div class="container"">';
  html += '    <input id="IDToken3" name="IDToken3" tabindex="8" type="text" value=""/><br/>';//BR: Opera fix

  if (_browser.isIE6 || _browser.isIE7) {
	html += '<div id="iebutton" class="Button2" style="width: 1px;">';
  }

  html += '      <a id="FORGOT_USER" class="Button2" tabindex="9" href="javascript:xmlForgotUser();">';
  html += '        <span>Submit</span>';
  html += '      </a>';

  if (_browser.isIE6 || _browser.isIE7) {
	html += '</div>';
  }

  html += '  </div>';
  html += '</form>';

  customDialog('DialogForgotUser', 'Forgot User Name', html);
  document.getElementById('IDToken3').focus();
}

function login()
{
  if (!loginProcess) {
    loginProcess = true;
    var password = document.getElementById('IDToken2');
    password.value = escape(encodeURI(password.value));
    document.forms[0].submit();
    closeDialog();
  }
}

function onKeyUp(event)
{
  var id;
  if (_browser.isIE) {
    id = event.srcElement.id;
  } else {
    id = event.target.id;
  }

  //Login
  if(id == 'IDToken1' || id == 'IDToken2' || id == 'LOGIN') {
    if (event.keyCode == 13) {
      var user = document.getElementById('IDToken1');
      var pass = document.getElementById('IDToken2');
      if (user.value.length > 0 && pass.value.length > 0) {
        login();
      } else {
        if (id == 'IDToken1' && user.value.length > 0) {
          pass.focus();
        }
        if (id == 'IDToken2' && pass.value.length > 0) {
          user.focus();
        }
      }
    }
  } else if (id == 'IDToken3' || id == 'FORGOT_USER') {
    if (event.keyCode == 13) {
      xmlForgotUser();
    }
  } else if (id == 'IDToken4' || id =='FORGOT_PASS') {
    if (event.keyCode == 13) {
      xmlForgotPass();
    }
  }
}

function onLoad(event)
{
  if (_error != null) {
    customErrorDialog(_error, "history.back()");
  }

  var path = location.pathname;
  var parameters = window.location.search.substr(1);
  if (path == '/'){
    updateTab("TAB_0");
  } else if (path.indexOf('main.html') > 0) {
    if (parameters != null && parameters.length > 0) {
      cookieSet('link', parameters);
    }
    customNotifyDialog(i18n['dialogTitle'], i18n['sessionLost'], i18n['ok'], 'sessionLost()');
    //customDialog('DialogLogin', 'Not Authorized', 'Login is required to view link');
  }


  var date = new Date();
  var copyright = '';
  
  copyright +=  '&copy;2000-'+ date.getFullYear() + ' Networks In Motion, Inc. All rights reserved';
  copyright +=  '<a href="http://www.networksinmotion.com" target="_blank">';
  copyright +=  '<img src="/images/logo_nim.gif" alt="Networks In Motion" />';
  copyright +=  '</a>';
  setInnerHTML('COPYRIGHT', copyright);

  cookieDelete('pref', COOKIE_URL, '');
  cookieDelete('NIMSID', COOKIE_URL, '');
}

function sessionLost()
{
  window.location = getUrl('/', false);
}

function showHide(id)
{
  var obj = document.getElementById(id);
  var parentElement = obj.parentNode;
  if (obj) {
    if (obj.style.display == 'none'){
      obj.style.display = 'block';
      parentElement.className = 'Selectedlink';
    } else {
      obj.style.display = 'none';
      parentElement.className = 'Featurelink';
    }
  }
  return;
}

function updateTab(tab)
{
  var id = tab.split('_')[1];

  var tabNodes = document.getElementById('TABS').childNodes;
  for ( var i = 0; i < tabNodes.length; i++) {
    if (tabNodes[i].id != null){
      var tabID = tabNodes[i].id.split('_')[1];
      var tabElement = document.getElementById(tabNodes[i].id);
      if (tabNodes[i].id == tab){
        tabElement.className = 'TabSelected';
        show(TAB_SECTION_ID[tabID], 'block');
      }else{
        tabElement.className = 'Tab';
        hide(TAB_SECTION_ID[tabID]);
      }
    }
  }
}

function xmlForgotPass()
{
  var username = document.getElementById('IDToken4').value;

  var request = 'forgot-password';
  var xml = '';

  xml +=  '<?xml version="1.0" encoding="UTF-8"?>';
  xml +=  '<request type="' + request                     + '">';
  xml +=    '<username>'    + escape(encodeURI(username)) +'</username >';
  xml +=  '</request>';

  closeDialog();
  var html = '<div style="width:250px;"></div>' + i18n['processRequest'];  
  customNotifyDialog(i18n['dialogTitle'], html, i18n['ok'], 'closeDialog();');

  xmlRequest(xml, xmlForgotPassResponse, request);
}

function xmlForgotPassResponse(xmlDoc, type, result)
{
  closeDialog();

  if (type != 'forgot-password') {
    alert('Invalid protocol');
    return;
  }

  var resultNode = xmlDoc.getElementsByTagName('result')[0];
  var msg = resultNode.getAttribute('msg');

  if (result == 0) {
	var html = '<div style="width:250px;"></div>';
	if (unescape(msg) == 'null') {
		html += i18n['passSentMsg'];
	} else {
		html += '&nbsp;&nbsp;&nbsp;&nbsp;';
		html += unescape(msg);
		html += '&nbsp;&nbsp;&nbsp;&nbsp;';
	}
	customNotifyDialog(i18n['forgotPassDialogTitle'], html, i18n['ok'], 'closeDialog();');
  } else {
    alert("[" + unescape(msg) + "]" + i18n['unRegNumber']);
  }
}

function xmlForgotUser()
{
  var email = document.getElementById('IDToken3').value;

  var request = 'forgot-user';
  var xml = '';

  xml +=  '<?xml version="1.0" encoding="UTF-8"?>';
  xml +=  '<request type="' + request                  + '">';
  xml +=    '<email>'       + escape(encodeURI(email)) +'</email>';
  xml +=  '</request>';

  closeDialog();
  var html = '<div style="width:250px;"></div>' + i18n['processRequest'];  
  customNotifyDialog(i18n['dialogTitle'], html, i18n['ok'], 'closeDialog();');
  
  xmlRequest(xml, xmlForgotUserResponse, request);
}

function xmlForgotUserResponse(xmlDoc, type, result)
{
  closeDialog();

  if (type != 'forgot-user') {
    alert('Invalid protocol');
    return;
  }

  var resultNode = xmlDoc.getElementsByTagName('result')[0];
  var msg = resultNode.getAttribute('msg');

	if (result == 0) {
	var html = '<div style="width:250px;"></div>';
	if (unescape(msg) == 'null') {
		html += i18n['userSentMsg'];
	} else {
		html += '&nbsp;&nbsp;&nbsp;&nbsp;';
		html += unescape(msg);
		html += '&nbsp;&nbsp;&nbsp;&nbsp;';
	}
	customNotifyDialog(i18n['forgotUserDialogTitle'], html, i18n['ok'], 'closeDialog();');
  } else {
    alert("[" + unescape(msg) + "]" + i18n['unRegNumber']);
  }
}

function xmlRequest(content, callback, request, sync)
{
  var xmlHttp = new XmlHttpRequest();
  xmlHttp.send('/ajax', content, xmlResponse, callback, sync);
}

function xmlResponse(callback, response)
{
  document.body.style.cursor = 'default';

  if (response == null || response.length == 0) {
    return;
  }

  var xmlDoc = xmlParse(response);
  if (xmlDoc) {
    var responseNode = xmlDoc.getElementsByTagName('response')[0];
    if (responseNode) {
      var type = responseNode.getAttribute('type');
      var resultNode = xmlDoc.getElementsByTagName('result')[0];
      var result = parseInt(resultNode.childNodes[0].nodeValue);
      if (result >= 0) {
        callback(xmlDoc, type, result);
      } else {
        switch (result)
        {
          case -1: // invalid utf-8
            alert(resultNode.getAttribute('msg'));
          break;
          case -2: // no session
            customNotifyDialog(i18n['dialogTitle'], resultNode.getAttribute('msg'), i18n['ok'], 'sessionLost()');
          break;
          case -3: // unknown request type
            alert(resultNode.getAttribute('msg'));
          break;
          case -4: // exception
            alert(resultNode.getAttribute('msg'));
          break;
          case -5: // custom failure
            callback(xmlDoc, type, result);
          break;
        }
      }
    } else {
      alert(i18n['invalidWebProtocol']);
    }
  } else {
    alert(i18n['invalidXMLDoc']);
  }
}
