
/* Browser Window Size and Position */
function pageWidth() { 
  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

function pageHeight() {
  return window.innerHeight != null ? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null;
}

function posLeft() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

function posTop() {
  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

function posRight() {
  return posLeft() + pageWidth();
}

function posBottom() {
  return posTop() + pageHeight();
}

/* Mouse Position */
function getNsMouseXY(e) {
  if (document.getElementById && !document.all) {
    nsmousepos.pageX = e.pageX;
    nsmousepos.pageY = e.pageY;
    nsmousepos.clientX = e.clientX;
    nsmousepos.clientY = e.clientY; 
  }
}

function ietruebody() {
  return (document.compatMode && document.compatMode != 'BackCompat') ? document.documentElement : document.body;
}

function getMouseX() {
  return (document.getElementById && ! document.all) ? nsmousepos.pageX : event.x + ietruebody().scrollLeft;
}

function getMouseY() {
  return (document.getElementById && ! document.all) ? nsmousepos.pageY : event.y + ietruebody().scrollTop;
}

/* Show alexa preview */
function showPic( item_url ) {
  var picMouseMarginX = 20;
  var picMouseMarginY = 40;

  var myDiv = document.getElementById( 'divPic' );

  var x = getMouseX() + picMouseMarginX;
  var y = getMouseY() - picMouseMarginY;

  if ( myDiv.style.visibility == 'hidden' ) {
    myDiv.style.visibility = 'visible';
    myDiv.innerHTML = '<img src="http://pthumbnails.alexa.com/image_server.cgi?size=big&amp;url='+item_url+'">';
  }

  y = ( y < 0 ) ? 0 : y;
  myDiv.style.top  = y + 'px';
  myDiv.style.left = x + 'px';
}

/* Show rate banner */
function showBan( item_id ) {
  var rateBannerWidth = 130;
  var rateBannerHeight = 150;
  var rateBannerMouseMarginX = 20;
  var rateBannerMouseMarginY = 40;
  var x = 0;
  var y = 0;
  
  var myDiv = document.getElementById( 'divPic' );
  
  var mouseX = getMouseX();
  var maxPosRight = mouseX + rateBannerWidth + rateBannerMouseMarginX;
  if ( maxPosRight > posRight() ) {
    x = mouseX - rateBannerWidth - rateBannerMouseMarginX;
  } else {
    x = mouseX + rateBannerMouseMarginX;
  }
  
  var mouseY = getMouseY();
  var maxPosTop = mouseY - rateBannerMouseMarginY;
  var maxPosBottom = mouseY + rateBannerHeight - rateBannerMouseMarginY;
  if ( maxPosTop < posTop() ) {
    y = posTop() + 2;
  } else if ( maxPosBottom > posBottom() ) {
    y = posBottom() - rateBannerHeight - 2;
  } else {
    y = mouseY - rateBannerMouseMarginY;
  }
  
  if ( myDiv.style.visibility == 'hidden' ) {
    myDiv.style.visibility = 'visible';
    var timestamp =  new Date().getTime();
    myDiv.innerHTML = '<img src="index.php?a=image&lid='+item_id+'">';
  }

  y = ( y < 0 ) ? 0 : y;
  myDiv.style.top  = y + 'px';
  myDiv.style.left = x + 'px';
}

/* Hide image */
function hideImg() {
  var myDiv = document.getElementById( 'divPic' );
  myDiv.style.visibility = 'hidden';
  myDiv.innerHTML = '';
}

/* Start global section */
if (document.getElementById && !document.all) {
  var nsmousepos = new Object();
  nsmousepos.pageX = 0;
  nsmousepos.pageY = 0;
  nsmousepos.clientX = 0;
  nsmousepos.clientY = 0;
}

document.onmousemove = getNsMouseXY;

var tips;
// Функции для валидации значений в формах
function updateTips( t ) 
{
	tips
		.text( t )
		.addClass( "ui-state-highlight" );
	setTimeout(function() 
	{
		tips.removeClass( "ui-state-highlight", 1500 );
	}, 800 );
}

function checkLength( o, n, min, max ) 
{
	if ( o.val().length > max || o.val().length < min ) 
	{
		o.addClass( "ui-state-error" );
		updateTips( "Length of " + n + " must be between " +
			min + " and " + max + "." );
		return false;
	} 
	else 
	{
		return true;
	}
}

function checkNoEmpty( o, t )
{
	if ( o.val().length == 0)
	{
		o.addClass( "ui-state-error" );
		updateTips( t );
		return false;
	}
	else return true;
}

function checkEqual( o, o2, t ) 
{
	if ( o.val() != o2.val()) 
	{
		o.addClass( "ui-state-error" );
		o2.addClass( "ui-state-error" );
		updateTips( t );
		return false;
	} 
	else 
	{
		return true;
	}
}

function checkRegexp( o, regexp, n ) 
{
	if ( !( regexp.test( o.val() ) ) ) 
	{
		o.addClass( "ui-state-error" );
		updateTips( n );
		return false;
	} 
	else 
	{
		return true;
	}
}

// UTF-8 encode / decode by Johan Sundstr?m
function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}


function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}

