//var jQ = jQuery.noConflict();
jQuery.noConflict();

var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
var maxChatHeartbeat = 33000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;
var chatUserId;
var chatId;

var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();

jQuery(document).ready(function(){
	
	originalTitle = document.title;
	startChatSession();

	jQuery([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
}); // end jQuery(document).ready

function restructureChatBoxes(chatboxtitle) {
	
	align = 0;
	
	for (i=0;i<chatBoxes.length;i++) {
		
		chatboxtitle = chatBoxes[i];
		if (jQuery("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				jQuery("#chatbox_"+chatboxtitle).css('right', '20px');
			
			} else  {
				width = (align)*(225+7)+20;
				jQuery("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			
			align++;
		}			
	}
	/*for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if (jQuery("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				jQuery("#chatbox_"+chatboxtitle).css('right', '20px');
			
			} else  {
				width = (align)*(225+7)+20;
				jQuery("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			
			align++;
		}
	} */
	
	/*if (jQuery(".chatbox").length==1) {
		jQuery("#chatbox_"+chatboxtitle).css('right', '20px');
	} else {
		jQuery("#chatbox_"+chatboxtitle).css('right', '252px');
	}*/
} // end function restructureChatBoxes()

function rejected(chatuser, chatuserid){
	chatUserId= chatuserid;
	
	jQuery.post("chat.php?action=rejectedperson", { chatbox: chatuser, chatuserid: chatuserid} , function(data){	
		});
	
	chatbilgikutukaldir();
}

function removeChatBox(chatboxtitle) {
	
	jQuery('#chatbox_'+chatboxtitle).remove();
	chatBoxes.remove(chatboxtitle);
	restructureChatBoxes(chatboxtitle);

	jQuery.post("chat.php?action=endconversation", { chatbox: chatboxtitle} , function(data){	
	});

} // function closeChatBox

function chatWith(chatuser, chatuserid, chatid) {
	chatUserId= chatuserid;
	chatId = chatid;
	
	for (i=0;i<chatBoxes.length;i++) {
		
		chatboxtitle = chatBoxes[i];
		if (chatboxtitle==chatuser){
			chatBoxes.remove(chatboxtitle);
			jQuery('#chatbox_'+chatboxtitle).remove();
			removeChatBox(chatboxtitle);
		}
	}
	
	if (chatBoxes.length>=2) {
		
		jQuery(" <div />" ).attr("id","chatbox_warning")
		.addClass("chatbox")
		.html('<div class="chatboxhead"><div class="chatboxtitle">Ayni anda en fazla 2 kisi ile konusabilirsiniz.</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox(\'warning\')">X</a></div><br clear="all"/></div>')
		.appendTo(jQuery( "body" ));
				   
		jQuery("#chatbox_warning").css('bottom', '0px');
		jQuery("#chatbox_warning").css('right', '504px');
		
		jQuery("#chatbox_warning").show();
		
	} else {
		
		if (jQuery('#aktifcount').val() > 1){
			if (jQuery('#pchatwarning_'+chatuserid).length > 0) {
				jQuery('#pchatwarning_'+chatuserid).css('display','block');
			}
		}else{
			jQuery('#aktifcount').val(parseInt(jQuery('#aktifcount').val())+1);
			
			if (jQuery('.'+chatuserid).length > 0) {
				jQuery('.'+chatuserid).css('display','none');
			}
			
			createChatBox(chatuser);
			jQuery("#chatbox_"+chatuser+" .chatboxtextarea").focus();
			
			jQuery.post("chat.php?action=activeperson", { chatbox: chatuser, chatuserid: chatuserid, chatid: chatId} , function(data){	
			});
			
			if (jQuery('#aktifcount').val()==2){
				chatbilgikutukaldir();
			}else if (jQuery('#talepcount').val()==1){
				chatbilgikutukaldir();
			}
		}
	}
	
} // end function chatWith

function createChatBox(chatboxtitle,minimizeChatBox) {
	
	if (jQuery("#chatbox_"+chatboxtitle).length > 0) {
		if (jQuery("#chatbox_"+chatboxtitle).css('display') == 'none') {
			jQuery("#chatbox_"+chatboxtitle).css('display','block');
			restructureChatBoxes(chatboxtitle);
		}
		jQuery("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		return;
	}
		
	jQuery(" <div />" ).attr("id","chatbox_"+chatboxtitle)
	.addClass("chatbox")
	.html('<div class="chatboxhead"><div class="chatboxtitle">'+chatboxtitle+'</div><div class="chatboxoptions"><a href="javascript:void(0)" id="toggleChatBox" name="toggleChatBox" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')">X</a></div><br clear="all"/><div class="chatboxhead1"> <a href="javascript:void(0)" onclick="javascript:banPerson(\''+chatboxtitle+'\',\''+chatUserId+'\',\''+chatId+'\')">Yasakla</a> - <a href="javascript:void(0)" onclick="javascript:reportPerson(\''+chatboxtitle+'\',\''+chatUserId+'\',\''+chatId+'\')">Sikayet et</a> - <a id="endconversation" name="endconversation" href="javascript:void(0)" onclick="javascript:endSession(\''+chatboxtitle+'\',\''+chatUserId+'\',\''+chatId+'\')">Konusmayi bitir</a> </div></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></div>')
	.appendTo(jQuery( "body" ));
			   
	chatBoxes.push(chatboxtitle);
	
	jQuery("#chatbox_"+chatboxtitle).css('bottom', '0px');
	jQuery("#chatbox_"+chatboxtitle).css('z-index', '9998');
	

	/*for (x in chatBoxes) {
		if (jQuery("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
			chatBoxeslength++;
		}
	}
	
	if (jQuery(".chatbox").length==1) {
		jQuery("#chatbox_"+chatboxtitle).css('right', '20px');
	} else {
		jQuery("#chatbox_"+chatboxtitle).css('right', '252px');
	}*/	
	
	
    chatBoxeslength = 0;

	for (i=0;i<jQuery(".chatbox").length;i++) {
		if (jQuery("#chatbox_"+chatBoxes[i]).css('display') != 'none') {
			chatBoxeslength++;
		}
	}

	if (chatBoxeslength == 0) {
		jQuery("#chatbox_"+chatboxtitle).css('right', '20px');
	} else  {
		width = (chatBoxeslength)*(225+7)+20;
		jQuery("#chatbox_"+chatboxtitle).css('right', width+'px');
	} 
	
	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		if (jQuery.cookie('chatbox_minimized')) {
			minimizedChatBoxes = jQuery.cookie('chatbox_minimized').split(/\|/);
		}
		
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == chatboxtitle) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			jQuery('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			jQuery('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}

	chatboxFocus[chatboxtitle] = false;

	jQuery("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
		chatboxFocus[chatboxtitle] = false;
		jQuery("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[chatboxtitle] = true;
		newMessages[chatboxtitle] = false;
		jQuery('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
		jQuery("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});

	jQuery("#chatbox_"+chatboxtitle).click(function() {
		if (jQuery('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
			jQuery("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		}
	});

	jQuery("#chatbox_"+chatboxtitle).show();
} // end function createChatBox


function chatHeartbeat(){

	var itemsfound = 0;
	
	if (windowFocus == false) {
 
		var blinkNumber = 0;
		var titleChanged = 0;
		for (x in newMessagesWin) {
			if (newMessagesWin[x] == true) {
				++blinkNumber;
				if (blinkNumber >= blinkOrder) {
					document.title = x+' der ki...';
					titleChanged = 1;
					break;	
				}
			}
		}
		
		if (titleChanged == 0) {
			document.title = originalTitle;
			blinkOrder = 0;
		} else {
			++blinkOrder;
		}

	} else {
		for (x in newMessagesWin) {
			newMessagesWin[x] = false;
		}
	}

	for (x in newMessages) {
		if (newMessages[x] == true) {
			if (chatboxFocus[x] == false) {
				//FIXME: add toggle all or none policy, otherwise it looks funny
				jQuery('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
			}
		}
	}
	
	jQuery.ajax({
	  url: "chat.php?action=chatheartbeat",
	  cache: false,
	  dataType: "json",
	  success: function(data) {

		jQuery.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxtitle = item.f;
				if (item.c!=null && item.c!='' && item.c!=0)
					chatId = item.c;
					
				if (item.u!=null && item.u!='' && item.u!=0)
					chatUserId = item.u;

				if (jQuery("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle);
				}
				if (jQuery("#chatbox_"+chatboxtitle).css('display') == 'none') {
					jQuery("#chatbox_"+chatboxtitle).css('display','block');
					restructureChatBoxes(chatboxtitle);
				}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					newMessages[chatboxtitle] = true;
					newMessagesWin[chatboxtitle] = true;
					if (item.m == "askclose007win"){
						
						jQuery('#chatbox_'+chatboxtitle+' .chatboxinput').remove();
						
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">konuşmadan ayrıldı.</span></div>');
						
						if (jQuery('#chatbox_'+chatboxtitle+' #toggleChatBox').length > 0) {
							jQuery('#chatbox_'+chatboxtitle+' #toggleChatBox').css('display','none');
						}
						if (jQuery('#chatbox_'+chatboxtitle+' #endconversation').length > 0) {
							jQuery('#chatbox_'+chatboxtitle+' #endconversation').css('display','none');
						}
						
					}else if (item.m == "askopen007win"){
						
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagecontent">chat\'e başlayabilirsiniz.</span></div>');
						
					}else if (item.m == "askopen006win"){
						
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagecontent">chat\'e başlayabilirsiniz.</span></div>');
						
					}else{
							jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
						
					}
				}

				jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				itemsfound += 1;
			}
			
		});

		chatHeartbeatCount++;

		if (itemsfound > 0) {
			chatHeartbeatTime = minChatHeartbeat;
			chatHeartbeatCount = 1;
		} else if (chatHeartbeatCount >= 10) {
			chatHeartbeatTime *= 2;
			chatHeartbeatCount = 1;
			if (chatHeartbeatTime > maxChatHeartbeat) {
				chatHeartbeatTime = maxChatHeartbeat;
			}
		}
		
		setTimeout('chatHeartbeat();',chatHeartbeatTime);
	}});
} // end function chatHeartbeat()

function closeChatBox(chatboxtitle) {
	jQuery('#chatbox_'+chatboxtitle).css('display','none');
	
	if (jQuery('#chatbox_'+chatboxtitle+' #endconversation').css('display') == 'none') {
		
		jQuery('#chatbox_'+chatboxtitle).remove();
		chatBoxes.remove(chatboxtitle);
		restructureChatBoxes(chatboxtitle);
	
		jQuery.post("chat.php?action=endconversation", { chatbox: chatboxtitle} , function(data){	
		});
		
	}else{

		jQuery.post("chat.php?action=closechat", { chatbox: chatboxtitle } , function(data){	
	});
	
		restructureChatBoxes(chatboxtitle);
	}
} // function closeChatBox


function endSession(chatboxtitle,chatuserid,chatid) {
	if (jQuery('.kabulet').length > 0) {
		jQuery('.kabulet').css('display','block');
	}
	
	if (jQuery('.'+chatuserid).length > 0) {
		jQuery('.'+chatuserid).remove();
	}
	
	if (jQuery('#aktifcount').length > 0) {
		jQuery('#aktifcount').val(jQuery('#aktifcount').val()-1);
	}
	
	jQuery('#chatbox_'+chatboxtitle).remove();
	chatBoxes.remove(chatboxtitle);
	restructureChatBoxes(chatboxtitle);

	jQuery.post("chat.php?action=endsession", { chatbox: chatboxtitle, chatid: chatid} , function(data){	
	});
} // end function endSession


function reportPerson(chatboxtitle, chatuserid, requestid) {
	jQuery('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes(chatboxtitle);

	jQuery.post("chat.php?action=reportperson", { chatbox: chatboxtitle, chatuserid:chatuserid, requestid:requestid} , function(data){	
	});

} // end function reportPerson


function banPerson(chatboxtitle, chatuserid, requestid) {
	jQuery('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes(chatboxtitle);

	jQuery.post("chat.php?action=banperson", { chatbox: chatboxtitle, chatuserid:chatuserid, requestid:requestid} , function(data){	
	});

} // end function banPerson

function toggleChatBoxGrowth(chatboxtitle) {
	if (jQuery('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if (jQuery.cookie('chatbox_minimized')) {
			minimizedChatBoxes = jQuery.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		jQuery.cookie('chatbox_minimized', newCookie);
		jQuery('#chatbox_'+chatboxtitle+' .chatboxhead1').css('display','block');
		jQuery('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		jQuery('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if (jQuery.cookie('chatbox_minimized')) {
			newCookie += '|'+jQuery.cookie('chatbox_minimized');
		}


		jQuery.cookie('chatbox_minimized',newCookie);
		jQuery('#chatbox_'+chatboxtitle+' .chatboxhead1').css('display','none');
		jQuery('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		jQuery('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
	}
	
} // end function toggleChatBoxGrowth

function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {
	 
	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = jQuery(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");

		jQuery(chatboxtextarea).val('');
		jQuery(chatboxtextarea).focus();
		jQuery(chatboxtextarea).css('height','44px');
		if (message != '') {
			jQuery.post("chat.php?action=sendchat", {to: chatboxtitle, message: message, chatid: chatId, chatuserid: chatUserId} , function(data){
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+username+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
				jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			});
		}
		chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;

		return false;
	}

	var adjustedHeight = chatboxtextarea.clientHeight;
	var maxHeight = 94;

	if (maxHeight > adjustedHeight) {
		adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
		if (maxHeight)
			adjustedHeight = Math.min(maxHeight, adjustedHeight);
		if (adjustedHeight > chatboxtextarea.clientHeight)
			jQuery(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		jQuery(chatboxtextarea).css('overflow','auto');
	}
	 
} // end function checkChatBoxInputKey

function startChatSession(){  
	jQuery.ajax({
	  url: "chat.php?action=startchatsession",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;

		jQuery.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxtitle = item.f;
				
				if (item.c!=null && item.c!='' && item.c!=0)
					chatId = item.c;
					
				if (item.u!=null && item.u!='' && item.u!=0)
					chatUserId = item.u;

				if (jQuery("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle,1);
				}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					if (item.m == "askclose007win"){
						
						jQuery('#chatbox_'+chatboxtitle+' .chatboxinput').remove();
						
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">konuşmadan ayrıldı.</span></div>');
						
						if (jQuery('#chatbox_'+chatboxtitle+' #toggleChatBox').length > 0) {
							jQuery('#chatbox_'+chatboxtitle+' #toggleChatBox').css('display','none');
						}
						if (jQuery('#chatbox_'+chatboxtitle+' #endconversation').length > 0) {
							jQuery('#chatbox_'+chatboxtitle+' #endconversation').css('display','none');
						}
						
					}else if (item.m == "askopen007win"){
						
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagecontent">chat\'e başlayabilirsiniz</span></div>');
					
					}else if (item.m == "askopen006win"){
						
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagecontent">chat\'e başlayabilirsiniz.</span></div>');
						
					}else{
					
						jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
						
					}
				}
			}
		});
		
		for (i=0;i<chatBoxes.length;i++) {
			chatboxtitle = chatBoxes[i];
			jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			setTimeout('jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
		}
	
	setTimeout('chatHeartbeat();',chatHeartbeatTime);
		
	}});
} // end function startChatSession

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}; // end jQuery.cookie