function updateTips(t)
{
	$("#validateTips").text(t).addClass('ui-state-highlight');
	setTimeout(function() {
		$("#validateTips").removeClass('ui-state-highlight', 1500);
	}, 500);
}

function checkError(o,lang)
{
	o.addClass('ui-state-error');
	n = o.parent("td").prev("td").text();
	if(lang == "ru")
		updateTips("Поле '" + n + "' не заполнено.");
	else if(lang == "ua")
		updateTips("Поле '" + n + "' не заповнено.");
	if(lang == "en")
		updateTips("Please fill in the field '" + n + "'.");
}

function checkNull(o,lang)
{
	if(o[0].tagName == "SELECT")
	{
		if ( o.val() == 0 ) 
		{
			checkError(o,lang);
			return false;
		} 
		else return true;
	}
	else if(o[0].tagName == "INPUT")
	{
		if(o.val().length < 1)
		{
			checkError(o,lang);
			return false;
		}
		else return true;	
	}
}

function checkLength(o,n,min,max)
{
	if ( o.val().length > max || o.val().length < min ) 
	{
		//alert(o.parent("td").prev("td").text());
		o.addClass('ui-state-error');
		//updateTips("Длина поля " + n + " должна быть от "+min+" до "+max+".");
		updateTips("Поле " + n + " не заполнено.");
		//destination = jQuery("#"+o.attr("id")).offset().top - 20;
		//jQuery("html:not(:animated),body:not(:animated)").animate({scrollTop: destination}, 1100);
		return false;
	} 
	else return true;	
}

function checkSelect(o,n,v)
{
	if ( o.val() == v ) 
	{
		o.addClass('ui-state-error');
		updateTips("Поле '" + n + "' не заполнено.");
		return false;
	} 
	else return true;	
}

function ua_checkLength(o,n,min,max)
{
	if ( o.val().length > max || o.val().length < min ) 
	{
		o.addClass('ui-state-error');
		//updateTips("Длина поля " + n + " должна быть от "+min+" до "+max+".");
		updateTips("Поле " + n + " не заповнено.");
		return false;
	} 
	else return true;	
}

function ua_checkSelect(o,n,v)
{
	if ( o.val() == v ) 
	{
		o.addClass('ui-state-error');
		updateTips("Поле '" + n + "' не заповнено.");
		return false;
	} 
	else return true;	
}

function en_checkSelect(o,n,v)
{
	if ( o.val() == v ) 
	{
		o.addClass('ui-state-error');
		updateTips("Please fill in the field '" + n + "'.");
		return false;
	} 
	else return true;	
}

