if(!window.isAjaxForm) window.isAjaxForm = false;
if(!window.IsShowMessageOnError) window.IsShowMessageOnError = false;
if(!window.IsShowAlertOnError) window.IsShowAlertOnError = false;
if(!window.IsScrollTopOnError) window.IsScrollTopOnError = false;


/*Build the Window object to save the qForm Tab*/
var CurrentPageID = 0;
var ProcessingPage = new Object;
var CashedURL = new Object;
var qListTab = new Object;
var SaveURL = new Object;
var IsPageActionMenu = false;
var IsFirstClick = true;
var AutoSaveStartAt = null;
var AutoSaveTimer = null;
var AutoSaveCount = 0;
var AutoSaveTimeout = 0;
var AutoSaveSavedQuery = '';

var AutoSave_LoadForm_FieldItems = null;
var AutoSave_LoadForm_Section = 0;
var AutoSave_LoadForm_FieldCount = 0;
var AutoSave_LoadForm_Timer = null;
var AutoSave_LoadForm_Interval = 10;
var TheFormContent = '';
var isBuildQueryAll = false;

function CancelWizard() {
  if(window.name=='PopupIFrame') {
     parent.ClosePopup();
  } else if(window.opener) {
    window.close();
  } else {
    history.go(-1);
  }
}

function AutoSave_Load(ID) {
  var FORM = document.forms['WizardAjaxForm'];
  if(!FORM) FORM = document.forms['qEditForm'];
  //If no form, return
  if(!FORM) {
    alert('qForm is not found... Can not retrieve changes');
    return false;
  }  
  if(FORM['qForm_RecoveryItems']) {
    FORM['qForm_RecoveryItems'].selectedIndex = 0;
  }
  
  //Clear the timer if selected
  if(AutoSaveTimer) window.clearInterval(AutoSaveTimer);
  AutoSaveTimer = null;
  
  //find the instanse id and form name
  var qFormName = FORM['~qFormName'];
  var InstanseID = FORM['~InstanseID'];
  var req = new XMLHttpRequest();
  var URL = getBaseURL + 'wizard/autosave_load.asp?ID=' +ID 
  if(qFormName) URL += '&qFormName=' + escape(qFormName.value);
  if(InstanseID) URL += '&InstanseID=' + escape(InstanseID.value);
  URL += '&R=' + escape(Math.random())
  req.open('GET', URL, true);
  //Send the proper header information along with the request
  req.onreadystatechange = function(){
    if (req.readyState == 4) {
      AutoSave_LoadForm(FORM, req.responseText);
    }
  }
  req.send('');      
}

function AutoSave_LoadForm(FORM, Text) {
  if(AutoSaveTimer) window.clearInterval(AutoSaveTimer);
  AutoSaveTimer = null;
  
  AutoSave_LoadForm_FieldItems = Text.split('\r\n');
  AutoSave_LoadForm_Section = 0;
  AutoSave_LoadForm_FieldCount = 0;
  AutoSave_LoadForm_Timer = window.setTimeout('AutoSave_LoadForm_TimerFn()',AutoSave_LoadForm_Interval);
  var Elem = document.getElementById('qForm_CountDown');
  if(Elem) Elem.innerHTML = 'Loading... Please wait.';
}

function AutoSave_LoadForm_TimerFn() {
  var FORM = document.forms['WizardAjaxForm'];
  if(!FORM) FORM = document.forms['qEditForm'];
  var Elem = document.getElementById('qForm_CountDown');

  var i = AutoSave_LoadForm_FieldCount++;
  if(i >= AutoSave_LoadForm_FieldItems.length) {
    AutoSave_LoadForm_Section++;
    if(AutoSave_LoadForm_Section >= 3) {
      if(Elem) Elem.innerHTML = 'Complete recovering...';
      return;
    } else {
      AutoSave_LoadForm_FieldCount = 0;
      i = 0;
    }  
  } 
  var FieldItem = AutoSave_LoadForm_FieldItems[i];    
  if(Elem) Elem.innerHTML =  'Parse ' + (AutoSave_LoadForm_Section +1) +  ' of 3 / '  +
  'Field: ' + (AutoSave_LoadForm_FieldCount +1) + ' of ' + AutoSave_LoadForm_FieldItems.length; 
  
  /*
  document.title = 'AutoSave_LoadForm_Section: ' + AutoSave_LoadForm_Section + ', ' +
  'AutoSave_LoadForm_FieldCount: ' + AutoSave_LoadForm_FieldCount + ', ' +
  'i: ' + i + ', ' + 
  'FieldItem: ' + FieldItem;
  */
  
  var TypeAndField = FieldItem.split(':');
  var FieldType = TypeAndField.shift();
  var aFieldValue = TypeAndField.join(':').split('=');
  var FieldName = aFieldValue.shift();    
  var FieldValue = aFieldValue.join('=');
  FieldValue = FieldValue.replace(/\\n/g, '\n');
  FieldValue = FieldValue.replace(/\\r/g, '\r');
    //now check the field 
  var Expr = 'FORM' + FieldName;
  //Use try box when building the form field. If the Field does not exist
  //in the form, this may generate error.
  try {
    var FORMField = eval(Expr);
  } catch(e) {
    FORMField = null;
  }
  if(!FORMField) {
    AutoSave_LoadForm_Timer = window.setTimeout('AutoSave_LoadForm_TimerFn()',AutoSave_LoadForm_Interval);
    document.onkeypress = AutoSave_StartListen;
    return;
  }
  
  switch(AutoSave_LoadForm_Section){
  case 0: //first section
      switch(FieldType) {
      case 'hidden':
      case 'password':
      case 'text':
      case 'hidden':
      case 'textarea':
        FORMField.value = FieldValue;
        break;
      case 'checkbox':
      case 'radio':
        if(FieldValue=='checked') {
          FORMField.checked = true;
        } else {
          FORMField.checked = false;
        }
      }//switch(FieldType)
      break;
  case 1: //second section
      if(FORMField.className == 'InputAutoComplete') {
        var FName = FORMField.name;
        var FID   = FName.substr(2);
        //alert(FID);
        if(window.AutoComplete_ModifyClick) {
          AutoComplete_ModifyClick(FID, FORM[FID].value,FORM[FName].value); 
        }
      }
      break;       
  case 2: //Third Section
      switch(FieldType) {
      case 'hidden':
      case 'password':
      case 'text':
      case 'hidden':
      case 'textarea':
        FORMField.value = FieldValue;
        break;
      case 'checkbox':
      case 'radio':
        if(FieldValue=='checked') {
          FORMField.checked = true;
          if(FORMField.onclick) FORMField.onclick();
        } else {
          FORMField.checked = false;
          if(FORMField.onclick) FORMField.onclick();
        }
        break;
      case 'select-multiple':
        var aFieldValue = unescape(FieldValue).split(',');
        FORMField.options.length = aFieldValue.length;
        for(var j = 0; j < aFieldValue.length; j++) {
          var aFieldValue2 = unescape(aFieldValue[j]).split('=');        
          var ListVal = aFieldValue2.shift();
          var ListTxt = aFieldValue2.join('=');
          FORMField.options[j].value = ListVal;
          FORMField.options[j].text = ListTxt;          
        }
        break;
      case 'select-one':      
        var aFieldValue = unescape(FieldValue).split('=');
        var ListVal = aFieldValue.shift();
        var ListTxt = aFieldValue.join('=');
        FORMField.value=ListVal;
        FORMField.text = ListTxt;        
      }//switch(FieldType)  
    break;
  }//switch(AutoSave_LoadForm_Section)   
  AutoSave_LoadForm_Timer = window.setTimeout('AutoSave_LoadForm_TimerFn()',AutoSave_LoadForm_Interval);
  document.onkeypress = AutoSave_StartListen;
  return;  
}

