
// auto completer methods

function add_entry(token){
	new Request({method: 'POST',
		url: '/add_entry/',
		data: 'q='+escape(token),
		onSuccess: function(txt){
		if (txt) {}
		}
	}).send();
}

function delete_entry(token) {
	autocomp.choiceSelect(null);
	new Request({
		method: 'POST',
		url: '/delete_entry/',
		data: 'q='+escape(token),
		onComplete: function(txt) {
			$('numberBox').value = tmp_value;
			xmppClient.deleteFromRoster(token, function() {autocomp.prefetch();});
		}
	}).send();
}

function display_balance(new_balance){
	Cookie.write("balance", new_balance, {duration: 30});
	$('balanceHolder').innerHTML = new_balance+" "+gettext("rur");
}

function check_balance(){
	new Request({method: 'GET',
				url: '/balance/',
				onSuccess: function(txt){
				if (txt) {
					balance=new Number(txt);
					display_balance(balance.toFixed(2));
				}
			}
	}).send();
}

function onSampleClick(e){
	$('numberBox').value = e.innerHTML;
	autocomp.prefetch();
}

function send_feedback(){
	$('feedback_button').disabled=true;
	var email = '';
	var FeedBackEmail=$('FeedBackEmail');
	if (FeedBackEmail) 
		email=FeedBackEmail.value;
    var needDebug = true; //$('SendDebug').checked;
    var debugInfo = "";

	var msgstr = 'msg='+escape($('FeedBackTextArea').value)+'&email='+escape(email);

    if (needDebug) {
		try {
			var log = softPhone.getLog();
			if (log)
				debugInfo = log;
		} catch (err) {
			debugInfo = 'softphone is not installed';
		}
		var msgstr=msgstr+'&debuginfo='+encodeURIComponent(debugInfo);
    }

	new Request({method: 'POST',
				url: '/feedback/',
				encoding: 'utf-8',
				data: msgstr,
				onSuccess: function(txt){
				if (txt) {
					$('FeedBackTextArea').value='';
					feedbackPanel.toggle();
					$('feedback_button').disabled=false;
				}
			},
				onFailure: function() {
				$('feedback_button').disabled=false;
			}
	}).send();
}

function npay(){
	var amount = $('amountBox').value;
	amount = amount.replace(/,/g,'.');
	if ($('radio_wm').checked) {
		wm_pay(amount);
	} else
		if ($('radio_sbrf').checked) {
			$('sbrf_amount').value=amount;
			$('sbrf_form').submit();
		} else 
			if ($('radio_rk').checked) {
				rk_pay(amount);
			} else
				if ($('radio_qiwi').checked) {
					isruphone(amount);
				} else
					if ($('radio_paypal').checked) {
						paypal_pay(amount);
					}
}

function isruphone(amount){
	new Request({method: 'GET',
				url: '/isruphone/',
				onSuccess: function(txt){
				if (txt=='1') {
					qiwi_pay(amount);
				} else {
					var myFx = new Fx.Tween($('qiwi_comment'), {'duration':'1000'});
					myFx.start('color','#FF0000','#666666');
				}
			}}).send();
}

function qiwi_pay(amount){
	$('payment_submit').disabled=true;
	new Request({method: 'POST',
				url: '/qiwi_pay/',
				data: 'amount='+amount,
				onSuccess: function(txt){
				if (txt) {
					var response = txt.split("|");
                    var inv = response[0];
                    var amount = response[1];
					paymentPanel.toggle();
					alert(gettext("qiwi_order_complete"));
				} else {
					alert(gettext("qiwi_order_error"));
					$('payment_submit').disabled=false;
				}
			},
				onFailure: function() {
				$('payment_submit').disabled=false;
			},
				onComplete: function() {
				$('payment_submit').disabled=false;
			}
			
	}).send();
}

function wm_pay(amount){
	$('payment_submit').disabled=true;
	new Request({method: 'POST',
				url: '/wm_pay/',
				data: 'amount='+amount,
				onSuccess: function(txt){
				if (txt) {
					var form = $('wm_form');
                    $('lmi_amount').value=amount;
                    $('lmi_id').value = txt;
					form.submit();
				}
			},
				onFailure: function() {
				$('payment_submit').disabled=false;
			}
	}).send();
}

