// Utils for work

var data = {};
var doNotShowHomeMessage=false;

function writeCookie(c_name, value, exdays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
	document.cookie = c_name + "=" + c_value;
}

function changeLocation(){
	location = '/?restoreParams';
}

function xorString(str, val){
  if(!str || !val){
    return '';
  }
  var res='';
  for(var i=0; i<str.length; i++){
    res+=String.fromCharCode(str.charCodeAt(i)^val);
  }
  return res;
}

function reloadDatePicker(){
  var mregional = {
		  closeText: JS.messages.Calendar.Close,
		  prevText: JS.messages.Calendar.Prev,
		  nextText: JS.messages.Calendar.Next,
		  currentText: JS.messages.Calendar.Today,
		  monthNames: [JS.messages.Calendar.Jan.l,JS.messages.Calendar.Feb.l,JS.messages.Calendar.Mar.l,JS.messages.Calendar.Apr.l,JS.messages.Calendar.May.l,JS.messages.Calendar.Jun.l,
			  JS.messages.Calendar.Jul.l,JS.messages.Calendar.Aug.l,JS.messages.Calendar.Sep.l,JS.messages.Calendar.Oct.l,JS.messages.Calendar.Nov.l,JS.messages.Calendar.Dec.l],
		  monthNamesShort: [JS.messages.Calendar.Jan.s,JS.messages.Calendar.Feb.s,JS.messages.Calendar.Mar.s,JS.messages.Calendar.Apr.s,JS.messages.Calendar.May.s,JS.messages.Calendar.Jun.s,
			  JS.messages.Calendar.Jul.s,JS.messages.Calendar.Aug.s,JS.messages.Calendar.Sep.s,JS.messages.Calendar.Oct.s,JS.messages.Calendar.Nov.s,JS.messages.Calendar.Dec.s],
		  dayNames: [JS.messages.Calendar.Sunday.l, JS.messages.Calendar.Monday.l, JS.messages.Calendar.Tuesday.l, JS.messages.Calendar.Wednesday.l, JS.messages.Calendar.Thursday.l, JS.messages.Calendar.Friday.l, JS.messages.Calendar.Saturday.l],
		  dayNamesShort: [JS.messages.Calendar.Sunday.s, JS.messages.Calendar.Monday.s, JS.messages.Calendar.Tuesday.s, JS.messages.Calendar.Wednesday.s, JS.messages.Calendar.Thursday.s, JS.messages.Calendar.Friday.s, JS.messages.Calendar.Saturday.s],
		  dayNamesMin:  [JS.messages.Calendar.Sunday.s, JS.messages.Calendar.Monday.s, JS.messages.Calendar.Tuesday.s, JS.messages.Calendar.Wednesday.s, JS.messages.Calendar.Thursday.s, JS.messages.Calendar.Friday.s, JS.messages.Calendar.Saturday.s],
		  dateFormat: JS.messages.Calendar.Format,
		  firstDay: 1,
		  isRTL: false,
		  showOn: 'button',
			showButtonPanel: true,
			changeMonth: true,
			changeYear: true,
			duration: 0
	  };
  $.datepicker.setDefaults(mregional);
}

function daysBetween(date1, date2) {
    var ONE_DAY = 1000 * 60 * 60 * 24;
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();
    var difference_ms = Math.abs(date1_ms - date2_ms);
    return Math.round(difference_ms/ONE_DAY);
}

function changeModified(){
	$('#isModified', '#divRightWrapContent').val('1');
}
function changeModifiedDate(that){
	$(that).attr('validclass', 'date');
	$('#isModifiedDate', '#divRightWrapContent').val('1');
	changeModified();
}

function initDatePicker(id1, id2, toDate, date1, date2){
  $(id1).datepicker({
    maxDate: maxDate=$.datepicker.parseDate(JS.messages.Calendar.Format, date1)
  });
  $(id2).datepicker({
    maxDate: maxDate=$.datepicker.parseDate(JS.messages.Calendar.Format, date1)
  });
  return;
  /*
  var minDate;
  var maxDate;
  if(toDate){
    maxDate=0;
    minDate=$.datepicker.parseDate(JS.messages.Calendar.Format, date1);
  }else{
    maxDate=$.datepicker.parseDate(JS.messages.Calendar.Format, date1);
  }
  function reinitDatePicker(id, toDate, date){
    $(id).datepicker('option', toDate?'minDate':'maxDate', $.datepicker.parseDate(JS.messages.Calendar.Format, date));
  }
  $(id1).datepicker({
    maxDate: maxDate,
    minDate: minDate,
    onClose: function(dateText) { reinitDatePicker(id2, !toDate, dateText); }
  });
  if(date2){
    initDatePicker(id2, id1, !toDate, date2);
  }*/
}

function reloadCurrencyConverter(RateType, RateGroup){
	if(RateType=='')RateType='1';
	loadModule("#divCurrencyConverterBodyConv", "CurrencyConverter", {a:'converter', RateGroup: RateGroup, RateType: RateType}, function(){try{calculateSumms();}catch(e){}});
}
function reloadCurrencyConverterDate(RateGroup, RateDate){
	if(!validForm('divSlctCurrConvRateTypeWrap')){return false;}
	loadModule("#divCurrencyConverterBodyConv", "CurrencyConverter", {a:'converter', RateGroup: RateGroup, ExchangeDate:RateDate}, function(){try{calculateSumms();}catch(e){}});
}
function GetJSMessages(callback, mess){
  try{
    $.ajax({
      type: 'POST',
      url: '/exec.jsp?c=GetJSMessages',
      data: {sessionKey:sessionKey},
      async: true,
      cache: false,
      success: function(data){
          var obj;
          try{
            obj = eval('(' + data + ')');
            mess.messages=obj.messages;
          }catch(e){
          }
        },
      complete: function(){
          if(callback)callback();
        }
    });
  }catch(e){
  }
}

function ismaxlength(obj,eventObj){
	if(!obj.getAttribute("maxlength") || obj.getAttribute("maxlength")==''){
		return true;
	}
  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
  if(eventObj){
    var keyCode = (eventObj.keyCode) ? eventObj.keyCode : eventObj.which
    if (keyCode==8 || keyCode==46) return true;
  }
  return obj.value.length+1 <= mlength;
}

function selRadio(id){
  $("input",id).attr("checked", "true"); 
}
function chLang(lang, callback) {
  if(lang==null || lang==''){
    return;
  }
  execTran("ChangeLang",{"lang": lang},function () {
    GetJSMessages(function(){
      reloadDatePicker();
      if(callback)callback();
    }, JS);
  });
}

function isValidAccount(pAccountNo, bic, ptype){
	var pQBIC='';
	if(ptype==1)
		pQBIC=bic.substring(4,6);
	else 
		pQBIC=bic.substring(6,9);
	var vStr=LPad(pQBIC,3,"0")+pAccountNo, len=vStr.length, vMask=RPad("713",len,"713"), vRet=0;
	for(i=0;i<len;i++) vRet+=((vStr.charCodeAt(i)-"0".charCodeAt(0))*(vMask.charCodeAt(i)-"0".charCodeAt(0))%10);
	return (vRet%10==0);
}

function LPad(string,num,ch){
	var lenStr=string.length, lenCh=ch.length, flenStr=lenStr, st;
	while(lenStr<num){
		string = ch + string;
		lenStr += lenCh;}
	if(num>flenStr) st = lenStr - num;
	else st = 0;
	return string.substring(st,st + num);
}

function RPad(string,num,ch){
	var lenStr=string.length, lenCh=ch.length, flenStr=lenStr, st;
	while(lenStr<num){
		string += ch;
		lenStr += lenCh;}
	return string.substring(0,num);
}
		
function isValidAccountOld(acct, bic){
  var x = bic.replace(/^\s+|\s+$/g,"");
	var y = acct.replace(/^\s+|\s+$/g,"");
	n = 0;
	n += (parseInt(x.charAt(6))*7)%10;
	n += (parseInt(x.charAt(7))*1)%10;
	n += (parseInt(x.charAt(8))*3)%10;
	for(i=0;i<18;i+=3){
		n += (parseInt(y.charAt(i))*7)%10; 
		n += parseInt(y.charAt(i+1))%10;
		n += (parseInt(y.charAt(i+2))*3)%10;
	}
	n += (parseInt(y.charAt(18))*7)%10;
	n += parseInt(y.charAt(19))%10;
  return (n%10)==0;
}

function isValidINN(i){
  if ( i.match(/\D/) ) return false;
  var inn = i.match(/(\d)/g);
  if ( inn.length == 10 ){
    return inn[9] == String(((
      2*inn[0] + 4*inn[1] + 10*inn[2] + 
      3*inn[3] + 5*inn[4] +  9*inn[5] + 
      4*inn[6] + 6*inn[7] +  8*inn[8]
    ) % 11) % 10);
  }else if (inn.length == 12){
    return inn[10] == String(((
       7*inn[0] + 2*inn[1] + 4*inn[2] +
      10*inn[3] + 3*inn[4] + 5*inn[5] +
       9*inn[6] + 4*inn[7] + 6*inn[8] +
       8*inn[9]
    ) % 11) % 10) && inn[11] == String(((
      3*inn[0] +  7*inn[1] + 2*inn[2] +
      4*inn[3] + 10*inn[4] + 3*inn[5] +
      5*inn[6] +  9*inn[7] + 4*inn[8] +
      6*inn[9] +  8*inn[10]
    ) % 11) % 10);
  }
  return false;
}

function sendForm(formID,url,targetID,callback){
/**************************
* Функция посылает форму formID по адресу url и грузит результат в targetID
***************************/
if (!validForm(formID)){return false;}
	$.post(url, $('#'+formID).serialize(), function(data) {
		$('#'+targetID).html($("#divWait").html());
		$('#'+targetID).html(data);
		if (callback) callback();
	});
}//sendForm

function clearMenuSelection(){
  $('#divMenu .rtable tr').each(function(){
    $(this).removeClass('selected');
  });
  $('.rmenu_empty.rmenu_sel').removeClass('rmenu_sel');
}

var tableTextExtraction = function(node){
  var nc=$(node).attr("rsort");
  if(!nc || nc==""){
    nc=$(node).html();
  }
  return nc;
}

function errorMessager(item) {
  if ($('#actionContentDivWrap').is(':visible')) {
    return false;
  }
  var elem = $(item);
  var cls = elem.attr('validclass');
  var id = elem.attr('id')?elem.attr('id'):elem.attr('name');
  var inputTitle = '';
  var parentTdIndex = '';
  var errorMessagesText = JS.messages.errorMessages.emptyFields;
  if (elem.parent().is('form')) {
    inputTitle = elem.parent().parent().parent().find('td').first().text();
  }
  else  if (elem.parent().parent().find('td').length > 1) {
    if (elem.parent().parent().find('td').first().find('label')>0) {
      inputTitle = elem.parent().parent().find('td').first().find('label').text();
    }
    else {
      elem.parent().parent().find('td').each(function (){
        if ($(this).find('input,textarea,select').attr('id') == id || $(this).find('input,textarea,select').attr('name') == id) {
          parentTdIndex = Number($(this).index())-1;
        }
      })
      inputTitle = elem.parent().parent().find('td').eq(parentTdIndex).text();
    }
  }
  else inputTitle = elem.parent().find('div').first().text();
  if (inputTitle.indexOf('*')!=-1) {
    inputTitle = inputTitle.replace('*','');
  }
  errorMessagesText = errorMessagesText.substr(0,errorMessagesText.indexOf('%field%'))+' "'+inputTitle+'" '+ errorMessagesText.substr(errorMessagesText.indexOf('%field%')+7);
  var valueField = Number(elem.val());
  if (elem.attr('errmes')) {
    errorMessagesText = elem.attr('errmes');
  }
  else {
    if (cls=='summ' && valueField==0) {
      errorMessagesText = JS.messages.errorMessages.sumFields;
    } else {
      if (elem.val()!='') {
        errorMessagesText = JS.messages.errorMessages.filledWrong;
      }
    }
  }
  $('.div-error').each(function() {
    if ($(this).attr('inputid')==id) {
      $(this).empty();
      $(this).append(errorMessagesText).show();
      if ($(this).hasClass('only-div')) {
        var widthElem = elem.width()!=0 ? elem.width(): 'auto';
        $(this).width(widthElem);
      }
      $(this).parent().parent().show();
      mresize();
    }
  })
}
function addWrapErrorMessages(obj) {
  obj.find('input,select,textarea').each(function() {
    if ($(this).attr('validclass') || $(this).attr('validexp')) {
      var inputID = $(this).attr('id') ? $(this).attr('id') : $(this).attr('name');
      var id = '#'+inputID;
      var elem = '<div class="div-error" inputid="'+inputID+'"></div>'
      if ($('.logonWrap').length>0) {
        $(this).parent().append('<div class="div-error only-div" inputid="'+inputID+'"></div>')
      }
      else {
        if ($(this).hasClass('file_input')) {
          $(this).parent().parent().after('<td></td><td colspan="3">'+elem+'</td></tr>')
        }
        else $(this).parent().append('<div class="div-error" inputid="'+inputID+'"></div>')
      }
    }
  })
}
function delErrorMessages(item) {
  var id = $(item).attr('id')?$(item).attr('id'):$(item).attr('name');
  $('.div-error').each(function() {
    if ($(this).attr('inputid')==id) $(this).empty();
  })
  $('.tr-error').hide();
  $('.td-error').empty();
  mresize();
}
function SetError(item){
  if(!$(item).attr('readonly')){
    $(item).focus();
  }
  $(item).addClass('ValidError').keypress(function(){delValidError(item);delErrorMessages(item);});
}