function AutoSaveTimerFn() {
  var Elem = document.getElementById('qForm_CountDown');
  var Msg = '';
  if(!Elem) return;
  var AutoSaveCount = (new Date()) - AutoSaveStartAt;
  AutoSaveCount = AutoSaveTimeout - parseInt(AutoSaveCount/2000);  
  if(AutoSaveCount < 1) {
    //Msg = 'Checking and saving form...';
    if(AutoSaveTimer) window.clearInterval(AutoSaveTimer);
    AutoSave_SaveForm();
  } else {
    var MyMsg = document.getElementById('qForm_MsgCountDown');
    if(MyMsg) Msg = MyMsg.innerHTML;
    if(Msg=='') Msg = 'Autosave in #remain#' + AutoSaveTimeout + ', AutoSave: ' + (AutoSaveCount);
    Msg = Msg.replace('#remain#', AutoSaveCount);
    Msg = Msg.replace('#elapsed#', AutoSaveTimeout - AutoSaveCount);
    Msg = Msg.replace('#total#', AutoSaveTimeout);
  }
  if(Msg != '') Elem.innerHTML = Msg;
}

function AutoSave_SaveNow() {
  //Allow manual save
  var Elem = document.getElementById('qForm_CountDown');  
  if(AutoSaveTimer) window.clearInterval(AutoSaveTimer);
  AutoSaveTimer = null;
  if(Elem) Elem.innerHTML = 'Running Manual Save...';
  
  AutoSave_SaveForm();  
}

function AutoSave_SaveForm() {
  var FORM = document.forms['WizardAjaxForm'];
  if(!FORM) FORM = document.forms['qEditForm'];
  var Query = '';
  var IndexedObject = new Object();
  for (var i = 0; i < FORM.length; i++){
    var Index = '';
    var Value = '';
    var FormName = FORM[i].name + ''; 
    if (FormName != '' && FormName != 'qForm_RecoveryItems') {
      if(FORM[FormName].length) {
        if(IndexedObject[FormName]+'' == 'undefined') IndexedObject[FormName] = -1;
        IndexedObject[FormName] ++;
        Index = '[' + IndexedObject[FormName] + ']';
      }
      switch(FORM[i].type + '') {
      case 'select-multiple':
        Index = ''; //FORM[FormName].length will return 0 even though there is only one item
        Value = WizardFormSelectBox(FORM[i], true);
        break;
      case 'select-one':
        Index = ''; //FORM[FormName].length will return 0 even though there is only one item
        Value = WizardFormSelectBox(FORM[i], false);
        break;
      case 'radio':
      case 'checkbox':
        if(FORM[i].checked) Value = 'checked';
        break;
      case 'password':
      case 'text':
      case 'hidden':
      case 'textarea':
        Value = FORM[i].value;
        break;
      case 'button':
      case 'submit':
      case 'undefined':
        isBuildQuery = false;
        break;
      default:
        Value = FORM[i].value;
        alert('Wizard Submit error for field :' + FORM[i].name +
        '\nField Type:' + FORM[i].type + '\n'+
        '\nPlease fix it in wizard.js');
        break;
      }     
      if(Query != '') Query += '&';
      Query += escape(FORM[i].type + ':[\'' + FormName + '\']' + Index) + '=' + escape(Value);
    }//if (FormName != '')
  }//for (var i = 0; i < FORM.length; i++){
  if(AutoSaveSavedQuery != Query) {
    var Elem = document.getElementById('qForm_CountDown');
    if(Elem) Elem.innerHTML = 'Saving information to server...';
    AutoSaveSavedQuery = Query;

    var req = new XMLHttpRequest();
    var URL = getBaseURL + 'wizard/autosave.asp';
    req.open('POST', URL, true);
    //Send the proper header information along with the request
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", Query.length);
    req.setRequestHeader("Connection", "close");
    req.onreadystatechange = function(){
      if (req.readyState == 4) {
        AutoSave_SavedForm(req.responseText);
        AutoSave_StartTimer();
      }
    }
    req.send(Query);    
    //Restart the timer after information is saved to the server
  } else {
    //if nothing to save, wait for pressing the key
    var Elem = document.getElementById('qForm_CountDown');
    if(Elem) Elem.innerHTML = 'Waiting for changes...';    
    document.onkeypress = AutoSave_StartListen;
  }
}

