/*
 * Js file for OpenBonus clients
 * kraken icq 757-834
 * 01.02.2011
 * 
 */
 
/* Later!!!
var card_info_popup_dom	 	= false; // card Info popup is not load in DOM
var card_register_popup_dom	= false; // card Register popup is not load in DOM
var card_auth_popup_dom		= false; // card Auth popup is not load in DOM
*/

var load_register_popup = false;
var load_card_info_popup = false;
var load_auth_popup = false;

var card_data = {
					auth : 0,// autch user
					balance : 0,
					bonus : 0,
					last: "",
					hash: ""
				}

$(document).ready(function()
{
	
});

function show_register_popup()
{
	if (!load_register_popup) // not load popup
	{
		$.ajax(
		{
			type: "POST", 
			url: "/openbonus.php", 
			async: false,
			data: {
				'action'	: 'get_popup_html',
				'type'		: 'register_popup',
				'rnd'		: Math.random(100)
			},  
			dataType: "html",
			beforeSend: function(xhr) 
			{
				xhr.setRequestHeader("Cookie", document.cookie);
			},
			success: function(data)
			{       
				//card_data = data;
				$('body').append(data);
				load_register_popup = true;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				
			}
		});
	}
	$("#ob_register_popup").show();
	$("#ob_popup_bg").show();
	
	return false;
}

function hide_register_popup()
{
	$("#ob_register_popup").hide();
    return false;
}

function show_card_info_popup()
{
	
	// no load popup html
	if (!load_card_info_popup)
	{
		$.ajax(
		{
			type: "POST", 
			url: "/openbonus.php", 
			async: false,
			data: {
				'action'	: 'get_popup_html',
				'type'		: 'card_info_popup',
				'rnd'		: Math.random(100)
			},  
			dataType: "html",
			beforeSend: function(xhr) 
			{
				xhr.setRequestHeader("Cookie", document.cookie);
			},
			success: function(data)
			{       
				//card_data = data;
				$('body').append(data);
				load_card_info_popup = true;
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				
			}
		});
	}
	// is not isset auth data info
	if (card_data.auth == 0)
	{
		// get auth info
		card_data = card_stat();
	}
	//alert("card info auth  "+card_data.auth);
	// check autch
	if (card_data.auth == 1) // is auth user
	{
		// insert card info in popup
		$("#ob_card_balance").html(card_data.balance);
		if (card_data.percent != undefined)
			$("#ob_card_percent").html(card_data.percent+"%");
		else
			$("#ob_card_percent").html('5%');
		$("#ob_card_card").html(card_data.card);
		
		if (card_data.date != undefined)
			$("#ob_card_lastdate").html(card_data.date);
		else 
			$("#ob_card_lastdate").html('Неизвестно');
		// show card info popup
		$("#ob_card_info_popup").show();

	}
	else // is not autch
	{
		// show auth popup
		show_auth_popup();
	}
	return false;
}

function hide_card_info_popup()
{
	// hide popup
	$("#ob_card_info_popup").hide();
}

function show_auth_popup()
{
	// no load popup html
	if (!load_auth_popup)
	{
		$.ajax(
		{
			type: "POST", 
			url: "/openbonus.php", 
			async: false,
			data: {
				'action'	: 'get_popup_html',
				'type'		: 'auth_popup',
				'rnd'		: Math.random(100)
			},  
			dataType: "html",
			beforeSend: function(xhr) 
			{
				xhr.setRequestHeader("Cookie", document.cookie);
			},
			success: function(data)
			{       
				//card_data = data;
				$('body').append(data);
				load_auth_popup = true;
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				
			}
		});
	}
	// show popup
    $("#ob_auth_popup").show();
	$("#ob_popup_bg").show();
    return false;
}

function hide_auth_popup()
{
	// hide popup
    $("#ob_auth_popup").hide();
    return false;
}

/*
 * Return Type:JSON [balance ... ]
 */
function card_stat()
{
	// request to openbouns for get card info 
	$.ajax(
	{
		type: "POST", 
		url: "/openbonus.php", 
		async: false,
		data: {
			'action'	: 'card_stat', 
			'hash'		: card_data.hash,
			'rnd'		: Math.random(100)
		},  
		dataType: "json",
		beforeSend: function(xhr) 
		{
			xhr.setRequestHeader("Cookie", document.cookie);
		},
		success: function(data)
		{       
			card_data = data;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			
		}
	});
	//alert(card_data.auth);
	return card_data;
}

// check registr form inputs 
// output: true OR false
function check_register_card_form_inputs()
{
	// check all inputs is NULL
	var error = 0;
	$('.Error').empty();
	// phone
	phone = $('#ob_phone').val();
	if ($('#ob_phone').val() == '') 
	{
		error = 1;
		$('#ob_phone').parents('.Field').find('.Error').empty();
		$('#ob_phone').parents('.Field').find('.Error').append("Введите номер мобильного телефона");
	}
	// name
	if ($('#ob_surname').val() == '') 
	{
		error = 1;
		$('#ob_surname').parents('.Field').find('.Error').empty();
		$('#ob_surname').parents('.Field').find('.Error').append("Введите фамилию");
	}
	// surname
	if ($('#ob_name').val() == '') 
	{
		error = 1;
		$('#ob_name').parents('.Field').find('.Error').empty();
		$('#ob_name').parents('.Field').find('.Error').append("Введите имя");
	}
	// patronymic
	if ($('#ob_patronymic').val() == '') 
	{
		error = 1;
		$('#ob_patronymic').parents('.Field').find('.Error').empty();
		$('#ob_patronymic').parents('.Field').find('.Error').append("Введите отчество");
	}
	// birthday
	if ($('#ob_birthday').val() == '') 
	{
		error = 1;
		$('#ob_birthday').parents('.Field').find('.Error').empty();
		$('#ob_birthday').parents('.Field').find('.Error').append("Введите дату рождения");
	}
	if(!$('#AgreeWith').is(':checked'))
	{
		error = 2;
	}
	return error;
}

