
var 
  currAppDataDir='';

function getCommandLinkElement(childEl){
    if (childEl == null)
        return null;
    var nofMatches = $('.commandLink', childEl.parentElement).length;
    if (nofMatches> 0){
        return childEl;        
    }        
    else{
        return getCommandLinkElement(childEl.parentElement);
    }
}

function handleCommandLinkMouseEnter(el){
    id = el.id;
       
    aParent = getCommandLinkElement(el);
        
    var fadeInSpeed = 250;
    if (aParent)
        fadeInSpeed = aParent.LayerButton['hover'].fadeIn.speed;

    currForeColor = el.currentStyle.color;    
    el.setAttribute('lastForeColor', currForeColor);
    $(el).stop();
    $(el).animate({ color: '#2F4AE5'}, fadeInSpeed);      
}

function handleCommandLinkMouseLeave(el){
    id = el.id;
    
    aParent = getCommandLinkElement(el);
    
    var fadeOutSpeed = 300;
    if (aParent)
        fadeOutSpeed = aParent.LayerButton['hover'].fadeOut.speed;

    lastForeColor = '#000000';
    $(el).stop();
    $(el).animate({ color: lastForeColor}, fadeOutSpeed);
}

function BodyLoaded()
{

/* ============================ Action links ============================ */

  $('a.action img[@src$=.png]').ifixpng(16, 16);
  $('a.action').click(handleActionClick);
  
  function handleActionClick(event)
  {
    // Get the target of the clicked link
    var clickedElement = $(event.target);
    if (!clickedElement.is('a.action'))
    {
      var clickedElement = clickedElement.parents('a.action');
    }
    var elementName    = clickedElement.attr('name');
    //var taskCaption    = clickedElement.text().replace(/&nbsp;/g, ' ');
    
    // Send the task target link to the software
    alert('#onClick:' + elementName);
    event.preventDefault();
  }

/* ======================= Input Control Handling ======================= */

  $('input[associatedTo]').focus(handleAssociatedInputFocus);
  $('input').click(handleInputClick);
  updateAssociatedInputControls();
  
  function handleInputClick(event)
  {
    // Get clicked input element
    var clickedElement     = $(event.target);
    var clickedElementId   = clickedElement.attr('id');
    
    // Update associated controls
    updateAssociatedInputControls(clickedElementId);
  }
  
  function updateAssociatedInputControls(clickedElementId)
  {
    // Correct tabIndex properties of all associated elements
    $('input[associatedTo]').each(
      function ()
      {
        
        var associatedElement = $(this);
        var parentElementId   = associatedElement.attr('associatedTo');
        var parentElement     = $('#' + parentElementId);
        if (parentElement.is(':checked'))
        {
          associatedElement.attr('tabIndex', 0);
          // If the parent element was just clicked, focus the associated element
          if (
               clickedElementId &&
               (clickedElementId == parentElementId) &&
               !$.keyboardNavigation
             )
          {
            associatedElement.focus();
          }
        }
        else
        {
          associatedElement.attr('tabIndex', -1);
        }
      }
    );
  }
  
  function handleAssociatedInputFocus(event)
  {
    
    // Get ID of the associated input element
    var associatedElementId = $(event.target).attr('associatedTo');
    // Find element
    var associatedElement   = $('#' + associatedElementId);
    // Check it
    associatedElement
    associatedElement.each(
      function ()
      {
        if (!$(this).attr('checked'))
        {
          $(this).attr('checked', true);
          notifyAppAboutChange(this);
        }
      }
    );
  }

  $('input:radio, input:checkbox').click(notifyAppAboutChangeHandler);
  $('input:text, input:password')
    .bind('keyup', notifyAppAboutChangeHandler)
    .bind('cut',   notifyAppAboutChangeHandler)
    .bind('paste', notifyAppAboutChangeHandler);

  function notifyAppAboutChangeHandler(event)
  {
    var changedElement = event.target;
    window.setTimeout(
      function ()
      {
        notifyAppAboutChange(changedElement);
      },
      1
    );
  }
function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}
  function notifyAppAboutChange(changedElement)
  {
    
    // Get changed input element
    var changedElement     = $(changedElement);
    var changedElementName = changedElement.attr('name');
    
    // Get element value
    if (changedElement.is(':checkbox'))
    {
      var changedElementValue = '';
      var checkedValuesWithSameName = $('input[name=' + changedElementName + ']:checked');
      checkedValuesWithSameName.each(
        function ()
        {
          if (changedElementValue.length)
          {
            changedElementValue = changedElementValue + ',';
          }
          changedElementValue = changedElementValue + $(this).val();
        }
      );
    }
    else
    {
      var changedElementValue = changedElement.val();
    }
    
    alert('#onChange:' + changedElementName + ':' + changedElementValue);
  }