function AutoSave_LoadRecovery() {
  var FORM = document.forms['WizardAjaxForm'];
  if(!FORM) FORM = document.forms['qEditForm'];
  var req = new XMLHttpRequest();
  var URL = getBaseURL + 'wizard/autosave.asp';
  var Query = 
    'hidden:[\'~InstanseID\']=' + FORM['~InstanseID'].value + '&' +
    'hidden:[\'~qFormName\']=' + FORM['~qFormName'].value + '&' +
    'IsSave=0';            
    
    req.open('POST', URL, true);
    //Send the proper header information along with the request
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", Query.length);
    req.setRequestHeader("Connection", "close");
    req.onreadystatechange = function(){
      if (req.readyState == 4) {
        AutoSave_SavedForm(req.responseText);
      }
    }
    req.send(Query);    

}

function AutoSave_StartTimer() {
  //Restart the timer
  AutoSaveStartAt = new Date();
  AutoSaveTimer = window.setInterval('AutoSaveTimerFn()',200);     
}

function AutoSave_SavedForm(ResponseText) {
  //-- parse the response and display  
  if(ResponseText.substr(0, 7) == 'ERROR\r\n') {
    var Msg = '<font color="red">' + ResponseText.substr(8) + '</font>';
    var Elem = document.getElementById('qForm_CountDown');    
    if(Elem) Elem.innerHTML = Msg;
  } else {
    var FORM = document.forms['WizardAjaxForm'];
    if(!FORM) FORM = document.forms['qEditForm'];
    var ListBox = FORM['qForm_RecoveryItems'];    
    if(!ListBox) return;
    
    //load items to the list box
    ListBox.options.length = 1;
    var aOptions = ResponseText.split('\r\n');
    ListBox.options.length = aOptions.length;
    for(var i = 0; i < aOptions.length-1; i++) {
      var Opt = aOptions[i].split(',');
      ListBox.options[i+1].value = Opt.shift();
      ListBox.options[i+1].text = Opt.join(',');
    }
  }  
}

function qFormWindowOnLoad(iAutoSaveTimeout) {
  //if autorun is already been saved run it now.
  if(qFormSavedFn) qFormSavedFn();
  var Elem = document.getElementById('qForm_AutoSave');
  AutoSaveTimeout = iAutoSaveTimeout;  
  //AutoSave_LoadRecovery();
  //document.captureEvents(Event.KEYPRESS);
  //document.onkeypress=catchkey;  
  document.onkeypress = AutoSave_StartListen;
}

function AutoSave_StartListen() {
  AutoSave_StartTimer();
  //document.title = 'key :' + Math.random();
  document.onkeypress = null;
}

/* Functions for loading the tab */
function Tab(Name, URL, isNotAvailable) {
  var MyTab = new Object();
  MyTab.name = Name;
  MyTab.isVisible = true;
  MyTab.isNotAvailable = (isNotAvailable==1);
  MyTab.URL = URL;
  return MyTab;
}

function getResponse(URL, theButton) {
  // this function will load the url and return
  // any message received from the URL
  var FormQuery = getFormQuery();
  var Response = new Object;

  if(URL.substring(0,7) != 'http://') URL = BaseURL + URL;
  if (FormQuery != '') FormQuery += '&';
  FormQuery += 'FromWizard=1';

  //add the value of button, if it is valid
  if(theButton && theButton.type && theButton.type == 'button') {
    FormQuery += '&' + theButton.name + '=' + escape(theButton.value);
  }

  var req = new XMLHttpRequest();
  //alert('getResponse URL: ' + URL);
  req.open('POST', URL, false);
  //Send the proper header information along with the request
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  req.setRequestHeader("Content-length", FormQuery.length);
  req.setRequestHeader("Connection", "close");
  req.send(FormQuery);
  //Reading response from the server
  if (req.readyState == 4) {
    var Text = req.responseText;
    //alert(Text);
    Response = parseResponse(Text);
  }
  return Response;
}

function parseResponse(Text) {
  var Response = new Object;
  var Items = Text.split('\r\n');
  switch(Items[0]) {
  case 'OK':
  case 'ERROR':
  case 'REDIRECT':  
    Response.status = Items[0];
    Items[0]='';
    break;
  default:
    Response.status = 'CONTENT';
  }
  Response.text = Items.join('\r\n');
  return Response;
}

