/* START 3 KEREDE REDIRECT */

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
  endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
    return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0)
    break;
  }
  return null;
}

function SetCookie (name, value) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (2 < argc) ? argv[2] : null;
  var path = (3 < argc) ? argv[3] : null;
  var domain = (4 < argc) ? argv[4] : null;
  var secure = (5 < argc) ? argv[5] : false;
  document.cookie = name + "=" + escape (value) +
   ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
   ((path == null) ? "" : ("; path=" + path)) +
   ((domain == null) ? "" : ("; domain=" + domain)) +
   ((secure == true) ? "; secure" : "");
}

function DisplayInfo() {
  var expdate = new Date();
  var visit;
  expdate.setTime(expdate.getTime() +  (24 * 60 * 60 * 1000 * 1));
  if(!(visit = GetCookie("visit")))
  visit = 0;
  visit++;
  SetCookie("visit", visit, expdate, "/", null, false);
  var message;
  if(visit == 1)
    alert("\n"+"- Ucretsiz sohbet modundasiniz -                \n\n"
              +"  Bugunku "+visit+". sohbetiniz \n"
              +"                          "+""+""
              );
  if(visit== 2)
    alert("\n"+"- Ucretsiz sohbet modundasiniz -                \n\n"
              +"  Bugunku "+visit+". sohbetiniz \n"
              +"                          "+""+""
              );

  if(visit == 3)
    alert("\n"+"- Ucretsiz sohbet modundasiniz -                \n\n"
              +"  Bugunku "+visit+". sohbetiniz \n"
              +"                          "+""+""
              );
  if(visit >= 4)
  location.href = "http://www.liselilerlesohbet.com/index_redirect_tb.php";
}


/* END 3 KEREDE REDIRECT */
















/* CONFIGURATION VARIABLES - modify at will */

var MAX_RECONNECT_ATTEMPTS = 10;

var MAX_STILL_THERE_ATTEMPTS = 2;

/* END CONFIGURATION VARIABLES */



var divScroll;

var lastScrollPosition = 0;

var lostConnection = false;

var reconnectAttempts = 0;

var stillThereAttempts = 0;

var nextMessageType = '';



var timer = {

	getMessage:	{

		timerInstance: null,

		func: function() { getMessage(); }

	},

	showTyping:	{

		timerInstance: null,

		func: function() { 

			$('status').innerHTML = $('operatorName').innerHTML + ' yaziyor';

			/* TO DO - CHANGE THIS TO A RANDOM NUMBER BETWEEN 15000 and 20000 (15 and 20 seconds) */

			startTimer('getMessage', 8000);

		}

	},

	stillThere: {

		timerInstance: null,

		func: function() {

			stillThereAttempts++;

			if (stillThereAttempts > MAX_STILL_THERE_ATTEMPTS) {

				nextMessageType = 'goodbye';

				startTimer('showTyping', 1);						// show "typing..." message NOW, followed by goodby message

			}

			else {

				// Don't need to restart the stillThere timer - the processGetResponse() function will do that

				nextMessageType = 'stillThere';

				startTimer('showTyping', 1);						// show "typing..." message NOW, followed by stillThere message

			}

		}

	}

}



window.onload = function() {
	
	divScroll = new chatscroll.Pane('conversation');			// initialize the auto-scrolling capability

	$('message').disabled=true;

	initialize();
	

}







function startTimer(timerID, milliseconds) {

	stopTimer(timerID);					// stop the current timer if there is one

	timer[timerID]['timerInstance'] = setTimeout(function() { timer[timerID]['func'](); }, milliseconds);

}

function stopTimer(timerID) {

	// stop the timer if there is one

	if (timer[timerID]['timerInstance']!=null) clearTimeout(timer[timerID]['timerInstance']);

}













/* AJAX - retrieves the operator's message from the server */

function getMessage(type) {

	if (nextMessageType != '') type=nextMessageType;			// if a global nextMessageType exists, use it for this getMessage()

	var params = 'getMessage=yes';

	if (type != null) params = params + "&type="+type;			// add type parameter if a type is specified for this getMessage()

	var ajax = new Ajax.Request("chat-ajax.php", { method: 'post', parameters: params, onSuccess: processGetResponse, onFailure: processGetFailure } );

}

function processGetResponse(request) {

	var response = eval('(' + request.responseText + ')');

	nextMessageType = '';										// reset global message type since it was just finished/retrieved

	addToConversation('app', response.message);					// add operator response to the conversation window

	lostConnection = false;										// the connection is restored (or still good)

	reconnectAttempts = 0;										// the connection is restored (or still good)

	$('status').innerHTML = (lostConnection) ? "Reconnected!" : "";		// clear status ("XXXXXX is typing"), or "Reconnected!"

	if (response.code!='goodbye') startTimer('stillThere', 40000);		// if not finished, start "Are you there?" timer (20 secs)

	$('message').disabled=false;								// enable the user's input field

}

