_cfgTimer = null;
_bsRes = "";
function loadConfigurationWizard( domain )
{
  
  ConfigurationStepOne( domain ); 
  $('#dialog').load( "ConfigurationHTML.php?domain=" + domain, function ( data ) {
  btns = {}
  rebuildConfigurationWizard( btns );

  
  });
  	
}

function ConfigurationStepOne( theDomain ) 
{
	$.get( "/CTK/ConfigurationXML.php", 
         { domain: theDomain, step: '1' }, 
         function ( data ) {

          $( 'Error', data ).each( function ( i )  {
            var msg = $( this ).find( "ErrorMsg" ).text();
            $( '#dialog .unverified' ).append( msg + "<br/>" );
          });

          var gAdmin = getTagText( data, 'gAdmin' );
					var gDomain = getTagText( data, 'Domain' );
          var altEmail = getTagText( data, 'gAltEmail' );
          var userCount = getTagText( data, 'gUserCt' );
          var idNo = getTagText( data, 'gCID' );
          var appsD = getTagText( data, 'AppsDomain' )

          document.getElementById( 'gAdmin' ).value = gAdmin;
					document.getElementById( 'gDomain' ).value = gDomain;
          document.getElementById( 'gEmail' ).value = altEmail;
          document.getElementById( 'cid' ).appendChild( document.createTextNode(idNo) );
          document.getElementById( 'userct' ).appendChild( document.createTextNode(userCount) )

          if ( appsD == '1' )
            $( '.conf_opt' ).show();
          
          buttons = {
            "Close": function() { 
              clearTimeout( _cfgTimer );
              loadDashboardTab();
              btns = { "Updating...": function(){} };
              rebuildConfigurationWizard( btns );
              setTimeout( "$('#dialog').dialog('close')", 4000 ); 
            },
            "Save": function() {  
              ConfigurationStepTwo( theDomain );
            } 
          }
    
          rebuildConfigurationWizard( buttons );
          
          $( '#loader' ).hide();
          $( '#confArea' ).show();
  });
} 

function ConfigurationStepTwo( domain )
{
  $.post( "/CTK/ConfigurationXML.php?step=2&domain=" + domain, 
					$( "#wizardForm" ).serialize(), function ( data ) 
          {
						if ( data.getElementsByTagName( 'Settings' ).length == 0 )
						{
							$( '#dialog .unverified' ).text( 'There was an error in your settings. Please try again.' );
							return false;
						}
						else {
							$( '#dialog .unverified' ).text( 'Save complete.' );
						} 
					}
				);
}

function gCheck( )
{
  var user = $( '#gAdmin' ).attr( 'value' );
  var pass = $( '#gPwd' ).attr( 'value' );
  var domain = $( '#gDomain' ).attr( 'value' );
  $.post( "UtilitySettingVerifyXML.php?step=1",  { 'domain' : domain, 'user': user, 'pass': pass }, 
		function ( data )
		{
			var result = getTagText( data, 'Result' );
				if (result == 1) {
					$( ".ui-icon-check" ).parent().css( 'border', '1px solid #24FF00' );
          $( '#dialog .unverified' ).empty( );
          document.getElementById("gPwd").className = "text ui-widget-content ui-corner-all";
				} else {
					document.getElementById("gPwd").className = "text ui-widget-content-error ui-corner-all";
          $( ".ui-icon-check" ).parent().css( 'border', '1px solid #FF0000' );
          $( '#dialog .unverified' ).text( 'There was an error in your Google Credentials.' );
				}
		}
	);
}

function backSync( domain )
{
  $('#backSyncNotify').html( "<span class=\"loader\"></span>Synchronizing..." );
  $.get( "/CTK/ConfigurationXML.php?domain=" + domain + "&step=3", 
    function( data ) {
      jobId = $( 'Started', data ).text();
      _cfgTimer = setTimeout( "ConfigCheckBackSyncStatus( \"" + domain + "\", \"" + jobId + "\" )", 10000 );
    
  });
}

function ConfigCheckBackSyncStatus( domain, id )
{
  $.get( "/CTK/ConfigurationXML.php?domain=" + domain + "&id=" + id + "&step=31", 
    function( data )
    {
      // id for empty results testing id = 1243;
      // id for results testing id = 1159;
      var status = getTagText( data, 'Status' );
      if ( status == "Completed" )
      {
        _bsRes = data;
        $('#backSyncNotify').html( "<a href=\"javascript:ConfigViewBSyncResults( '" + domain + "' )\">View Results</a>" );
      }
      else
        _cfgTimer = setTimeout( "ConfigCheckBackSyncStatus( \"" + domain + "\", \"" + id + "\" )", 10000 );
    }
  );
}

function ConfigViewBSyncResults( domain )
{
  $( '#wizardForm' ).empty();
  $( '#wizTitle' ).text( 'Back Sync Results' );
  var cnt = 0;
  $( 'Change', _bsRes ).each( function ( i ) {
    cnt++;
    var usr = $( this ).find( 'UserName').text();
    var first = $( this ).find( 'FirstName').text();
    var last = $( this ).find( 'LastName').text();
    var act = $( this ).find( 'Action').text();
    var reportStr = "User " + usr + " ( " + first + " " + last + " ) : " + act;
    $('#wizardForm').append( reportStr + "<br/>" );
  });
  if ( cnt == 0 )
    $('#wizardForm').append( "<strong>There were no changes to made this sync.</strong>" );
    
  btns = {
    "Close": function() { 
      $('#dialog').dialog("close"); 
    },
    "Back": function() {  
      loadConfigurationWizard( domain );
    } 
  }
  
  rebuildConfigurationWizard( btns );
}


function rebuildConfigurationWizard( btns )
{
  
  $('#dialog').dialog("destroy");
		$('#dialog').dialog({
			autoOpen: false,
			width: 630,
			modal: true,
			buttons: btns
		});
		$('#dialog').dialog('open');	
}