var dlgEditUser, dlgPayoutsForm, dlgShowHistory, dlgSendLetters;

function setShowHistory()
{
	dlgShowHistory = $("<div id=\"formShowHistory\" addParam=\"\"></div>")
		.html("<div id=\"userHistory\"></div>")
		.dialog({
			autoOpen: false,
			resizable: false,
			modal: true,
			width: 650,
			height: 445,
			title: "-= Balance History =-",
			open: function()
			{
				$( "#userHistory" ).html("<div align=\"center\"><img src=\"../images/ajax-loader.gif\"></div>").show();
				var curUserId = $("#formShowHistory").attr("addParam");
				var formData =	{	id : curUserId	};
				$( "#userHistory" ).load("../inc/ajaxFunc2.php", {func:"getBalanceHistoryForUser", formData:""+jQuery.param(formData)});
			},
			buttons:{	"Close" : function(){ $(this).dialog("close"); } }
		});
}

function showBalanceHistory(curId, curLogin)
{
	if (dlgShowHistory == undefined) setShowHistory();
	$( "#formShowHistory" ).attr("addParam", curId);
	if (curId == "0")
	{
		dlgShowHistory.dialog("option", "title", "-= Balance History for All Users =-");
		dlgShowHistory.dialog("option", "height", 450);
	}
	else
	{
		dlgShowHistory.dialog("option", "title", "-= Balance History for user " + curLogin + " =-");
		dlgShowHistory.dialog("option", "height", 350);
	}
	dlgShowHistory.dialog("open");
}

function loadNextHistoryRecords(btnId)
{
	var fromRec = 0, countRec = 0;
	fromRec = $("#"+btnId).attr("from");
	countRec = $("#"+btnId).attr("count");
	var formData =	{	from : fromRec,
										count : countRec
									};
	jQuery("#showNextRecordsProgress").html("<img src=\"../images/ajax-loader.gif\">");
	jQuery.post("../inc/ajaxFunc2.php", {func:"getBalanceHistoryNextForUser", formData:""+jQuery.param(formData)}, function(data)
	{
		jQuery("#showNextRecordsProgress").html("");
		$( "#tableUsersHistory tbody" ).append(data);
	});
}

function setSendLetters()
{
	var htmlForDlg;
	htmlForDlg = "<style>";
	htmlForDlg += ".ui-dialog .ui-state-error { padding: .3em; }";
	htmlForDlg += ".validateTips { border: 1px solid transparent; padding: 0.3em; }";
	htmlForDlg += "</style>";
	htmlForDlg += "<p class=\"validateTips\" style=\"text-indent: 0px;\"></p>";
	htmlForDlg += "<div id=\"sendLettersProgress\" align=\"center\"></div><br>";
	htmlForDlg += "<div align=\"center\">";
	htmlForDlg += "<table id=\"sendLettersComplete\" cellpadding=4 cellspacing=0 class=\"servicesT\" style=\"width:100%;text-align:center;\">";
	htmlForDlg += "<tr><td colspan=\"3\" class=\"servHd2\">Complete send notification to ...</td></tr>";
	htmlForDlg += "<tr><td class=\"servHd3\" width=\"15%\">ID</td><td class=\"servHd3\" width=\"35%\">Login</td><td class=\"servHd3\" width=\"50%\" style=\"border-right:0\">E-Mail</td></tr>";
	htmlForDlg += "</table>";
	htmlForDlg += "</div>";
	dlgSendLetters = $("<div id=\"formSendLetters\" addParam1=\"\" addParam2=\"\" addParam3=\"\"></div>")
		.html("<div id=\"sendLetters\"></div>")
		.dialog({
			autoOpen: false,
			resizable: false,
			modal: true,
			width: 500,
			height: 350,
			title: "-= Send Notification to Users =-",
			open: function()
			{
				$( "#sendLetters" ).html(htmlForDlg).show();
				tips = $( ".validateTips" );
				tips.text("Comment for current operation").show();
				$( "#sendLettersProgress" ).progressbar();
				sendMailToUser(0);
			},
			close: function()
			{
				window.location.reload();
			},
			buttons:{	"Close" : function(){ $(this).dialog("close"); } }
		});
}

