var ErrorLoadingInproc = false;
var UACDialogStarted = false;

var isTurboActive = false;
var isEcoModeActive = false;
var isInAction = false;
var checkForServiceConnection = false;

function initTUAnalyzeResult()
{
  ErrorLoadingInproc = false;
  if (typeof(wAnalyzeResult) == "undefined")
  {
    try
    {
      wAnalyzeResult = new ActiveXObject("TUAnalyzeInfo.TUAnalyzeResult");
    }
    catch (e)
    {
      ErrorLoadingInproc = true;
      $('.statuspanel').hide();
      $('.tuningbuttons_backgnd').hide();
      $('.tuningbuttons').hide();
      $('.errormessage').show();
      return;
    }
    
    updateStatus();
  }
}

function initBackground()
{
  if(ErrorLoadingInproc)
    System.Gadget.background = "images\\bg_error.png";
  else
    System.Gadget.background = "images\\bg_gadget.png";
}
      
String.format = function( format ) {
  var arg = arguments;
  var i = 1;
  return format.replace( /%((%)|s|d)/g, function( m ) {
    return m[ 2 ] || arg[ i++ ];
  } );
}

var EcoButton = '';
var NormalButton = '';
var TurboButton = '';

function GetTurboButtonText()
{
  if( EcoButton == '')
  {
    EcoButton = translate('<localized>Economy-Modus</localized>');
    NormalButton = translate('<localized>Standard-Modus</localized>');
    TurboButton = translate('<localized>Turbo-Modus</localized>');
  }
  
  var Formater =  translate('<localized>%s aktiviert</localized>');
  
  if(isTurboActive)
    return String.format( Formater, TurboButton );
  else if(isEcoModeActive)
    return String.format( Formater, EcoButton );
  else
    return String.format( Formater, NormalButton );
  }

function SetTurboDescription()
{
  $('#TurboDescription').html(GetTurboButtonText());
}

function GetChangeButtonText(id)
{
  var Formater =  translate('<localized>Wechsel zu %s… </localized>');
  return String.format( Formater, id );
}

function SetChangeDescription(id)
{
  $('#TurboDescription').html(GetChangeButtonText(id));
}

function CheckTUServiceState()
{
  initTUService();
  if(checkForServiceConnection)
    setTimeout("CheckTUServiceState()", 1000);
}

function initTUService()
{
  if (ErrorLoadingInproc == true)
    return;
  
  if (wAnalyzeResult)
  { 
    if (wAnalyzeResult.IsTUServiceRunning == 1)
    {
      checkForServiceConnection = false;
      $('.serviceerrormessage').hide();
      $('.tuningbuttons').show();
      $('.tuningbuttons_backgnd').show();
      
      if(wAnalyzeResult.IsTurboModeActive == 1)
        isTurboActive = true;
      else if (wAnalyzeResult.IsEcoModeActive == 1)
        isEcoModeActive = true;

      SetNewButtonState();
      
      SetTurboDescription();
      $('.turbomessage').show();
    }
    else
    {
      $('.serviceerrormessage').show();
      if(checkForServiceConnection)
        setTimeout("CheckTUServiceState()", 1000);
    }
  }
}

function StartTUApp()
{
  UACDialogStarted = true;
  
  execApp('Integrator.exe', '/initstatuspage');
  
  if($('.statuspanel').find('.hover').is(':visible'))
    $('.statuspanel').find('.hover').hide();
    
  if($('.serviceerrormessage').is(':visible'))
  {
    checkForServiceConnection = true;
    setTimeout("CheckTUServiceState()", 1000);
  }
 
 return false;
}

function changeStatus(id, classname)
{
  $('#' + id).removeClass('good warning critical unknown').addClass(classname);
}

function updateStatus(updatetype)
{
  $('.statuspanel').show();
  
  changeStatus('status', TotalState());
}

function closeGadget()
{
  System.Gadget.close();
}

function initEvent()
{
  if (wAnalyzeResult)
  {
    wAnalyzeResult.RegisterOnClose(closeGadget);
    wAnalyzeResult.RegisterOnChange(updateStatus);
    wAnalyzeResult.RegisterOnChangeTurbo(updateTurboEvent);
  }
}

