// preload images

var myimages = new Array();
function preloadimages(){
	for (i = 0; i < preloadimages.arguments.length; i++) {
		myimages[i] = new Image();
		myimages[i].src = preloadimages.arguments[i];
	}
}

preloadimages(
	'/common/img/calendar_2.png',
	'/common/img/input_active.gif',
	'/common/img/ico_open_up_black.gif',
	'/common/img/reg_input_active.gif',
	'/common/img/reg_textarea_active.png',
	'/common/img/short_input_bg_active.gif',
	'/common/img/alert_small.png',
	'/common/img/input_passive_4sym.png',
	'/common/img/input_active_4sym.png',
	'/common/img/input_short_ext_active.gif',
	'/common/img/input_short_ext_passive.gif',
	'/common/js/jquery/images/date/gui_calendar_bg_top.png',
	'/common/js/jquery/images/date/gui_calendar_bg_bottom.png',
	'/common/img/orange_marker_left.gif',
	'/common/img/orange_marker_right.gif',
	'/common/img/orange_oval.gif',
	'/common/img/orange_close.gif',
	'/common/img/orange_square_border.gif',
	'/common/img/orange_square.gif',
	'/common/img/way-1-a.gif',
	'/common/img/way-2-a.gif',
	'/common/img/way-3-a.gif',
	'/common/img/way-4-a.gif',
	'/common/img/way-5-a.gif',
	'/common/img/m-payments-a.gif',
	'/common/img/m-payments-h.gif',
	'/common/img/input_left_bg.gif',
	'/common/img/input_right_bg.gif',
	'/common/img/input_center_bg.gif',
	'/common/img/input_left_bg_active.gif',
	'/common/img/input_right_bg_active.gif',
	'/common/img/input_center_bg_active.gif',
	'/common/img/corners_active.png'
);

// form inputs style & menu of comments

function input_focus(elem, field, node_name){
	if (document.getElementById('comment_0')){
	document.getElementById('comment_0').style.display = 'none';
	}
	border = document.getElementById(elem);
	pref = (typeof(node_name)!='undefined')? (node_name+'_'):'';
	border.className = (/passive/.test(border.className))? border.className.replace(pref+'passive', pref+'active') : border.className ;
	
	if (document.getElementById(field)) {
		note = document.getElementById(field);
		note.className = (/hidden/.test(note.className))? note.className.replace(/hidden/,'showed') : note.className ;
	}

	// подсказки внизу страницы должны перекрывать ссылки в подвале
	if(document.getElementById('footer_menu'))
		document.getElementById('footer_menu').style.zIndex = '1';
}

function input_blur(elem, field, node_name){
	clearTimeout(blurTimeout)
	if (document.getElementById('comment_0')){
	document.getElementById('comment_0').style.display = 'block';
	}

	border = document.getElementById(elem);
	pref = (typeof(node_name)!='undefined')? (node_name+'_'):'';
	border.className = (/active/.test(border.className))? border.className.replace(pref+'active', pref+'passive') : border.className ;

	if (document.getElementById(field)) {
		note = document.getElementById(field);
		note.className = (/showed/.test(note.className))? note.className.replace(/showed/,'hidden') : note.className;
	}

	// activate footer
	fff = document.getElementById('footer_menu');
	if(fff)fff.style.zIndex = '11';
}

var blurTimeout;

function input_blur_timeout(elem, field, node_name){
	if (typeof node_name != 'undefined'){
		blurTimeout = setTimeout("input_blur('" + elem + "', '" + field + "', '" + node_name + "')", 250)
	}else{
		blurTimeout = setTimeout("input_blur('" + elem + "', '" + field + "')", 250)
	}
}

// onmouseover, onmoouse out для чекбоксов, радиокнопок и файл инпутов, чтобы подсказку выводить при наведении можно было
	function tiptoolover(it){
		$('input.text, .textarea, .select').blur();
		$('#'+it).show();
	}

	function tiptoolout(it){
		$('#'+it).hide();
	}

function blue_dotted_td_open (td_id, tarea_id) {
	var blue_dotted_td = 'blue_dotted_td_' + td_id + '_' + tarea_id;
	$("#" + blue_dotted_td).addClass("blue_dotted_td");
}
function blue_dotted_td_close (td_id, tarea_id) {
	var blue_dotted_td = 'blue_dotted_td_' + td_id + '_' + tarea_id;
	$("#" + blue_dotted_td).removeClass("blue_dotted_td");
}
//	GUI table drop down


 

