﻿/*
 * --------------------------------------------------------------------------------------------------------------------
 * GLOBAL MEMBERS
 * --------------------------------------------------------------------------------------------------------------------
 */

var hashState = {
  filterBC : ''
}; // filterBC:'' -> force to load all items at the beginning
var hashListeners = {};

// var $overlay = $('<div class="ui-widget-overlay" style="z-index: 1002;
// background: #ffffff"><img src="/img/loading.gif" alt="loading"
// class="loading" /></div>');
// var $loading = $('<img src="/img/loading.gif" alt="loading"
// class="loading">');
var $overlay = $('<div class="ui-widget-overlay" style="z-index: 1001; background: #ffffff"><img src="/img/www_sap_com_global/rm_images/rm_blue_preloader.gif" alt="loading" class="loading" /></div>');
var $loading = $('<img src="/img/www_sap_com_global/rm_images/rm_blue_preloader.gif" alt="loading" class="loading">');

/*
 * --------------------------------------------------------------------------------------------------------------------
 * GLOBAL METHODS
 * --------------------------------------------------------------------------------------------------------------------
 */

function submitForm(id) {
  var form = document.forms[id];
  if (!form) {
    form = document.getElementById(id);
  }
  form.submit();
}

function addHashListener(key, handler) {
  hashListeners[key] = handler;
}

function removeHashListener(key, handler) {
  delete hashListeners[key];
}

/**
 * Function to convert a hash into a name-value-pair
 * 
 * @param str
 *         The hash-code
 * @return object
 */
function hashToObj(str) {
  var _nvp = new Object();
  if (str.length > 0) {
    str = (str.charAt(0) == "#") ? str.substring(1) : str;
    var _pairs = str.split('&');
    for (i in _pairs) {
      if (_pairs[i].indexOf('=') > 0) {
        var _pair = _pairs[i].split('=');
        _nvp[_pair[0]] = _pair[1];
      }
    }
  }
  return _nvp;
}

/**
 * Function to convert a name-value-pair into a hash
 * 
 * @param obj
 *         The name-value-container
 * @return string The hash-code
 */
function objToHash(obj) {
  var ary = new Array();
  for (key in obj) {
    ary.push(key + '=' + obj[key]);
  }
  return ary.join('&');
}

/**
 * Function to handle the hash-code
 * 
 * @param obj
 *         The name-value-container
 * @return null
 */
function checkHash(obj) {
  // CHECK: if there are any listeners
  if (isEmpty(hashListeners))
    return;
  // CHECK: if there is a definition to change
  for (key in obj) {
    if (hashListeners[key] != undefined
        && (hashState[key] == undefined || hashState[key] != obj[key])) {
      hashListeners[key].call(this, {
        'key' : key,
        'value' : obj[key]
      });
      if (hashState[key] != undefined)
        delete hashState[key];
    }
  }
  // CHECK: if there is a definition to reset
  for (key in hashState) {
    if (hashListeners[key] != undefined && obj[key] == undefined) {
      hashListeners[key].call(this, {
        'key' : key,
        'value' : ''
      });
    }
  }
  hashState = obj;
}

/**
 * Checks is an object has properties
 * 
 * @param obj
 *         The object to check
 * @return bool
 */
function isEmpty(obj) {
  for ( var prop in obj) {
    if (obj.hasOwnProperty(prop))
      return false;
  }
  return true;
}

/**
 * jQuery function to check if a selector exist
 */
jQuery.fn.exists = function() {
  return jQuery(this).length > 0;
}

jQuery.fn.flash = function() {
  this.css('backgroundColor', '#000000');
  this.css('color', '#ffffff');
  this.animate( {
    backgroundColor : '#eeeeee',
    color : '#000000'
  }, 500);
}

/*
 * --------------------------------------------------------------------------------------------------------------------
 * GLOBAL EVENT-HANDLERS
 * --------------------------------------------------------------------------------------------------------------------
 */

/**
 * Hash-Change Handler
 */
$(window).hashchange(function() {
  checkHash(hashToObj(window.location.hash));
});

/**
 * Window-Load Handler
 */
$(window).load(function() {
  // INITIAL CALLS
    checkHash(hashToObj(window.location.hash));
  });

/**
 * Tab-Change Handler
 * 
 * @param e
 * @return
 */
function changeTabHandler(e) {
  var tabNavId = e.key;
  var selectedTabIndex = (e.value == '') ? 0 : parseInt(e.value);
  var $nav = $('#' + tabNavId);
  if (!$nav.exists())
    return;
  var $tabs = $nav.find('.ui-tabnav-tab');
  var $activeTab = $nav.find('.ui-tabnav-tab-active');
  if ($activeTab.exists()) {
    var activeTabIndex = $tabs.index($activeTab);
    if (activeTabIndex != selectedTabIndex) {
      _deactivateTab(tabNavId, activeTabIndex);
      _activateTab(tabNavId, selectedTabIndex);
    }
  } else {
    _activateTab(tabNavId, selectedTabIndex);
  }
}

/*
 * --------------------------------------------------------------------------------------------------------------------
 * Tab-Navigation-Functions
 * --------------------------------------------------------------------------------------------------------------------
 */