function sendMailToUser(curUserNum)
{
	var countUsers = parseInt($( "#formSendLetters" ).attr("addParam1"));
	var curData = $( "#formSendLetters" ).attr("addParam2");
	var curComment = $( "#formSendLetters" ).attr("addParam3");
	var tmpArr = curData.split("<#>");
	var curUser, formData, valForProgress, strForTips, strForTable;
	if (curUserNum < countUsers)
	{
		valForProgress = Math.round((curUserNum+1) * 100 / countUsers);
		strForTips = ""; strForTable = "";
		$( "#sendLettersProgress" ).progressbar("value",valForProgress);
		curUser = tmpArr[curUserNum].split("<;>");
		if (curUser[0] != "" && curUser[0] != undefined && curUser[1] != "" && curUser[1] != undefined && curUser[2] != "" && curUser[2] != undefined)
		{
			strForTips = "Send notification to " + curUser[1] + " [" + curUser[2] + "]";
			updateTips(strForTips);
			formData =	{	id : curUser[0],
										login : curUser[1],
										email	: curUser[2],
										amount	: curUser[3],
										comment : curComment
									};
			jQuery.post("../inc/ajaxFunc2.php", {func:"sendLetter", formData:""+jQuery.param(formData)}, function(data)
			{
				strForTable = "<tr><td class=\"list\">" + curUser[0] + "</td><td class=\"list\">" + curUser[1] + "</td><td class=\"list\">" + curUser[2] + "</td></tr>";
				$( "#sendLettersComplete tbody tr:eq(1)" ).after( strForTable ); 
				sendMailToUser(++curUserNum);
			});
		}
		else sendMailToUser(++curUserNum);
	}
	else
	{
		updateTips("Send notifiation complete. Close this dialog, please.");
	}
}

function sendLetters(count, str, comment)
{
	if (dlgSendLetters == undefined) setSendLetters();
	$( "#formSendLetters" ).attr("addParam1", count);
	$( "#formSendLetters" ).attr("addParam2", str);
	$( "#formSendLetters" ).attr("addParam3", comment);
	dlgSendLetters.dialog("open");
}