function getFirstTab(TabValue) {
  var nTab = setget_ActiveTabID(0);
  if(nTab > 0 ) {
    return nTab;
  } else {
    return TabValue;
  }
  
  //Try to parse automatic switching of tab
  //if the action = new, then do not create
  var ActTab = getSession('ActiveTab');
  var QueryID = top.location.search.substring(1);  
  var qIndex = QueryID.indexOf('action=new');
  if( qIndex >= 0) ActTab = '';  
  ActTab = parseInt(ActTab);
  if(!isNaN(ActTab)) TabValue = ActTab;
  return TabValue;
}

function ActiveNextTab(theButton) {
  var ThisTabID = getActiveTab();
  var NextTabID = ThisTabID+1
  var NextTab = 'WizardTab' + NextTabID;
  if (document.getElementById(NextTab)) {
    ActiveTab(NextTabID, NextTabID, '', theButton)
  }
}

function getTab(TheName) {
	TheName = TheName.replace(/^\s+/g,'-');
	TheName = TheName.replace(/\s+$/g,'-');
	for(var i = 1; i <= 10; i++) {
	  var tTab = document.getElementById('WizardTab' + i);
	  if (! tTab) return null;
		var TabName = tTab.textContent;
    if(!TabName) TabName = tTab.innerText;
  	TabName = TabName.replace(/^\s+/g,'');
  	TabName = TabName.replace(/\s+$/g,'');
    if(TabName == TheName) return tTab;
  }
}

function getFormQuery() {
  var FORM = document.forms['WizardAjaxForm'];
  var CheckedFields = new Object();
  var Query = '';
  for (var i = 0; i < FORM.length; i++){
    var isBuildQuery = true;
    var Value = '';
    switch(FORM[i].type + '') {
    case 'select-multiple':
      Value = WizardFormSelectAll(FORM[i]);
      break;
    case 'radio':
    case 'checkbox':
	    isBuildQuery = false;	    
	    if(!CheckedFields[FORM[i].name]) CheckedFields[FORM[i].name] = '';
      if(FORM[i].checked) {
      	if(CheckedFields[FORM[i].name] != '') CheckedFields[FORM[i].name]+=',';
      	CheckedFields[FORM[i].name] += FORM[i].value;
      }
      break;
    case 'password':
    case 'text':
    case 'hidden':
    case 'textarea':
    case 'select-one':    
      Value = FORM[i].value;
      break;
    case 'button':
    case 'submit':
    case 'undefined':
      isBuildQuery = false;
      break;
    default:
      Value = FORM[i].value;
      alert('Wizard Submit error for field :' + FORM[i].name +
      '\nField Type:' + FORM[i].type + '\n'+
      '\nPlease fix it in wizard.js');
      break;
    }
    
    if(isBuildQuery) {
      if(isBuildQueryAll || Value != '') {
        if(Query != '') Query += '&';
        Query += FORM[i].name + '=' + escape(Value);
      }//if(isBuildQueryAll || Value != '')
    }//if(isBuildQuery)
  }//for
  
  
  //build for check boxes
  for(var I in CheckedFields) {
  	Value = CheckedFields[I];
    if(isBuildQueryAll || Value != '') {
      if(Query != '') Query += '&';
      Query += I + '=' + escape(Value);
    }//if(isBuildQueryAll || Value != '')  	
  }
  
  return Query;
}

function showLoading(ELEM) {
	
  var Loading = document.getElementById('TB_IFrame');
  var height = (ELEM ? ELEM.clientHeight : 0);
  if(height == 0) height = ELEM.offsetHeight;

  var ErrInfo = document.getElementById('WizardErrorInfo');
  if(ErrInfo) {
    var mheight = ErrInfo.clientHeight;
    if(mheight == 0) mheight = ErrInfo.offsetHeight;
    height+= mheight;
  }

  var header = document.getElementById('header');
  if(header) {
    var mheight = header.clientHeight;
    if(mheight == 0) mheight = header.offsetHeight;
    height+= mheight;
  }
	//Loading.style.left = ELEM.offsetLeft + 'px';

  if(height < 100) height = 200;

  var width = (ELEM ? ELEM.clientWidth : 0);
  if (width == 0) width = ELEM.offsetWidth;
  width = (width == 0 ? '100%' : width + 'px');

  if (Loading){
    Loading.style.display = 'block';
    Loading.style.width = width;
    Loading.style.height = height + 'px';
    Loading.style.zIndex = 3000;
  }
  	//alert('Load URL...');
}


function clearHash() {
  if(document.location.hash == '') return;
	//If a popup, then do not change the hash header	
	if(window.opener) return false;
	
  var Doc = top.document.location;
  var URL = Doc.protocol + '//' + Doc.hostname + Doc.pathname + Doc.search;
  Doc.href = URL ;// + '#';
}
function hideLoading() {
  var Loading = document.getElementById('TB_IFrame');
  if (Loading) Loading.style.display = 'none';
}
/* Other Processes */



function showList(name){
  showLoading(null);
  window.frames[name].scrolling = 'auto';
  window.frames[name].location.href = SaveURL[name];
}

function LoadEventCalendar(qViewID, name){
  if(name == '') name = 'T' + CurrentPageID + '_qListTab_' + qViewID
  var Loading = document.getElementById('TB_IFrame');
  var Filter = qListTab['T' + CurrentPageID + '_' + qViewID + '_filter'];
  SaveURL[name] = getBaseURL + 'qBook/show_list.asp?qViewID=' + qViewID + '&filter=' + escape(Filter);
  var Filter = 'T' + CurrentPageID + '_' + qViewID + '_filter';
  if (Loading){
    Loading.style.display = 'block';
    Loading.style.width = '100%';
    Loading.style.height = '600px';
  }

  var MyqListTab = document.getElementById(name);
  if(MyqListTab) MyqListTab.style.height = '500px';
  window.frames[name].scrolling = 'no';

  var URL = getBaseURL + 'qBook/iCal/weekplanner.asp' +
    '?qViewID=' + escape(qViewID) +
    '&filter=' + escape(qListTab[Filter]);
  window.frames[name].location.href = URL
}