/* =============================== Other stuff ============================== */
  //set default epmty.gif through protocol handler.
  $.ifixpng('#BaseHref#../empty.gif');
  
  $('#headerIcon img').ifixpng();
  $('#header img').ifixpng(32, 32);  
  $('.recommendation img').ifixpng(16, 16);

/*  $('.setting .default label').append(' (Standard)'); */
/*  $('.setting .recommended label').append(' (empfohlen)'); */
  
/* =============================== Command Links ============================== */
  
  // convert current html code to <button> elements with css class "commandLinkButton" 
  $('.choose-one:has(.link)').each(function(){
        
        rowsHTML = '';
        nofEl = $('.action', this).length;

        for(i=0; i < nofEl; i++){

          innerText = $('.action:eq(' + i + ')', this).text();
          nameAttr  = $('.action:eq(' + i + ')', this).attr('name');
          

          hintText  = $('.explanation:eq(' + i + ')', this).text();
          if (!hintText)
            hintText = '';
          hintText  = str_replace('"','&quot;',hintText   ); 
          objIndex = $('.action:eq(' + i + ')', this).get(0).sourceIndex;
          rowsHTML = rowsHTML + 
             '<tr>'+
             '  <td id="commandLink' + objIndex + '" class="commandLink" align="left" name="' + nameAttr+ '">'+
             '    <button id="commandLinkButton' + objIndex + '" class="commandLinkButton" title="' + hintText + '">' + innerText +  '</button>'+
             '  </td>'+
             '</tr>';
        }
        html='<table cellspacing="2" cellpadding="2" width="100%">'+rowsHTML+'</table>';
        $(this).replaceWith(html);

        
    }
   );

  //convert all <button> elements with css class ".commandLinkButton" into vista's command link style buttons (using LayerButton extension)
  $('.commandLinkButton').each(function(){

        id = $(this).attr('id');
        iconSrcNormal = $('img', this).attr('src');
        iconSrcHover  = $('img', this).attr('hoverSrc');
     
        if (!iconSrcNormal){
            iconSrcNormal = currAppDataDir+'command_link_normal.png';                      
            iconWidth  = '20px';
            iconHeight = '20px';
        }else{
          iconWidth   = $('img', this).get(0).offsetWidth + 'px';
          iconHeight  = $('img', this).get(0).offsetHeight + 'px';        
        }
        if (!iconSrcHover){
            iconSrcHover  = currAppDataDir + 'command_link_hover.png';
        }
        
        hintText = $(this).attr('title');        
        if (!hintText)
            hintText = '';
        
        html = '<a href="javascript:void(0);" class="commandLinkContent" style="cursor:hand;" >'+
               '<table id="' + id + '" cellspacing="5" cellpadding="5"  style="width:100%; "'+
               '     iconSrcNormal="' + iconSrcNormal + '"'+
               '     iconSrcHover= "' + iconSrcHover  + '"'+
	           '     onmouseenter="handleCommandLinkMouseEnter(this);" '+
	           '     onmouseleave="handleCommandLinkMouseLeave(this);"> '+
	           '   <tr>'+
		       '     <td  id="' + id + '.iconCont' + '" class="image" valign="top" width="' + iconWidth + '" style="padding-left:5px;">' +
		       '         <span class="commandLinkIcon" id="' + id + '.icon' + '" style="display:block; width:' + iconWidth + '; height:' + iconHeight + '; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale, src=\'' + iconSrcNormal + '\')"/>'+
		       '     </td>'+
		       '     <td valign="top" style="">' +
		       '         <div id="' + id + '.actionText' + '" class="commandLinkAction">' + $(this).text() + '</div>'+
               '         <div class="commandLinkHint"  >' + hintText       + '</div>'+
		       '     </td>'+
	           '   </tr>'+
	           '</table>'+
	           '</a>';
	    //alert(html);
        $(this).replaceWith(html);        
    }
  );  

  //bind on click event
  $('.commandLink').click(function(){
    var elementName = $(this).attr('name');
    alert('#onClick:' + elementName);
   
   }
  );
  

   $('.commandLink').LayerButton(
    {
     'hover':
      {
        'imageSource':  { 'prefix': currAppDataDir + 'CommandLink/command_link_hover_', 'suffix': '.png' },
        'imageBorders': { 'top': 4, 'right': 4, 'bottom': 4, 'left': 4 },
        'fadeIn':       { 'speed': 250, 'easing': 'easeOutQuad' },
        'fadeOut':      { 'speed': 300, 'easing': 'easeOutQuad' }
      }
    }
  );
};