function validForm(formID){
/**************************
* Функция валидации формы
* У поля ввода надо указать атрибут validexp с RegExp выражением проверки, либо атрибут validclass с классом 
* проверки (в этом случае RegExp будет подставлен автоматически).
* Форма может иметь еще функцию указанную в атрибуте validfn тега form для проверки взаимосвязанных случаев.
***************************/  
  var retValue = true;
  var f=true;
  var mark=function(item){
    if(f && !$(item).attr('readonly')){
      $(item).focus();
      f=!f;
    }
    errorMessager(item);
    $(item).addClass('ValidError').keypress(function(e){
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;
        if (keycode != 13){
          delErrorMessages(item);
          delValidError(item);
        }
    }).change(function(e){
        delErrorMessages(item);
        delValidError(item);
    });
    retValue=false;
  }
  $('input', '#'+formID).add('textarea', '#'+formID).add('select', '#'+formID).each(function(){
    var elem=this;
    //alert("["+$(this).val()+"]");
    if($(this).attr('disabled')){
    	return;
    }
    if(!($(this).attr('mempty')=='1' && $(this).val()=='' || $(this).attr('mzero')=='1' && $(this).val()=='0')){
    	if($(this).attr('mempty')=='0' && $(this).val()==''){
    		mark(elem);
    	}else{
		    var res='';
		    var vc='';
		    delValidError(elem);
		    if ($(elem).attr('validexp')!=null){
		      res=$(elem).attr('validexp');
                if(res!=''){
	              try{
	                re = new RegExp(res);
	                if (!re.test($(elem).val().replace(/^\s+|\s+$/g,""))){
	                  mark(elem);
	                  return;
	                }else{
	                }
	              }catch(ex){};
	            }
		    }
		    res='';
		    if($(elem).attr('validclass')!=null){
		      vc=$(elem).attr('validclass');
		      var minlen=$(elem).attr('minlen');
		      var maxlen=$(elem).attr('maxlen')!=null?$(elem).attr('maxlen'):$(elem).attr('maxlength')!=-1?$(elem).attr('maxlength'):null;
		      if(vc=="float"){
		    	  if($.trim($(elem).val())=='' || minlen && (minlen > $.trim($(elem).val()).length) || maxlen && (maxlen < $.trim($(elem).val()).length) ){mark(elem);}
		      }
		      if(vc=="int"){
		        if($(elem).val()==''){mark(elem);}
		        res='^([0-9]';
		        if(maxlen || minlen){
		          res+='{';
		          if(minlen){
		            res+=minlen;
		          }else{
		            res+='0';
		          }
		          res+=',';
		          if(maxlen){
		            res+=maxlen;
		          }
		          res+='}';
		        }else{
		          res+='+';
		        }
		        res+=')$';
		      }
		    }

            if(res!=''){
              try{
                re = new RegExp(res);
                if (!re.test($(elem).val().replace(/^\s+|\s+$/g,""))){
                  mark(elem);
                  return;
                }else{
                }
              }catch(ex){};
            }

		    if(vc=="string"){
		      if(maxlen && $(elem).val().length>maxlen || minlen && $(elem).val().length<minlen){
		       mark(elem);
		      }
		      var vsc=$(elem).attr('validsubclass');
		      if(vsc && vsc=='ppfield'){
		    	  vcsre=/^[ !"#$%&'()*+,-.\/\\0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\]^_`abcdefghijklmnopqrstuvwxyz{|}~АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёЁ№<>«»]+$/;
		        if (!vcsre.test($(elem).val().split('\n').join(''))){
		          mark(elem);
		        }
		      }
		    }

		    if(vc=="summ" || vc=="float"){
		      $(elem).val($(elem).val().replace(',', '.'));
		      if(isNaN($(elem).val()) || $.trim($(elem).val()).length==0){
		        mark(elem);
		      }else{
                try{
                  re = new RegExp(res);
                  if (!re.test($(elem).val().replace(/^[0-9]*\.?[0-9]+$/g,""))){
                    mark(elem);
                    return;
                  }else{
                  }
                }catch(ex){};

                var minval=$(elem).attr('minval');
		        var maxval=$(elem).attr('maxval');
		        var elVal=Number($(elem).val());
		        var bl=elVal<=0 && vc == "summ";
		        if(minval && minval!='' && !isNaN(minval)){
		          bl=elVal<minval;
		        }
		        if(maxval && maxval!='' && !isNaN(maxval)){
		          bl=bl || (elVal>maxval);
		        }
		        if(bl){
		          mark(elem);
		        }else{
		          var num = Number($(elem).val());
                  if(vc=="summ") {
                    $(elem).val(num.toFixed(2));
                  }
		        }
		      }
		    }
		    if(vc=="int"){
		      var maxval=$(elem).attr('maxval');
		      var minval=$(elem).attr('minval');
		      var elVal=Number($(elem).val());
		      var bl=false;
		      if(minval && minval!='' && !isNaN(minval)){
		        bl=elVal<minval;
		      }
		      if(maxval && maxval!='' && !isNaN(maxval)){
		        bl=bl||elVal>maxval;
		      }
		      if(bl){
		        mark(elem);
		      }
		    }
		    if(vc=="date"){
		      var bl=false;
	        var elVal=$(elem).val();
		      var maxval=$(elem).datepicker('option','maxDate');
		      var minval=$(elem).datepicker('option','minDate');
		      var dateArr=elVal.split('/');
		      if(dateArr.length==3 && isDate(dateArr[0],dateArr[1],dateArr[2])){
						var dateTest=new Date(dateArr[2],Number(dateArr[1])-1,dateArr[0]);
						if(maxval){
							maxval.setHours(0);
							maxval.setMinutes(0);
							maxval.setSeconds(0);
							maxval.setMilliseconds(0);
							if(dateTest.getTime() > maxval.getTime()){
		      			bl=true;
							}
						}
						if(minval){
							minval.setHours(0);
							minval.setMinutes(0);
							minval.setSeconds(0);
							minval.setMilliseconds(0);
							if(dateTest.getTime() < minval.getTime()){
		      			bl=true;
							}
						}
		      } else{
		      	bl=true;
		      }
		      if(bl){
		        mark(elem);
		      }
		    }
		    if(vc=="datetime"){
		      var bl=false;
	        var elVal=$(elem).val();
		      var maxval=$(elem).datepicker('option','maxDate');
		      var minval=$(elem).datepicker('option','minDate');
				var tmpArr = elVal.split(' ');	
		      var dateArr=tmpArr[0].split('/');
			  var timeArr=tmpArr[1].split(':');
		      if(dateArr.length==3 && isDate(dateArr[0],dateArr[1],dateArr[2])&& tmpArr.length==1){
						var dateTest=new Date(dateArr[2],Number(dateArr[1])-1,dateArr[0]);
						if(maxval){
							maxval.setHours(0);
							maxval.setMinutes(0);
							maxval.setSeconds(0);
							maxval.setMilliseconds(0);
							if(dateTest.getTime() > maxval.getTime()){
		      			bl=true;
							}
						}
						if(minval){
							minval.setHours(0);
							minval.setMinutes(0);
							minval.setSeconds(0);
							minval.setMilliseconds(0);
							if(dateTest.getTime() < minval.getTime()){
		      			bl=true;
							}
						}
		      } else if(dateArr.length==3 && timeArr.length==2 && isDate(dateArr[0],dateArr[1],dateArr[2],timeArr[0],timeArr[1])){
						var dateTest=new Date(dateArr[2],Number(dateArr[1])-1,dateArr[0],timeArr[0],timeArr[1]);
						if(maxval){
							maxval.setSeconds(0);
							maxval.setMilliseconds(0);
							if(dateTest.getTime() > maxval.getTime()){
		      			bl=true;
							}
						}
						if(minval){
							minval.setSeconds(0);
							minval.setMilliseconds(0);
							if(dateTest.getTime() < minval.getTime()){
		      			bl=true;
							}
						}
		      }  else{
		      	bl=true;
		      }
		      if(bl){
		        mark(elem);
		      }
		    }
      }
    }
  });
  if ($('#'+formID).attr('validfn')!=null){retValue = eval($('#'+formID).attr('validfn')) && retValue};
	return retValue;
}//validForm

function isDate (day,month,year) {
	try{
		day=Number(day);
		month=Number(month);
		year=Number(year);
	}catch(e){
		return false;
	}
	month--;
  var test = new Date(year,month,day);
  if ((test.getFullYear() == year) &&
       (month == test.getMonth()) &&
       (day == test.getDate()) )
      return true;
  else
      return false;
}

function loadCardsMenu(pan, mbr){
    saveHomeModulesPos();
    MainMenu.openMenu("MainMenu_AcctsCards");
    $('#divMain').empty();
    $("#divLeftMenu").show();
  loadModule('#divMenu','AcctsCardsMenu',{},function() {
    AcctsMenu.showMenu("hdrCards");
    if($('#AcctMenu_Cards_Tbl').length>0){
      loadModule('#AcctMenu_Cards_Tbl', 'AcctsCardsMenu', {a:'cards'}, function(){
       $("#trCard_"+pan+"-"+mbr).addClass("selected");
        mresize();
      });
    }
    if($('#AcctMenu_Accts_Tbl').length>0){
      loadModule('#AcctMenu_Accts_Tbl', 'AcctsCardsMenu', {a:'accts', type:'1'}, function(){
        mresize();
      });
    }
    if($('#AcctMenu_Credit_Tbl').length>0){
      loadModule('#AcctMenu_Credit_Tbl', 'AcctsCardsMenu', {a:'accts', type:'31'}, function(){
        mresize();
      });
    }
    if($('#AcctMenu_Deposit_Tbl').length>0){
      loadModule('#AcctMenu_Deposit_Tbl', 'AcctsCardsMenu', {a:'accts', type:'11'}, function(){
        mresize();
      });
    }
    if($('#AcctMenu_Bonus_Tbl').length>0){
      loadModule('#AcctMenu_Bonus_Tbl', 'AcctsCardsMenu', {a:'accts', type:'91'}, function(){
        mresize();
      });
    }	
  });
}
function reloadCardsMenu(pan , mbr){     
  clearMenuSelection(); 
  AcctsMenu.showMenu('hdrCards');
  loadModule('#AcctMenu_Cards_Tbl', 'AcctsCardsMenu', {a:'cards'}, function(){
      $('#divMenu #trCard_'+pan+'-'+mbr).addClass('selected');
      mresize();
  });
}
function goToAcctHist(acct, actype){
  var menu="";
  if(actype=='1'){
    menu="hdrAccts";
  }else if(actype=='31'){
    menu="hdrCredit";
  }else if(actype=='11'){
    menu="hdrDeposit";
  }else if(actype=='91'){
    menu="hdrBonus";
  }
  showModuleRightWrap('AcctInfo',{'Acct': acct},function(){
	  loadModule('#divAcctLimits', 'AcctLimits',{'Account': acct});												 	
      AcctsInfoTabs.showMenu('AcctsInfoTabs_OperHist', function(){
        loadModule('#divOperHist', 'OperHist',{'pacct':acct}, function(){
          $('#btnMakeHistory').click();
        });
      });
    });
  AcctsMenu.showMenu(menu, function(){

    clearMenuSelection();
    $("#trAcct_"+acct).addClass('selected');
  });
}
function goToAcct(acct, actype){
  var menu="";
  if(actype=='1'){
    menu="hdrAccts";
  }else if(actype=='31'){
    menu="hdrCredit";
  }else if(actype=='11'){
    menu="hdrDeposit";
  }else if(actype=='91'){
    menu="hdrBonus";
  }
  showModuleRightWrap('AcctInfo',{'Acct': acct},function(){
      loadModule('#divOperHist', 'OperHist',{'pacct':acct});
	  loadModule('#divAcctLimits', 'AcctLimits',{'Account': acct});
    });
  AcctsMenu.showMenu(menu, function(){

    clearMenuSelection();
    $("#trAcct_"+acct).addClass('selected');
  });
}
function goToCardHist(pan, mbr){
     showModuleRightWrap('CardInfo',{'PAN': pan, 'MBR': mbr}, function(){
      CardsInfoTabs.showMenu('CardsInfoTabs_OperHist', function(){
        loadModule('#divOperHist', 'OperHist',{'pcard':pan+'-'+mbr}, function(){
          $('#btnMakeHistory').click();
        });
        loadModule('#divLimits', 'CardLimits',{'PAN':pan, 'MBR':mbr}, function(){  
          loadModule('#divCardLimitsBottom', 'CardLimits',{a:'buttons', 'PAN':pan, 'MBR':mbr});
        });
      });
    });
  AcctsMenu.showMenu("hdrCards", function(){
    clearMenuSelection();
    $("#trCard_"+pan+"-"+mbr).addClass('selected');
  });
}
function goToCard(pan, mbr){
  showModuleRightWrap('CardInfo',{'PAN': pan, 'MBR': mbr}, function(){
        loadModule('#divOperHist', 'OperHist',{'pcard':pan+'-'+mbr});
        loadModule('#divLimits', 'CardLimits',{'PAN':pan, 'MBR':mbr}, function(){  
          loadModule('#divCardLimitsBottom', 'CardLimits',{a:'buttons', 'PAN':pan, 'MBR':mbr});
        });
    });
  AcctsMenu.showMenu("hdrCards", function(){
    
    clearMenuSelection();
    $("#trCard_"+pan+"-"+mbr).addClass('selected');
  });
}
function loadAcctsMenu(acct, type){
  saveHomeModulesPos();
  MainMenu.openMenu("MainMenu_AcctsCards");
  $('#divMain').empty();
  $("#divLeftMenu").show();
  loadModule('#divMenu','AcctsCardsMenu',{},function() {
    if($('#AcctMenu_Cards_Tbl').length>0){
      loadModule('#AcctMenu_Cards_Tbl', 'AcctsCardsMenu', {a:'cards'}, function(){
        mresize();
      });
    }
    if($('#AcctMenu_Accts_Tbl').length>0){
      loadModule('#AcctMenu_Accts_Tbl', 'AcctsCardsMenu', {a:'accts', type:'1'}, function(){
        var acctItem = $('#trAcct_'+acct, '#AcctMenu_Accts_Tbl');
        acctItem.addClass('selected');
        if(acctItem.length>0){
            var menu = acctItem.parents('.rmenu').attr('id');
            AcctsMenu.showMenu(menu);
        }
        mresize();
      });
    }
    if($('#AcctMenu_Credit_Tbl').length>0){
      loadModule('#AcctMenu_Credit_Tbl', 'AcctsCardsMenu', {a:'accts', type:'31'}, function(){
        var acctItem = $('#trAcct_'+acct, '#AcctMenu_Credit_Tbl');
        acctItem.addClass('selected');
        if(acctItem.length>0){
            var menu = acctItem.parents('.rmenu').attr('id');
            AcctsMenu.showMenu(menu);
        }
        mresize();
      });
    }
    if($('#AcctMenu_Deposit_Tbl').length>0){
      loadModule('#AcctMenu_Deposit_Tbl', 'AcctsCardsMenu', {a:'accts', type:'11'}, function(){
        var acctItem = $('#trAcct_'+acct, '#AcctMenu_Deposit_Tbl');
        acctItem.addClass('selected');
        if(acctItem.length>0){
            var menu = acctItem.parents('.rmenu').attr('id');
            AcctsMenu.showMenu(menu);
        }
        mresize();
      });
    }
    if($('#AcctMenu_Bonus_Tbl').length>0){
      loadModule('#AcctMenu_Bonus_Tbl', 'AcctsCardsMenu', {a:'accts', type:'91'}, function(){
        var acctItem = $('#trAcct_'+acct, '#AcctMenu_Bonus_Tbl');
        acctItem.addClass('selected');
        if(acctItem.length>0){
            var menu = acctItem.parents('.rmenu').attr('id');
            AcctsMenu.showMenu(menu);
        }
        mresize();
      });
    }	
  });
}
function reloadPaymMenu(menu, item){
  //PaymentsMenu.showMenu(menu);
  clearMenuSelection();
  if(menu=="hdrPayments"){
    loadModule('#PaymentsMenu_Payments_Tbl', 'PaymentsMenu', {a:'payments'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }else if(menu=="hdrCardPayments"){
    loadModule('#PaymentsMenu_CardPayments_Tbl', 'PaymentsMenu', {a:'cards'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }else if(menu=="hdrSchedulePayments"){
    loadModule('#PaymentsMenu_Schedules_Tbl', 'PaymentsMenu', {a:'schedules'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }
}
function reloadDraftsMenu(menu, item){
  //DraftsMenu.showMenu(menu);
  clearMenuSelection();
  if(menu=="hdrDrafts"){
    loadModule('#DraftsMenu_Drafts_Tbl', 'DraftsMenu', {a:'drafts'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }else if(menu=="hdrScheduleDrafts"){
    loadModule('#DraftsMenu_Schedules_Tbl', 'DraftsMenu', {a:'schedules'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }
}
function reloadPaymTransMenu(menu, item){

  //PaymentsTransfersMenu.showMenu(menu);
  clearMenuSelection();
  if(menu=="hdrPaymentsTransfers"){
    loadModule('#PaymentsTransfersMenu_PaymentsTransfers_Tbl', 'PaymentsTransfersMenu', {a:'templates'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }else if(menu=="hdrCardPayments"){
    loadModule('#PaymentsTransfersMenu_CardPayments_Tbl', 'PaymentsTransfersMenu', {a:'cards'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }else if(menu=="hdrSchedulePaymentsTransfers"){
    loadModule('#PaymentsTransfersMenu_SchedulePaymentsTransfers_Tbl', 'PaymentsTransfersMenu', {a:'schedules'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }
}
function reloadTransMenu(menu, item){
  TransfersMenu.showMenu(menu);
  clearMenuSelection();
  if(menu=="hdrTransfers"){
    loadModule('#TransfersMenu_Transfers_Tbl', 'TransfersMenu', {a:'transfers'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }else if(menu=="hdrScheduleTransfers"){
    loadModule('#TransfersMenu_Schedules_Tbl', 'TransfersMenu', {a:'schedules'},function(){
      if(item) $('#divMenu '+item).addClass('selected');
      mresize();
    });
  }
}
function delValidError(elem){
/**************************
* Функция удаления признака ошибки валидации
***************************/
		$(elem).removeClass('ValidError');
    $('.tr-error').hide();
    $('.td-error').empty();
    //$(elem).parent().find('.div-error').empty();
		//$('#'+$(elem).attr('name')+'_ValidError').hide();
}//delValidError

/*var GlobalXMLHttpRequest;*/
var GlobalRequestArr = new Array();
var GlobalTmpWin = null;
var GlobalParams = new Array();
var GlobalCommand;
var GlobalCallback;

function hideMessageDiv() {
	restorePrintDiv();
  $('#fadeDiv').css('visibility', 'hidden');
  $("#fadeDiv #fadeContent").empty();
  if($.browser.msie && $.browser.version == 6){
   $('select').css('visibility', 'visible');
  }
}

function submitenter(field,e, fn){
  //if($('#fadeDiv').css('visibility')!='hidden'){return false;}
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if (keycode == 13){
     if(fn)fn();
     return false;
  }else return true;
}

function showMessageDiv() {
  $('input').each(function(){$(this).blur();});
  $('#fadeDiv').css('visibility', 'visible');
  if($.browser.msie && $.browser.version == 6){
    $('select').css('visibility', 'hidden');
    $('#fadeDiv select').css('visibility', 'visible');
  }
} 
function showCustomContent(content) { 
  $("#fadeDiv #fadeContent").empty().html(content);
	showMessageDiv();
  mresize();
} 
function saveToFile(text){
  sendData('/txt','string='+encodeURIComponent(text));
}
function saveTableContentToCSV(text){
  text=text.replace(new RegExp('\r', 'g'), '')
           .replace(new RegExp('\n', 'g'), ' ');

  while(text.indexOf('  ')!=-1){
    text=text.replace(new RegExp('  ', 'g'), ' ');
  }
  text="<table>"+text+"</table>";
  sendData('/csv','html='+encodeURIComponent(text));
}
function sendData(url, data, method){
	if( url && data ){ 
		var inputs = '';
		$.each(data.split('&'), function(){ 
			var pair = this.split('=');
			inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
		});
		$('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
		.appendTo('body').submit();
	};
}

function execTran(tran,params,callback,hidemessage,err_callback, secondary_callb, HideCommission){
  var InterProList = "";
  copyToTmp();
  if(!hidemessage) showCustomContent($("#divBigWait").html());
 
  if(params && !params.push){
    var data=new Array();
 	for(key in params){
      data.push({name:key, value:params[key]});
    }
    params=data;
  }else{
	  if(!params){
		  params = new Array();
	  }
  }
  params.push({name:'cookiesDisabled', value:navigator.cookieEnabled?'0':'1'});
  sendTran = tran;
  if(tran=="GetPANRq"
  	|| tran=="ScheduleRq"
  	|| tran=="CalcVCardCVV2Rq"
  	|| tran=="ChangeCMSAddressRq"
  	|| tran=="SetExtraAuthLevelRq"
  	|| tran=="SetExtraAuthAddressRq"
  	|| tran=="ChangeCardCMSAddressRq"
  	|| tran=="PINChangeRq"
  	|| tran=="ChangePasswordRq"
  	|| tran=="ChangeCardPasswordRq"
  	|| tran=="InternetPINChangeRq"
  	|| tran=="CardPaymentRq"
  	|| tran=="ReverseRq"
  	|| tran=="CardLockRq"
  	|| tran=="CardActivationRq"
  	|| tran=="CancelScheduleRq"
  	|| tran=="UpdateScheduleRq"
  	|| tran=="PrepaidRq"
  	|| tran=="SetTmpCardLimitsRq"
  	|| tran=="BMSSendMessageRq"
  	|| tran=="CreateVCardRq"
  	|| tran=="AddAbonentRq"
  	|| tran=="DelAbonentRq"
  	|| tran=="UpdateAbonentRq"
  	|| tran=="AddVendorRq"
  	|| tran=="DelVendorRq"
  	|| tran=="AddCardVendorRq"
  	|| tran=="DelCardVendorRq"
  	|| tran=="AddTransferTemplateRq"
  	|| tran=="DelTransferTemplateRq"
  	|| tran=="UpdateTransferTemplateRq"
  	|| tran=="UpdateVendorRq"
  	|| tran=="SetCardLimitsRq"){
  	if(!params || params==null){
  		params=new Array();
  	}
    params.push({name: 'FormMustBeSigned', value: ''});
 	for(key in params){
	  InterProList += params[key].name+";";
    }
	sendTran += "&InterProList="+InterProList;
  }
  /* TWIB-545 */
  
  var sessionKeyPresent = false;
  for(key in params){
    if(params[key].name=='sessionKey'){
        sessionKeyPresent = true;
        break;
    }
  }
    if(!sessionKeyPresent){
        params.push({name: 'sessionKey', value: sessionKey});
    }
    
  var args = arguments;
  $.ajax({
    type: 'POST',
    url: '/exec.jsp?c='+sendTran,
    async: true,
    cache: false,
    data: params,
    success: function(data){
        var resp = eval('(' + data + ')');
        if(hidemessage) {if (secondary_callb) secondary_callb(); if(callback){callback(resp);}return;}
        var name = "";
        if (resp!=null){
          $.each(resp, function(i, n){
            name = i;
          });
        }
        if(resp.NoLogin  || resp.BadSession){
          /*var csm="";
          if(CSMName){
            csm="?CSMName="+CSMName;
          }*/
          changeLocation();
          return;
        }
        if(resp.Fault){
          /* TWIB-545 */
          if(execTranFaultHandler(args, resp)){
            return;
          }
          if(resp.Fault.DynResp && (resp.Fault.Code.Value=="1013"
            || resp.Fault.Code.Value=="1014"
            || resp.Fault.Code.Value=="1015"
            || resp.Fault.Code.Value=="1016"
            || resp.Fault.Code.Value=="1017"
            || resp.Fault.Code.Value=="1020"
            || resp.Fault.Code.Value=="1023"
            ) || resp.Fault.CapResp && resp.Fault.Code.Value=="53"){
            showErrorMessageNC(resp, function(){
              copyFromTmp();
            });
            return;
          }
          if (resp.Fault.Code.Value=="1026") {
            showMessage(JS.messages.CommonLogin,'','','',function(){
              var doCh=true;
              params.push({name: "CommonLoginType", value: $("#ltype").val()});

              if($('#tmpDivDynamic').children().length>0){
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
              }else{
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
              }
              mresize();
            },function(){
              loadModule('#actionContentDiv','Logon',{a: 'CommonLogin'});
            },function(){copyFromTmp();},'','',JS.messages.Next,JS.messages.Cancel,null,null,true);
          }else if (resp.Fault.Code.Value=="5006") {
            if(resp.Fault.AxsResp){
              var axspan = '';
              for(key in params){
                if(params[key].name== "AXSPAN"){
                  axspan = params[key].value;
                }
              }
              showMessage(JS.messages.AXS,'','','',function(){
                if(!validForm('fadeDiv')){return false;}
                params.push({name: 'AXSToken', value: $('#AXSToken').val()});
                if($('#tmpDivDynamic').children().length>0){
                  copyFromTmp();
                  execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();});
                }else{
                  copyFromTmp();
                  execTran(tran,params,callback,hidemessage,err_callback);
                }
              },function(){
                loadModule('#fadeDiv #actionContentDiv','AXS',{masked:axspan, a: 'AXSSign'}, function(){
                    axsSetupFlickering(resp.Fault.Detail.Flicker);
                });
              },function(){copyFromTmp();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
            }else{
                loadModuleSimple('#tmpDivSimpleLoad', 'AXS',{
			        a:'CountExtended'
		        },function(){
		            var loadCAP = function(axspan){
                        var doCh=true;
		                if (params.push){ 
                              for(key in params){
                                if(params[key].name== 'AXSPAN'){
                                  doCh=false;
                                  params[key].value=axspan;
                                }
                              }
                            }
                            if(doCh){
                              params.push({name: 'AXSPAN', value: axspan});
                            }
                            copyFromTmp();
                            execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
		            }
			        if($('#count', '#tmpDivSimpleLoad').val()=='1'){
                        var axspan=$('#axspan', '#tmpDivSimpleLoad').val();
			            loadCAP(axspan);
			        }else{
			            showMessage(JS.messages.AXS,'','','',function(){
                            if(!validForm('fadeDiv')){return false;}
                            var axspan=$('#axspan  option:selected').attr('pan');                            
                            loadCAP(axspan);
                          },function(){
                            loadModule('#fadeDiv #actionContentDiv','AXS',{a:'AXSCards'});
                          },function(){copyFromTmp();},'','',JS.messages.Next,JS.messages.Cancel,null,null,true);
			        }
		        },function(rpp){
		            var rppe = eval('(' + rpp + ')');
		            showErrorMessage(rppe);
		        });
            }
          } else if (resp.Fault.Code.Value=="1022") {
            if(resp.Fault.CapResp){
              var prevTranId='';
		      if(resp.Fault.Detail && resp.Fault.Detail.TranId && resp.Fault.Detail.TranId != ''){
			      prevTranId=resp.Fault.Detail.TranId;
		      }
              var capChlng=false;
		      if(resp.Fault.Detail && resp.Fault.Detail.CAPChallenge && resp.Fault.Detail.CAPChallenge != ''){
			      capChlng=true;
		      }
              var panForCAP = '';
              for(key in params){
                if(params[key].name== "MaskedPAN"){
                  panForCAP = params[key].value;
                }
              }
              showMessage(JS.messages.CAP2,'','','',function(){ 
                if(!validForm('fadeDiv')){return false;}
                params.push({name: "CAPToken", value: $("#CAPToken").val()});
                if($('#tmpDivDynamic').children().length>0){
                  copyFromTmp();
                  execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();});
                }else{
                  copyFromTmp();
                  execTran(tran,params,callback,hidemessage,err_callback);
                }
              },function(){
                var sendDataForCapDyn = {masked:panForCAP, a: capChlng?"CAPSign":"CAPSignDyn","CAPChallenge":resp.Fault.Detail.CAPChallenge};
                if(!capChlng){
                  for(key in params){
                    if(params[key].name== 'GenerateDynPasswordRq___Address'){
                      sendDataForCapDyn['GenerateDynPasswordRq___Address'] = params[key].value;
                    }else if(params[key].name== 'GenerateDynPasswordRq___Channel'){
                      sendDataForCapDyn['GenerateDynPasswordRq___Channel'] = params[key].value;
                    }else if(params[key].name== 'MaskedAdr'){
                      sendDataForCapDyn['MaskedAdr'] = params[key].value;
                    }
                  }
                  sendDataForCapDyn['PrevTranId'] = prevTranId;
                  sendDataForCapDyn['What'] = 2;
                }
                loadModule('#fadeDiv #actionContentDiv',"CAP",sendDataForCapDyn);
              },function(){copyFromTmp();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
            }else{
                var capChlng=false;
		        if(resp.Fault.Detail && resp.Fault.Detail.CAPChallenge && resp.Fault.Detail.CAPChallenge != ''){
			        capChlng=true;
		        }
                loadModuleSimple('#tmpDivSimpleLoad', 'CAP',{
			        a:(capChlng?'CountExtended':'CountExtendedDyn')
		        },function(){
		            var loadCAP = function(pan,mbr,masked, address, channel, maskedAdr){
                        var doCh=true;
		                if (params.push){ 
                              for(key in params){
                                if(params[key].name== "AuthPAN"){
                                  doCh=false;
                                  params[key].value=pan;
                                }else if(params[key].name== "AuthMBR"){
                                  doCh=false;
                                  params[key].value=mbr;
                                }else if(params[key].name== "MaskedPAN"){
                                  doCh=false;
                                  params[key].value=masked;
                                }else if(params[key].name== "GenerateDynPasswordRq___Address"){
                                  doCh=false;
                                  params[key].value=address;
                                }else if(params[key].name== "GenerateDynPasswordRq___Channel"){
                                  doCh=false;
                                  params[key].value=channel;
                                }else if(params[key].name== "MaskedAdr"){
                                  doCh=false;
                                  params[key].value=maskedAdr;
                                }
                              }
                            }
                            if(doCh){
                              params.push({name: "AuthPAN", value: pan});
                              params.push({name: "AuthMBR", value: mbr});
                              params.push({name: "MaskedPAN", value: masked});
                              
                              params.push({name: "GenerateDynPasswordRq___Address", value: address});
                              params.push({name: "GenerateDynPasswordRq___Channel", value: channel});
                              params.push({name: "MaskedAdr", value: maskedAdr});
                            }
                            copyFromTmp();
                            execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
		            }
			        if($('#count', '#tmpDivSimpleLoad').val()=='1'){
                        var pan=$('#pan', '#tmpDivSimpleLoad').val();
                        var mbr=$('#mbr', '#tmpDivSimpleLoad').val();
                        var masked=$('#masked', '#tmpDivSimpleLoad').val();
                        var address=$('#address', '#tmpDivSimpleLoad').val();
                        var channel=$('#channel', '#tmpDivSimpleLoad').val();
                        var maskedAdr=$('#maskedAdr', '#tmpDivSimpleLoad').val();
			            loadCAP(pan, mbr, masked, address, channel, maskedAdr);
			        }else{
			            showMessage(JS.messages.CAP2,'','','',function(){
                            if(!validForm('fadeDiv')){return false;}
                            var pan=$("#AuthPAN  option:selected").attr("pan");
                            var mbr=$("#AuthPAN  option:selected").attr("mbr");
                            var masked=$("#AuthPAN").val();
                            
                            var address=$('#dynAuthField option:selected').attr('daa');
                            var channel=$('#dynAuthField option:selected').attr('dac');
                            var maskedAdr=$('#dynAuthField option:selected').attr('mac');
                            
                            loadCAP(pan, mbr, masked, address, channel, maskedAdr);
                          },function(){
                            loadModule('#fadeDiv #actionContentDiv','CAP',{a: capChlng?'CAPCards':'CAPCardsDyn'});
                          },function(){copyFromTmp();},'','',JS.messages.Next,JS.messages.Cancel,null,null,true);
			        }
		        },function(rpp){
		        var rppe = eval('(' + rpp + ')');
		        showErrorMessage(rppe);
		        });
            }
          } else if (resp.Fault.Code.Value=="1021") {
            showMessage(JS.messages.CAP,'','','',function(){
              if(!validForm('fadeDiv ')){return false;}
              var doCh=true;
              var pan=$("#AuthPAN  option:selected").attr("pan");
              var mbr=$("#AuthPAN  option:selected").attr("mbr");
              if (params.push){ 
                for(key in params){
                  if(params[key].name== "AuthPAN"){
                    doCh=false;
                    params[key].value=pan;
                  }else if(params[key].name== "CAPToken"){
                    doCh=false;
                    params[key].value=$("#CAPToken").val();
                  }else if(params[key].name== "AuthMBR"){
                    doCh=false;
                    params[key].value=mbr;
                  }
                }
              }
              if(doCh){
                params.push({name: "CAPToken", value: $("#CAPToken").val()});
                params.push({name: "AuthPAN", value: pan});
                params.push({name: "AuthMBR", value: mbr});
              }

              if($('#tmpDivDynamic').children().length>0){
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
              }else{
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
              }
              mresize();
            },function(){
              loadModule('#actionContentDiv','CAP',{a: 'CAPToken'});
            },function(){copyFromTmp();},'','',JS.messages.Next,JS.messages.Cancel,null,null,true);
            
          } else if (resp.Fault.Code.Value=="18") {
            var prevTranId='';
			if(resp.Fault.Detail && resp.Fault.Detail.TranId && resp.Fault.Detail.TranId != ''){
				prevTranId=resp.Fault.Detail.TranId;
			}
		    loadModuleSimple('#tmpDivSimpleLoad', 'DynamicAuth',{
			    a:'CountExtended'
		    },function(){
		        var loadDynPassForm = function(sdata){
                    showMessage(JS.messages.Dynamic,'','','',function(){
                        if(!validForm('fadeDiv')){return false;}
                        var doCh=true;
                        if (params.push){ 
                          for(key in params){
                            if(params[key].name == "DynamicPassword"){
                              params[key].value=$("#inDynamicPassword").val();
                              doCh=false;
                            }
                          }
                        }else {
                          params = new Array();
                        }
                        if(doCh){
                          params.push({name: "DynamicPassword", value: $("#inDynamicPassword").val()});
                          params.push({name: "PrevTranId", value: prevTranId});
                        }
                        if($('#tmpDivDynamic').children().length>0){
                          copyFromTmp();
                          execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
                        }else{
                          copyFromTmp();
                          execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
                        }
                        mresize();
                      },function(){
                         $('#btn1', '#fadeDiv').hide();
                         loadModule('#fadeDiv #actionContentDiv','DynamicAuth', sdata, function(){
                            $('#btn1', '#fadeDiv').show();
                         });
                      },function(){copyFromTmp();},'','', JS.messages.Ok,JS.messages.Cancel,null,null,true);
                }
			    if($('#count', '#tmpDivSimpleLoad').val()=='1'){
			        var sdata = {
			            a:'Password',
			            PrevTranId:prevTranId,
			            GenerateDynPasswordRq___Address:$('#address', '#tmpDivSimpleLoad').val(),
			            GenerateDynPasswordRq___Channel:$('#channel', '#tmpDivSimpleLoad').val(),
			            Masked:$('#masked', '#tmpDivSimpleLoad').val()
			        };
			        loadDynPassForm(sdata);
			    }else{
			        showMessage(JS.messages.Dynamic,'','','',function(){
                      var frmDA=$('#frmDynamicAuth').formToArray();
                      var daa=$('#dynAuthField option:selected').attr('daa');
                      var dac=$('#dynAuthField option:selected').attr('dac');
                      var mac=$('#dynAuthField option:selected').attr('mac');
                      frmDA.push({name: "GenerateDynPasswordRq___Address", value: daa});
                      frmDA.push({name: "GenerateDynPasswordRq___Channel", value: dac});
	                  frmDA.push({name: "Masked", value: mac});
	                  frmDA.push({name: "PrevTranId", value: prevTranId});
                      loadDynPassForm(frmDA);
                    },function(){
                     $('#btn1', '#fadeDiv').hide();
                      loadModule('#fadeDiv #actionContentDiv','DynamicAuth',null,function(){
                        $('#btn1', '#fadeDiv').show();
                      });
                    },function(){copyFromTmp();},'','',JS.messages.Send,JS.messages.Cancel,null,null,true);
			    }
		    },function(rpp){
		        var rppe = eval('(' + rpp + ')');
		        showErrorMessage(rppe);
		    });
          } else if (resp.Fault.Code.Value=="11") {
            showMessage(JS.messages.PINChange,'','','',function(){
              if(!validForm('frmPINChange')){return false;}

              var tranName=$("#tranName").val();
              var PCData;
              if(tranName=='ChangePasswordRq'){
              	PCData={NewPassword : xorString($("#NewPIN").val(),$("#AuthKEY").val())};
              }else{
              	PCData={NewPIN : xorString($("#NewPIN").val(),$("#AuthKEY").val())};
              }
              execTran(tranName, PCData, function(resp){
								/*var csm="";
								if(CSMName){
								csm="?CSMName="+CSMName;
								}*/
						          showMessage('', JS.messages.UseNewPIN, function(){
						          	execTran("LogoffRq",{},function(){
						          		changeLocation();
						          	});
						          },null,function(){
						          	execTran("LogoffRq",{},function(){
						          		changeLocation();
						          	});
						          });
						        },null,function(){
								/*var csm="";
								if(CSMName){
								csm="?CSMName="+CSMName;
								}*/
								execTran("LogoffRq",{},function(){
									changeLocation();
		          	});
	            });
            },function(){
              loadModule('#fadeDiv #actionContentDiv','PINChange');
            },function(){hideMessageDiv();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
          } else if (resp.Fault.Code.Value=="14") {
            var txt="";
            if(resp.Fault.Detail && resp.Fault.Detail.CustConfirmText){
              txt=resp.Fault.Detail.CustConfirmText.replace(/&lt;/g, '<').replace(/&gt;/g, '>')+"<br/>";
            }
            {
							if(resp.Fault.ShowDeclineReason && resp.Fault.Reason && resp.Fault.Reason.Text){
								txt+=resp.Fault.Reason.Text.replace(/&lt;/g, '<').replace(/&gt;/g, '>')+"<br/>";
							}
							if(resp.Fault.Detail && resp.Fault.Detail.TextMessage && resp.Fault.Detail.TextMessage != ''){
								txt+=resp.Fault.Detail.TextMessage.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
							}
            }
            showMessage('',txt,'','',function(){
              var doCh=true;
              if (params.push){ 
                for(key in params){
                  if(params[key].name=="CustomerConfirmationState"){
                    doCh=false;
                  }
                }
              }
              if(doCh){
                params.push({name: "CustomerConfirmationState", value: 1});
              }
              if($('#tmpDivDynamic').children().length>0){
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
              }else{
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
              }
              mresize();
            },null,function(){copyFromTmp();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
          }else if (resp.Fault.Code.Value=="5014") {
            showMessage(JS.messages.RatesChanged,'','','',function(){
              if($('#tmpDivDynamic').children().length>0){
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
              }else{
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
              }
              mresize();
            },function(){
                loadModule('#fadeDiv #actionContentDiv','RatesHome', {a:'RatesChanged'},function(){
                    loadModule('#fadeDiv #changedRates','RatesHome', {a:'rate', RateGroup:resp.Fault.Reason.GroupID,RateType:resp.Fault.Reason.RateType});
                });
            },function(){copyFromTmp();},'rwin_pop_rates','',JS.messages.Continue,JS.messages.Cancel,null,null,true);
          }else if (resp.Fault.Code.Value=="12") {
            var txt="";
            var thisTranId='';
            {
							if(resp.Fault.ShowDeclineReason && resp.Fault.Reason && resp.Fault.Reason.Text){
								txt+=resp.Fault.Reason.Text.replace(/&lt;/g, '<').replace(/&gt;/g, '>')+"<br/>";
							}
							if(resp.Fault.Detail && resp.Fault.Detail.TextMessage && resp.Fault.Detail.TextMessage != ''){
								txt+=resp.Fault.Detail.TextMessage.replace(/&lt;/g, '<').replace(/&gt;/g, '>')+"<br/>";
							}
							if(resp.Fault.Detail && resp.Fault.Detail.AuthRespText && resp.Fault.Detail.AuthRespText != ''){
								txt+=resp.Fault.Detail.AuthRespText.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
							}
							if(resp.Fault.Detail && resp.Fault.Detail.TranId && resp.Fault.Detail.TranId != ''){
								thisTranId=resp.Fault.Detail.TranId;
							}
            }
            showMessage('',txt,'','',function(){
              var doCh=true;
              if (params.push){ 
                for(key in params){
                  if(params[key].name=="ThisTranId"){
                    doCh=false;
                  }
                }
              }
              if(doCh){
                params.push({name: "ThisTranId", value:thisTranId});
              }
              if($('#tmpDivDynamic').children().length>0){
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
              }else{
                copyFromTmp();
                execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
              }
              mresize();
            },null,function(){copyFromTmp();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
          } else if (resp.Fault.Code.Value=="5004") {
              showMessage(JS.messages.Captcha,'',function(){
                  hideMessageDiv();
              },'',function(){
                  if(!validForm('fadeDiv')){return false;}
                  var doCh=true;
                  if (params.push){
                      for(key in params){
                          if(params[key].name == "captcha"){
                              params[key].value=$("#Captcha", "#fadeDiv").val();
                              doCh=false;
                          }
                      }
                  }else {
                      params = new Array();
                  }
                  if(doCh){
                      params.push({name: "captcha", value: $("#Captcha", "#fadeDiv").val()});
                  }

                  if($('#tmpDivDynamic').children().length>0){
                      copyFromTmp();
                      execTran(tran,params,callback,hidemessage,err_callback, function(){copyFromTmp();},HideCommission);
                  }else{
                      copyFromTmp();
                      execTran(tran,params,callback,hidemessage,err_callback,null,HideCommission);
                  }
                  mresize();
              },function(){
                  $('#fadeDiv #actionContentDiv').html(
                      '<div style="float:right; clear:right;width:200px;">' +
                          '<table cellspacing="0" cellpadding="0" border="0" class="rsettable" style="width:100%;margin:0;">' +
                          '<tbody><tr>' +
                              '<td class="right pad"><input class="input" validclass="string" minlen="1" id="Captcha"></td>' +
                          '</tr>' +
                          '<tr>' +
                              '<td class="lasthint">' + JS.messages.CaptchaHint + '</td>' +
                          '</tr>' +
                          '</tbody></table>' +
                      '</div>' +
                      '<div style="clear:none; margin-right:200px; padding-right:10px; text-align: center;">' +
                          '<img src="' + CSMWait + '" id="captchaImg"/>' +
                      '</div>');
                  document.getElementById('captchaImg').src = '/trancaptcha?w=' + (new Date()).getTime();
              },function(){
                  document.getElementById('captchaImg').src = CSMWait;
                  document.getElementById('captchaImg').src = '/trancaptcha?w=' + (new Date()).getTime();
              },'rwin_captcha','', JS.messages.Send,JS.messages.Reload,null,null,true);
          } else {
          	if (secondary_callb) secondary_callb();
            if(err_callback) {
            	copyToTmp();
              showErrorMessageNC(resp, function(){
                copyFromTmp(); 
                err_callback(resp);
              });
            } else {
            	copyToTmp();
              showErrorMessageNC(resp, function(){copyFromTmp();}); 
            }
          }
        } else{
        	var respNode;
        	for(iter in resp){
        		respNode=resp[iter];
        		break;
        	}
            if (respNode && respNode.Response && respNode.Response.Response == "93") {
                showMessage(JS.messages.SelectCard,'', '', '', function(){
                    if ($("#fadeDiv input[name=CardUID]:checked").length > 0) {
                        params.push({name: "CardUID", value: $('#fadeDiv input[name=CardUID]:checked').val()});
                        execTran(tran, params, callback, hidemessage, err_callback, secondary_callb, HideCommission);
                    }
                }, function(){
                    var cards = respNode.Response.Cards;
                    $('#fadeDiv #actionContentDiv').append('<div class="divCardSelectDescription">'
                        + JS.messages.SelectCardText
                        + '</div>');
                    for (var i = 0; i < cards.Row.length; i++) {
                        $('#fadeDiv #actionContentDiv').append('<div class="divCardSelect"><label class="redspan" for="CardUID'
                            + cards.Row[i].CardUID + '"><input name="CardUID" type="radio" value="'
                            + cards.Row[i].CardUID + '" id="CardUID' + cards.Row[i].CardUID + '"/>'
                            + cards.Row[i].PAN + '</label></div>');
                    }
                    $('#fadeDiv #btn1').fadeTo(1,0.1);
                    $("#fadeDiv input[name=CardUID]").click(function(){
                        $('#fadeDiv #btn1').fadeTo(500,1);
                    });
                }, function() {
                    copyFromTmp();
                }, 'mesCardSelect', '', JS.messages.Ok, JS.messages.Cancel, '', '', true);
            } else {
                if(respNode && respNode.Response && respNode.Response.IssuerFee && Number(respNode.Response.IssuerFee)>0 && respNode.Response.FeeCurrency){
                        resp.CommissionMessage=JS.messages.Commission + ' ' + Number(respNode.Response.IssuerFee) + ' ' + decodeCurrency(respNode.Response.FeeCurrency);
                        resp.IssuerFee=respNode.Response.IssuerFee;
                        resp.CurrFee=decodeCurrency(respNode.Response.FeeCurrency);
                }
                if(!HideCommission && resp.CommissionMessage){
                    showMessage('',resp.CommissionMessage, '', '', function(){
                          copyFromTmp();
                          if (secondary_callb) secondary_callb();
                          if (callback) callback(resp);
                    }, '', '', '', '', JS.messages.Ok, '', '', '', true);
                }else{
                          copyFromTmp();
                          if (secondary_callb) secondary_callb();
                          if (callback) callback(resp);
                }
            }
        }
      },
    error: function(){
    	if (secondary_callb) secondary_callb();
        if(err_callback) {showErrorMessage(JS.messages.ServerError, function(){err_callback(resp);});} else if(!hidemessage) showErrorMessage(JS.messages.ServerError);
      }
  });
}

function transformForBMS(arr, formn){
  var DDL=arr.length
  for(i=0; i < DDL; i++){
    if(arr[i].name.match("^"+"ID__")!=null){
      arr[i].name="Name__"+arr[i].name.substring(4);
    }else if(arr[i].name.match("^"+"VAL__")!=null){
      arr[i].name="Value__"+arr[i].name.substring(5);
    }else if(arr[i].name.match("^"+"SEQ__")!=null){
    }else{
      arr.push({name: "Name__"+(i+200), value: arr[i].name.toUpperCase()});
      arr[i].name="Value__"+(i+200);
    }
  }
  arr.push({name: "FormName", value: formn});
}

function copyFromTmp(tmp){
	if(tmp==null){tmp='';}
  if($('#tmpDivDynamic'+tmp).children().length>0){
    $('#fadeDiv #fadeContent').remove();
    $('#fadeDiv').append($('#tmpDivDynamic'+tmp).children().clone(true));
    $('#tmpDivDynamic'+tmp).empty();
    if($('.mayPrint','#fadeDiv #fadeContent').length!=0){
    	getPrintContentFromFadeDiv();
    }
    $('#fadeDiv select').css('visibility', 'visible');
		$('select', '#fadeDiv #fadeContent').each(function(){
			var selOpt=$(this).attr('sel');
			$('option', this).each(function(){
				if($(this).val()==selOpt){
					$(this).attr('selected', 'selected');
				}
			});
		});

    //IE10 blinking ghost cursor fix
    if ($('#fadeDiv input').length > 0) {
        $('#fadeDiv input').first().focus();
    }
  }else{
    hideMessageDiv();
  }
}

function copyToTmp(tmp){
	if(tmp==null){tmp='';}
  if($('#fadeDiv').css('visibility')=='visible' && $('#fadeDiv #wincontent').length>0){
  	$('select', '#fadeDiv #fadeContent').each(function(){
  			$(this).attr('sel', $(this).val());
  	});
    //fix for IE
    $('input','#fadeDiv #fadeContent').each(function(){
      var value = $(this).val();
      $(this).attr('newval',value);
    })
    $('#tmpDivDynamic'+tmp).empty().append($('#fadeDiv #fadeContent').clone(true));
    //fix for IE
    $('input','#tmpDivDynamic'+tmp).each(function(){
      $(this).val($(this).attr('newval'));
    })
  }
}

function loadURL(id,url,params,callback){
  if(params && !params.push){
    var data=new Array();
    for(key in params){
      data.push({name:key, value:params[key]});
    }
    params=data;
  }else{
	  if(!params){
		  params = new Array();
	  }
  }
  params.push({name:'cookiesDisabled', value:navigator.cookieEnabled?'0':'1'});
  
  var sessionKeyPresent = false;
  for(key in params){
    if(params[key].name=='sessionKey'){
        sessionKeyPresent = true;
        break;
    }
  }
    if(!sessionKeyPresent){
        params.push({name: 'sessionKey', value: sessionKey});
    }
  /* TWIB-545 */
  var args = arguments;
  $.ajax({
    type: 'POST',
    url: url,
    async: true,
    cache: false,
    data: params,
    beforeSend: function(XMLHttpRequest){
        if(GlobalRequestArr[id] && GlobalRequestArr[id].readyState!=4){
          GlobalRequestArr[id].abort();
        }
        $(id).html($("#divWait").html());
        mresize();
        GlobalRequestArr[id]=XMLHttpRequest;
      },
    success: function(data){
  		if(arguments[2].status=='0'){return;}
        if(data.indexOf('{"NoLogin"')!=-1 || data.indexOf('{"BadSession"')!=-1){
          var resp = eval('(' + data + ')');

          if(resp.NoLogin || resp.BadSession){
            /*var csm="";
            if(CSMName){
              csm="?CSMName="+CSMName;
            }*/
        	  changeLocation();
            return;
          }
        }
        if(data.indexOf('{"Fault"')!=-1){
          var resp = eval('(' + data + ')');
          /* TWIB-545 */
          if(loadURLFaultHandler(args, resp)){
            return;
          }
          if(resp.Fault.DynResp && (resp.Fault.Code.Value=="1013"
            || resp.Fault.Code.Value=="1014"
            || resp.Fault.Code.Value=="1015"
            || resp.Fault.Code.Value=="1016"
            || resp.Fault.Code.Value=="1017"
            || resp.Fault.Code.Value=="1020"
            || resp.Fault.Code.Value=="1023"
            ) || resp.Fault.CapResp && resp.Fault.Code.Value=="53"){
            copyToTmp();
            showErrorMessageNC(resp, function(){
              copyFromTmp();
              $(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');
		          $('.errDiv .reloadSpan', id).click(function(){
		          	loadURL(id,url,params,callback)
		          });
              mresize();
            });
            return;
          }
          if (resp.Fault.Code.Value=="5006") {

            if(resp.Fault.AxsResp){
              copyToTmp();
              var axspan = '';
              for(key in params){
                if(params[key].name== "AXSPAN"){
                  axspan = params[key].value;
                }
              }
              showMessage(JS.messages.AXS,'','','',function(){ 
                if(!validForm('fadeDiv')){return false;}
                params.push({name: "AXSToken", value: $("#AXSToken").val()});
                if($('#tmpDivDynamic').children().length>0){
                  copyFromTmp();
                  loadURL(id,url,params,callback);
                }else{
                  showCustomContent($("#divBigWait").html());
                  loadURL(id,url,params,callback);
                }
              },function(){
                loadModule('#fadeDiv #actionContentDiv','AXS',{masked:axspan, a: 'AXSSign'}, function(){
                    axsSetupFlickering(resp.Fault.Detail.Flicker);
                });
              },function(){copyFromTmp();$(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');
				        $('.errDiv .reloadSpan', id).click(function(){
				        	loadURL(id,url,params,callback)
				        });
              	mresize();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
            }else{
                loadModuleSimple('#tmpDivSimpleLoad', 'AXS',{
			        a:'CountExtended'
		        },function(){
		            var loadCAP = function(axspan){
                        var doCh=true;                            
                        if (params.push){ 
                          for(key in params){
                            if(params[key].name== "AXSPAN"){
                              doCh=false;
                              params[key].value=axspan;
                            }else if(params[key].name == "AxsTran"){
                              params[key].value=resp.Fault.Tran;
                              doCh=false;
                            }
                          }
                          
                        }
                        if(doCh){
                          params.push({name: "AXSPAN", value: axspan});
                          params.push({name: "AxsTran", value: resp.Fault.Tran});
                        }

                        if($('#tmpDivDynamic').children().length>0){
                          copyFromTmp();
                          loadURL(id,url,params,callback);
                        }else{
                          showCustomContent($("#divBigWait").html());
                          loadURL(id,url,params,function(){
                            hideMessageDiv();
                            if(callback)callback();
                          });
                        }
                        mresize();
		            }
		            
			        if($('#count', '#tmpDivSimpleLoad').val()=='1'){
                        var axspan=$('#axspan', '#tmpDivSimpleLoad').val();
			            loadCAP(axspan);
			        }else{
		              copyToTmp();
                      showMessage(JS.messages.AXS,'','','',function(){
                        if(!validForm('fadeDiv')){return false;}
                        var axspan=$("#axspan option:selected").attr("pan");
                        loadCAP(axspan);
                      },function(){
                        loadModule('#fadeDiv #actionContentDiv','AXS',{a:'AXSCards'});
                      },function(){copyFromTmp();$(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');       
			                    $('.errDiv .reloadSpan', id).click(function(){
			                    	loadURL(id,url,params,callback)
			                    });
                      	mresize();},'','',JS.messages.Next,JS.messages.Cancel,null,null,true);
			        }
		        },function(rpp){
		        var rppe = eval('(' + rpp + ')');
		        showErrorMessage(rppe);
		        });
            }
          } else if (resp.Fault.Code.Value=="1022") {

            if(resp.Fault.CapResp){
              copyToTmp();
              var prevTranId='';
		      if(resp.Fault.Detail && resp.Fault.Detail.TranId && resp.Fault.Detail.TranId != ''){
			      prevTranId=resp.Fault.Detail.TranId;
		      }
              var capChlng=false;
		      if(resp.Fault.Detail && resp.Fault.Detail.CAPChallenge && resp.Fault.Detail.CAPChallenge != ''){
			      capChlng=true;
		      }
              var panForCAP = '';
              for(key in params){
                if(params[key].name== "MaskedPAN"){
                  panForCAP = params[key].value;
                }
              }
              showMessage(JS.messages.CAP2,'','','',function(){ 
                if(!validForm('fadeDiv')){return false;}
                params.push({name: "CAPToken", value: $("#CAPToken").val()});
                if($('#tmpDivDynamic').children().length>0){
                  copyFromTmp();
                  loadURL(id,url,params,callback);
                }else{
                  showCustomContent($("#divBigWait").html());
                  loadURL(id,url,params,callback);
                }
              },function(){
                var sendDataForCapDyn = {masked:panForCAP, a: capChlng?"CAPSign":"CAPSignDyn","CAPChallenge":resp.Fault.Detail.CAPChallenge};
                if(!capChlng){
                  for(key in params){
                    if(params[key].name== 'GenerateDynPasswordRq___Address'){
                      sendDataForCapDyn['GenerateDynPasswordRq___Address'] = params[key].value;
                    }else if(params[key].name== 'GenerateDynPasswordRq___Channel'){
                      sendDataForCapDyn['GenerateDynPasswordRq___Channel'] = params[key].value;
                    }else if(params[key].name== 'MaskedAdr'){
                      sendDataForCapDyn['MaskedAdr'] = params[key].value;
                    }
                  }
                  sendDataForCapDyn['PrevTranId'] = prevTranId;
                  sendDataForCapDyn['What'] = 2;
                }
                loadModule('#fadeDiv #actionContentDiv',"CAP",sendDataForCapDyn);
              },function(){copyFromTmp();$(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');
				        $('.errDiv .reloadSpan', id).click(function(){
				        	loadURL(id,url,params,callback)
				        });
              	mresize();},'','',JS.messages.Ok,JS.messages.Cancel,null,null,true);
            }else{
                var capChlng=false;
		        if(resp.Fault.Detail && resp.Fault.Detail.CAPChallenge && resp.Fault.Detail.CAPChallenge != ''){
			        capChlng=true;
		        }
                loadModuleSimple('#tmpDivSimpleLoad', 'CAP',{
			        a:(capChlng?'CountExtended':'CountExtendedDyn')
		        },function(){
		            var loadCAP = function(pan,mbr,masked, address, channel, maskedAdr){
                        var doCh=true;                            
                        if (params.push){ 
                          for(key in params){
                            if(params[key].name== "AuthPAN"){
                              doCh=false;
                              params[key].value=pan;
                            }else if(params[key].name== "AuthMBR"){
                              doCh=false;
                              params[key].value=mbr;
                            }else if(params[key].name == "CapTran"){
                              params[key].value=resp.Fault.Tran;
                              doCh=false;
                            }else if(params[key].name== "MaskedPAN"){
                              doCh=false;
                              params[key].value=masked;
                            }else if(params[key].name== "GenerateDynPasswordRq___Address"){
                              doCh=false;
                              params[key].value=address;
                            }else if(params[key].name== "GenerateDynPasswordRq___Channel"){
                              doCh=false;
                              params[key].value=channel;
                            }else if(params[key].name== "MaskedAdr"){
                              doCh=false;
                              params[key].value=maskedAdr;
                            }
                          }
                          
                        }
                        if(doCh){

                          params.push({name: "AuthPAN", value: pan});
                          params.push({name: "AuthMBR", value: mbr});
                          params.push({name: "CapTran", value: resp.Fault.Tran});
                          params.push({name: "MaskedPAN", value: masked});
                              
                          params.push({name: "GenerateDynPasswordRq___Address", value: address});
                          params.push({name: "GenerateDynPasswordRq___Channel", value: channel});
                          params.push({name: "MaskedAdr", value: maskedAdr});
                        }
                        if($('#tmpDivDynamic').children().length>0){
                          copyFromTmp();
                          loadURL(id,url,params,callback);
                        }else{
                          showCustomContent($("#divBigWait").html());
                          loadURL(id,url,params,function(){
                            hideMessageDiv();
                            if(callback)callback();
                          });
                        }
                        mresize();
		            }
		            
			        if($('#count', '#tmpDivSimpleLoad').val()=='1'){
                        var pan=$('#pan', '#tmpDivSimpleLoad').val();
                        var mbr=$('#mbr', '#tmpDivSimpleLoad').val();
                        var masked=$('#masked', '#tmpDivSimpleLoad').val();
                        var address=$('#address', '#tmpDivSimpleLoad').val();
                        var channel=$('#channel', '#tmpDivSimpleLoad').val();
                        var maskedAdr=$('#maskedAdr', '#tmpDivSimpleLoad').val();
			            loadCAP(pan, mbr, masked, address, channel, maskedAdr);
			        }else{
		              copyToTmp();
                      showMessage(JS.messages.CAP2,'','','',function(){
                        if(!validForm('fadeDiv')){return false;}
                        var pan=$("#AuthPAN  option:selected").attr("pan");
                        var mbr=$("#AuthPAN  option:selected").attr("mbr");
                        var masked=$("#AuthPAN").val();
                        var address=$('#dynAuthField option:selected').attr('daa');
                        var channel=$('#dynAuthField option:selected').attr('dac');
                        var maskedAdr=$('#dynAuthField option:selected').attr('mac');
                        loadCAP(pan, mbr, masked, address, channel, maskedAdr);
                      },function(){
                        loadModule('#fadeDiv #actionContentDiv','CAP',{a: capChlng?'CAPCards':'CAPCardsDyn'});
                      },function(){copyFromTmp();$(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');       
			                    $('.errDiv .reloadSpan', id).click(function(){
			                    	loadURL(id,url,params,callback)
			                    });
                      	mresize();},'','',JS.messages.Next,JS.messages.Cancel,null,null,true);
			        }
		        },function(rpp){
		        var rppe = eval('(' + rpp + ')');
		        showErrorMessage(rppe);
		        });
            }
          } else if (resp.Fault.Code.Value=="1021") {
            copyToTmp();
            showMessage(JS.messages.CAP,'','','',function(){
              if(!validForm('fadeDiv')){return false;}
              var doCh=true;
              var pan=$("#AuthPAN  option:selected").attr("pan");
              var mbr=$("#AuthPAN  option:selected").attr("mbr");
              if (params.push) {
                for(key in GlobalParams){
                  if(params[key].name== "AuthPAN"){
                    doCh=false;
                    params[key].value=pan;
                  }else if(params[key].name== "CAPToken"){
                    doCh=false;
                    params[key].value=$("#CAPToken").val();
                  }else if(params[key].name== "AuthMBR"){
                    doCh=false;
                    params[key].value=mbr;
                  }else if(params[key].name == "CapTran"){
                      params[key].value=resp.Fault.Tran;
                      doCh=false;
                  }
                }
              }
              if(doCh){
                params.push({name: "CAPToken", value: $("#CAPToken").val()});
                params.push({name: "AuthPAN", value: pan});
                params.push({name: "AuthMBR", value: mbr});
                params.push({name: "CapTran", value: resp.Fault.Tran});
              }

              if($('#tmpDivDynamic').children().length>0){
                copyFromTmp();
                loadURL(id,url,params,callback);
              }else{
                showCustomContent($("#divBigWait").html());
                loadURL(id,url,params,function(){
                  hideMessageDiv();
                  if(callback)callback();
                });
              }
              mresize();
            },function(){
              loadModule('#actionContentDiv','CAP',{a: 'CAPToken'});
            },function(){copyFromTmp();$(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>'); 
		          $('.errDiv .reloadSpan', id).click(function(){
		          	loadURL(id,url,params,callback)
		          });
            	mresize();},'','', JS.messages.Ok,JS.messages.Cancel,null,null,true);
          } else if (resp.Fault.Code.Value=="18") {
            var prevTranId='';
			if(resp.Fault.Detail && resp.Fault.Detail.TranId && resp.Fault.Detail.TranId != ''){
				prevTranId=resp.Fault.Detail.TranId;
			}
            copyToTmp();
            var onCancelDyn1 = function(){
            	copyFromTmp(); $(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');
		          $('.errDiv .reloadSpan', id).click(function(){
		          	loadURL(id,url,params,callback)
		          });
            	mresize();
            };

		    loadModuleSimple('#tmpDivSimpleLoad', 'DynamicAuth',{
			    a:'CountExtended'
		    },function(){
		        var loadDynPassForm = function(sdata){
		            showMessage(JS.messages.Dynamic,'','','',function(){
	                  if(!validForm('fadeDiv')){return false;}
	                  var doCh=true;
	                  if (params.push){
	                    for(key in params){
	                      if(params[key].name == "DynamicPassword"){
	                        params[key].value=$("#inDynamicPassword").val();
	                        doCh=false;
	                      }else if(params[key].name == "DynamicPasswordTran"){
	                        params[key].value=resp.Fault.Tran;
	                        doCh=false;
	                      }
	                    }
	                  }
	                  else {
	                    params = new Array();
	                  }
	                  if(doCh){
	                    params.push({name: "DynamicPassword", value: $("#inDynamicPassword").val()});
                        params.push({name: "PrevTranId", value: prevTranId});
	                    params.push({name: "DynamicPasswordTran", value: resp.Fault.Tran});
	                  }

	                  if($('#tmpDivDynamic').children().length>0){
	                    copyFromTmp();
	                    loadURL(id,url,params,callback);
	                  }else{
	                    showCustomContent($("#divBigWait").html());
	                    loadURL(id,url,params,function(){
	                      hideMessageDiv();
	                      if(callback)callback();
	                    });
	                  }
	                  mresize();
	                },function(){
                     $('#btn1', '#fadeDiv').hide();
	                  loadModule('#fadeDiv #actionContentDiv','DynamicAuth',sdata,function(){
                        $('#btn1', '#fadeDiv').show();
	                  });
	                },function(){onCancelDyn1();},'','', JS.messages.Ok,JS.messages.Cancel,null,null,true);
                }
			    if($('#count', '#tmpDivSimpleLoad').val()=='1'){
			        var sdata = {
			            PrevTranId:prevTranId,
			            a:'Password',
			            GenerateDynPasswordRq___Address:$('#address', '#tmpDivSimpleLoad').val(),
			            GenerateDynPasswordRq___Channel:$('#channel', '#tmpDivSimpleLoad').val(),
			            Masked:$('#masked', '#tmpDivSimpleLoad').val()
			        };
			        loadDynPassForm(sdata);
			    }else{
			        showMessage(JS.messages.Dynamic,'','','',function(){
	                    var frmDA=$('#frmDynamicAuth').formToArray();
	                    var daa=$('#dynAuthField option:selected').attr('daa');
	                    var dac=$('#dynAuthField option:selected').attr('dac');
                        var mac=$('#dynAuthField option:selected').attr('mac');
	                    frmDA.push({name: "GenerateDynPasswordRq___Address", value: daa});
	                    frmDA.push({name: "GenerateDynPasswordRq___Channel", value: dac});
	                    frmDA.push({name: "Masked", value: mac});
	                    frmDA.push({name: "PrevTranId", value: prevTranId});
	                    loadDynPassForm(frmDA);
	                  },function(){
                        $('#btn1', '#fadeDiv').hide();
	                    loadModule('#fadeDiv #actionContentDiv','DynamicAuth',null,function(){
                            $('#btn1', '#fadeDiv').show();
	                    });
	                  },function(){copyFromTmp(); $(id).html('<div class="errDiv">'+JS.messages.NeedDynamic+'</div>');
			                $('.errDiv .reloadSpan', id).click(function(){
			                	loadURL(id,url,params,callback)
		                	});
	                  	mresize();
	                  },'','',JS.messages.Send,JS.messages.Cancel,null,null,true);
			    }
		    },function(rpp){
		        var rppe = eval('(' + rpp + ')');
		        showErrorMessage(rppe);
		    });
          } else {
            var text=resp.Fault.Code.Value;
            if(resp.Fault.Explanation){
              text=resp.Fault.Explanation;
            }
	        if(resp.Fault.ShowDeclineReason && resp.Fault.Reason && resp.Fault.Reason.Text){
	            text+="<br/>"+resp.Fault.Reason.Text.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
	        }

		    if(resp.Fault.Detail && resp.Fault.Detail.TextMessage && resp.Fault.Detail.TextMessage != ''){
			    text+="<br/>"+resp.Fault.Detail.TextMessage.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		    }
		    if(resp.Fault.Detail && resp.Fault.Detail.CustConfirmText && resp.Fault.Detail.CustConfirmText != ''){
			    text+="<br/>"+resp.Fault.Detail.CustConfirmText.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		    }
            var activateChatLink = jabberEnabled === 'true' ? '<div class="errDiv"><span class="chatSpan">' + JS.messages.OnlineHelp + '</span></div>' : '';
            $(id).html('<div class="errDiv">'+text+'. <span class=\"reloadSpan\">'+JS.messages.Reload+'</span></div>' + activateChatLink);
            $('.errDiv .reloadSpan', id).click(function(){
            	loadURL(id,url,params,callback)
            });
            $('.errDiv .chatSpan', id).click(function(){
                activateChat();
            });
            clearIfEmpty();
            mresize();
          }
        }else{
          $(id).empty().html(data);
          addWrapErrorMessages($(id));
          mresize();
	        if (callback){
            callback();
          }
        }
      },
    error: function(){
        var activateChatLink = jabberEnabled === 'true' ? '<div class="errDiv"><span class="chatSpan">' + JS.messages.OnlineHelp + '</span></div>' : '';
        $(id).html('<div class="errDiv">'+JS.messages.ServerError+'. <span class=\"reloadSpan\">'+JS.messages.Reload+'</span></div>' + activateChatLink);
        $('.errDiv .reloadSpan', id).click(function(){
        	loadURL(id,url,params,callback)
        });
        $('.errDiv .chatSpan', id).click(function(){
            activateChat();
        });
        clearIfEmpty();
      },
    complete: function(){
        if(arguments[0].status=='0'){
            var activateChatLink = jabberEnabled === 'true' ? '<div class="errDiv"><span class="chatSpan">' + JS.messages.OnlineHelp + '</span></div>' : '';
            $(id).html('<div class="errDiv">'+JS.messages.ClientError+'. <span class=\"reloadSpan\">'+JS.messages.Reload+'</span></div>' + activateChatLink);
            $('.errDiv .reloadSpan', id).click(function(){
                loadURL(id,url,params,callback)
            });
            $('.errDiv .chatSpan', id).click(function(){
                activateChat();
            });
		    clearIfEmpty();
        }
        //GlobalRequestArr[id]=null;
        delete GlobalRequestArr[id];
        mresize();
      }
  });
}

function clearIfEmpty(){
  if($('#fadeDiv').css('visibility')=='visible' && $('#fadeDiv #wincontent').length==0){
    hideMessageDiv();
  }
}
function loadURLSimple(id,url,params,callback, err_callback){
  if(params && !params.push){
    var data=new Array();
    for(key in params){
      data.push({name:key, value:params[key]});
    }
    params=data;
  }else{
	  if(!params){
		  params = new Array();
	  }
  }
  params.push({name:'cookiesDisabled', value:navigator.cookieEnabled?'0':'1'});
  
  var sessionKeyPresent = false;
  for(key in params){
    if(params[key].name=='sessionKey'){
        sessionKeyPresent = true;
        break;
    }
  }
    if(!sessionKeyPresent){
        params.push({name: 'sessionKey', value: sessionKey});
    }

  $.ajax({
    type: 'POST',
    url: url,
    async: true,
    cache: false,
    data: params,
    beforeSend: function(XMLHttpRequest){
        if(GlobalRequestArr[id] && GlobalRequestArr[id].readyState!=4){
          GlobalRequestArr[id].abort();
        }
        GlobalRequestArr[id]=XMLHttpRequest;
      },
    success: function(data){
		var resp = null;
		data = $.trim(data);
        if(data.indexOf('{')==0){
            resp = eval('(' + data + ')');	
        }
        if(data.indexOf('{"NoLogin"')!=-1 || data.indexOf('{"BadSession"')!=-1){ 	  		
          if(resp.NoLogin || resp.BadSession){
            /*var csm="";
            if(CSMName){
              csm="?CSMName="+CSMName;
            }*/
        	  changeLocation();
            return;
          }
        }
        $(id).empty();
        if(data.indexOf('{"Fault"')==-1){
          $(id).html(data);
	      if (callback) callback(resp);
        }else{
	      if (err_callback) err_callback(data);
        }
      },
    error: function(){
        $(id).empty();
	    if (err_callback) err_callback();
      },
    complete: function(){
        //GlobalRequestArr[id]=null;
        delete GlobalRequestArr[id];
      }
  });
}
function appendNewMessagesCounter(){
	if($('#MainMenu_Messages').length>0){
		loadModuleSimple('#tmpDivSimpleLoad', 'Messaging',{a:'NewMessagesCount'},function(){
			var tabtitle=$('.tabtitle', '#MainMenu_Messages');
			if($(tabtitle).attr('originaltitle')==null || $(tabtitle).attr('originaltitle')==''){
				$(tabtitle).attr('originaltitle', $(tabtitle).html());
			}
			$(tabtitle).html($(tabtitle).attr('originaltitle')+' '+$('#tmpDivSimpleLoad').html());
			$(tabtitle).attr('wi','');
			addVisualEffects('.header');
		},function(){
			//if error
		});
	}
}

function loadModule(id,name,params,callback){
  if($(id).length<1){return;}
	var url = module[name];
	if (url) loadURL(id,url,params,function(){
    if (callback) callback();
    addVisualEffects(id);
    mresize();
  });
}
function loadModuleSimple(id,name,params,callback,err_callback){
    if($(id).length<1){return;}
	var url = module[name];
	if (url) loadURLSimple(id,url,params,callback,err_callback);
}

function showStamp(){
	$('#printDivStamp').show();
}
function hideStamp(){
	$('#printDivStamp').hide();
}
function getPrintContentFromFadeDiv(){
	$('#printDiv').html($('#actionContentDiv','#fadeDiv').html());
	showStamp();
}
function restorePrintDiv(){
	$('#printDiv').html($('#printDivTmp').html());
	$('#printDivTmp').empty();
}
function savePrintDiv(){
	$('#printDivTmp').html($('#printDiv').html());
	$('#printDiv').empty();
}
function clearPrintDiv(){
	$('#printDiv').empty();
	hideStamp();
}
function setPrintDivContent(content){
	$('#printDiv').html(content);
	showStamp();
}

function showMessage(title, text, close_callback, help_callback, btn1_callback, ad_callback, btn2_callback, wrap_class, btn3_callback, btn1_text, btn2_text, btn3_text, toppadding, CloseSameAsBtn2, HideEmptyOk, btn4_callback, btn4_text, btn5_callback, btn5_text) {
  $("#fadeDiv #fadeContent").empty().attr('class','fadeContent').html($("#actionDivTmpl").html());
  animWinBtn('#fadeDiv #fadeContent');
  if(wrap_class){
    $("#fadeDiv #fadeContent").addClass(wrap_class);
  }
	$("#fadeDiv #actionContentDiv").html(text);
  if(toppadding){
    $('#fadeDiv #actionContentDivWrap').attr('toppadding', toppadding);
  }
  if(!title){
    title=JS.messages.Message;
  }
	$("#fadeDiv #actionDivTitle").html(title);
  $("#fadeDiv #close_btn").click(function(){
    if(close_callback){
      close_callback();
    }else{
    	if(CloseSameAsBtn2 && btn2_callback){
    		btn2_callback();
    	}else{
    		hideMessageDiv();
    	}
    }
  });
  if (help_callback){
    $("#fadeDiv #help_btn").click(function(){
      if(help_callback) {
        help_callback();
      }
    });
  }else{
    $("#fadeDiv #help_btn").css('display', 'none');
  }
  if(btn1_text){
    $("#fadeDiv #btn1 .newbtncontent").html(btn1_text);
  }else{
    $("#fadeDiv #btn1 .newbtncontent").html(JS.messages.Ok);
  }
  if(btn2_text){
    $("#fadeDiv #btn2 .newbtncontent").html(btn2_text);
  }else{
    $("#fadeDiv #btn2 .newbtncontent").html('');
  }
  if(btn3_text){
    $("#fadeDiv #btn3 .newbtncontent").html(btn3_text);
  }else{
    $("#fadeDiv #btn3 .newbtncontent").html('');
  }
  if(btn4_text){
    $("#fadeDiv #btn4 .newbtncontent").html(btn4_text);
  }else{
    $("#fadeDiv #btn4 .newbtncontent").html('');
  }
  if(btn5_text){
    $("#fadeDiv #btn5 .newbtncontent").html(btn5_text);
  }else{
    $("#fadeDiv #btn5 .newbtncontent").html('');
  }
  if(HideEmptyOk && !btn1_callback){
    $("#fadeDiv #btn1").css('display', 'none');
  }
  $("#fadeDiv #btn1").click(function(){
    if(btn1_callback) {
      btn1_callback();
    }else{
      hideMessageDiv();
    }
  });
  if (btn2_callback){
    $("#fadeDiv #btn2").click(function(){
      btn2_callback();
    });
  }else {
    $("#fadeDiv #btn2").parent().css('display', 'none');
  }
  if (btn3_callback){
    $("#fadeDiv #btn3").click(function(){
      btn3_callback();
    });
  }else{
    $("#fadeDiv .centerbtn").css('display', 'none');
  }
  if (btn4_callback){
    $("#fadeDiv #btn4").click(function(){
      btn4_callback();
    });
  }else{
    $("#fadeDiv #tdbtn4").css('display', 'none');
  }
  if (btn5_callback){
    $("#fadeDiv #btn5").click(function(){
      btn5_callback();
    });
  }else{
    $("#fadeDiv #tdbtn5").css('display', 'none');
  }
	savePrintDiv();
  if(ad_callback){
    ad_callback();
  }
  showMessageDiv();
  addVisualEffects('#fadeDiv');
  mresize();
}

Mousetrap.bind('escape', function(){
    $("#fadeDiv #close_btn").click();
});

function showErrorMessage(resp, close_callback, help_callback) {
	var text = "";
	if(resp.Fault){
	    text=resp.Fault.Code.Value;
	    if(resp.Fault.Explanation){
	      text=resp.Fault.Explanation;
		  var limitRegexp=/ID=([0-9]*)$/;
		  if(resp.Fault.Reason && resp.Fault.Reason.Text && limitRegexp.test(resp.Fault.Reason.Text)){
		  	var limitID=limitRegexp.exec(resp.Fault.Reason.Text)[1];
		  	if(GlobalCardLimits[limitID] && GlobalCardLimits[limitID]!=''){
		  		text+=' ('+GlobalCardLimits[limitID]+')';
		  	}
		  }
	    }
	    if(resp.Fault.ShowDeclineReason && resp.Fault.Reason && resp.Fault.Reason.Text){
	      text+="<br/>"+resp.Fault.Reason.Text.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
	    }
		if(resp.Fault.Detail && resp.Fault.Detail.TextMessage && resp.Fault.Detail.TextMessage != ''){
			text+="<br/>"+resp.Fault.Detail.TextMessage.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		}
		if(resp.Fault.Detail && resp.Fault.Detail.CustConfirmText && resp.Fault.Detail.CustConfirmText != ''){
			text+="<br/>"+resp.Fault.Detail.CustConfirmText.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		}
        if(jabberEnabled === 'true' && !resp.Fault.HideChatButton){
            text+="<br/><span class=\"chatSpan redspan\">"+JS.messages.OnlineHelp+"</span>";
        }
	}else{
		text=resp;
	}
    showMessage(JS.messages.Error, text, close_callback, help_callback,function(){if(close_callback){close_callback();} hideMessageDiv();});
    $('#fadeDiv .chatSpan').click(function(){
        hideMessageDiv();
        activateChat();
    });
}
function showErrorMessageNC(resp, close_callback, help_callback) {
	var text = "";
	if (resp.Fault) {
	    text=resp.Fault.Code.Value;
	    if(resp.Fault.Explanation){
	      text=resp.Fault.Explanation;
			  var limitRegexp=/ID=([0-9]*)$/;
			  if(resp.Fault.Reason && resp.Fault.Reason.Text && limitRegexp.test(resp.Fault.Reason.Text)){
			  	var limitID=limitRegexp.exec(resp.Fault.Reason.Text)[1];
			  	if(GlobalCardLimits[limitID] && GlobalCardLimits[limitID]!=''){
			  		text+=' ('+GlobalCardLimits[limitID]+')';
			  	}
			  }
	    }
	    if(resp.Fault.ShowDeclineReason && resp.Fault.Reason && resp.Fault.Reason.Text){
	      text+="<br/>"+resp.Fault.Reason.Text.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
	    }
		if(resp.Fault.Detail && resp.Fault.Detail.TextMessage && resp.Fault.Detail.TextMessage != ''){
			text+="<br/>"+resp.Fault.Detail.TextMessage.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		}
		if(resp.Fault.Detail && resp.Fault.Detail.CustConfirmText && resp.Fault.Detail.CustConfirmText != ''){
			text+="<br/>"+resp.Fault.Detail.CustConfirmText.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		}
        if(jabberEnabled === 'true' && !resp.Fault.HideChatButton){
            text+="<br/><span class=\"chatSpan redspan\">"+JS.messages.OnlineHelp+"</span>";
        }
	} else {
		text = resp;
	}
    showMessage(JS.messages.Error, text, close_callback, help_callback,function(){if(close_callback){close_callback();}});
    $('#fadeDiv .chatSpan').click(function(){
        hideMessageDiv();
        activateChat();
    });
}

function activateChat() {
    MainMenu.showMenu('MainMenu_Settings',function(){
        SettingsMenu.showMenu('hdrChat');
    });
}

function doExit(){
  showCustomContent($("#divBigWait").html());
  /*var csm="";
  if(CSMName){
    csm="?CSMName="+CSMName;
  }*/
  saveHomeModulesPos(function(){
		$.post("exec.jsp?c=LogoffRq",{sessionKey:sessionKey},function(){changeLocation();});
		});
  showCustomContent($("#divBigWait").html());
  
}
function saveHomeModulesPos(callback){
  var modules='';
  if($('#tblHome').length==0){
  	if(callback){callback();}
    return;
  }
  $('#divAdv').hide();
  $('#tblHome .rwin_home').each(function(){
    modules+='<m name="'+$(this).attr('name')+'"';
    if($(this).attr('pos')){
      modules+=' pos="'+$(this).attr('pos')+'"';
    }
    if($(this).attr('col')){
      modules+=' col="'+$(this).attr('col')+'"';
    }
    if($(this).attr('hide')){
      modules+=' hide="'+$(this).attr('hide')+'"';
    }
    modules+='/>';
  });
  execTran('SetCustomerUserFieldsRq',{Name:"HomePageModules",XMLValue: '<modules>'+modules+'</modules>'},function (resp) {
    if(callback){callback();}
  },true);
}
function setEqualHeight(columns){
  var tallestcolumn = 0;
  columns.each(function(){
    currentHeight = $(this).height();
    if($('.tabtitle',this).attr('wi')==null || $('.tabtitle',this).attr('wi')==''){
    	$('.tabtitle',this).attr('wi', $('.tabtitle',this).width());
    }
    $(this).parent().width(Number($('.tabtitle',this).attr('wi'))+30); /*tab padding*/
    if(currentHeight > tallestcolumn){
      tallestcolumn = currentHeight;
      $(this).parent().parent().parent().attr('hght',tallestcolumn+5);
    }
  });
  columns.height(tallestcolumn);
}
function animWinBtn(id){
  $(id+" .close_img").mouseover(function(){
    $(this).addClass("close_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("close_img_hovered");
  });
  $(id+" .mini_img").mouseover(function(){
    $(this).addClass("mini_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("mini_img_hovered");
  });
  $(id+" .help_img").mouseover(function(){
    $(this).addClass("help_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("help_img_hovered");
  });
  $(id+" .save_img").mouseover(function(){
    $(this).addClass("save_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("save_img_hovered");
  });
  $(id+" .question_img").mouseover(function(){
    $(this).addClass("question_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("question_img_hovered");
  });
  $(id+" .print_img").mouseover(function(){
    $(this).addClass("print_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("print_img_hovered");
  });
  $(id+" .pdf_img").mouseover(function(){
    $(this).addClass("pdf_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("pdf_img_hovered");
  });

  $(id+" .refresh_img").mouseover(function(){
    $(this).addClass("refresh_img_hovered");
  }).mouseout(function(){
    $(this).removeClass("refresh_img_hovered");
  });
  if($('#tblHome').length==0 || $('#winheader', '#fadeDiv').length>0)
  $(".input",id).add(".select",id).first().focus();
}

function smartWrap(id){
  if($.browser.msie || $.browser.webkit){
    return;
  }else{
    return;
    $(id+" .cblong").each(function(){
      $(this).html(parseWrap($(this).html()));
    });
  }
}

function parseWrap(text){

/*  if(text.length == 0){return text;}

  var a=text.indexOf("&");
  var b=text.indexOf(";", a);
  if(a!=-1 && b!=-1 && text.substring(a, b).indexOf(" ")==-1){
    text=parseWrap(text.substring(0, a))+text.substring(a, b)+parseWrap(text.substring(b));
  }else{
    var splitArr=text.split(" ");
    var subres='';
    for(key in splitArr){
      if(splitArr[key].length > 2){
        subres+=parseWrap(splitArr[key].split("").join("&#8203;"));
      }else{
        subres+=splitArr[key];
      }
      if(key!=splitArr.length-1){
        subres+=" ";
      }
    }
    text=subres;
  }*/
  return text;
}

function addVisualEffects(id){
    smartWrap(id);
	titleIcon(id);
    $(id+" .rwininfotable").each(function(){
      var b=false;
      $("tr", this).each(function(){
        if(b){
          $(this).addClass("even");
        }else{
          $(this).addClass("odd");
        }
        b=!b;
      });
    });
		$(id+" .newbtnbodywrap").mouseup(function(){
			$(this).removeClass('newbtnbodywrapclicked');
		}).mousedown(function(){
			$(this).addClass('newbtnbodywrapclicked');
      return false;
		}).mouseout(function(){
			$(this).removeClass('newbtnbodywrapclicked');
        $(this).removeClass("newbtnbodywraphovered");
    });
    if($.browser.msie){
      $(id+" .newbtnbody").bind('selectstart',function(){return false;});
    }
        
    if($.browser.msie && $.browser.version == 6){
      $('.rwintable').addClass('rwintable_ie');
      $('.rwininfotable').addClass('rwininfotable_ie');

      animWinBtn(id);
      $(id+" .raccord").mouseover(function(){
        var that=this;
        $(that).each(function(){
          $(this).addClass("raccordopn_hover");
        });
        $(that).not(".raccordopn").each(function(){
          $(this).removeClass("raccordopn_hover");
          $(this).addClass("raccord_hover");
        });
      }).mouseout(function(){    
        $(this).removeClass("raccordopn_hover").removeClass("raccord_hover");
      });

      $(id+" .rtable tr").mouseover(function(){
        $(this).addClass("hovered");
      }).mouseout(function(){
        $(this).removeClass("hovered");
      });
      $(id+" .newbtnbodywrap").mouseover(function(){
        $(this).addClass("newbtnbodywraphovered");
      })
    }
    $(id+" .rmenu").mouseover(function(){
      $(this).addClass("rmenu_hov");
    }).mouseout(function(){
      $(this).removeClass("rmenu_hov");
    });
    
    if($.browser.msie && $.browser.version == 6 && $('#fadeDiv').css('visibility')=='visible'){
      $('select').css('visibility', 'hidden');
      $('#fadeDiv select').css('visibility', 'visible');
    }
    $(id+" .rtablist").each(function(){
      setEqualHeight($(".tabcontent", this));
    });

    $(id+" .datepick").click(function(e) {
	    if(!e || !e.currentTarget || !e.currentTarget.getClientRects().item(0)){
	      return;
	    }
	    var cx=e.clientX;
	    var cy=e.clientY;
	    var r=e.currentTarget.getClientRects().item(0);
	    if(cx && cy && r && cx < r.right && cx > r.right-20 && 
	          cy < r.bottom && cy > r.top){
		    delValidError(this);
    		$(this).datepicker("show");
	    }
	  });
	if($('#tblHome').length==0 || $('#winheader', '#fadeDiv').length>0)
      $(".input",id).add(".select",id).first().focus();
  //  setEqualHeight
}
function TabMenu(menuId,selectedClass) {

	this.MenuList = new Array();
	this.MenuId = menuId;
	this.selectedClass = selectedClass;
	this.selectedItem;
	
	this.addMenuItem = function(headerId,openAction,closeAction,click_callback){
		this.MenuList[headerId] = new TabMenuItem(headerId,openAction,closeAction);

		var _this = this;
		if($("#"+headerId).hasClass('rmenu') && !$("#"+headerId).hasClass('rmenu_empty')){
		    $("#"+headerId+">.menuheader").add("#"+headerId+">.top").click(function () {
		    	_this.triggerMenu(headerId, click_callback);
		    });
		}else{
		    $("#"+headerId).click(function () {
		    	if(window.dontClickTooFast === false || window.dontClickTooFast === undefined || window.dontClickTooFast == null){
		    		window.dontClickTooFast = true;
		    		setTimeout(function(){		
		    			window.dontClickTooFast = false;
		    		},500);
		    		_this.showMenu(headerId, click_callback);
		    	} 
		    });		
		}
	}
  this.first = function(){
    for (var g in this.MenuList) return g;
    return null;
  }
  this.last = function(){
    var gl;
    for (var g in this.MenuList) gl=g;
    return gl;
  }
  this.next = function(){
    var cr=false;
    for (var g in this.MenuList){
      if(cr){
        return g;
      }
      if(g==this.selectedItem){
        cr=true;
      }
    }
    return this.first();
  }
  this.prev = function(){
    var prr;
    for (var g in this.MenuList){
      if(g==this.selectedItem){
        break;
      }
      prr=g;
    }
    if(prr){
      return prr;
    }else{
      return this.last();
    }
  }
	this.showMenu = function(id,callback){
        if(this.MenuList[id] == undefined){
            throw 'no such menuItem';
        }
    if (this.selectedItem && this.selectedItem != id) this.MenuList[this.selectedItem].close(this.selectedClass);
    if (this.MenuList[id]) this.MenuList[id].open(this.selectedClass, callback);
		if (this.selectedItem != id) this.selectedItem = id;

		//if (callback) callback();
	}
	
	this.hideMenu = function(id,callback){
		this.MenuList[id].close(this.selectedClass, callback);
		//if (this.selectedItem && this.selectedItem != id) this.MenuList[this.selectedItem].close(this.selectedClass);
		//if (this.selectedItem != id) this.selectedItem = id;

		//if (callback) callback();
	}
	
    this.triggerMenu = function(id,callback){
        if($("#"+id).hasClass('rmenu_sel')){
           this.hideMenu(id,callback); 
        }else{
           this.showMenu(id,callback); 
        }		
	}

	this.openMenu = function(id,callback){
		this.MenuList[id].show(this.selectedClass, callback);
		if (this.selectedItem && this.selectedItem != id) this.MenuList[this.selectedItem].hide(this.selectedClass);
		if (this.selectedItem != id) this.selectedItem = id;
		//if (callback) callback();
	}
	this.closeAll = function(callback){
		if (this.selectedItem) this.MenuList[this.selectedItem].hide(this.selectedClass);
		//if (callback) callback();
	}
}
var TabMenuItem = function (headerId,openAction,closeAction){
	this.headerId = headerId;
	this.openAction = openAction;
	this.closeAction = closeAction;
	
	this.open = function(selectedClass, callback){
		$("#"+this.headerId).addClass(selectedClass);
		if (this.openAction) this.openAction(callback);
	}
	
	this.close = function(selectedClass){
		$("#"+this.headerId).removeClass(selectedClass);
		if (this.closeAction) this.closeAction();
	}
	
	this.show = function(selectedClass, callback){
		$("#"+this.headerId).addClass(selectedClass);
    if (callback) callback();
	}
	
	this.hide = function(selectedClass){
		$("#"+this.headerId).removeClass(selectedClass);
	}
}

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",

			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),

			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


// Drag'n'Drop
var dragObj;
var x,y;

function Container (id) {
	this.id = id;
	this.offset = $("#"+id).offset();
	this.width =  $("#"+id).width();
	this.height =  $("#"+id).height();
	this.obj = new Array();
	
	this.addObj = function (id) {
		var ob = new Object();

		ob.id = id;

		ob.offset = $("#"+id).offset();
		ob.width = $("#"+id).width();
		ob.height = $("#"+id).height();
		ob.pos = 0;
		this.obj[this.obj.length] = ob;
		this.refreshAll();
	}
	this.delObj = function (id) {
		for (var ob in this.obj) {
			if (this.obj[ob].id == id) {
				this.obj.splice(ob,1);
			}
		}
		this.refreshAll();
	}
	this.refreshObj = function (id) {
		for (var ob in this.obj) {
			if (this.obj[ob].id == id) {
				this.obj[ob].offset = $("#"+id).offset();
				this.obj[ob].width = $("#"+id).width();
				this.obj[ob].height = $("#"+id).height();
			}
		}
	}
	this.refreshAll = function () {
		for (var ob in this.obj) {
			this.refreshObj(this.obj[ob].id);
		}
		for (var ob in this.obj) {
			this.obj[ob].pos = 1;
			for (var objI in this.obj)
				if (this.obj[ob].offset.top > this.obj[objI].offset.top){
					this.obj[ob].pos++;
				}
        
        $("#"+this.obj[ob].id).attr('pos',this.obj[ob].pos);
			/*var m = xPath(HomePageModules,'/modules/m[@name=\''+this.obj[ob].id.substring(3)+'\']');
			if (m && m[0]) {
				m[0].setAttribute("pos",this.obj[ob].pos);
			}*/
		}
	}
}
function Dragable() {
	this.cont = new Array();
	
	this.addCont = function (id) {
		this.cont.push(new Container(id));
	}
	this.addObj = function (id) {
		var offset = $("#"+id).offset();
		for (var c in this.cont) {
			if ( (this.cont[c].offset.left < offset.left+10) && 
			   ( (this.cont[c].offset.left+this.cont[c].width) > offset.left+10) ){
				
				this.cont[c].addObj(id);
        //$("#"+id).attr('col',parseInt(c)+1);
      //  alert("#"+id);
        /*
				var m = xPath(HomePageModules,'/modules/m[@name=\''+id.substring(3)+'\']');
				if (m && m[0]) {
					m[0].setAttribute("col",parseInt(c)+1);
				}*/
        
			}
		}
        $("#"+id).attr('col',$("#"+id).parent().attr('id').replace('col', ''));
	}
	this.delObj = function (id) {
		for (var c in this.cont) {
			this.cont[c].delObj(id);
		}
	}
}

function moveObj (ev) {
	ev = ev || window.event;
	if(ev.pageX || ev.pageY){ 
		x = ev.pageX;
		y = ev.pageY;
	} else {
		x = ev.clientX;
		y = ev.clientY;
	}
	
	setTimeout('showTarget('+x+','+y+')');
	//showTarget(x,y);
	$("#divDrag").css("left",(x-offx)+"px").css("top",(y-offy)+"px");
}
function showTarget(x,y){
	var contTop = 0;
	var contLeft = 0;
	var contWidth = 0;
	var ob;
	for (var c in drg.cont) {
		contTop = drg.cont[c].offset.top;
		contLeft = drg.cont[c].offset.left;
		contWidth = drg.cont[c].width;
		if (parseInt(c) == 0) contLeft = 0;
		if (parseInt(c) == drg.cont.length-1) contWidth  = 1000000000;
		
		if (x > contLeft && x < contLeft+contWidth) {
			if (drg.cont[c].obj.length==0){
				$("#"+drg.cont[c].id).append(divTarget);
				return;
			}
			if (y < contTop){
				$("#"+drg.cont[c].id).prepend(divTarget);
				return;
			}
			for (var objI in drg.cont[c].obj) {
				ob = $("#"+drg.cont[c].obj[objI].id);//drg.cont[c].obj[objI];
				if ( y > ob.offset().top-10 && y < (ob.offset().top+ob.height()) ) {
					ob.after(divTarget);
					return;
				}
			}
			$("#"+drg.cont[c].id).append(divTarget);
			return;
		}
	}
}
var h = "0px;"
var offx=0;
var offy=0;
var divDrag, divTarget;
function lift(obj,ev) {
	$(obj).find("table.tablesorter").each(function(){
			var jThis = $(this);
			
			var currentSortOrder = [];
			if(jThis.find("."+$.tablesorter.defaults.cssHeaderRow)){
				jThis.find("."+$.tablesorter.defaults.cssHeader).each(function(index){
					
					if($(this).hasClass($.tablesorter.defaults.cssAsc) || $(this).hasClass($.tablesorter.defaults.cssDesc)){
						var order = $(this).hasClass($.tablesorter.defaults.cssAsc) ? 0 : 1;
						currentSortOrder.push([index,order]);
					}
					
				});
	
				jThis.trigger("destroy"); //kill tablesorter
				jThis.addClass("hadTableSorter");
				jThis.data("currentSortOrder",currentSortOrder);
			}	
		});
	
	
  	ContextAction();
	ev = ev || window.event;
	if(ev.pageX || ev.pageY){ 
		x = ev.pageX;
		y = ev.pageY;
	} else {
		x = ev.clientX;
		y = ev.clientY;
	}
	offx = x - $(obj).offset().left;
	offy = y + $("#tblHome").offset().top-5-$(obj).offset().top;
	dragObj=$(obj).clone(true);
	h = $(obj).height()+"px";
	
	divDrag = $("#divDrag");
	divDrag.css("left",(x-offx)+"px");
	divDrag.css("top",(y-offy)+"px");
	divDrag.css("height",$(obj).height()+"px");
	divDrag.css("width",$(obj).width()+"px");
	divDrag.append($(dragObj));
	divDrag.show();
	
	if (divTarget) divTarget.remove();
	divTarget = null;
	$(obj).replaceWith($("#divTarget").clone());
	divTarget = $("#tblHome #divTarget");
	divTarget.css("height",h);
	divTarget.show();		
	
	drg.delObj($(dragObj).attr("id"));

	document.onmousemove = moveObj;
	document.onmouseup = drop;
}
function drop() {
	/*document.onmousemove = null;
	document.onmouseup = null;*/
	divTarget.replaceWith($(dragObj));
	divDrag.hide().empty();
	divTarget = null;
	
	drg.addObj($(dragObj).attr("id"));
  
	document.onmousemove = null;
	document.onmouseup = null;
	//addVisualEffects('tblHome');
	$(dragObj).find("table.hadTableSorter").each(function(){
		var jThis = $(this);
		var sortList = jThis.data("currentSortOrder");
		sortList = (typeof(sortList)=="object") ? sortList : '' ;
		jThis.tablesorter({sortList:sortList, cancelSelection:true, textExtraction:tableTextExtraction, widgets: ['sortPersist'],cssInfoBlock: 'rtable-nosort' }).removeClass('saveForbiden');
	});
	dragObj=null;
	mresize();
}

/**************************
* Функция проверки вводимого символа
***************************/

function keyCheck(eventObj, obju){
  var keyCode;
  if (document.all){
    keyCode=eventObj.keyCode;
  }else{
    keyCode=eventObj.which;
  }
  if((keyCode<47||keyCode>58)&&(keyCode!=0)&&(keyCode!=8)&&(keyCode!=13)){
    return false;
  }else{
    return true;
  }
  return true;
}
function amountKeyCheck(id) {
	var amtObj = $("#"+id);
	amtObj.focus(function(){
		if (isNaN(this.value) || Number(this.value)==0) this.value = "";
	});
	amtObj.change(function(){
		if (isNaN(this.value)) {this.value = "0.00";return;}
		var val = '000' + (Math.round(this.value*100));
		val = Number(val.substring(0,val.length-2))+'.'+val.substr(val.length-2);
		this.value = val;
	});
	amtObj.keypress(function(ev){
		keyCode = ev.charCode || ev.which;
		var char = String.fromCharCode(keyCode);
		
		if (char=="," && this.value.indexOf('.')==-1) {
			if ($.browser.mozilla){
				var evt = document.createEvent("KeyEvents");
				evt.initKeyEvent("keypress",true,true,window,false,false,false,false,0,46);
				this.dispatchEvent(evt);
			} else if ($.browser.msie){
				var range = document.selection.createRange();
				range.text = ".";

			}
			return false;
		}
		
		if (char==".") {
			if (this.value.indexOf('.')!=-1) return false;
		}
		
		if(keyCode==0 || keyCode==8 || /[.0-9]/.test(char)) return true;
		return false;
	});
}
function getTextFromDoc(doc) {
	if (doc==null) return null;
	if ($.browser.msie) {
		return doc.xml;
	} else {
		var serializer = new XMLSerializer();
		var xml = serializer.serializeToString(doc);
		return xml;
	}
}
function getValue(doc){
	var txtval = "";
	if (doc==null) return "";
	if (doc.hasChildNodes()) {
		if (doc.childNodes.length==1 && !doc.childNodes[0].hasChildNodes()) {
			txtval = doc.firstChild.nodeValue;
		} else {
			txtval = getTextFromDoc(doc)
			txtval = txtval.substring(txtval.indexOf("<"+doc.nodeName+">")+("<"+doc.nodeName+">").length)
			txtval = txtval.substring(0,txtval.lastIndexOf("</"+doc.nodeName+">"));
		}
	}
	return txtval;
}
function xPath(oNodes, sXPath) {
    if(oNodes) {
		if($.browser.msie) {
            try {
                oNodes.setProperty ("SelectionLanguage", "XPath");
                var oSelectedNode = oNodes.documentElement.selectNodes(sXPath);
                return oSelectedNode;
            } catch (e) {
            }
        } else {
            try {
                var oXpe = new XPathEvaluator();
                var oNsResolver = oXpe.createNSResolver(oNodes.ownerDocument == null ? oNodes.documentElement : oNodes.ownerDocument.documentElement);
                var oResult = oXpe.evaluate(sXPath, oNodes, oNsResolver, 0, null);
                var aFound = [];
                var oRes;
                while (oRes = oResult.iterateNext()) {
                    aFound.push(oRes);
                }
                return aFound;
            } catch (e) {
            }

        }
    }
}

function mresize(){
	if(sessionLastActivityTime!=null){
		sessionLastActivityTime=(new Date()).getTime();
	}
	if($('.mayPrint', '#body').length==0 && $('.mayPrint', '#fadeDiv').length==0){
		clearPrintDiv();
	}
  //console.log('=======================================================================');
  //$('#divRightWrapFixedTop div').each(function(){console.log('id='+$(this).attr('id')+';class='+$(this).attr('class'));});
  if($('#fadeDiv').css('visibility')=='visible'){
    var maxh=$('#fadeDiv').height();
    var maxw=$('#fadeDiv').width();
    $('#fadeDiv #fadeContent').css('left', (maxw-$('#fadeDiv #fadeContent').width())/2);
    if($('#fadeDiv #actionContentDivWrap').length){
      var toppadding=$('#fadeDiv #actionContentDivWrap').attr('toppadding')?$('#fadeDiv #actionContentDivWrap').attr('toppadding'):0.25;
      $('#fadeDiv #fadeContent').css('top', (maxh*toppadding));
      var ch=0;
      if($('#fadeDiv #confirm_block').css('display')!='none'){
        ch=$('#fadeDiv #confirm_block').height();
      }
      var nmax=maxh-10-maxh*toppadding-12-ch-$('#fadeDiv #winheader').height();
      if($('#fadeDiv #actionContentDiv').height()>=nmax){

        $('#fadeDiv #actionContentDivWrap').height(nmax);
      }else{
        $('#fadeDiv #actionContentDivWrap').css('height', 'auto');
      }      
    }else{
      $('#fadeDiv #fadeContent').css('top', (maxh-$('#fadeDiv #fadeContent').height())*0.35);
    }
  }

  if($('#divKeyboardWrap').length>0 && $('#Password').length>0){
  	px=$('#Password').offset().left;
  	py=$('#Password').offset().top+20;
  	$('#divKeyboardWrap').css({left: px + "px", top: py + "px"});
  }

  if ($('.logonWrapRegistration').length>0) {
    var logonWrap = $('.logonWrapRegistration');
    var logonReg = $('.logonRegistration');
    if ((logonReg.height() + logonReg.offset().top) > logonWrap.height()){
      logonWrap.height(logonReg.height()+logonReg.offset().top+15)
      $('#body').css('overflow','auto');
    }
  }

  if(!$('#MainContent').length){
    return;
  }
  var topp=$('#MainContent').offset().top;
  var bott=$('#divFooter').offset().top;
  var tabh=1;
  if($('#divMain #ulRightWrap').length>0 && $('#divMain #ulRightWrap').attr('hght') && $('#divMain #ulRightWrap').attr('hght')!=""){
    tabh=$('#divMain #ulRightWrap').attr('hght');
  }
  var maxH=bott-topp-7-21-10-Number(tabh)-2;// $(this).parent().attr('hght',tallestcolumn+4);
  $('#pipka').css('top', topp+'px');
  $('#pipka').height(bott-topp);
  $('#divMain').height(bott-topp);
    

  if($('#divLeftMenu').css('display')=='none'){ 
    $('#divMain').width($('#pipka').width());
  }else{
    $('#divMain').width($('#pipka').width()- $('#divLeftMenu').width()-7);//-5
    $('#divMenu').height(bott-topp-8-10);
    if($.browser.msie && ($.browser.version == 6 || $.browser.version == 7 )){
      if($('#divMenu').height() < $('#divMenu > .rmenulist').height()){
        $('#divMenu > .rmenulist .rtable').each(function(){
          $(this).width(400-8-10-18);
          /*$('#divMenu').width()=392*/
        });
      }else{        
        $('#divMenu > .rmenulist .rtable').each(function(){
          $(this).width(400-8-10);
        });
      }
    }
    if($.browser.msie && ($.browser.version == 8 || $.browser.version == 9)){
      if($('#divMenu').height() < $('#divMenu > .rmenulist').height()){
		$('#divMenu').css('width','auto');
      }else{   
		$('#divMenu').width(392);
      }
    }	
  }  
  
  if($('#divMain #divRightWrapScrlMiddleWrap').length>0 && $('#divMain #divRightWrapScrlMiddleWrap').css('display')!='none'){
    var mH=maxH; 
    if($('#divMain #divRightWrapFixedTop').css('display')!='none'){
      //console.log($('#divMain #divRightWrapScrlMiddle').offset().top);
      mH-=$('#divMain #divRightWrapFixedTop').height();//console.log('-top='+$('#divMain #divRightWrapFixedTop').height());
    }
    if($('#divMain #divRightWrapFixedBottom').css('display')!='none'){
      mH-=$('#divMain #divRightWrapFixedBottom').height();//console.log('-bot='+$('#divMain #divRightWrapFixedBottom').height());
	  if($('#divMain #divHelp').css('display')!='none'){
		mH+=$('#divMain #divHelp').height();
		}
    }
    if(mH < 80){
      mH=80;
    }
    if($('#divMain #divRightWrapScrlMiddle').height()>mH){
      $('#divMain #divRightWrapScrlMiddleWrap').height(mH);
      if ($('#div-switch').length>0 && $('#div-switch').is(':visible')) {
        $('#divMain #divRightWrapScrlMiddleWrap').height(mH-$('#switch-view').height()+12);
      }
    }else{
		  $('#divMain #divRightWrapScrlMiddleWrap').height($('#divMain #divRightWrapScrlMiddle').height());
	}
  }
  
  if($('#divMain #divRightWrapContent').length>0){
    if($('#divMain #divRightWrapContent').height()<80){
      $('#divMain #divRightWrapContentWrap').height(80);
    }else{
      if($('#divMain #divRightWrapContent').height()>maxH){
        $('#divMain #divRightWrapContentWrap').css('height',maxH);
      }else{
        $('#divMain #divRightWrapContentWrap').css('height', 'auto');
      }
    }
  }

  if($('#tblHome').length>0){
    if($('#tblHome').height() > $('#divMain').height()-5){
      $('#tblHome').width( $('#pipka').width()-18-5);
    }else{
      $('#tblHome').width( $('#pipka').width()-5);
    }
  }
}

function resize(){}

function showModuleRightWrap(name,params,callback){
  if(GlobalRequestArr['#divMain']){
    GlobalRequestArr['#divMain'].abort();
    //GlobalRequestArr['#divMain']=null;
    delete GlobalRequestArr[id];
  }
  $('#divMain').empty();
  $('#divMain').append($('#divRightWrap').children().clone(true));
	var url = module[name];  

  var Callback = function () {
    $('#ulRightWrap', '#divMain').empty().append($('#moduleTabs').children().clone(true));
    $('#moduleTabs').remove();
    if($('#moduleMiddle').length){
      $('#divRightWrapScrlMiddle', '#divMain').empty().append($('#moduleMiddle').children().clone(true));
      $('#moduleMiddle').remove();
    }
    if($('#moduleBottom').length){
      $('#divRightWrapFixedBottom', '#divMain').empty().append($('#moduleBottom').children().clone(true));
      $('#moduleBottom').remove();
    }
    if($('#moduleTitle').length){
      $('#icolistTitle', '#divMain').html($('#moduleTitle').html());
      $('#moduleTitle').remove();
    }   
    if($('#moduleIcons').length){
      if ($('#icolistIcons').length) {
		$('#icolistIcons', '#divMain').prepend($('#moduleIcons').children().clone(true));
	  } else {
		$('#icolistIcons', '#divMain').html($('#moduleIcons').html());
		}
      $('#moduleIcons').remove();
    }
    var cbs = $('#callback').html();
    eval(cbs);
    $('#callback').remove();
		addVisualEffects('#divMain');
    mresize();
		if (callback) callback();
	}
	if (url) loadURL('#divMain #divRightWrapFixedTop',url,params,Callback);
  else $('#divMain').empty();
}

function ContextAction(e){
  $(".CntxtSh").hide();
  $(".CntxtSh").removeClass("CntxtSh");
  $(".CntxtMaySh").show();
  $(".CntxtMaySh").addClass("CntxtSh").removeClass("CntxtMaySh");  
}

var sessionTimer;
var sessionLastActivityTime;
var checkSessionTimeout;

function initSessionTimer(timeout, checkF, onInitF){
	stopSessionTimer();
	sessionLastActivityTime=(new Date()).getTime();
	if(onInitF){
		onInitF();
	}
	checkSessionTimeout=checkF;
	sessionTimer=setInterval("checkSessionTimeout("+timeout+")", 5000);
}

//(title,text,close_callback,help_callback,btn1_callback,ad_callback,btn2_callback,wrap_class,btn3_callback,btn1_text,btn2_text,btn3_text,toppadding)
function stopSessionTimer(){
	if(sessionTimer!=null){
		clearInterval(sessionTimer);
		sessionTimer=null;
		sessionLastActivityTime=null;
	}
}

function doExitOnTimeout(){
	doExit();
}
function titleIcon(id){
	var icon=JS.messages.Icons;
	for(var i in icon){
		$('.'+i, id).attr('title', icon[i]).attr('alt', icon[i]);
	}
}

/* TWIB-545 */
  
function execTranFaultHandler(args, resp){
    var handled = false;
    try{
        var faultCode = Number(resp.Fault.Code.Value);
        
        if(window.ExecTranFaultHandlers instanceof Array){
	        var tmpHandlers = window.ExecTranFaultHandlers.slice(0).reverse();
	        for (key in tmpHandlers) {
		        if (tmpHandlers[key].faultCode == faultCode) {
			        if (typeof tmpHandlers[key].handler == 'function') {
				        handled = handled || tmpHandlers[key].handler(args, resp);
				        if (handled) {
					        break;
				        }
			        }
		        }
	        }
	    }
	}catch(e){
	
	}
	return handled;
}

function addExecTranFaultHandler(faultCode, handler){
    if(!(window.ExecTranFaultHandlers instanceof Array)){
        window.ExecTranFaultHandlers = new Array();
    }
    window.ExecTranFaultHandlers.push({faultCode:faultCode, handler:handler});
}

function loadURLFaultHandler(args, resp){
    var handled = false;
    try{
        var faultCode = Number(resp.Fault.Code.Value);
        
        if(window.loadURLFaultHandlers instanceof Array){
	        var tmpHandlers = window.loadURLFaultHandlers.slice(0).reverse();
	        for (key in tmpHandlers) {
		        if (tmpHandlers[key].faultCode == faultCode) {
			        if (typeof tmpHandlers[key].handler == 'function') {
				        handled = handled || tmpHandlers[key].handler(args, resp);
				        if (handled) {
					        break;
				        }
			        }
		        }
	        }
	    }
	}catch(e){
	
	}
	return handled;
}

function addloadURLFaultHandler(faultCode, handler){
    if(!(window.loadURLFaultHandlers instanceof Array)){
        window.loadURLFaultHandlers = new Array();
    }
    window.loadURLFaultHandlers.push({faultCode:faultCode, handler:handler});
}

function ajaxUploader(frm, callback, startImmidiately)
{
	var source = frm;
	var iframeDoc = null;
	var iframeNode = null;
	var frameId = null;
	var form = null;
	var callbackTimeout = -1;
	var onloadcallback = function(arg){
		var result = {uploaded:-1, files:[], error: "Empty response"};
		if(arg==="timeout")
		{
			showErrorMessage(JS.messages.Timeout);
			result = {uploaded: -1, files:[], error: JS.messages.Timeout};
		}
		else
		{
			if(callbackTimeout!=-1)
			{
				window.clearTimeout(callbackTimeout);
				callbackTimeout = -1;
			}
			//*/
			var resultText = $(docGetter(document.getElementById(frameId)).body).text();
			if(resultText.length>0)
				eval('result=' + resultText);
		}
		if(callback)
			callback(result);
	};
	this.createIframe = function()
	{
		frameId = "iframe_" + new Date().getTime();
		var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"/>';
		$(iframeHtml).appendTo(document.body);
		iframeNode = document.getElementById(frameId);
		iframeDoc = this.getDoc(iframeNode);
		return iframeDoc;
	}
	var docGetter = null;
	this.getDoc = function(n)
	{
		if(docGetter==null)
		{
			if(n.contentDocument)
				docGetter = function(n) {return n.contentDocument;}
			else if(n.contentWindow)
				docGetter = function(n) {return n.contentWindow.document;}
			else
				docGetter = function(n) {return n.document;}
		}
		return docGetter(n);
	}

	this.createForm = function(targetdoc, action)
	{
		var formId = 'formUpload_' + new Date().getTime();
		var html = '<form  action="' + action + '" method="POST" name="'
			+ formId + '" id="'
			+ formId + '" enctype="multipart/form-data"></form>';
		targetdoc.open();
		targetdoc.write(html);
		targetdoc.close();
		form = $('#' + formId, targetdoc);
		$(iframeNode).load(onloadcallback);
	}

	this.upload = function()
	{
		showCustomContent($("#divBigWait").html());
		if(form)
			form.html('');
		var totalFiles = 0;
		$("input[type='file']", source).each(function()
		{
            $(this).after($(this).clone(true)).appendTo(form);
			totalFiles++;
		});
		if(totalFiles>0)
		{
			callbackTimeout = setTimeout(onloadcallback, 30*1000, "timeout");
			form.submit();
			setTimeout(function(){$(iframeNode).remove();}, 300);
		}
		else
		{
			if(callback)
				callback({uploaded:0, files:[], error:false});
		}
		// showErrorMessage(JS.messages.ServerError)
	}
	var filesCount = $("input[type='file']", source).length;
	if(filesCount>0)
	{
		this.createForm(this.createIframe(), '/preupload.jsp');
	}
	if(startImmidiately)
		this.upload();
}

addExecTranFaultHandler(12, function(src, resp){
    var tran = src[0];
    if(tran == 'ScheduleRq'){
        var params = src[1];
        var callback = src[2];
        var hidemessage = src[3];
        var err_callback = src[4];
        var HideCommission = src[6];
        var isGorodPayment = false;
        var curr = '';
        
        for(key in params){
            var obj = params[key];
            if(obj['name'] == 'GorodPayment'){
                isGorodPayment = true;
                curr = obj['value'];
                break;
            }
        }
        if(isGorodPayment){
            var txt = '';
            var thisTranId = '';
            var feeAmount = '';
            {
                if(resp.Fault.Detail && resp.Fault.Detail.AuthRespText && resp.Fault.Detail.AuthRespText != '' && Number(resp.Fault.Detail.AuthRespText) != 0){
                    feeAmount = resp.Fault.Detail.AuthRespText;
                }
                txt += JS.messages.FeeApplied + feeAmount + ' ' + curr + JS.messages.ContinueMessage;
                if(resp.Fault.ShowDeclineReason && resp.Fault.Reason && resp.Fault.Reason.Text){
                    txt += resp.Fault.Reason.Text.replace(/&lt;/g, '<').replace(/&gt;/g, '>') + '<br/>';
                }
                if(resp.Fault.Detail && resp.Fault.Detail.TextMessage && resp.Fault.Detail.TextMessage != ''){
                    txt += resp.Fault.Detail.TextMessage.replace(/&lt;/g, '<').replace(/&gt;/g, '>') + '<br/>';
                }
                if(resp.Fault.Detail && resp.Fault.Detail.TranId && resp.Fault.Detail.TranId != ''){
                    thisTranId = resp.Fault.Detail.TranId;
                }
            }
            var toDo = function(){
                var doCh = true;
                if (params.push){ 
                    for(key in params){
                        if(params[key].name == 'ThisTranId'){
                            doCh = false;
                        }
                    }
                }
                if(doCh){
                    params.push({name: 'ThisTranId', value: thisTranId});
                }
                if($('#tmpDivDynamic').children().length > 0){
                    copyFromTmp();
                    execTran(tran, params, callback, hidemessage, err_callback, function(){copyFromTmp();}, HideCommission);
                }else{
                    copyFromTmp();
                    execTran(tran, params, callback, hidemessage, err_callback, null, HideCommission);
                }
                mresize();
            }
            if(feeAmount != ''){
                showMessage('', txt, '', '', function(){
                    toDo();
                }, null, function(){copyFromTmp();}, '', '', JS.messages.Ok, JS.messages.Cancel, null, null, true);
            }else{
                toDo();
            }
            return true;
        }
    }
    return false; 
});

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


// Tablesorter Widget для сохранения состояния сортировки
$.tablesorter.addWidget({id: 'sortPersist', format: function(table){
    if (!$(table).hasClass('saveForbiden')) {
        execTran('SaveUserModuleSettings',{Id: $(table).attr('confid')+'_Sort', Value: table.config.sortList},'',true);
    }
}});

$.tablesorter.addWidget({id: 'copyToPrintDiv', format: function(table){
    var sourceSelector = $(table).attr('printDivSourceSelector');
	if(sourceSelector != null && sourceSelector !== undefined && typeof(sourceSelector) == 'string')
		setPrintDivContent($(sourceSelector).html());
}});

function updateAddressRegex()	{
	var channel=$('#fadeDiv .slctChannel').val();
	if(channel !== undefined && channel != null ){
		var typeCh = $('#fadeDiv .slctChannel option[value='+channel+']').attr("typeChannel");
		if(typeCh !== undefined && typeCh != null){
	       	 if(typeof(channelRegexArr[""+typeCh]) == 'string'  ){
	          		if($.trim(channelRegexArr[""+typeCh]).length)
	          			$('#inpAddress','#fadeDiv').attr("validexp",channelRegexArr[""+typeCh]);
	          	}	
			}
		}
	}

if(cssesc!== undefined){
	cssesc.options.escapeEverything = false;
	cssesc.options.wrap = false;
	cssesc.options.isIdentifier = true;
}