function ActivateTabTo(Caption) {
  Caption = Caption.toLowerCase();
  for(var i = 4; i <= 12; i++) {
    var Elem = document.getElementById('WizardTab' + i);
    if(!Elem) return;
    var Text = Elem.childNodes[0].innerHTML.toLowerCase();
    if(Text == Caption) {
      TabID = i;
      Elem.onclick();
      return;
    } //if(Text == Caption)
  }//for(var i = 4
}

function ActiveFirstTab(ActiveTabID) {
  ActiveTabID = getFirstTab(ActiveTabID);
  var Elem = document.getElementById('WizardTab' + ActiveTabID);
  if(!Elem) Elem = document.getElementById('PageTab' + ActiveTabID);
  if(Elem) Elem.onclick();
}

function ActiveTab(TotalTabs, ActiveTabID, qListID, thisButton, qFormID){
  var FixedqFormID = qFormID + '';
  if(FixedqFormID == '1') FixedqFormID = 'undefined';
  var IDPrefix = (FixedqFormID == 'undefined' ? '' : FixedqFormID + '_');
  //alert('FixedqFormID: ' + FixedqFormID + '\nIDPrefix' + IDPrefix);
  
  var ActiveTab = 'Tab' + IDPrefix + ActiveTabID;
  var MainTab = document.getElementById('WizardMainDIV');
  //setSession('ActiveTab',ActiveTabID);
  //if(!IsFirstClick) clearHash();
  IsFirstClick = false;
  
  /*
  alert(
  'IDPrefix: ' + IDPrefix + '\n' +
  'Calling Active Tab for: ' + ActiveTabID + '\n' +
  'TotalTabs: ' + TotalTabs  + '\n' +
  'ActiveTabID: ' +ActiveTabID  + '\n' +
  'qListID: ' + qListID  + '\n' +
  'thisButton: ' + thisButton
  );
  */
  
  
  var TabName = '';
  //qListID = (qListID + '')
  //ActiveTabID = ActiveTabID.parseInt(ActiveTabID);
  if (ActiveTabID > TotalTabs || ActiveTabID < 1) return;
  CurrentPageID = ActiveTabID;

  //for AJAX Processing
  //if the activate tab is > 1, then it should submit
  //the last tab. If it return OK, then move to next tab
  var ThisTabID = getActiveTab();

  if(MainTab) {
    var ErInfo = document.getElementById('WizardErrorInfo');
    if(ThisTabID > 0 && (ActiveTabID > ThisTabID) ) {
      var URL = TabArrays[ThisTabID-1].URL;
      showLoading(MainTab);
      var Response = getResponse(URL, thisButton);
      switch(Response.status) {
      case 'OK':
        ErInfo.innerHTML = '';
        break;
      case 'REDIRECT':
        var URL = Response.text + '';
        URL = URL.replace(/\r\n/g, '');
        document.location.href = URL;
        return false;
      case 'ERROR':
        if(window.IsShowMessageOnError || (!window.IsShowMessageOnError && !window.IsScrollTopOnError && !window.IsShowAlertOnError)) {        
	        ErInfo.style.display = 'block';
	        if(ErInfo) ErInfo.innerHTML = Response.text;
	        hideLoading();
        }
        if(window.IsScrollTopOnError) window.scrollTo(0,0);        
        if(window.IsShowAlertOnError)   {
			    alert(Response.text);   
	        hideLoading();
		    }        
        return false;
      default:
        ErInfo.style.display = 'none';
        MainTab.innerHTML = PutInForm(Response.text);
        hideLoading();
        return false;
      }//switch(Response.status)
    }//if(ThisTabID > 0)
  }//if(MainTab)



  for (var i = 1; i <= TotalTabs; i++){
    var Item = document.getElementById('WizardTab' + IDPrefix + i);
    if (! Item) Item = document.getElementById('PageTab' + IDPrefix + i);
    var tTab = document.getElementById('WizardPage' + IDPrefix + i);
    var tPage = document.getElementById('WizardPage' + IDPrefix + i);
    /*
    alert('i=' + i + ', ActiveTabID:' + ActiveTabID + '\n' + 
    	', Item: ' + Item + '\n' + 
    	', tTab: ' + tTab + '\n' + 
    	'(tTab || MainTab):' + (tTab || MainTab));
    */
    if (Item && (tTab || MainTab)){
      Item.className = (i + '' == ActiveTabID ? 'active' : '');
      if(tTab) tTab.style.display = (i == ActiveTabID ? 'block' : 'none');
      if (i == ActiveTabID) {
        if (tPage) tPage.style.display = 'block';
        TabName = Item.textContent;
        if(!TabName) TabName = Item.innerText;
        if (ProcessingPage['P' + IDPrefix + i]) LoadURL(ProcessingPage['P' + IDPrefix + i], IDPrefix + i);
        
      } else {
        if (tPage) tPage.style.display = 'none';
      } //if (i == ActiveTabID)
    } else {
      //alert('Missing: Item && (tTab || MainTab)'); 
    }//if (Item && tTab)

  }
  WizardLoadButton(ActiveTabID);

  //return false;

  var Pfx = 'T' + ActiveTabID + '_'
  if (qListID != '' && (qListID + '') != 'undefined'){
    
    //Read the saved info
    var SavedInfo = document.location.hash;
    if(SavedInfo.substr(0,1) == '#') SavedInfo = SavedInfo.substr(1);
    SavedInfo = unescape(SavedInfo)

    var FRAME = window.frames[Pfx + 'qListTab_' + qListID];
    var URL = qListTab[Pfx + qListID];
    var Filter = qListTab[Pfx + qListID + '_filter']
    var qListDiv = document.getElementById(Pfx + 'qListDiv_' + qListID);
    var MyqListTab = document.getElementById(Pfx + 'qListTab_' + qListID);
    var DefaultView = '';
    DefaultView = qListTab[Pfx + qListID + '_DefaultView'];
    //if(!DefaultView || DefaultView == '') DefaultView = getParam(SavedInfo,'CalendarView');
    
    var lSearch = unescape(top.location.hash.toLowerCase());
    LoadActionForTab(qListID, TabName, Pfx + 'qListTab_' + qListID);
    if(DefaultView) {
      if (DefaultView != "") {
        LoadEventCalendar(qListID, Pfx + 'qListTab_' + qListID)
        //so that the show list will start function
        qListTab[Pfx + qListID + '_DefaultView'] = "";
        return;
      }
    }

    var Height = MyqListTab ? MyqListTab.height : 0;
    if (! Height) Height = 150;
    //qListDiv.style.display = 'block';
    qListDiv.style.position = 'absolute';
    qListDiv.style.height = Height;
    var eURL = FRAME.document.location.href.toLowerCase();
    var Query = window.location.search.substring(1);
    var MyURL;

    //if(SavedInfo == '') {
      MyURL = URL + '&Filter=' + escape(Filter) + '&' + Query;
    //} else {
    //  MyURL = getBaseURL + 'qBook/show_list.asp?' + SavedInfo;
    //}
    //MyURL = MyURL.toLowerCase();
    
   /* alert(
    'MyURL: ' + MyURL + '\n\n' +
    'qListID: ' + qListID+ '\n\n' +
    SavedInfo + '\n\n' +
    'URL: ' + FRAME.document.location.href);    
    */
    
    if (FRAME.document.location.href == 'about:blank' || eURL != MyURL){
      top.location.hash = '';
      FRAME.document.location.href = MyURL;
     } else{
       WizardLoadButton(ActiveTabID);
       hideLoading();
		   resizeIframe(Pfx + 'qListTab_' + qListID);
    } //FRAME
    
  } else { //if (qListID != '' && (qListID + '') != 'undefined')
    if(MainTab) { //if (qListID != '' && (qListID + '') != 'undefined')
      var URL = TabArrays[ActiveTabID-1].URL;
      LoadURL(URL,ActiveTabID, ThisTabID);
    }  else {
      //Load any action menu for the tab
   	  LoadActionForTab('0', TabName, '');
   	}
   	setget_ActiveTabID(ActiveTabID);
  }  
  //clearHash();
}