function setEditUserForm()
{
	var userLogin, userEmail, userAvatar, userLr, userPm, userAp, userAmount, allFields, formChange;
	formChange = "<style>";
	formChange += ".ui-dialog .ui-state-error { padding: .3em; }";
	formChange += ".validateTips { border: 1px solid transparent; padding: 0.3em; }";
	formChange += "</style>";
	formChange += "<div id=\"ajaxImg4\"><div align=\"center\"><img src=\"../images/ajax-loader.gif\"></div></div>";
	formChange += "<p class=\"validateTips\" style=\"text-indent: 0px;\"></p>";
	formChange += "<form onsubmit=\"return false;\"><fieldset style=\"padding:0; border:0; margin-top:15px;\"><table width=\"100%\">";
	formChange += "<tr><td width=\"25%\"><label for=\"userLoginC\">Login</label></td>";
	formChange += "<td colspan=\"2\" width=\"75%\"><input type=\"text\" name=\"userLoginC\" id=\"userLoginC\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "<tr><td><label for=\"userEmailC\">E-Mail</label></td>";
	formChange += "<td colspan=\"2\"><input type=\"text\" name=\"userEmailC\" id=\"userEmailC\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "<tr><td><label for=\"userAvatarC\">Avatar</label></td>";
	formChange += "<td colspan=\"2\"><input type=\"text\" name=\"userAvatarC\" id=\"userAvatarC\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "<tr><td colspan=\"3\" height=\"10px\"></td></tr>";
	formChange += "<tr><td colspan=\"2\" width=\"50%\"><label for=\"userLrC\">Liberty Reserve</label></td>";
	formChange += "<td><input type=\"text\" name=\"userLrC\" id=\"userLrC\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "<tr><td colspan=\"2\" width=\"50%\"><label for=\"userPmC\">Perfect Money</label></td>";
	formChange += "<td><input type=\"text\" name=\"userPmC\" id=\"userPmC\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "<tr><td><label for=\"userApC\">Alert Pay</label></td>";
	formChange += "<td colspan=\"2\"><input type=\"text\" name=\"userApC\" id=\"userApC\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "<tr><td colspan=\"3\" height=\"10px\"></td></tr>";
	formChange += "<tr><td colspan=\"2\"><label for=\"userAmountC\">Balance Amount</label></td>";
	formChange += "<td><input type=\"text\" name=\"userAmountC\" id=\"userAmountC\" style=\"width:100%; text-align:right; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	formChange += "</table></fieldset></form>";
	
	dlgEditUser = $("<div id=\"formChangeDlgA\" addParam=\"\"></div>")
		.html(formChange)
		.dialog({
			autoOpen: false,
			resizable: false,
			modal: true,
			width: 300,
			title: "-= Edit User Info =-",
			open: function()
			{
				userLogin = $( "#userLoginC" );
				userEmail = $( "#userEmailC" );
				userAvatar = $( "#userAvatarC" );
				userLr = $( "#userLrC" );
				userPm = $( "#userPmC" );
				userAp = $( "#userApC" );
				userAmount = $( "#userAmountC" );
				allFields = $( [] ).add( userLogin ).add( userEmail ).add( userAvatar ).add( userLr ).add( userPm ).add( userAp ).add( userAmount );
				tips = $( ".validateTips" );
				$("#ajaxImg4").hide();
				tips.show();
				tips.text("Edit User info and press 'Ok'");

				allFields.removeClass( "ui-state-error" );
			},
			buttons:{	
								"Ok" : function()
								{
									var bValid = true;
									allFields.removeClass( "ui-state-error" );
									
									bValid = bValid && checkLength( userLogin, "Login", 3, 16 );
									bValid = bValid && checkRegexp( userLogin, /^[a-z]([0-9a-z_])+$/i, "Login may consist of a-z, 0-9, underscores, begin with a letter." );
									bValid = bValid && checkRegexp( userEmail, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Wrong E-Mail" );
									if (userAvatar.val().length > 0) bValid = bValid && checkRegexp( userAvatar, /^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i, "Wrong URL for avatar" );
									if (userLr.val().length > 0) bValid = bValid && checkRegexp( userLr, /^[a-z]{1}([0-9]{7})+$/i, "Wrong Liberty Reserve account number" );
									if (userPm.val().length > 0) bValid = bValid && checkRegexp( userPm, /^[a-z]{1}([0-9]{7})+$/i, "Wrong Perfect Money account number" );
									if (userAp.val().length > 0) bValid = bValid && checkRegexp( userAp, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Wrong Alert Pay account number." );
									// Если число указали через запятую, то заменим её на точку
									userAmount.val(userAmount.val().replace(",","."));
									bValid = bValid && checkRegexp( userAmount, /^\d{0,}[.]{0,}\d{0,4}$/i, "Input correct amount (x.xxxx)" );

									if (bValid)
									{
										var formData =	{	id : $("#formChangeDlgA").attr("addParam"),
																			login : userLogin.val(),
																			email	: userEmail.val(),
																			avatar	: userAvatar.val(),
																			lr	: userLr.val(),
																			pm	: userPm.val(),
																			ap	: userAp.val(),
																			amount	: userAmount.val()
																		};
										tips.hide();
										tips.text("");
										$("#ajaxImg4").show();
										jQuery.post("../inc/ajaxFunc2.php", {func:"editUserInfo", formData:""+jQuery.param(formData)}, function(data)
										{
											$("#ajaxImg4").hide();
											tips.show();
											if (data == "0") updateTips( "Something wrong. Try again, please." );
											else
											{
												dlgEditUser.dialog("close");
												window.location.reload();
											}
										});
									}
								},
								"Cancel" : function(){ $(this).dialog("close"); }
							}
		});
}

function editUserForm(curId, curLogin, curEmail, curAvatar, curLr, curPm, curAp, curAmount)
{
	if (dlgEditUser == undefined) setEditUserForm();
	$( "#userLoginC" ).val(curLogin);
	$( "#userEmailC" ).val(curEmail);
	$( "#userAvatarC" ).val(curAvatar);
	$( "#userLrC" ).val(curLr);
	$( "#userPmC" ).val(curPm);
	$( "#userApC" ).val(curAp);
	$( "#userAmountC" ).val(curAmount);
	$( "#formChangeDlgA" ).attr("addParam", curId);
	dlgEditUser.dialog("open");
}

function setPayoutsForm()
{
	var allFields, form;
	form = "<style>";
	form += ".ui-dialog .ui-state-error { padding: .3em; }";
	form += ".validateTips { border: 1px solid transparent; padding: 0.3em; }";
	form += "</style>";
	form += "<p class=\"validateTips\" style=\"text-indent: 0px;\"></p>";
	form += "<div align=\"center\" id=\"selectedUsers\" style=\"float:right;width:55%\"></div>";
	form += "<form onsubmit=\"return false;\"><fieldset style=\"padding:0; border:0; margin-top:15px;\"><table width=\"100%\">";
	form += "<tr><td width=\"25%\"><label for=\"radio_payoutsTo\">Payout to</label></td>";
	form += "<td colspan=\"2\" align=\"center\"><div id=\"radio_payoutsTo\">";
	form += "<input type=\"radio\" id=\"radio1\" name=\"radio\" /><label for=\"radio1\">All users</label>";
	form += "<input type=\"radio\" id=\"radio2\" name=\"radio\" /><label for=\"radio2\">Selected users</label>";
	form += "</div></td></tr>";
	form += "<tr><td colspan=\"2\" width=\"70%\"><input type=\"checkbox\" id=\"checkbox1\" name=\"checkbox1\" /><label for=\"checkbox1\">Users with balance more than</label></td>";
	form += "<td><input type=\"text\" name=\"moreThanAmount\" id=\"moreThanAmount\" style=\"width:90%; text-align:right; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	form += "<tr><td colspan=\"2\" width=\"70%\"><input type=\"checkbox\" id=\"checkbox2\" name=\"checkbox2\" /><label for=\"checkbox2\">Users with balance less than</label></td>";
	form += "<td><input type=\"text\" name=\"lessThanAmount\" id=\"lessThanAmount\" style=\"width:90%; text-align:right; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	form += "<tr><td width=\"25%\"><input type=\"checkbox\" id=\"checkbox3\" name=\"checkbox3\" /><label for=\"checkbox3\">Project</label></td>";
	form += "<td colspan=\"2\"><select id=\"project\" name=\"project\" style=\"width:96%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\"><option disabled selected>-= Loading ... =-</option></select></td></tr>";
	form += "<tr><td colspan=\"2\" width=\"70%\"><input type=\"radio\" id=\"radio11\" name=\"radio_2\" /><label for=\"radio11\">Payout by sum ($)</label></td>";
	form += "<td><input type=\"text\" name=\"payoutAmount\" id=\"payoutAmount\" style=\"width:90%; text-align:right; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	form += "<tr><td>&nbsp;</td><td colspan=\"2\"><input type=\"radio\" id=\"radio21\" name=\"radio_3\" /><label for=\"radio21\">Add this sum to users</label></td></tr>";
	form += "<tr><td>&nbsp;</td><td colspan=\"2\"><input type=\"radio\" id=\"radio22\" name=\"radio_3\" /><label for=\"radio22\">Divide this sum equal parts</label></td></tr>";
	form += "<tr><td>&nbsp;</td><td colspan=\"2\"><input type=\"radio\" id=\"radio23\" name=\"radio_3\" /><label for=\"radio23\">Divide this sum proportionally</label></td></tr>";
	form += "<tr><td colspan=\"2\" width=\"70%\"><input type=\"radio\" id=\"radio12\" name=\"radio_2\" /><label for=\"radio12\">Payout by percent (%)</label></td>";
	form += "<td><input type=\"text\" name=\"payoutPercent\" id=\"payoutPercent\" style=\"width:90%; text-align:right; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td></tr>";
	form += "<tr><td colspan=\"3\"><button id=\"reCalcBtn\" style=\"width:97%\">Calculate and show result in table</button></td></tr>";
	form += "</table></fieldset>";
	form += "<table width=\"100%\"><tr><td width=\"12%\"><label for=\"comment\">Comment</label></td>";
	form += "<td width=\"88%\"><input type=\"text\" name=\"comment\" id=\"comment\" style=\"width:100%; padding: .2em;\" class=\"text ui-widget-content ui-corner-all\" /></td>";
	form += "</tr></table>";
	form += "</form>";
	
	// Функция проверки корректности значений в диалоге
	function checkDlgCorrect()
	{
		// Уберем класс ошибок
		$("#moreThanAmount").removeClass( "ui-state-error" );
		$("#lessThanAmount").removeClass( "ui-state-error" );
		$("#project").removeClass( "ui-state-error" );
		$("#payoutAmount").removeClass( "ui-state-error" );
		$("#payoutPercent").removeClass( "ui-state-error" );
		$( ".validateTips" ).text("Select users, Select payout type, Check calculated sum in table, Press 'Ok'");
		bValid = true;
		// Если число указали через запятую, то заменим её на точку
		$("#moreThanAmount").val($("#moreThanAmount").val().replace(",","."));
		$("#lessThanAmount").val($("#lessThanAmount").val().replace(",","."));
		$("#payoutAmount").val($("#payoutAmount").val().replace(",","."));
		// Проверки на правильность введенных значений
		if ($("#radio2:checked").length)
		{
			if ($("#checkbox1:checked").length) bValid = bValid && checkRegexp( $("#moreThanAmount"), /^\d{0,}[.]{0,}\d{0,4}$/i, "Input correct amount (x.xxxx)" );
			if ($("#checkbox2:checked").length) bValid = bValid && checkRegexp( $("#lessThanAmount"), /^\d{0,}[.]{0,}\d{0,4}$/i, "Input correct amount (x.xxxx)" );
			if ($("#checkbox3:checked").length && $("#project").val() == 0)
			{
				bValid = false;
				$("#project").addClass( "ui-state-error" );
				updateTips( "Select some project from a list." );
			}
			if (!$("#checkbox1:checked").length && !$("#checkbox2:checked").length && !$("#checkbox3:checked").length && !$("div#selectedUsers input:checkbox:checked").length)
			{
				bValid = false;
				updateTips( "You are check 'Selected users', but don't check any options or users." );
			}
		}
		if ($("#radio11:checked").length) bValid = bValid && checkRegexp( $("#payoutAmount"), /^\d{0,}[.]{0,}\d{0,4}$/i, "Input correct amount (x.xxxx)" );
		if ($("#radio12:checked").length) bValid = bValid && checkRegexp( $("#payoutPercent"), /^\d{0,3}$/i, "Input correct percent value (xxx)" );
		
		if (bValid) return true;
		else return false;
	}
	// Описываем сам диалог
	dlgPayoutsForm = $("<div id=\"formAddPayouts\"></div>")
		.html(form)
		.dialog({
			autoOpen: false,
			resizable: false,
			modal: true,
			width: 650,
			title: "-= Additional Bonus Payouts =-",
			open: function()
			{
				allFields = $( [] ).add( $( "#payoutAmount" ) ).add( $( "#payoutPercent" ) ).add( $( "#moreThanAmount" ) ).add( $( "#lessThanAmount" ) ).add( $( "#project" ) );
				tips = $( ".validateTips" );
				$("#radio1").attr("checked","checked");
				$("#radio11").attr("checked","checked");
				$("#radio21").attr("checked","checked");
				$("#payoutPercent").attr("disabled","disabled");
				tips.show();
				tips.text("Select users, Select payout type, Check calculated sum in table, Press 'Ok'");
				$("#selectedUsers").html("<img src=\"../images/ajax-loader.gif\">").show();
				$("#selectedUsers").load("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""});
				$("#project").html("<option disabled selected>-= Loading ... =-</option>").show();
				$("#project").load("../inc/ajaxFunc2.php", {func:"loadProjectForSel", formData:""});

				allFields.removeClass( "ui-state-error" );
			},
			buttons:{	
								"Ok" : function()
								{
									// Если все значения правильные - формируем запрос и отсылаем
									if (checkDlgCorrect() && confirm("Do you really want to made payout to this users ? "))
									{
										var checkedRec = "", tmpName;
										$("div#selectedUsers input:checkbox:checked").each(function()
										{
											tmpName = $(this).attr("name");
											if (checkedRec == "") checkedRec += tmpName;
											else checkedRec += ("," + tmpName);
										});
										if (checkedRec == "") checkedRec = 0;
										var data =	{	chSelUsers : $("#radio2:checked").length,
																	chMoreThan : $("#checkbox1:checked").length,
																	moreThanA : $("#moreThanAmount").val(),
																	chLessThan : $("#checkbox2:checked").length,
																	lessThanA : $("#lessThanAmount").val(),
																	chProject : $("#checkbox3:checked").length,
																	iProject : $("#project").val(),
																	chPayBySum : $("#radio11:checked").length,
																	paySumAmount : $("#payoutAmount").val(),
																	chPayFixedSum : $("#radio21:checked").length,
																	chPayDivideEqual : $("#radio22:checked").length,
																	chPayProportionally : $("#radio23:checked").length,
																	chPayByPercent : $("#radio12:checked").length,
																	paySumPercent : $("#payoutPercent").val(),
																	checkedUsers : checkedRec,
																	comment : $("#comment").val()
																};
										tips.html("<div align=\"center\"><img src=\"../images/ajax-loader.gif\"></div>").show();
										jQuery.post("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""+jQuery.param(data), process:"1"}, function(retData)
										{
											if (retData == "1")
											{
												dlgPayoutsForm.dialog("close");
												window.location.reload();
											}
											else if (retData == "0") 
											{
												updateTips( "Something wrong. Try again, please." );
												// Обновляем табличку с пользователями
												$("#selectedUsers").html("<img src=\"../images/ajax-loader.gif\">").show();
												$("#selectedUsers").load("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""+jQuery.param(data)});
											}
											else if (retData == "-1")
											{
												updateTips( "You are don't select any user for this payout." );
												// Обновляем табличку с пользователями
												$("#selectedUsers").html("<img src=\"../images/ajax-loader.gif\">").show();
												$("#selectedUsers").load("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""+jQuery.param(data)});
											}
											else
											{
												var tmpArr = retData.split("<~>");
												var errStr = "";
												if (tmpArr[0] == "" || tmpArr[0] == undefined) tmpArr[0] = "0";
												if (tmpArr[0] == "-2")
												{
													errStr = "Something wrong.";
													if (tmpArr[1] != "" && tmpArr[1] != undefined) errStr += (" " + tmpArr[1]);
													updateTips( errStr );
													// Обновляем табличку с пользователями
													$("#selectedUsers").html("<img src=\"../images/ajax-loader.gif\">").show();
													$("#selectedUsers").load("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""+jQuery.param(data)});
												}
												else if (tmpArr[0] == "1")
												{
													// А это у нас будет правильный ответ. Дальше будем отправлять письма
													dlgPayoutsForm.dialog("close");
													sendLetters(tmpArr[1], tmpArr[2], $("#comment").val());
												}
												else
												{
													errStr = "Something wrong.";
													updateTips( errStr );
													// Обновляем табличку с пользователями
													$("#selectedUsers").html("<img src=\"../images/ajax-loader.gif\">").show();
													$("#selectedUsers").load("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""+jQuery.param(data)});
												}
											}
										});
									}
								},
								"Cancel" : function(){ $(this).dialog("close"); }
							}
		});
		$("#radio_payoutsTo").buttonset();
		$("#reCalcBtn").button();
		// Set control react
		$("#radio1").click(function()
		{
			$("#checkbox1").attr("disabled","disabled"); 
			$("#checkbox2").attr("disabled","disabled"); 
			$("#checkbox3").attr("disabled","disabled"); 
			$("div#selectedUsers input:checkbox").attr("disabled","disabled"); 
			$("#moreThanAmount").attr("disabled","disabled"); 
			$("#lessThanAmount").attr("disabled","disabled"); 
			$("#project").attr("disabled","disabled"); 
		});
		$("#radio2").click(function()
		{
			$("#checkbox1").removeAttr("disabled"); 
			$("#checkbox2").removeAttr("disabled"); 
			$("#checkbox3").removeAttr("disabled"); 
			$("div#selectedUsers input:checkbox").removeAttr("disabled"); 
			if ($("#checkbox1:checked").length) { $("#moreThanAmount").removeAttr("disabled"); $("#moreThanAmount").focus(); }
			else $("#moreThanAmount").attr("disabled","disabled");
			if ($("#checkbox2:checked").length) { $("#lessThanAmount").removeAttr("disabled"); $("#lessThanAmount").focus(); }
			else $("#lessThanAmount").attr("disabled","disabled");
			if ($("#checkbox3:checked").length) { $("#project").removeAttr("disabled"); $("#project").focus(); }
			else $("#project").attr("disabled","disabled");
		});
		$("#checkbox1").click(function()
		{
			if ($("#checkbox1:checked").length) { $("#moreThanAmount").removeAttr("disabled"); $("#moreThanAmount").focus(); }
			else $("#moreThanAmount").attr("disabled","disabled");
		});
		$("#checkbox2").click(function()
		{
			if ($("#checkbox2:checked").length) { $("#lessThanAmount").removeAttr("disabled"); $("#lessThanAmount").focus(); }
			else $("#lessThanAmount").attr("disabled","disabled");
		});
		$("#checkbox3").click(function()
		{
			if ($("#checkbox3:checked").length) { $("#project").removeAttr("disabled"); $("#project").focus(); }
			else $("#project").attr("disabled","disabled");
		});
		$("#radio11").click(function()
		{ 
			$("#payoutAmount").removeAttr("disabled"); 
			$("#payoutAmount").focus(); 
			$("#payoutPercent").attr("disabled","disabled"); 
			$("#radio21").removeAttr("disabled"); 
			$("#radio22").removeAttr("disabled"); 
			$("#radio23").removeAttr("disabled"); 
		});
		$("#radio12").click(function()
		{ 
			$("#payoutPercent").removeAttr("disabled"); 
			$("#payoutPercent").focus(); 
			$("#payoutAmount").attr("disabled","disabled"); 
			$("#radio21").attr("disabled","disabled"); 
			$("#radio22").attr("disabled","disabled"); 
			$("#radio23").attr("disabled","disabled"); 
		});
		$("#reCalcBtn").click(function()
		{
			// Если все значения правильные - формируем запрос и отсылаем
			if (checkDlgCorrect())
			{
				var checkedRec = "", tmpName;
				$("div#selectedUsers input:checkbox:checked").each(function()
				{
					tmpName = $(this).attr("name");
					if (checkedRec == "") checkedRec += tmpName;
					else checkedRec += ("," + tmpName);
				});
				if (checkedRec == "") checkedRec = 0;
				var data =	{	chSelUsers : $("#radio2:checked").length,
											chMoreThan : $("#checkbox1:checked").length,
											moreThanA : $("#moreThanAmount").val(),
											chLessThan : $("#checkbox2:checked").length,
											lessThanA : $("#lessThanAmount").val(),
											chProject : $("#checkbox3:checked").length,
											iProject : $("#project").val(),
											chPayBySum : $("#radio11:checked").length,
											paySumAmount : $("#payoutAmount").val(),
											chPayFixedSum : $("#radio21:checked").length,
											chPayDivideEqual : $("#radio22:checked").length,
											chPayProportionally : $("#radio23:checked").length,
											chPayByPercent : $("#radio12:checked").length,
											paySumPercent : $("#payoutPercent").val(),
											checkedUsers : checkedRec
										};
				// Обновляем табличку с пользователями
				$("#selectedUsers").html("<img src=\"../images/ajax-loader.gif\">").show();
				$("#selectedUsers").load("../inc/ajaxFunc2.php", {func:"showSelectedUsers", formData:""+jQuery.param(data)});
			}
		});
}

function additionalBonusPayoutsForm()
{
	if (dlgPayoutsForm == undefined) setPayoutsForm();
	dlgPayoutsForm.dialog("open");
	$("#radio1").button("refresh");
	$("#payoutAmount").val("0.0000"); 
	$("#moreThanAmount").val("0.0000"); 
	$("#lessThanAmount").val("0.0000"); 
	$("#payoutPercent").val("10"); 
	if ($("#radio1:checked").length)
	{
		$("#checkbox1").attr("disabled","disabled"); 
		$("#checkbox2").attr("disabled","disabled"); 
		$("#checkbox3").attr("disabled","disabled"); 
		$("#moreThanAmount").attr("disabled","disabled"); 
		$("#lessThanAmount").attr("disabled","disabled"); 
		$("#project").attr("disabled","disabled"); 
	}
	if ($("#radio2:checked").length)
	{
		$("#checkbox1").removeAttr("disabled"); 
		$("#checkbox2").removeAttr("disabled"); 
		$("#checkbox3").removeAttr("disabled"); 
	}
}

function togglediv(id) 
{
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == 'none') 
		{
			document.getElementById(id).style.display = 'block';
		} 
		else
		{
			document.getElementById(id).style.display = 'none'
		}
	}
	else 
	{
		if (document.layers) 
		{ // Netscape 4
			if(document.id.display == 'none')
			{
				document.id.display = 'block';
			}
			else
			{
				document.id.display = 'none';
			}
		}
		else 
		{ // IE 4
			if( document.all.id.style.display == 'none')
			{
				document.all.id.style.display = 'block';
			}
			else
			{
				document.all.id.style.display = 'none';
			}
		}
	}
}