function en_checkLength(o,n,min,max)
{
	if ( o.val().length > max || o.val().length < min ) 
	{
		o.addClass('ui-state-error');		
		updateTips("Please fill in the field '" + n + "'.");
		return false;
	} 
	else return true;	
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function zakazat_deposit(v)
{
	expires = new Date();
	expires.setTime(expires.getTime() + (1000 * 86400 * 365)); // вычисляем срок хранения cookie
	set_cookie("deposit", v, expires);
	//setCookie("deposit",v);
	location.replace("/mobilnyj_bank/zakaz_depozita/");
}

function ua_zakazat_dposit(v)
{
	expires = new Date();
	expires.setTime(expires.getTime() + (1000 * 86400 * 365)); // вычисляем срок хранения cookie
	set_cookie("deposit", v, expires);
	//setCookie("deposit",v);
	location.replace("/ua/mob_lnij_bank/zakaz_depozita/");
}

function en_zakazat_dposit(v)
{
	expires = new Date();
	expires.setTime(expires.getTime() + (1000 * 86400 * 365)); // вычисляем срок хранения cookie
	set_cookie("deposit", v, expires);
	//setCookie("deposit",v);	
	location.replace("/en/mobile_bank/deposit_order/");
}

function set_cookie(name, value, expires)
{
	if (!expires)
	{
		expires = new Date();
	}
	document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() +  "; path=/";
}

function get_cookie(name)
{
	cookie_name = name + "=";
	cookie_length = document.cookie.length;
	cookie_begin = 0;
	while (cookie_begin < cookie_length)
	{
		value_begin = cookie_begin + cookie_name.length;
		if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
		{
			var value_end = document.cookie.indexOf (";", value_begin);
			if (value_end == -1)
			{
				value_end = cookie_length;
			}
			return unescape(document.cookie.substring(value_begin, value_end));
		}
		cookie_begin = document.cookie.indexOf(" ", cookie_begin) + 1;
		if (cookie_begin == 0)
		{
			break;
		}
	}
	return null;
}


﻿function openMenu(id, group_only, href) {
	if(group_only){
		elem = this.document.getElementById(id);
		if(elem.style.display == '')
			this.document.getElementById(id).style.display = 'none';
		else
			this.document.getElementById(id).style.display = '';
	} else {
		window.location = href;
	}
}

var deposit = new Array;
var table = new Array;
var prolong = new Array;

var m_titles = [];
var m_lang = "";
var m_summ;
var m_durationItem;
var m_currency;
var m_count;
var m_table_content;
var m_bfloatingDate;
var m_bclearTable;

/**
 * function changeDatePicker
 *
 * Функция подсчета количества дней между двумя датами
 * из поля datepicker1 читается первая дата из поля datepicker2
 * вторая дата, рузельтат вычитания записывается в поле days
 */
function changeDatePicker()
{	
	clearTable();
    valPicker1 = $("#datepicker1").attr("value");
    valPicker2 = $("#datepicker2").attr("value");
    if(valPicker1.length >0 && valPicker2.length >0)
    {
		var arr1 = valPicker1.split("-");
		var arr2 = valPicker2.split("-");
		
        var date1 = new Date(arr1[0],arr1[1]-1,arr1[2],3,0,0);
        var date2 = new Date(arr2[0],arr2[1]-1,arr2[2],3,0,0);
		
//		var date1 = new Date(valPicker1);
//		var date2 = new Date(valPicker2);

//		alert(date11.toString()+"\n"+date1.toString());
        if(date1 <= date2)
        {
            time = date2.getTime() - date1.getTime();
            var days = Math.floor((time / 86400/1000)+1);
            $("#days").attr("value",days);
        }
        else {
            $("#days").attr("value","0");
        }
    }
}

/**
 * function changeDuration
 *
 * 
 */
function changeDuration()
{
	clearTable();
	valueDuration = $("#duration").val();
	if(valueDuration == -1)
	{
		$("#annotation").hide();
		$('#datePickerPanel').show();	
		m_bfloatingDate = true;	
	}
	else
	{	
		$("#annotation").show();
		$('#datePickerPanel').hide();
		m_bfloatingDate = false;
	}
}

function showCalc2(lang){
	$('#summ').val($('#summ2').val());
	$('#currency2').val($('#currency22').val());
	$("#duration").val($("#duration2").val());
	$('#type1').attr("checked",$('#type12').attr("checked"));
	$('#type2').attr("checked",$('#type22').attr("checked"));
	$('#type3').attr("checked",$('#type32').attr("checked"));
	showCalc(lang);
	calculate();
}

function showCalc(lang)
{    
	m_lang = lang;
	m_titles = {"ua":{"prolong":"Пролонгація","month":"-й місяц", "warning":"Треба заповнити всі поля."},
	"ru":{"prolong":"Пролонгация", "month":"-й месяц", "warning":"Нужно заполнить все поля"},
	"en":{"prolong":"Prolongation", "month":" month", "warning":"Please, fill in all the fields"}};	
	
	clearTable();
	m_bfloatingDate = false;
	m_bclearTable = true;
	
	$.datepicker.setDefaults($.datepicker.regional['uk']);
	$("#datepicker1").datepicker();
    $("#datepicker1").datepicker('option', {dateFormat: "yy-mm-dd"});		
    
	$("#datepicker2").datepicker();
    $("#datepicker2").datepicker('option', {dateFormat: "yy-mm-dd"});

	$('#datepicker1').bind("change",changeDatePicker);
	$('#datepicker2').bind("change",changeDatePicker);
	$('#duration').bind("change",changeDuration);
	$('#currency').bind("change",clearTable);
	$('#summ').bind("change",clearTable);
	$('#type1').bind("change",clearTable);
	$('#type2').bind("change",clearTable);
	$('#type3').bind("change",clearTable);

/////
	//$('#summ').val("");
	//$('#days').val("");
	//$('#datepicker1').val("");
	//$('#datepicker2').val("");	
	//$('#duration').val(0);
	//$('#currency').val(0);	
	//$('#type1').attr("checked", "checked");
	//$('#type2').attr("checked", "checked");
	//$('#type3').attr("checked", "checked");
	$("#annotation:hidden").show();
/////
	
	$('#calc').show('slow'); 
	$('#datePickerPanel:visible').hide();		
		
    $.post("/calc2.php", {lang:m_lang},
        function(rezdata)
        {
            if(!rezdata) return;            
            var rez = null;
            eval('rez = '+rezdata+';');
            deposit = rez.deposit;
	    prolong = rez.prolong;
	    calculate();
	});	
}


function calculate()
{
    m_summ = $("#summ").val()-0;
    m_durationItem = $("#duration").val();
    m_currency = $("#currency2").val();
			
	var type1 = $('#type1').attr('checked')?1:0;	// Срочный
	var type2 = $('#type2').attr('checked')?2:0;	// До востребования
	var type3 = $('#type3').attr('checked')?3:0;	// С плавающей датой
	
	if(m_summ == "" || m_currency == 0 || m_durationItem == 0 || (m_durationItem == -1 && $('#days').val()=="") || 
		(type1==0 && type2==0 && type3==0) )
	{
		alert(m_titles[m_lang]["warning"]);
	}
	else
	{
	
		table = [];
		if(m_durationItem == -1)
		{
			var days = $("#days").val()-0;
			//days = days / 30;	
			m_durationItem = days / 30;//Math.floor(days*100)/100;
		}	
		
	    m_count = 1;
	    
	    m_table_content = "";
	    
	    for(var depositNum in deposit)
	    {
			min_vklad = deposit[depositNum]['min_vklad'];
			max_vklad = deposit[depositNum]['max_vklad'];
			deposit_type = deposit[depositNum]['deposit_type'];	
		    
			if(deposit[depositNum]['currency'] == m_currency)						
	        {													
				if(type1 == 1)	
				{																
					if(deposit_type == type1)	// Срочный
					{
						if(deposit[depositNum]['min_month'] == m_durationItem)
							addRowToTable(depositNum);
						else if(deposit[depositNum]['prolong'] == 1)
						{
							len = prolong[deposit[depositNum]["id"]][m_currency]["months"].length;
							max_month = prolong[deposit[depositNum]["id"]][m_currency]["months"][len-1]-0;
							min_month = 1-0;
							if( (max_month >= m_durationItem) && (min_month <= m_durationItem) )
							{								
								addRowToTable(depositNum);
							}
								
						}
					}								
				} 				
				if(type2 == 2)
				{
					if(deposit_type == type2)	// До востребования
					{					
						if(deposit[depositNum]['min_month'] == "null" && deposit[depositNum]['max_month'] == "null")
							addRowToTable(depositNum);
					}
				}				
				if(type3 == 3)
				{
					if(deposit_type == type3)	// С плавающей датой
					{								
						if(deposit[depositNum]['min_month'] <= m_durationItem && 
							deposit[depositNum]['max_month'] >= m_durationItem )
							addRowToTable(depositNum)
					}	      
				}				
	        }
	    }
		showTable();
	}
}

function addRowToTable(depositNum)
{
	percent = deposit[depositNum]['percent_year'];
	var duration = 0;
	if(deposit[depositNum]['prolong'] == 0)	
	{	
		if((deposit[depositNum]['deposit_type'] == 1) && m_bfloatingDate == true)
			duration = Math.floor(m_durationItem-0);
		else if(m_bfloatingDate == true)
			duration = ($("#days").val()-0) / 30;//duration = m_durationItem;
		else
			duration = m_durationItem;
			
		year = percent  * m_summ / 100;
		month = year / 12;
		period = (month*1.0) * duration;
		day = month / 30;		
	}
	else	// Пролонгация
	{		
		prolongMonth = Math.floor(m_durationItem-0);		
		month = percent * m_summ / 100 / 12;
		period = month;
		for(i=2; i<=prolongMonth;i++)
		{
			percent = prolong[deposit[depositNum]["id"]][m_currency][i];						
			month = percent * m_summ / 100 / 12;			
			period += month;						
		}
		month = period / prolongMonth;
		day = month / 30;
	}	

	table[m_count] = new Array;
	table[m_count]["depositNum"] = depositNum;
	table[m_count]["id"] = deposit[depositNum]['id'];
	table[m_count]["name"] = deposit[depositNum]['name'];					// название депозита
	
	table[m_count]["day"] = Math.round(day*100)/100;						// прибыль за день
	table[m_count]["month"] = Math.round(month*100)/100;					// ежемесяная прибыль
	table[m_count]["period"] = Math.round(period*100)/100;					// за весь период
	
	table[m_count]["percent_year"] = deposit[depositNum]['percent_year'];	// годовая ставка
	table[m_count]["pay_type"] = deposit[depositNum]['pay_type'];			// периодичность выплат
	table[m_count]["type"] = deposit[depositNum]['deposit_type_name'];		// тип депозита
	if(deposit[depositNum]['prolong']==1)
		table[m_count]["prolong"] = "<a onclick=\"prolongation("+m_count+")\" id=\"p_"+m_count+"\">"+m_titles[m_lang]["prolong"]+"</a>"; // пролонгация
	else
		table[m_count]["prolong"] = "---";
	m_count++;	
}

function showTable()
{
	$("#tablebody").html("");
    for(var i in table)
    {
		parity = "";
		column = "";
		row = "";
		if((i % 2) == 0) parity = "even";
		else parity = "odd";
		column += "<td>" + table[i]["name"] + "</td>";
		column += "<td>" + table[i]["day"] + "</td>";
		column += "<td>" + table[i]["month"] + "</td>";
		column += "<td>" + table[i]["period"] + "</td>";
		column += "<td>" + table[i]["percent_year"] + "</td>";	
		column += "<td>" + table[i]["pay_type"] + "</td>";
		column += "<td>" + table[i]["type"] + "</td>";
		column += "<td>" + table[i]["prolong"] + "</td>";
		
		row = "<tr id=\"row_"+i+"\" class=\""+parity+"\">" + column + "</tr>";	
		
		m_table_content = $("#tablebody").html();
		m_table_content += row;
		$("#tablebody").html(m_table_content);	
	}
	m_bclearTable = false;
}

function prolongation(num)
{	
	$("#dialog-modal").dialog({
		height: 120,
		width: 400,		
		modal: true,
		draggable: false,
		resizable: false
	});
	id = table[num]["id"];
	snum = "";
	headTable = "<tr>";
	bodyTable = "<tr>";
	for(i = 0; i < prolong[id][m_currency]["months"].length; i++)
	{
		percent = prolong[table[num]["id"]][m_currency][prolong[id][m_currency]["months"][i]];
		if(m_lang == "en")
		{
			if(prolong[id][m_currency]["months"][i] == 1) snum = "st";
			if(prolong[id][m_currency]["months"][i] == 2) snum = "nd";
			if(prolong[id][m_currency]["months"][i] == 3) snum = "rd";
			if(prolong[id][m_currency]["months"][i] >= 4) snum = "th";
			headTable += "<td>"+prolong[id][m_currency]["months"][i] + snum + m_titles[m_lang]["month"]+"</td>";
		}
		else
			headTable += "<td>"+prolong[id][m_currency]["months"][i]+m_titles[m_lang]["month"]+"</td>";
		bodyTable += "<td>"+percent+"</td>";
	}
	headTable += "</tr>";
	bodyTable += "</tr>";	
	$("#dialog-modal").html("<center><table class=\"calc_results\">"+headTable+bodyTable+"</table></center>");	
	//m_prolongIndex = num;
}

function clearTable()
{
	if(!m_bclearTable)
	{	
		table = [];
		rows = "";
		for(i=0; i<=8; i++)
		{
			rows += "<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>";
		}
		$("#tablebody").html(rows);
		m_bclearTable = true;
	}		
}



function send_message2() 
{
	var bValid = true;

	var name = $("#name2").val(),telephone = $("#telephone2").val(), 
		city = $("#city2").val();
	var allFields = $([]).add($("#name2")).add($("#telephone2")).add($("#city2")).add($("#deposit2").parent("td"));

	allFields.removeClass('ui-state-error');
		
	if(city == 1) city = "Киев";
	else if(city == 2) city = "Донецк";
	else if(city == 3) city = "Малиновка";
	
	var	deposit =  $('#deposit2').attr('checked')?1:0;
	var	card =  $('#card2').attr('checked')?1:0;
	var	account =  $('#account2').attr('checked')?1:0;
	var	safe =  $('#safe2').attr('checked')?1:0;
	var	other =  $('#other2').attr('checked')?1:0;

	var uslugi = "";
	if(deposit==1) uslugi += " 'Депозит'";
	if(card==1) uslugi += " 'Платежная карта'";
	if(account==1) uslugi += " 'Открытие текущего счета'";
	if(safe==1) uslugi += " 'Индивидуальные сейфы'";
	if(other==1) uslugi += " 'Другое'";
	
	// проверка на заполнение полей
//	bValid = bValid && checkLength($("#family"),"Фамилия",1,1);
	bValid = bValid && checkLength($("#name2"),"Имя",1,100);
//	bValid = bValid && checkLength($("#otchestvo"),"Отчество",1,1);
	bValid = bValid && checkLength($("#telephone2"),"Телефон",1,200);
//	bValid = bValid && checkLength($("#email"),"Email",1,1);
	if(uslugi=="" && bValid)
	{
		updateTips("Поле 'Какой продукт или услуга Вас интересует' не заполнено.");
		bValid = false;
		//$(":checkbox").addClass('ui-state-error');
		$("#deposit").parent("td").addClass('ui-state-error');
	}
	bValid = bValid && checkSelect($("#city2"),"Город",0);
	$("#res_message2").show(); 
	
//	bValid = bValid && checkLength($("#mesto"),"удобное место и время встречи",1,1);

	//bValid = bValid && checkLength($("#mesto"),"Имя",3,16);
	/*if(bValid)
	{
			
			$.post("/mobilnyj_bankir.php", {family: family, name: name, otchestvo: otchestvo, telephone: telephone, email: email, city: city, mesto: mesto, uslugi: uslugi, lang: "ru"},
		        
			function(rezdata)
			{
				$(".inp_bg4").slideToggle(500);
				//$("#bankir-table").slideToggle(500);
				$("#res_message2").show();            
			});		
	}*/
}

$(document).ready(function(){	
	$("#res_message2").hide();	
});