// action on click get_new_card
function new_card()
{
	var error = check_register_card_form_inputs();
	if (error == 2)
	{
		alert('Вы должны согласиться с условиями договора');
		return false;
	}
	else if (error >= 1)
	{
		alert('Все поля обязательны для заполнения. Исправьте ошибки и попробуйте еще раз');
		return false;
	}
	else
	{
		//alert('Go-->>');
		// request to openbouns for register new card
		$.ajax(
		{
			type: "POST", 
			url: "/openbonus.php", 
			async: false,
			data: {
				'action'	:	'new_card', 
				'ob_name'	:	$('#ob_name').val(),
				'ob_surname':	$('#ob_surname').val(),
				'ob_phone'	:	$('#ob_phone').val(),
				'ob_birthday':	$('#ob_birthday').val(),
				'ob_patronymic': $('#ob_patronymic').val(),
				'rnd'		: Math.random(100)
			},  
			dataType: "json",
			beforeSend: function(xhr) 
			{
				xhr.setRequestHeader("Cookie", document.cookie);
			},
			success: function(data)
			{       
				// register success == true
				if (data.success == 1)
				{
					//alert('карта успешно зарегистрирована');
					// hide register popup
					hide_register_popup();
					// show card_info popup
					show_card_info_popup();
				}
				else if (data.success == 2)
				{
					//alert('карта была уже зарегистрирована');
					// hide register popup
					hide_register_popup();
					// show card_info popup
					show_card_info_popup();
				}
				else 
				{
					alert(' Системная ошибка  #376');
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				
			}
		});
		
	}
}

function send_key_to_phone()
{
	if ($('#ob_key_phone').val() == '89171234567' || $('#ob_key_phone').val() == '')
	{
		alert('Введите номер мобильного телефона');
	}
	else
	{
		
		$.ajax(
		{
			type: "POST", 
			url: "/openbonus.php", 
			data: {
				'action': 'send_secret_key', 
				'ob_phone':$('#ob_key_phone').val(),
				'rnd': Math.random(100)
			},
			dataType: "json",
			beforeSend: function(xhr) 
			{
				xhr.setRequestHeader("Cookie", document.cookie);
			},
			success: function(data)
			{       
				// ok
				if (data.success == 1)
				{
					$('.ob_info').append('Код успешно отправлен на ваш телефон');
				}
				// no card for this phone
				else if (data.success == 2)
				{
					$('.ob_info').append('На данный номер телефона не зарегистрирвана ни одна карта');
				}
				// other error
				else
				{
					$('.ob_info').append('Произошла системная ошибка. Пожалуйста обратитесь к оператору');
				}
				
				//$("#card_form").append(data);

				//window.location.reload();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				
			}
		});
		alert('Пароль вылан на ваш мобильный');
	}
	return false;
}

function auth()
{
	var save_pass = 0;
	if($('#savePass').is(':checked')) save_pass = 1;
	
	$.ajax(
	{
		type: "POST", 
		url: "/openbonus.php", 
		data: {
			'action': 'auth', 
			'ob_phone':$('#ob_key_phone').val(),
			'ob_key':$('#ob_key').val(),
			'save_pass': save_pass,
			'rnd': Math.random(100)
		},
		dataType: "json",
		beforeSend: function(xhr) 
		{
			xhr.setRequestHeader("Cookie", document.cookie);
		},
		success: function(data)
		{       
			// ok
			if (data.success == 1)
			{
				// this is to reloar card info
				if (data.hash != undefined)
				{
					card_data.hash = data.hash;
				}
				hide_auth_popup();
				card_data = card_stat();
				// show card info popup
				show_card_info_popup();
				//$('.ob_info').append('Код ве');
			}
			// no card for this phone
			else if (data.success == 2)
			{
				alert('Вы ввели неверный пароль. Попробуйте еще раз');
			}
			// other error
			else
			{
				//alert('good');
				//$('.ob_info').append('системная ошибка. пожалуйста обратитсесь к админу');
			}
			
			//$("#card_form").append(data);

			//window.location.reload();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			
		}
	});
	return false;
}

function auth_to_reg()
{
	hide_auth_popup();
	show_register_popup();
	return false;
}

function delete_cookie(cookie_name)
{
	var cookie_date = new Date (); 
	cookie_date.setTime (cookie_date.getTime() - 1);
	document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function logout()
{
	$('#ob_key_phone').val('');
	$('#ob_key').val('');
	$("savePass").removeAttr("checked");
	delete_cookie("bonus_hash");
	card_data.auth = 0;
	hide_card_info_popup();
	show_auth_popup();
	return false;
}