function gui_drop_down(num, el){
	link = document.getElementById('more_'+num);
	head = el;
	info = document.getElementById('more_info_'+num);
	
	// check comment gradient
	gcut = 0;
	if (document.getElementById('gui_cut_' + num)) {
		gcutbg = document.getElementById('gui_cut_' + num);
		gcut = 1;
	}
	
	// change indicator
	link.className = (/passive/.test(link.className)) ? link.className.replace(/passive/, 'active') : ((/active/.test(link.className)) ? link.className.replace(/active/, 'passive') : link.className);

	// open-close info
	if (/closed/.test(info.className) && /head_closed/.test(head.className)) {
		
		$('#more_info_'+num).slideDown(700);
		info.className = info.className.replace(/closed/, 'opened');
		head.className = head.className.replace(/head_closed/, 'head_opened');
		/*if (gcut){
			gcutbg.className='';
			gcutbg.getElementsByTagName('div')[0].className='cut_bg_off';
		}
		*/
	}
	else if (/opened/.test(info.className) && /head_opened/.test(head.className)) {
		$('#more_info_'+num).slideUp(350);
		head.className = head.className.replace(/head_opened/, 'head_closed');
		info.className = info.className.replace(/opened/, 'closed');
		/*
		if (gcut){
			gcutbg.className='cut';
			gcutbg.getElementsByTagName('div')[0].className='cut_bg';
		}
		*/
	}
}

// GUI bock drop down

function gui_ddrop(ID,el){
	block = document.getElementById(ID);
	block.className = (/closed/.test(block.className)) ? block.className.replace('closed', 'opened'):(/opened/.test(block.className))?block.className.replace('opened','closed'):block.className;
}


/* faq hide'n'show */
function hns(id){
  el = document.getElementById(id);
	if(el.style.display == '' || el.style.display == 'none'){
	  	$(el).slideDown(300);
		}
		else{
	  	$(el).slideUp(300);
	}
}
/* /faq hide'n'show */

// ui popup

function ui_popup(el){
	$("#" + el).togglePopup();
	if( $('#maincss') || $('#maincss_merchant') ){
		$('#maincss').attr("href", ""); 
		$('#maincss_merchant').attr("href", "");
		$('#maincss').attr("media", ""); 	
		$('#maincss_merchant').attr("media", ""); 
	}
}

// ui popup

function ui_popup_css(src_popup, mode) {
	$('#maincss').attr("href", "/common/css/print_secret.css"); 
  $('#maincss_merchant').attr("href", "/common/css/merchant/print_popup.css");
	$('#maincss').attr("media", "print"); 	
  $('#maincss_merchant').attr("media", "print"); 
	if (mode == 1) 	 window.print();	 		
	$("#" + src_popup).togglePopup();	

}

// ui popup
// additional properties for jQuery object
$(document).ready(function(){
   //align element in the middle of the screen
   $.fn.alignCenter = function() {
      //get margin left
      var marginLeft =  - $(this).width()/2 + 'px';
      //get margin top
      var marginTop =  - $(this).height()/2 + 'px';
      //return updated element
      return $(this).css({'margin-left':marginLeft, 'margin-top':marginTop});
   };

   $.fn.togglePopup = function(e){

     //detect whether popup is visible or not
     if($('#popup').hasClass('hidden'))
     {
       //hidden - then display
       //when IE - fade immediately
       if($.browser.msie)
       {
         $('#opaco').height($(document).height()).toggleClass('hidden')
                    .click(function(){$(this).togglePopup();});
       }
       else
       //in all the rest browsers - fade slowly
       {
         $('#opaco').height($(document).height()).toggleClass('hidden').fadeTo('slow', 0.7)
                    .click(function(){$(this).togglePopup();});
       }

       $('#popup')
         .html($(this).html())
				 .addClass('ui_popup')  
				 .alignCenter()
         .toggleClass('hidden');
				$('body').addClass('printpopup');

				 
     }
     else
     {
       //visible - then hide
       $('#opaco').toggleClass('hidden').removeAttr('style').unbind('click');
       $('#popup').toggleClass('hidden');
       $('#popup').removeClass('ui_popup');
			 $('body').removeClass('printpopup');
     }
   };
});


// Если кликнуть по ячейке, в которой input[text], то фокус автоматически попадет в input[text]
function labelform(){
	formz = $('.form .input');
	for(i=0;i<formz.length;i++){
		formz[i].onclick = function(){
			inputz = this.getElementsByTagName('input');
			for (j=0;j<inputz.length;j++){
				if (inputz[j].type=='text' || inputz[j].type=='password'){
					inputz[j].focus();
				}
			}
		}
	}
}
 