function getActiveTab() {
  var ActiveTab = 0;
  for (var i = 1; i <= 10; i++){
    var tTab = document.getElementById('WizardTab' + i);
    if (!tTab) break;
    if(tTab.className == 'active') {
      ActiveTab = i;
      break;
    }//if(tTab.className == 'active')
  }//for
  return ActiveTab;
}

function LoadActionForTab(qListID, TabName, IFrameName) {

	var DIV = document.getElementById('Wizard_ActionForTab');
	if(!DIV) return;

	// create HTTP Request Object
  var req = new XMLHttpRequest();
  if (! req) return;
  req.abort(); //abort any previous request send
	if(qListID == '0') {
	  if(!IsPageActionMenu) {
	    DIV.style.display = 'none';
	  } else {
	    if(document.getElementById('Wizard_ActionForTab_'+ TabName.trim() +'_Content')){
     	  DIV.innerHTML =
    	  '<div>' +
    	  '<h1>' + TabName + '</h1>\n' +
    	  '<div id="Wizard_ActionForTab_Content">'+
    	  document.getElementById('Wizard_ActionForTab_'+ TabName.trim() +'_Content').innerHTML +'</div>' +
    	  '</div>';
    	}
	  }
	  return;
	} else { //if(qListID == '0')
	  DIV.innerHTML =
	  '<div>' +
	  '<h1>' + TabName + '</h1>\n' +
	  '<div id="Wizard_ActionForTab_Content">...</div>' +
	  '</div>';
    var URL = getBaseURL + 'qBook/getMenu.asp?qListID=' + qListID + '&IFrame=' + escape(IFrameName);
    req.open('GET', URL, true);
    req.onreadystatechange = function(){
      if (req.readyState == 4) {
        var Text = req.responseText;
        if(Text != 'EOF') {
      	  DIV.style.display = 'block';
          document.getElementById('Wizard_ActionForTab_Content').innerHTML = req.responseText;
        } else {
          DIV.style.display = 'none';
        }
      }
	  } //req.onreadystatechange
	  req.send('');
	}	//if(qListID == '0')
}