function cleanupEvent()
{
  if (wAnalyzeResult)
  {
    wAnalyzeResult.UnRegisterOnChange();
    wAnalyzeResult.UnRegisterOnClose();
    wAnalyzeResult.UnRegisterOnChangeTurbo();
  }
}

function StartTurboMode()
{
  if ((isTurboActive) || (isInAction))
    return;
    
  if (wAnalyzeResult)   
  {
    if (wAnalyzeResult.IsActionInProgress)
      return;
  
    highspeedToggle();
  }
}

function StartEcoMode()
{
  if ((isEcoModeActive) || (isInAction))
    return;
    
  if (wAnalyzeResult)   
  {
    if (wAnalyzeResult.IsActionInProgress)
      return;
    
    EcoModeToggle();
  }
}

function StartDefaultMode()
{
  if (isInAction)
    return;
    
  if (wAnalyzeResult)   
  {
    if (wAnalyzeResult.IsActionInProgress)
      return;
    
    if (isTurboActive)
      highspeedToggle();
    else if (isEcoModeActive)
      EcoModeToggle();
  }
}

var ActivePressedButton = null;
var SameButtonByMousUpDown = false;

function initAnimations()
{
  if (ErrorLoadingInproc == true)
    return;
  
  $('*').keydown(
    function (e)
    {
      switch (e.keyCode)
      {
        case 13:
          $(this).click();
          break;
      }
    }
  );
  
  $(".integrator-link").bind('click', function() {
    StartTUApp();
    return false;
  }).bind("focus focusin", function() {
    $(this).blur();
    return false;
  });
  

  $('.statuspanel .normal').mouseenter(
    function ()
    {
      if(UACDialogStarted) // mouseenter will be send after clicking UAC dialog
      {
        UACDialogStarted = false;
        return;
      }
      
      $(this).find('.hover').stop(false, true).stop(false, true);
      $(this).find('.hover').show();
    }
  );

  $('.statuspanel .normal').mouseleave(
    function ()
    {
      if($(this).find('.hover').is(':visible'))
        $(this).find('.hover').stop(false, true).stop(false, true).fadeIn(200).fadeOut(150);
    }
  );
  
  $('.tuningbuttons .normal').mouseenter(
    function ()
    {
      $(this).find('.hover').stop(false, true).stop(false, true);
      if (ActivePressedButton == null)
        $(this).find('.hover').show();
    }
  );
  
  $('.tuningbuttons .normal').mousedown(
    function (e)
    {
      if (isInAction)
        return;

      SameButtonByMousUpDown = false;
      if(($(this).parent().attr('id') == 'tuning_economy') && (isEcoModeActive))
        return;
      if(($(this).parent().attr('id') == 'tuning_turbo') && (isTurboActive))
        return;
      if(($(this).parent().attr('id') == 'tuning_standard') && (!isTurboActive) && (!isEcoModeActive))
        return;

      $('#tuning_economy').removeClass('inactive active unknown').addClass('inactive');
      $('#tuning_standard').removeClass('inactive active unknown').addClass('inactive');
      $('#tuning_turbo').removeClass('inactive active unknown').addClass('inactive');
        
      $(this).find('.hover').stop(false, true).stop(false, true).fadeIn(200).fadeOut(150);
      $(this).find('.clicked').show();
      ActivePressedButton = $(this);
    }
  );
  
   $('.tuningbuttons .normal').mouseup(
    function (e)
    {
      if (ActivePressedButton)
      {
        if($(this).parent().attr('id') == ActivePressedButton.parent().attr('id'))
          SameButtonByMousUpDown = true;
      }
    }
  );
  
  $('body').mouseup(
    function (e)
    {
      if ((ActivePressedButton) && (!SameButtonByMousUpDown))
      {
        SetNewButtonState;
      }
    }
  );
  
  $('body').mouseleave(
    function (e)
    {
      if (ActivePressedButton)
      {
        SetNewButtonState;
      }
    }
  );

  $('.tuningbuttons .normal').mouseleave(
    function ()
    {
      if(!$(this).find('.hover').is(':visible'))
        return;
        
      $(this).find('.hover').stop(false, true).stop(false, true).fadeIn(200).fadeOut(150);
    }
  );
}