// для элементов всех форм на странице добавить обработки кнопки Enter, чтобы отправлять без input[submit], кроме формы заключения договора организации 'first.vtmpl'
function enterForm(){
	var formz = $('form');
	// проходим по всем формам на странице
	for (i=0;i<formz.length;i++){
		var inputz = formz[i].getElementsByTagName('input');
		// проверяем наличие ID='do_not_submit_on_enter'
		var miss = 0;
		if(/do_not_submit_on_enter/.test(formz[i].id))
			miss = 1;
		else
			miss = 0;
		// проверяем наличие input[submit] или input[image] у формы Или ID='do_not_submit_on_enter'
		var flag = 1;
		for(k=0; k<inputz.length; k++){
			if(inputz[k].type == 'submit' || inputz[k].type == 'image' || miss){
				flag = 0;
			}
		}

		if(flag){
			var fm = formz[i];
			// я просто добавлю скрытый input type="submit" в эти формы, вместо onkeyup обработчика, который обламывает все остальные onkeyup в форме
				
			var sb = document.createElement('input');
			sb.type = 'submit';
			sb.style.display = 'none';
			sb.className = 'formSenderOnEnter';
			fm.appendChild(sb);
		}
	}
}

// для блокировки повторной отправки форм
function submitForm(){
	$('form:not(.unblock)').submit(function(){
		$(this).css({position:'relative', cursor:'wait'})
					 .append("<div style='background: transparent; opacity: 0; position: absolute; top: 0; left: 0; z-index: 10; width: " + $(this).width() + "px; height: " + $(this).height() + "px;'></div>")
	})
	$('.submit a').click(function(){
		$(this).parent().css({position:'relative', cursor:'wait'})
					 .append("<div style='background: transparent; opacity: 0; position: absolute; top: 0; left: 0; z-index: 10; width: " + $(this).parent().width() + "px; height: " + $(this).parent().height() + "px;'></div>")
	})
}

// супер фильтр для цифр 
	function digitsFilter(e)	{
		// Make sure to use event.charCode if available
		var key;
		if(typeof e.charCode == 'undefined' || e.charCode == 0){
			key = e.keyCode
		}
		else {
			key = e.charCode;
		}
		// Ignore special keys
		if (e.ctrlKey || e.altKey || key < 32 || key == 37 || key == 39)
			return true;

		key = String.fromCharCode(key);
		return /\d|\+/.test(key);
	}

// и автофокус-покус для Input с заданным maxlength на другой input с заданным ID

	function stepFilter(it, toElem){
		if(it.value.length == it.maxLength && document.getElementById(toElem)){
			document.getElementById(toElem).focus();
			document.getElementById(toElem).select();
		}
	}



// first, last таблицы для банковских карт .fn_card_table

function fn_card_table(){

	$('table.fn_card_table tr:first-child td, table.fn_card_table tr:first-child th').addClass('first');
	$('table.fn_card_table tr:last-child td, table.fn_card_table tr:last-child th').addClass('last');
	

	tdonly = $('table.fn_card_table td');
	thonly = $('table.fn_card_table th');
	
	for (i=0; i<tdonly.length; i++){
		if(/first/.test(tdonly[i].className) && /last/.test(tdonly[i].className)){
			tdonly[i].className += ' first_last';
		}
	}
	for (i=0; i<thonly.length; i++){
		if(/first/.test(thonly[i].className) && /last/.test(thonly[i].className)){
			thonly[i].className += ' first_last';
		}
	}
}

$(document).ready(function(){
    
	// Блокировка от двойных сабмитов
	enterForm();
	// добавляем скрытую кнопку сабмит в формы, которые отправляются по ссылке, чтобы по энтеру тоже отправлялись
	submitForm();
	if($('.form')){
		labelform();
	}

	preventDef();
	// ставим пробел через 4 символа в поле с номером банковской карты
   
	cardspacer(); 
    $('.card16').keyup();
	// активируем проверку по алгоритму Луна
	$('.luhn').blur(function(){
		isComplete()
	});
	
	// украшаем таблицу со счетами IM и банковскими картами
	fn_card_table();

/*-----append_flash-ugolka-----------*/	
 $("#u_g").appendTo("body"); 	
 $('#u_g').css( "position", "absolute" ); 
 $('#u_g').css( "top", "0" ); 
 $('#u_g').css( "right", "0" ); 

/* hover emulation for IE6 */  
  if($.browser.msie && jQuery.browser.version < "7.0"){
    $(".payments .unactive, .smallpayments .unactive").hover(
      function () {
        $(this).addClass(" hover");
      }, 
      function () {
        $(this).removeClass(" hover");
      }
    );
  }
/* /hover emulation for IE6 */
/* last-child emulation for all */
 $(".payments tr td:last-child").addClass(" last-child");
/* /last-child emulation for all */
});

/* prevent */

function preventDef(){
	$('.preventdefault').click(function(e){
		e.preventDefault();
	})
}

/* print styles */

function printme(){
  //jQuery('a.close_left, a.close').hide();
  window.print();
  }