function WizardActivateTab(TheLayerID){
  var isNextPage = false;

  //-- if the current page is hidden, find the
  //-- next available page;
  for (var i = TheLayerID; i <= 10; i++){
    var tTab = document.getElementById('WizardTab' + i);

    if (! tTab){
      break;
    }
    if (tTab.style.display == 'none') {
    //-- find the next item;
        } else {
      isNextPage = true;
      TheLayerID = i;
      break;
    }
  }

  if (! isNextPage){
    WizardProcessForm(document.forms['qEditForm']);
    return;
  }

  CurrentPageID = TheLayerID;

  for (var i = 1; i <= 10; i++){
    var tPage = document.getElementById('WizardPage' + i);
    var tTab = document.getElementById('WizardTab' + i);
    //alert(tPage)
    if (! tTab) break;
    if (tTab.style.display == '' || tTab.style.display == 'inline'){
      tTab.className = (TheLayerID == i ? 'active' : '');
      if (TheLayerID == i){
        if (tPage) tPage.style.display = 'block';
        if (ProcessingPage['P' + i]) LoadURL(ProcessingPage['P' + i], i);
      } else{
        if (tPage) tPage.style.display = 'none';
      } //if(TheLayerID == i )
    }   //if(tTab.display != 'none')
  }     //for
  WizardLoadButton(CurrentPageID);
}

function WizardProcessForm(FORM){
  for (var i = 0; i < FORM.length; i++){
    if (FORM[i].type == 'select-multiple') WizardFormSelectAll(FORM[i]);
  }
  if(window.WizardBeforeSubmit) if(!WizardBeforeSubmit(FORM)) return;
  FORM.submit();
  for (var i = 0; i < FORM.length; i++){
    FORM[i].disabled = true;
  }
}

function WizardFormSelectAll(ITEM){
  var Value = '';
  for (var i = 0; i < ITEM.options.length; i++){
    ITEM.options[i].selected = true;
    if(Value != '') Value += ',';
    Value += ITEM.options[i].value;
  }
  return Value;
}

function WizardFormSelectBox(ITEM, IsMulti){
  var Value = '';
  for (var i = 0; i < ITEM.options.length; i++){
    if(IsMulti || ITEM.options[i].selected) {
      if(Value != '') Value += ',';
      var thisVal = ITEM.options[i].value;    
      var thisTxt = ITEM.options[i].text;
      thisVal = thisVal.replace(/,/g,'&comma;');
      thisTxt = thisTxt.replace(/,/g,'&comma;');
      Value = Value + escape(thisVal + '=' + thisTxt);
    }
  }
  return Value;
}

function WizardSetTab(TheLayerID, IsShow){
  var tTab = document.getElementById('WizardTab' + TheLayerID);
  if (! tTab) return;
  tTab.style.display = IsShow ? 'inline' : 'none';
  WizardSetTab_Post(TheLayerID, IsShow);
  WizardLoadButton(CurrentPageID);
}

function WizardSetTab_Post(TheLayerID, IsShow) {
  return false;
}

function WizardLoadButton(CurrentPage){
  var TotalPages = 0;
  var Button = document.getElementById('BtnNext');
  var pButton = document.getElementById('BtnPrev');
  if (! Button) return;

  for (var i = CurrentPage + 1; i <= 10; i++){
    var tTab = document.getElementById('WizardTab' + i);
    if (tTab){
      if (tTab.style.display == 'inline' || tTab.style.display == '') TotalPages++;
    } else{
      break;
    }
  } //for
  /*
  alert('WizardLoadButton(CurrentPage:' + CurrentPage + '\n' +
  'TotalPages: ' + TotalPages + ');');
  */
  if (TotalPages > 0){
    //Button.value = 'Next >>';
  } else{
    //Button.value = 'Finish';
  }
  pButton.disabled = (CurrentPage == 1);
  Button.disabled = !(TotalPages > 0);
}

function WizardLoadTab(ID) { }

function WizardLoadTabDone(ID) { }

function LoadURL(URL, ID, ThisTabID) {
  var ELEM = document.getElementById('WizardPage' + ID);
  var MainDiv =  document.getElementById('WizardMainDIV')
  if(!ELEM) ELEM = MainDiv;
  showLoading(ELEM);


  // if(document.all) ELEM.innerHTML = 'loading...';
  // custom processing rules will be added here.
  WizardLoadTab(ID);

  var LastLoadedURL = "";
  //window.open(URL);

  if(MainDiv) {

  } else if (ProcessingPage['ChangedURL' + ID]){
    //if custom process has changed the URL, then
    if (ProcessingPage['LasLoaded' + ID]) LastLoadedURL = ProcessingPage['LasLoaded' + ID];
    URL = ProcessingPage['ChangedURL' + ID];
    if (LastLoadedURL == URL){
      hideLoading();
      WizardLoadTabDone(ID);
      return;
    }
  } else{
    //- do not process loaded ASP Pages.
    if (ProcessingPage['Processed' + ID]){
      hideLoading();
      WizardLoadTabDone(ID);
      return;
    }
  }

  var FORMQUERY = ProcessingPage['AdditionalParam' + ID];
  if(FORMQUERY) {
   // URL += (URL.indexOf('?') > 0 ? '&' : '?') + FORMQUERY;
   // above line will not work if the content is too long so it is changing to form posting 
   TheFormContent = FORMQUERY;
  }

  ProcessingPage['LasLoaded' + ID] = URL;
  if(URL.substring(0,7) != 'http://') {
    URL = BaseURL + URL;
  }

  var TheReq = new XMLHttpRequest();
  if (! TheReq) return;
  TheReq.abort(); //abort any previous request send
  TheReq.open('POST', URL, true);
  TheReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  TheReq.setRequestHeader("Content-length", TheFormContent.length);
  TheReq.setRequestHeader("Connection", "close");
  
  //Send the proper header information along with the request
  TheReq.onreadystatechange = function(){
  if (TheReq.readyState == 4) {
      ProcessLoadTab(ELEM, ID, TheReq.responseText, ThisTabID);
    }
  }
  TheReq.send(TheFormContent);
}

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

