﻿/// <reference path="jquery-1.7.1.min.js" />

//======= Форматирование ========
var decimalSeparator = '.';
var hideZeroCents = false;
var numberGroupSeparator  = '&thinsp;';
var currencySymbol = 'руб.';

function formatDecimal( value) {
  var result = groupDigits( value.toString());
  if( decimalSeparator != '.')
    result = result.replace( '.', decimalSeparator);
  return result;
}

function formatCV( value) {
  var s = value.toFixed(3);
  s = s.replace( /0{1,3}$/, '').replace( /\.$/, ''); // remove trailing zeroes and dot
  return formatDecimal( s);
}
function formatCV3( value) { // всегда с 3 цифрами после запятой
  var s = value.toFixed(3);
  return formatDecimal( s);
}

function formatMoney( value) {
  if( hideZeroCents && value == Math.floor( value))
    return groupDigits( value.toFixed( 0));
  var result = groupDigits( value.toFixed( 2));
  if( decimalSeparator != '.')
    result = result.replace( '.', decimalSeparator);
  return result;
}

function groupDigits( s) {
  var length = s.length;
  var intPartLength = s.indexOf('.');
  if( intPartLength < 0)
    intPartLength = length;
  if( intPartLength <= 3)
    return s;

  var a = new Array();
  var e = intPartLength;
  var i = 0;
  while( e > 0) {
    var b = e - 3;
    if( b < 0)
      b = 0;
    a[i++] = s.substr( b, e - b);
    e = b;
  }
  a.reverse();
  return a.join( numberGroupSeparator) + s.substr( intPartLength, length - intPartLength);
}

function formatOrderNumber( orderNumber) {
  var s = '0000000000' + orderNumber.toString();
  s = s.substr( s.length-10, 10);
  return s.substr( 0, 6) + '-' + s.substr( 6, 4);
}

// убирает пробелы слева и справа
function trimString( str){
  return $.trim( str);
}

// Добавляет точку в конец строки, если её там нет.
function appendDot( message) {
  if( message) {
    var lastChar = message.substring( message.length - 1);
    if( lastChar == ' ')
      return appendDot( trimString( message));
    if( lastChar != '.' && lastChar != '>')
      message += '.';
  }
  return message;
}
function capitalizeMessage( message) {
  if( message)
    message = message.substring( 0, 1).toUpperCase() + message.substring( 1);
  return message;
}

//====== Stub for IE's Debug object ======
try {
  Debug.write;
  Debug.writeln;
}
catch( ex) {
  Debug = {
    write: function() {},
    writeln: function() {}
  };
}

//======= Elapsed time =======
var operationStartTime = null;
function resetElapsedTime( message) {
  operationStartTime = new Date();
  Debug.writeln('--------------------------\t' + message);
}
function dumpElapsedTime( message) {
  if( operationStartTime != null) {
    var time = new Date()
    Debug.writeln( time.toTimeString() + ': ' + (time.getTime() - operationStartTime.getTime()) + ' ms' + (message ? '\t' + message : ''));
  }
}

//==== Начальные значения и подсказки =====

var defText = {};

function SetDefaultAndTooltip( id, defValue, tooltip) {
  if( !(id in defText))
    defText[id] = {};
  var d = defText[id];
  d['text'] = defValue;
  d['tooltip'] = tooltip;
}
function SetTooltip( id, tooltip) {
  SetDefaultAndTooltip( id, null, tooltip);
}

// возвращает текст умолчанию
function retDefText(id, arg) {
  if ( !(id in defText) || !(arg in defText[id])) {
    return null;
  }
  var r = defText[id][arg];
  return r;
}
function getFieldError( id) {
  if( !(id in fieldErrors)) {
    return null;
  }
  return fieldErrors[id];
}

//========= Сообщения о неправильных значениях в полях ввода ========
var fieldErrors = {};