/* /print styles */
 


/*----------разделение браузеров----------*/



var cssFix = function(){
  var u = navigator.userAgent.toLowerCase(),
  addClass = function(el,val){
    if(!el.className) {
      el.className = val;
    } else {
      var newCl = el.className;
      newCl+=(" "+val);
      el.className = newCl;
    }
  },
  is = function(t){return (u.indexOf(t)!=-1)};
  addClass(document.getElementsByTagName('html')[0],[
    (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
      :is('firefox/2')?'gecko ff2'
      :is('firefox/3')?'gecko ff3'
      :is('gecko/')?'gecko'
      :is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
	  :is('opera/10')?'opera opera10':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
      :is('konqueror')?'konqueror'
      :is('applewebkit/')?'webkit safari'
      :is('mozilla/')?'gecko':'',
    (is('x11')||is('linux'))?' linux'
      :is('mac')?' mac'
      :is('win')?' win':''
  ].join(" "));
}();


function print_inv(param) 
	{ 
	if (!param){
		jQuery("#ui_popup_22").appendTo("body");  
	}
	else {
		print_inv = document.createElement('div');
		print_inv.innerHTML = jQuery(".print_inv").html();
		document.body.appendChild(print_inv);
	}

 $('#maincss').attr("href", "/common/css/print_secret.css"); 
 $('#maincss').attr("media", "print"); 
   window.print();	  
}


/*-----append_flash-ugolka-----------*/	 

function sizeUp() {
 $('#u_g').css( "height", "650px" ); 
 $('#u_g').css( "z-index", "111" );  
}

function sizeDown() {
 $('#u_g').css( "height", "100px" ); 
 $('#u_g').css( "z-index", "1" );  
}


// пробеливатель для 16 значных номеров кредитных кардт
function trimming(str){
	return str.replace(/ /g, "");
}

function cardspacer(){
	$('.card16').keyup(function(e){
		// ignore backspace & arrows
		var key;
		if(typeof e.charCode == 'undefined' || e.charCode == 0){
			key = e.keyCode
		}
		else {
			key = e.charCode;
		}

		if (key == 8 || key == 37 || key == 39) 
			return false;
		var str = trimming($(this).val());
		$(this).val(str.substr(0,4) + (str.length >= 4 ? ' ' : '') + str.substr(4,4) + (str.length >= 8 ? ' ' : '') +str.substr(8,4) + (str.length >= 12 ? ' ' : '') + str.substr(12,4) + (str.length >= 16 ? ' ' : '') + str.substr(16,4))
	})
}

/* алгоритм Луна */
function isComplete(){
	luhn = $('.luhn');
	x='';
	for(i=0; i<luhn.length; i++){
		x += trimming(luhn[i].value);
	}
	
	if (x.length>=12){
		if (!(luhncheck(x))) {
			$('.alert_luhn, .error_luhn').css('display','block')
			.removeClass('invisible');
            $('#sbmt').attr('src','/common/img/submit_next24_disabled.png');
            $('#sbmt').attr('disabled','disabled');
		}
		else {
			$('.alert_luhn, .error_luhn').addClass('invisible');
            $('#sbmt').attr('src','/common/img/submit_next24.png');
            $('#sbmt').removeAttr('disabled');
		}
	}
}

function luhncheck(num) {
	num = (num + '').replace(/\D+/g, '').split('').reverse();
	if (!num.length)
		return false;
	var total = 0, i;
	for (i = 0; i < num.length; i++) {
		num[i] = parseInt(num[i])
		total += i % 2 ? 2 * num[i] - (num[i] > 4 ? 9 : 0) : num[i];
	}
	return (total % 10) == 0;
}

// auto rounded corners для мерчанта 
function getByClass(CLASS){
	var dumpHTML = document.getElementsByTagName('*')
	var tempArray = [];
	var regtst = new RegExp(CLASS);

	for(i=0; i<dumpHTML.length; i++){
		if(regtst.test(dumpHTML[i].className)){
			tempArray.push(dumpHTML[i]);
		}
	}
	return tempArray;
}

function initRadius(eL){
	blocks = getByClass(eL).reverse();

	for(i=0;i<blocks.length;i++){
		blocks[i].className += ' border-radius-js';
		blocks[i].parentNode.innerHTML = '<div class="' + eL + '-bg"><div class="' + eL + '-bg-in ' + eL + '-bg-1"><div class="' + eL + '-bg-in ' + eL + '-bg-2"><div class="' + eL + '-bg-in ' + eL + '-bg-3"><div class="' + eL + '-bg-in ' + eL + '-bg-4">' + blocks[i].parentNode.innerHTML + '<\/div><\/div><\/div><\/div><\/div>';
	}
}