function  ProcessLoadTab(ELEM, ID, Text, ThisTabID) {
  var Response = parseResponse(Text);

  var ErInfo = document.getElementById('WizardErrorInfo');
  switch(Response.status) {
  case 'OK':
    break;
  case 'ERROR':
    ErInfo.style.display = 'block';
    if(ErInfo) ErInfo.innerHTML = Response.text;
    for (var i = 1; i <= 10; i++){
      var Item = document.getElementById('WizardTab' + i);
      if(Item) Item.className = (i + '' == ThisTabID ? 'active' : '');
    }
    break;
  default:
    //document.title = 'Loading URL: ' + ID;
    if(ErInfo) if(ErInfo.innerHTML == '') ErInfo.style.display = 'none';
    Text = PutInForm(Text);
    try{
      ELEM.innerHTML = Text;
    } catch (e){
      ELEM.innerText = Text;
    }
    ProcessingPage['Processed' + ID] = 1;
    WizardLoadTabDone(ID);
  }
  hideLoading();
}

function PutInForm(Text) {
  if(!window.isAjaxForm) {
    return Text;
  } else if(Text.indexOf('<form') < 1) {
    Text =
    '<form style="margin:0px;padding:0px;" method="POST" action="about:blank" name="WizardAjaxForm">\n'+
    Text +
    '</form>';
  }
  return Text;
}


function setget_ActiveTabID(TabID) {
  var Hash = document.location.hash;
  if(Hash != '') Hash = Hash.substring(1);

  var LastTabID = 0;
  var nHash = '';
  var qParam = new Object();
  var isHashSet = false;
  var Params = Hash.split('&');
  for(var i = 0; i < Params.length; i++) {
    var NameValue = Params[i].split('=');
    if(NameValue.length == 2) {
      var Name = NameValue[0].toLowerCase();
      var Value = NameValue[1];
      if( Name == 't') {
        LastTabID = Value;
        if(TabID != 0) Value = TabID;
        isHashSet = true;
      }//if    
      if(nHash != '') nHash += '&';
      nHash = nHash + Name + '=' + Value;
    }//if(NameValue.length)
  }
  if(!isHashSet) {
    if(nHash != '') nHash = '&' + nHash;
    nHash = 't=' + TabID + nHash;
  }
  if(TabID > 0) {
    var nURL = top.location.pathname + top.location.search + '#' + nHash;
    //alert(nURL);    
    top.location.replace(nURL);
    //top.location.hash = nHash;  
  }
  LastTabID = parseInt(LastTabID);
  if(isNaN(LastTabID)) LastTabID = 0;  
  return LastTabID;
}

function getRefSession() {
  var PageRefURL = document.location.pathname.toLowerCase();
  var re = new RegExp("[#=:?/\\\\]", "g");
  PageRefURL = PageRefURL.replace(re,'~');
  return PageRefURL;
}

/* Session Variables */
var refSession = '';
var PageObj = parseSession(top.name);
var MyInfo = '';

function parseSession(SessionVars) {
  var Obj = new Object();
  if (refSession == '') refSession = getRefSession();
  try{
    var re = new RegExp("(" + refSession + ")\\?(.*?)#(.*)");
    var aVars = SessionVars.split('\r\n');
    for(var i = 0; i < aVars.length-1; i++) {
      var myvar = aVars[i];
      var m = myvar.match(re);
      if(m) {
        var VarName = m[1] + '?' + m[2];
        Obj[VarName] = m[3];
      } else {
        if(MyInfo+'' == 'undefined') MyInfo = '';
        MyInfo = MyInfo + aVars[i] + '\r\n';
      }
    }
    //Add listner for saving the window;
    if(window["addEventListener"]){
      addEventListener("unload",saveSession,false)
    } else if(window["attachEvent"]){
      window.attachEvent("onunload",saveSession)
    }
    window.PageObjExtra = MyInfo;
  } catch(e) {
    //nothing..
  }
  return Obj;
}

function getSession(VarName) {
  if (refSession == '') refSession = getRefSession();
  if(PageObj.length == 0 && top.name != '') PageObj = parseSession(top.name);
  VarName =  refSession+'?'+VarName
  if(PageObj[VarName]) {
    return PageObj[VarName];
  } else {
    return '';
  }
}

function setSession(VarName, VarValue) {
  if (refSession == '') refSession = getRefSession();
  if(PageObj.length == 0 && top.name != '') PageObj = parseSession(top.name);
  VarName =  refSession+'?'+VarName
  PageObj[VarName] = VarValue;
}

function saveSession() {
  var NameObj = '';
  for (var v in PageObj) {
    NameObj += (v +'#' + PageObj[v] + '\r\n');
  }
  if(window.PageObjExtra) NameObj += window.PageObjExtra;
  if(NameObj != '') top.name = NameObj;

  if(window["removeEventListener"]){
    removeEventListener("unload", saveSession, false)
  } else if(window["detachEvent"]){
    window.detachEvent("onunload", saveSession)
  }
}

function getParam(Param, qVal) {
  qVal = qVal.toLowerCase();
  var Obj = new Object();
  var Prm = Param.split('&');
  var Param = '';
  for(var i = 0; i < Prm.length; i++) {
    var Parts = Prm[i].split('=');
    if(Parts[0].toLowerCase() == qVal) {
      Param = Parts[1];
      break;
    }
  }
  if(Param+'' == 'undefined') Param = '';
  return Param;
}