function SetFieldError( id, message) {
  fieldErrors[id] = message;
}
function resetFieldsDefault() {
  $('input.inpText').each(function() {
    var txt = $(this).val();
    var def = retDefText($(this).attr("id"), "text");
    if (txt == def) {
      $(this).attr('value', '');
    }
  });
}

//========= Значения по умолчанию в полях ввода ========
function inputSetValue( $input, value) {
  $input.val( value);
  if( $input.val())
    inputLabelHide( $input);
  else
    inputLabelShow( $input);
}
function inputLabelHide( $input) {
  $input.next('label').hide();
}
function inputLabelShow( $input) {
  $input.next('label').show();
}

function arrangeInputLabels() {
  var $labelInput = $('.dInpRow label');
  var $inputText = $('.dInpRow input, .dInpRow textarea');

  $inputText.each(
    function () {
      if ($(this).val())
        inputLabelHide($(this));
    }
  );
  $labelInput.click(
    function () {
      $(this).prev('input, textarea').trigger('focus');
    }
  );
  // input change
  $inputText.focus(
    function () {
      inputLabelHide($(this));
    }
  )
  .blur(
    function () {
      var text = $.trim(this.value);
      this.value = text;
      if (text == '') {
        inputLabelShow($(this));
      }
    }
  );
}

function setInputReadonly( $input, readonly) {
  if( readonly) {
    $input.attr('readonly', 'readonly');
    $input.parent().parent().addClass('ReadOnly');
  } else {
    $input.removeAttr('readonly');
    $input.parent().parent().removeClass('ReadOnly');
  }
}

// POST 
function postTo( url, data, method) {
  var $form = $('<form method="' + (method ? method : 'POST') + '" action="' + url + '"></form>')
    .appendTo( document.body);
  if( data) {
    for( var key in data) {
      var value = data[key].toString();
      $('<input type="hidden" name="' + key + '" />')
        .val( value).appendTo( $form);
    }
  }
  $form.submit();
}
function navigateTo( url, data) {
  postTo( url, data, 'GET');
}

//======= Подсветка строки таблицы ========
var selectedRow = null, hoveredRow = null;

function resetSelectedRow() {
  if( selectedRow != null) {
    turnSelectedStyle( selectedRow, false);
    selectedRow = null;
  }
  if( hoveredRow != null) {
    turnSelectedStyle( hoveredRow, true);
  }
}

function turnSelectedStyle( row, on) {
  var $row = $(row);
  $row.toggleClass('selected', on);
  if( !on)
    $row.toggleClass('selectedDelay', false);
}

function onHoverIn( event) {
  var row = $(event.currentTarget);
  if( selectedRow == null) {
    turnSelectedStyle( row, true);
    window.setTimeout( function() {
      $(row).filter('.selected').toggleClass('selectedDelay', true);
    }, 150);
  }
  hoveredRow = row;
}

function onHoverOut( event) {
  var row = event.currentTarget;
  if( selectedRow == null) {
    turnSelectedStyle( row, false);
  }
  hoveredRow = null;
}

function handleRowHighlighting( tr) {
  $(tr).hover( onHoverIn, onHoverOut);
}

// Центрируем диалог по горизонтали и по вертикали
function positionMessageBox( $box, fixed) {
  var boxWidth  = $box.innerWidth();
  var boxHeight = $box.innerHeight();
  var windowHeight = $(window).height();
  var windowWidth  = $(window).width();

  var leftOffset = Math.max( Math.ceil((windowWidth - boxWidth) / 2), 0);
  var topOffset = Math.max( Math.ceil((windowHeight - boxHeight) / 2), 0);
  $box.css('left', (fixed ? 0 : $(document).scrollLeft()) + leftOffset);
  $box.css('top',  (fixed ? 0 : $(document).scrollTop()) + topOffset);
}
function extendBackground( $background) {
  var $window = $(window);
  $background.width( $window.width()).height( $window.height());
};

