/**
 * Offering Javascript functions
 * @copyright Pant24 O&Uuml;
 */

var userKey = '';
var req; // The request Object
var postId;
var failureUrl = 'http://pant24.ee';
var goBuying = false;

////////////
// TIMERS //
////////////

/** Offer timer counts from 60 to 0 */
var clientTimerOn = false;
function clientTimer(start, noNewsChecking)
{
	if (start != null)
	{
		clientTimerOn = true;
		if (noNewsChecking == null)
			checkNews(true);
	}
	if (!clientTimerOn)
		return; // Timer not working

	if (null === $('offeringSeconds'))
	{ // See element ei ole veel laetud...
		window.setTimeout('clientTimer()', 1000);
		return;
	}

	var secondsLeft = $('offeringSeconds').get('html');
	secondsLeft--;
	$('offeringSeconds').set('html', secondsLeft)

	if (secondsLeft <= 0) // Time over
	{
		if ($('bestOfferer') != null)
		{ // This client is best offerer
			checkNewsTimerOn = false;
			clientTimerOn = false;
			canGoBuying();
			return;
		}
		else
		{ // Someone else made better offer
			showProgress();
			payingTimerOthers(true);
		}
		return;
	}
	window.setTimeout('clientTimer()', 1000);
}

/**
 * Check offering news from AJAX-Gateway
 * Adopts new recived HTML
 */
var checkNewsTimerOn = false;
function checkNews(start)
{
	if (start != null)
		checkNewsTimerOn = true;
	if (!checkNewsTimerOn)
		return; // No need for check at the moment...

	req = new Request.HTML({url:'/ajax-gateway/?action=checkNews&postId=' + postId + '&key=' + userKey,
		onSuccess: function(html) {
			if (html.length != 0)
			{
				$('ajaxResult').set('text', '');
				$('ajaxResult').adopt(html);
				if (Browser.Engine.trident)
				{ // IE doesn't accept Javascript from AJAX response!
					if ($('offerProgress2'))
					{
						$('offer2').onclick = function () { offerMore(2); };
						$('offer5').onclick = function () { offerMore(5); };
						$('offer10').onclick = function () { offerMore(10); };
					}
				}
				if (clientTimerOn == false && $('offerProgress2') && !goBuying)
				{ // Start ticking from 60...
					clientTimer(true, true);
				}
			}
		},
		onFailure: function() {
			$('ajaxResult').set('text', 'Süsteemi viga! (AJAX request failed (4))');
		}
	});
	req.send();
	window.setTimeout('checkNews()', 5555);
}

/** 
 * Paying timer
 * For use in payment header!
 */
var payingTimerOn = false;
function payingTimer(start)
{
	if (start != null)
		payingTimerOn = true;
	if (!payingTimerOn)
		return; // Timer not working
	
	var secondsCount = $('payingSeconds').get('html');
	var minutesCount = $('payingMinutes').get('html');
	
	var timeOver = false
	if (secondsCount <= 0)
	{
		if (minutesCount > 0)
		{
			minutesCount--;
			secondsCount = 59;
		}
		else // timeOver
			timeOver = true;
	}
	else
		secondsCount--;
		
	$('payingSeconds').set('html', secondsCount);
	$('payingMinutes').set('html', minutesCount);
	
	if (timeOver)
	{
		paymentFailure();
		return;
	}
		
	window.setTimeout('payingTimer()', 1000);
	
}

/**
 * Timer for others then best offerer
 */
var payingTimerOthersOn = false;
function payingTimerOthers(start)
{
	if (start == true)
		payingTimerOthersOn = true;
	if (!payingTimerOthersOn)
		return; // Timer not working
	
	if (null === $('payingSeconds'))
	{
		window.setTimeout('payingTimerOthers()', 1000);
		return;
	}
	
	secondsCount = $('payingSeconds').get('html');
	minutesCount = $('payingMinutes').get('html');
	
	var timeOver = false
	if (secondsCount <= 0)
	{
		if (minutesCount > 0)
		{
			minutesCount--;
			secondsCount = 59;
		}
		else // timeOver
			timeOver = true;
	}
	else
		secondsCount--;
		
	$('payingSeconds').set('html', secondsCount);
	$('payingMinutes').set('html', minutesCount);
	
	if (timeOver)
	{
		showProgress();
		clientTimer(true, true);
		return;
	}
		
	window.setTimeout('payingTimerOthers()', 1000);
	
}

/**
 * Because Javascript timer is not exact at all
 * For use in payment window header!
 */