function paypal_pay(amount){
	$('payment_submit').disabled=true;
	new Request({method: 'POST',
				url: '/paypal_pay/',
				data: 'amount='+amount,
				onSuccess: function(txt){
				if (txt) {
					var response = txt.split("|");
					var form = $('paypal_form');
					$('id_invoice').value = response[0];
					$('id_amount').value = response[1];					
					form.submit();
				}				
			},
				onFailure: function() {
				$('payment_submit').disabled=false;
			}
	}).send();
}

function moneybookers_pay(amount){
	if (Math.floor(amount)<90) {
		var myFx = new Fx.Tween($('min_sum_msg'), {'duration':'1000'});
		myFx.start('color','#FF0000','#666666');
		return;
	}
	$('payment_submit').disabled=true;
	new Request({method: 'POST',
				url: '/moneybookers_pay/',
				data: 'amount='+amount,
				onSuccess: function(txt){
				if (txt) {
					var response = txt.split("|");
					var form = $('moneybookers_form');
					$('mb_invoice').value = response[0];
					$('mb_amount').value = response[1];
					$('mb_lang').value = response[2];
					form.submit();
				}				
			},
				onFailure: function() {
				$('payment_submit').disabled=false;
			}
	}).send();
}

function rk_pay(amount){
	$('payment_submit').disabled=true;
	new Request({method: 'POST',
				url: '/rk_pay/',
				data: 'amount='+amount,
				onSuccess: function(txt){
				if (txt) {
					var response = txt.split("|");
					var form = $('rk_form');
					$('rk_amount').value = response[0];
					$('rk_invoice').value = response[1];
					$('rk_sign').value = response[2];
					$('rk_lang').value = response[3];
					form.submit();
				}				
			},
				onFailure: function() {
				$('payment_submit').disabled=false;
			}
	}).send();
}

function liqpay_pay(amount){
	$('payment_submit').disabled=true;
	new Request({method: 'POST',
				url: '/liqpay_pay/',
				data: 'amount='+amount,
				onSuccess: function(txt){
				if (txt) {
					var response = txt.split("|");
					var form = $('liqpay_form');
					$('lp_inputxml').value = response[0];
					$('lp_inputsign').value = response[1];
					form.submit();
				}
			},
				onFailure: function() {
                $('payment_submit').disabled=false;
            }
	}).send();
}


function paypal_onclick() {
	$('radio_paypal').checked=true;
}

function rk_onclick() {
	$('radio_rk').checked=true;
}

function wm_onclick() {
	$('radio_wm').checked=true;
}

function liqpay_onclick() {
	$('radio_liqpay').checked=true;
}

function qiwi_onclick() {
	$('radio_qiwi').checked=true;
}

function sbrf_onclick() {
	$('radio_sbrf').checked=true;
}

function moneybookers_onclick() {
	$('radio_moneybookers').checked=true;
}

function checkuser() {
	$('id_submit').disabled = true;
	$('id_message_holder').innerHTML = '';
	new Request({method: 'POST',
				url: '/checkuser/',
				encoding: 'utf-8',
				data: 'username='+escape($('id_username').value)+'&passwd='+escape($('id_password').value),
				onSuccess: function(txt){
				if (txt) {
					var form = $('login_form');
					form.submit();
				} else {
					$('id_message_holder').innerHTML = gettext("Invalid credentials");
					$('id_submit').disabled = false;
				}
			},
				onFailure: function() {
				$('id_message_holder').innerHTML = gettext("Invalid credentials");
				$('id_submit').disabled=false;
			}
	}).send();
}

function softphone_data(compinfo){
    new Request({method: 'POST',
				url: '/softphone_data/',
				data: 'compinfo='+encodeURIComponent(compinfo),
				onSuccess: function(txt){
				if (txt) {
					$('balanceHolder').innerHTML = txt;
				}
			}
	}).send();
}

function softphone_debug(data){
    new Request({method: 'POST',
				url: '/softphone_debug/',
				data: 'data='+encodeURIComponent(data)}).send();
}