//=============== Action dialog ===============
(function( $) {
  var $background = null;
  var $activeDialog = null;

  $.showPopup = function( $dialog, options) {
    options = $.extend( { closeOnMiss: true }, options);
    $activeDialog = $dialog;
    $dialog.data("dialogOptions", options);

    // Создаем полупрозрачный фиксированный фон размером со всё окно.
    if( $background == null) {
      $background = $('<div class="dOverlay"><!-- --></div>').appendTo( $(document.body));
      extendBackground( $background);
      $(window).resize( function() { extendBackground( $background); });
      $background.click( function() {
        var dialogOptions = $activeDialog.data("dialogOptions");
        if( dialogOptions.closeOnMiss)
          $.hidePopup( $activeDialog);
      });
    }

    $dialog.show();
    $background.show();
    positionMessageBox( $dialog);
  };

  $.hidePopup = function( $dialog) {
    if( $dialog != null) {
      $dialog.hide();
      //$('li', $dialog).unbind();
      $background.hide();
      if( $activeDialog === $dialog)
        $activeDialog = null;
    }
  };
  /*function updateBackgroundSize() {
    var $window = $(window);
    $background.width( $window.width()).height( $window.height());
  };*/
})( jQuery);

( function( $) {
  var $dialog     = null;
  var $background = null;

  $.actionDialog = function( title, text, actions, options) {
    if( $dialog == null) {
      $dialog = $(
        '<div class="messageBox">' +
          '<div class="messageBoxInside">' +
            '<div class="messageBoxCategory" style="color: #ff0085"></div>' +
            '<div class="messageBoxTitle"></div>' +
            '<div class="messageBoxText"></div>' +
            '<ul class="uList"></ul>' +
          '</div>' +
        '</div>'
      );
      $dialog.appendTo( $(document.body));

      // Создаем полупрозрачный фиксированный фон размером со всё окно.
      $background = $('<div class="dOverlay"><!-- --></div>').appendTo( $(document.body));
      updateBackgroundSize();
      $(window).resize( updateBackgroundSize);
    }

    options = $.extend( { category: ResCommon.Attention }, options);

    $dialog.find('.messageBoxTitle').html( title);
    $dialog.find('.messageBoxCategory').html( options.category);
    var $textDiv = $dialog.find('.messageBoxText');
    $textDiv.html( '');
    switch( typeof( text)) {
      case 'string'  : $textDiv.html( text); break;
      case 'function': text.call( $textDiv); break;
      default: $textDiv.append( text);  break;
    }
    $dialog.show();
  
    var $ul = $('.uList', $dialog);
    $ul.empty();
    for( var i in actions) {
      var action = actions[i];
      $('<li>' + action.text + '</li>').
        appendTo( $ul).click( hideDialog).click( action.action);
    }
    $background.show();
    positionMessageBox( $dialog);
    return $dialog;
  };

  function hideDialog() {
    if( $dialog != null) {
      $dialog.hide();
      $('li', $dialog).unbind();
      //НЕ ДЕЛАТЬ ЭТОГО: $('.uList', $dialog).empty(); не работает в IE7!
      $background.hide();
    }
  };
  function updateBackgroundSize() {
    var $window = $(window);
    $background.width( $window.width()).height( $window.height());
  };
})( jQuery);

function pageStartupMessage( title, text, buttonLabel) {
  var $dialog = $.actionDialog( title, text, [{ text: buttonLabel, action: $.noop }]);
  // Компенсируем возможное действие MaintainScrollPositionOnPostback
  window.setTimeout( function() { positionMessageBox( $dialog); }, 100);
}