function processGetFailure(request) {

	lostConnection = true;

	reconnectAttempts++;

	if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {

		$('status').innerHTML = 'Sohbet Baglantiniz kesildi.  Birazdan yeniden deneyin.';

		$('message').disabled = true;

	}

	else {

		alert('baglaniyor');

		$('status').innerHTML = 'Baglantiniz koptu. Yeniden baglaniyor...';

		startTimer('getMessage', 1500);								// try again in 1.5 seconds - keep trying until success (or max reconnection attempts is reached)

	}

}











/* AJAX - send's the user's written message to the server */

function sendMessage() {

	var params = 'sendMessage=yes&message='+encodeURIComponent($('message').value);
	
	$('message').disabled = "true";

	var ajax = new Ajax.Request("chat-ajax.php", { method: 'post', parameters: params, onSuccess: processSendResponse, onFailure: processSendFailure } );

}

function processSendResponse(request) {

	$('message').disabled = null;

	var response = eval('(' + request.responseText + ')');

	$('status').innerHTML = (lostConnection) ? "Reconnected!" : "";		// clear status ("XXXXXX is typing"), or "Reconnected!"

	lostConnection = false;												// the connection is restored (or still good)

	stillThereAttempts = 0;												// any stillThere questions are answered with this response

	$('message').value = '';											// clear input field

	addToConversation('user', response.message);						// add user's message to the conversation window

	startTimer('showTyping', 1500);										// start timer to show "XXXXXX is typing" in 5 seconds

	stopTimer('getMessage');											// stop getMessage timer (in case it was started already)

	stopTimer('stillThere');											// stop stillThere timer since user has responded now

}

function processSendFailure(request) {

	$('status').innerHTML = 'Your connection with the server has been lost.  The other party did not receive your last message.';

	lostConnection = true; 

}













/* AJAX - initialize the conversation with the server */

function initialize() {

	DisplayInfo();
	var params = 'initialize=yes&operatorName='+$('operatorName').innerHTML

	var ajax = new Ajax.Request("chat-ajax.php", { method: 'post', parameters: params, onSuccess: processInitializeResponse, onFailure: processInitializeFailure } );

}

function processInitializeResponse(request) {

	//setTimeout(function(){$('status').innerHTML = 'Connected to '+$('operatorName').innerHTML; }, 2000);

	startTimer('showTyping', 2000);

}

function processInitializeFailure(request) {

	lostConnection = true;

	reconnectAttempts++;

	if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {

		$('status').innerHTML = 'A connection cannot be re-established with the server.  Please try back later, as this is a temporary problem.';

		$('message').disabled = true;

	}

	else {

		$('status').innerHTML = 'Your connection with the server has been lost.  Attempting reconnection...';

		setTimeout(initialize, 1500);								// try again in 1.5 seconds - keep trying until success (or max reconnection attempts is reached)

	}

}









/*

 * 

 */

function addToConversation(role, message) {

	var paragraphClass = (role=='user') ? 'user' : 'app';

	var name = (role=='user') ? 'Me' : $('operatorName').innerHTML;

	$('conversation').innerHTML = $('conversation').innerHTML + '<p class="'+paragraphClass+'"><span class="name">' + name + ':</span> &nbsp; ' + message + '</p>';

	//$('conversation').insertAdjacentHTML('beforeEnd', '<p class="'+paragraphClass+'"><span class="name">' + name + ':</span> &nbsp; ' + message + '</p>');

	//divScroll.activeScroll();

	//if ($('conversation').scrollTop==lastScrollPosition) {

		$('conversation').scrollTop = $('conversation').scrollHeight;

	//	lastScrollPosition = $('conversation').scrollTop;

	//}

}











function processFailure(request, response) {

	alert("The server can not be reached at this time.  Please try again later as the error is only temporary.");

}









/* fades an element (give amount as a decimal) */

function fade(element, amount) {

	element.style.filter = "alpha(opacity:"+Math.round(amount*100)+")";

	alert(element.style.filter);

	element.style.opacity = amount;

}













var chatscroll = new Object();

chatscroll.Pane = 

	function(scrollContainerId) {

		this.bottomThreshold = 25;

		this.scrollContainerId = scrollContainerId;

	}



chatscroll.Pane.prototype.activeScroll = function() {

	var scrollDiv = document.getElementById(this.scrollContainerId);

	var currentHeight = 0;

        

	if (scrollDiv.scrollHeight > 0)

		currentHeight = scrollDiv.scrollHeight;

	else if (objDiv.offsetHeight > 0)

		currentHeight = scrollDiv.offsetHeight;



	//if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)

		scrollDiv.scrollTop = currentHeight;

	scrollDiv = null;

}