var syncronizePaymentTimeOn = false;
function syncronizePaymentTime(start)
{
	if (start != null)
		syncronizePaymentTimeOn = true;
	if (!syncronizePaymentTimeOn)
		return;

	req = new Request.HTML({url:'/ajax-gateway/?action=syncronizePaymentTime&postId=' + postId,
		onSuccess: function(html) {
			var headerText = document.getElementById('headerText');
			headerText = $(headerText);
			headerText.set('text', '');
			headerText.adopt(html);
		},
		onFailure: function() {
			$('ajaxResult').set('text', 'Süsteemi viga! (AJAX request failed (5))');
		}
	});
	req.send();
	window.setTimeout('syncronizePaymentTime()', 9999);
}

///////////////////////
// ACTIONS ON TIMERS //
///////////////////////

/** When WP timer ticks to zero */
function timeOver()
{
	if (!$('ajaxResult'))
	{
		window.location.reload(); // Kui ei ole toote lehel
		return;
	}

	if ($('normalTimer'))
		$('normalTimer').setStyle('display', 'none');
	$('ajaxResult').setStyle('display', '');
	req = new Request.HTML({url:'/ajax-gateway/?action=timeOver&postId=' + postId, 
		onSuccess: function(html) {
			$('ajaxResult').set('text', '');
			$('ajaxResult').adopt(html);
			userKey = $('userKey').get('html');
			clientTimer(true); // Start offering timer
		},
		onFailure: function() {
			$('ajaxResult').set('text', 'Süsteemi viga! (AJAX request failed (1))');
		}
	});
	req.send();
}


/** Tries to go to product payment */
function canGoBuying()
{
 	goBuying = true;
	$('timerText').setStyle('display', 'none');
	$('getBuyButton').setStyle('display', '');
	clientTimerOn = false;
	req = new Request.HTML({url:'/ajax-gateway/?action=canGoBuying&postId=' + postId + '&key=' + userKey,
		onSuccess: function(html) {
			if (html.length != 0)
			{ // Everything okey, can buy...
				goBuy();
			}
			else
			{ // A new offer in last second...
				goBuying = false;
				checkNews(true);
				clientTimerOn = true;
				clientTimer(); // Timer starts clicking again...
			}
		},
		onFailure: function() {
			$('ajaxResult').set('text', 'Süsteemi viga! (AJAX request failed (3))');
		}
	});
	req.send();
}

//////////////////////////////
// ACTIONS ON USER ACTIVITY //
//////////////////////////////

/** Makes new offer trough AJAX-gateway */
function offerMore(sum)
{
	$('offerProgress' + sum).setStyle('display', '');
	req = new Request.HTML({url:'/ajax-gateway/?action=makeOffer&postId=' + postId + '&key=' + userKey + '&offer=' + sum, 
		onSuccess: function(html) {
			$('ajaxResult').set('text', '');
			$('ajaxResult').adopt(html);
		},
		onFailure: function() {
			$('ajaxResult').set('text', 'Süsteemi viga! (AJAX request failed (2))');
		}
	});
	req.send();
}

////////////////////////////////////
// FUNCTIONS CONNECTED TO PAYMENT //
////////////////////////////////////

function goBuy()
{
	window.location.href = '/payment/?postId=' + postId + '&key=' + userKey; 
}

/* For use from payment header */
function paymentFailure()
{
	payingTimerOn = false;
	syncronizePaymentTimeOn = false;
	alert("Makse ebaõnnestus! Probleemide korral võtke ühendust klienditeenindusega.");
	parent.window.location.href = failureUrl;
}

function paymentSuccess()
{
	payingTimerOn = false;
	syncronizePaymentTimeOn = false;
	var headerText = $('headerText');
	headerText.setStyle('background-color', 'green');
	headerText.set('html', 'Makse on edukalt sooritatud! Palun sisestage nüüd kontaktandmed!');
}

/////////////////////
// OTHER FUNCTIONS //
/////////////////////

var payingWindow = null;
function openPayingPopup(link)
{
	alert('openPayingPopup()');
}

function showProgress()
{
	$('ajaxResult').set('html', '<img src="http://pant24.ee/wp-content/themes/pant24/images/ajax-loader.gif" />');
	$('ajaxResult').setStyle('display', '');
}

function popUp(link)
{
  window.open(
    link,
    "popUp",
    "width=700,height=270,left="
      +((screen.width-700)/2)+",top="+((screen.height-270)/2)
  );
  return true;
}