//====== Busy indicator ======
(function( $) {
  var $box = null;
  var $background = null;

  $.busyOn = function( message) {
    if( $box == null) {
      $box = $('<div class="busyBox"><img src="img/busy.gif" alt="" width="64" height="64" /></div>');
      $box.appendTo( $(document.body));

      // Создаем полупрозрачный фиксированный фон размером со всё окно.
      $background = $('<div class="dOverlayWhite"><!-- --></div>').appendTo( $(document.body));
      updateBackgroundSize();
      $(window).resize( updateBackgroundSize);
    }
    resetElapsedTime( message);
    $box.show();
    positionMessageBox( $box, true);
    $background.show();
  }
  $.busyOff = function() {
    if( $box != null) {
      $box.hide();
      $background.hide();
    }
    dumpElapsedTime();
  }
  function updateBackgroundSize() {
    var $window = $(window);
    $background.width( $window.width()).height( $window.height());
  }
})( jQuery);

//====== Переключатель классов на hover ======
(function( $) {
  $.fn.changeClassOnHover = function( notHoveredCls, hoveredCls) {
    this.hover(
      function() {
        if( notHoveredCls)
          $(this).removeClass( notHoveredCls);
        if( hoveredCls)
          $(this).addClass( hoveredCls);
      },
      function() {
        if( hoveredCls)
          $(this).removeClass( hoveredCls);
        if( notHoveredCls)
          $(this).addClass( notHoveredCls);
      }
    );
  };
})( jQuery);
// работа с Cookie

// add Cookie
function addCookie( name, value) {
  var d = new Date();
  d.setMonth(d.getMonth() + 3);
  document.cookie = name + '=' + escape(value) + '; expires=' + d.toGMTString() + '; path=/';
}
// delete Cookie
function delCookie(name) {
  var d = new Date();
  document.cookie = name + '=' + '; expires=' + d.toGMTString() + '; path=/';
}

// parse Cookie
function parseCookie() {
  var cookieList = document.cookie.split("; ");
  var cookieArray = new Array();
  for( var i = 0; i < cookieList.length; i++) {
    var name = cookieList[i].split("=");
    cookieArray[unescape( name[0])] = unescape( name[1]);
  }
  return cookieArray;
}
/*
//========= Стандартная обработка ошибок ===========
function ExecuteAndReportError( func, actionTitle) {
  try {        // Выполняем важное действие
    func();
    return true;
  }
  catch( ex) { // показать сообщение пользователю, отправить отчет об ошибке на сервер
    ReportError( ex, actionTitle);
    return false; 
  }
}

function ExecuteAndIgnoreError( func) {
  try {        // Выполняем несущественную операцию
    func();
    return true;
  }
  catch( ex) { // Игнорируем ошибку
    return false; 
  }
}

function ReportError( ex, actionTitle) {
  // показать сообщение пользователю
  alert( 'Ошибка ' + ex + ' при выполнении "' + actionTitle + '"');

  // отправить отчет об ошибке на сервер
  // ...
}
*/

// Формирует внутренность диалога с описанием нарушений правил в закупке.
function explainValidationResults( validationResults) {
  var msg = ResCommon.InvalidPurchaseMessage;
  if( validationResults.length > 0) {
    $text = $('<div style="padding-top: 5px" />');
    $text.text( msg + ':');
    var $ul = $('<ul class="uErrors" />');
    for( var i in validationResults) {
      var vr = validationResults[i];
      $('<li/>').text( vr.message).appendTo( $ul);
    }
    $ul.appendTo( $text);
  }
  else
    $text =  msg + '.';
  return $text;
}

// Tabs
function selectTab( $tab) {
  $tab
    .closest('.linkTab')
    .children('div')
    .removeClass('tabSelected');
  $tab
    .parent()
    .addClass('tabSelected');
}

function tabClicked() {
  selectTab( $(this));
}

function selectTabByIndex( $tabs, tabIndex) {
  selectTab( $tabs.children().eq( tabIndex).children('a'));
/*
  var $div;
  if( tabIndex == undefined || tabIndex == null)
    $div = $tabs.children('.tabSelected');
  else
    $div = $tabs.children().eq( tabIndex);
  $div.children('a').trigger('click');

  //$tabs.children().eq( tabIndex).children('a').trigger('click');
*/
}