function get_descr(t, is_dropdown) {
	var number = t.num_colorized;
   	var iso = t.iso;
	var pos_x = t.pos_x;
	var pos_y = t.pos_y;
	var direction = t.status;
	var price = t.price;
	var currency = t.currency;
	var dom = t.dom;
	var sh = t.sh;

	var money = '';
	var status = '';
	var img_div = '';
	var text_span ='';

	var description = null;
	var descrIcon = null;
	var chatIcon = null;
	if (!dom) {
		if (direction)
			status = direction + "&nbsp;-&nbsp;";

		if (price && currency)
			money = price + " " + currency;

		if (status || money)
			description = status + money;

		if (pos_x && pos_y)
			descrIcon = new Element('div', {
				'class': 'flag_holder',
				'style': 'background-position:-'+pos_x+'px -'+pos_y+'px;'
			});
	} else {
		description = direction;

		descrIcon = new Element('div', {
			'class': 'favicon_holder',
			'style': 'background:transparent url(/p/'+sh+'/'+dom+') no-repeat scroll 0 2px;'
		});

		if (!number.match("@"))
			number = number + '@talkpad.ru';

		chatIcon = new Element('div', {
			'class': 'chat_icon_holder',
			'title': gettext('chat'),
			'events' :  {
				'click': function() {
					var panel = xmppClient.getChatPanel(number).panel;
					panel.focusChatBox();
					return false;
				}
			}
		});
	}

	if (!is_dropdown) {
		var d = new Element('span', {'class': is_dropdown ? 'dropdown_descr': 'descr'});
		if (chatIcon)
			chatIcon.inject(d);
	
		if (descrIcon)
			descrIcon.inject(d);

		if (description)		
			new Element('span', {'style': "float:left;", 'html': description}).inject(d);
		return d;
	}

	var dropDownItem = new Element('table', {'class': 'dropDownItem'});
	var tbody = new Element('tbody');
	tbody.inject(dropDownItem);
	
	var topRow = new Element('tr', {'class': 'dropDownRow'});
	topRow.inject(tbody);
	
	var bottomRow = new Element('tr', {'class': 'dropDownRow'});
	bottomRow.inject(tbody);
	
	var statusCell = new Element('td', {'class': 'dropDownStatusCell', 'rowspan': 2});
	statusCell.inject(topRow);
	if (dom) {
		var xmppStatus = 'offline';
		if (xmppClient.getStatus(number).status == 'available')
			xmppStatus = 'available';
		new Element('img', {
			'class': 'dropDownStatusImg',
			'src': '/static/img/pidgin/' + xmppStatus + '.png',
			'name': 'status_' + Base64.encode(number)
			}).inject(statusCell);
	}

	var contactCell = new Element('td', {'class': 'dropDownContact'});
	contactCell.inject(topRow);

	var descrCell = new Element('td', {'class': 'dropDownDescrCell', 'valign': 'middle'});
	descrCell.inject(bottomRow);
	if (descrIcon)
		descrIcon.inject(descrCell);
	if (description)
		new Element('span', {'class': 'dropDownDescription', 'html': description}).inject(descrCell);

	var actionCell = new Element('td', {'class': 'dropDownActionCell', 'rowspan': 2});
	actionCell.inject(topRow);

	if (chatIcon) {
		chatIcon.inject(actionCell);
		//new Element('div', {'html': ' chat ', styles: {'float': 'left', 'margin-right': 3, 'color': '#555', 'font-size': '0.9em'}}).inject(actionCell);
	}

	new Element('div', {
		'class': 'delete_entry',
		'title': gettext('delete_contact'),
		'events': {
			'click': function(){
				tmp_value = $('numberBox').value;
				delete_entry(number);
				return false;
			}
		}
	}).inject(actionCell);
	
	return dropDownItem;
}

// statistics

function report() {
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	new Asset.javascript(gaJsHost + "google-analytics.com/ga.js", {
		onload: function() {
			var pageTracker = _gat._getTracker("UA-9390996-1");
			pageTracker._trackPageview();
		}
	});

	var li_src = "http://counter.yadro.ru/hit?t52.6;r" + escape(document.referrer) + ((typeof(screen)=="undefined")?"":";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth?screen.colorDepth:screen.pixelDepth)) + ";u" + escape(document.URL) + ";" + Math.random();
	var limage = new Asset.image(li_src, {
			border: 0,
			width: 88,
			height: 31,
			alt: '',
			title: gettext('liveInternet')
		});
}

function initReport() {
	setTimeout(report,500);
}

function recordLink(category, action) {
	try {
		var myTracker=_gat._getTrackerByName();
		_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
	} catch(err){}
}

// in Google Chrome requests created by event handlers
// do not fire onreadystatechange event

var requestProcessor = {
	requests: [],
	
	init: function() {
		this.processRequests.periodical(100, this);
	},

	push: function(requestData) {
		this.requests.push(requestData);
	},

	processRequests: function() {
		while (this.requests.length > 0) {
			var requestData = this.requests.pop();
			new Request.JSON(requestData).send();
		}
	}
};