function _activateTab(tabNavId, tabIndex) {
  var id = '#' + tabNavId + '_tab' + tabIndex;
  var style = $('#' + tabNavId + '_style').val();
  $(id + '_tdLeft').removeAttr('class');
  $(id + '_imgLeft').attr('src',
      '/img/www_sap_com_global/TabActiveBgRepeat' + style + '.jpg');
  $(id + '_tdCenter').attr('class', 'TabActive' + style + '');
  $(id + '_link').attr('class',
      'TabActiveLink ui-tabnav-tab ui-tabnav-tab-active');
  $(id + '_tdRight').removeAttr('class');
  $(id + '_imgRight').attr('src',
      '/img/www_sap_com_global/TabActiveBgRepeat' + style + '.jpg');
  $(id + '_content').css('display', 'block');
}

function _deactivateTab(tabNavId, tabIndex) {
  var id = '#' + tabNavId + '_tab' + tabIndex;
  var style = $('#' + tabNavId + '_style').val();
  $(id + '_tdLeft').attr('class', 'TabInactiveEnd' + style);
  $(id + '_imgLeft').attr('src',
      '/img/www_sap_com_global/TabInactiveBgRepeat' + style + '.jpg');
  $(id + '_tdCenter').attr('class', 'TabInactiveCenter' + style);
  $(id + '_link').attr('class',
      'TabInactiveLink ui-tabnav-tab ui-tabnav-tab-default');
  $(id + '_tdRight').attr('class', 'TabInactiveEnd' + style);
  $(id + '_imgRight').attr('src',
      '/img/www_sap_com_global/TabInactiveBgRepeat' + style + '.jpg');
  $(id + '_content').css('display', 'none');
}

/*
 * --------------------------------------------------------------------------------------------------------------------
 * jQuery-Styles
 * --------------------------------------------------------------------------------------------------------------------
 */

$(document)
    .ready(function() {

      // DIALOG-LINK
        $('.dialog-link').each(function() {
          var $dialog = $('<div></div>');
          var $link = $(this);
          var r = true;
          var w = 450;
          if ($link.data('width')) {
            w = $link.data('width');
          }
          var h = 'auto';
          if ($link.data('height')) {
            h = $link.data('height');
            r = false;
            /*
             * if ($.browser.msie) { h += 50; }
             */
          }
          $link.click(function() {
            $dialog.html($loading.clone());
            $dialog.load($link.attr('href')).dialog( {
              title : $link.attr('title'),
              width : w,
              height : h,
              resizable : r,
              modal : true,
              autoOpen : false,
              position : 'center',
              close : function(event, ui) {
                $(this).remove();
              }
            });
             $dialog.dialog('open');
             return false;
           });
        });

        // IFRAME-LINK
        $('.iframe-link')
            .each(
                function() {
                  var $link = $(this);
                  var w = ($link.data('width')) ? $link.data('width') : 800;
                  var h = ($link.data('height')) ? $link.data('height') : 600;
                  /*
                   * if ($.browser.msie) { h += 50; }
                   */
                  $link
                      .click(function(e) {
                        e.preventDefault();
                        var $dialog = $('<div></div>');
                        var $iframe = $('<iframe width="100%" height="100%" frameborder="0" marginwidth="0" marginheight="0"></iframe>');
                        $dialog.append($iframe);
                        $dialog.dialog( {
                          title : $link.attr('title'),
                          width : w,
                          height : h,
                          modal : true,
                          close : function(event, ui) {
                            $(this).remove();
                          }
                        });
                        $dialog.dialog('open');
                        $iframe.attr('src', $link.attr('href'));
                        return false;
                      });
                });

        // DIALOG-MESSAGE
        $('#dialog-message').dialog( {
          width : 450,
          height : 200,
          modal : true,
          buttons : {
            "OK" : function() {
              $(this).remove();
        }
      }
        });

        // LINK-CONFIRM
        $('.link-confirm').each(
            function() {
              var $link = $(this);
              $link.click(function(e) {
                e.preventDefault();
                var title = ($link.data('ctitle')) ? $link.data('ctitle')
                    : 'Attention!';
                var message = ($link.data('cmessage')) ? $link.data('cmessage')
                    : 'Are you sure to perform this action?';
                var targetUrl = $link.attr('href');
                var $dialog = $('<div title="' + title + '">' + message
                    + '</div>');
                $dialog.dialog( {
                  width : 450,
                  height : 200,
                  modal : true,
                  buttons : {
                    'OK' : function() {
                      window.location.href = targetUrl;
                    },
                    'Cancel' : function() {
                      $(this).remove();
                      // $(this).dialog('close');
                  }
                  }
                });
              });
            });

        // TAB-NAV
        jQueryInitTabNav();

        // FILTER-SET
        // $( ".filterset" ).buttonset();

        // SAMPLE-TEXT
        $('.sample-text').focus(function(e) {
          if ($(this).hasClass('sample-text-active')) {
            $(this).removeClass('sample-text-active');
            $(this).val('');
          }
        });
        $('.sample-text').blur(function() {
          if ($(this).val() == '') {
            $(this).addClass('sample-text-active');
            $(this).val($(this).data('sample'));
          }
        });
        $('form:has(.sample-text)').submit(function(){
          $('.sample-text-active', this).val('');
        }); 
        $('.sample-text').blur();

      });

function jQueryInitTabNav() {

  $('.ui-tabnav').each(function() {
    var navid = $(this).attr('id');
    addHashListener(navid, changeTabHandler);
    var $tabs = $(this).find('.ui-tabnav-tab');
    $tabs.each(function(index) {
      $(this).click(function(e) {
        var _h = hashToObj(window.location.hash);
        _h[navid] = index;
        window.location.hash = objToHash(_h);
      });
    });
  });
}

