/*
Copyright (c) 2009 Anant Garg (anantgarg.com | inscripts.com)

This script may be used for non-commercial purposes only. For any
commercial purposes, please contact the author at 
anant.garg@inscripts.com

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
/*$(window).scroll(function() {
	if($.browser.msie){
	    $('.chatbox').css('top', ($('#chatBar').offset().top-282) + "px");
	}
});*/

var windowFocus = true;
var activeuser;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 2000;
var maxChatHeartbeat = 33000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;

var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();

function startChat(){
	originalTitle = document.title;
	startChatSession();
	chatOff=false;
	$([window, document]).blur(function(){windowFocus = false;}).focus(function(){	windowFocus = true;document.title = originalTitle;});
}

function chatWith(id) {
	$.post("chatTime.php?action=closechat", {} , function(data){	
		if(parseInt(data)>10){aSk('ASKemailUs',{'say':'Instant chat is currently offline, send us a message here and we will respond by email soon.'});
		}else{	createChatBox(id);	$("#chatbox_"+id+" .chatboxtextarea").focus();}
	});
}

function restructureChatBoxes() {
	qty=0;
	for (x in chatBoxes) {
		if ($("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
			if (qty == 0) {
				var width=0;
			} else {
				var width =(qty*(270));
			}
			$("#chatbox_"+chatBoxes[x]).css('right', width+'px');
			qty++;
		}
	}
}

function createChatBox(id,minimizeChatBox) {
	if ($("#chatbox_"+id).length > 0) {
		if ($("#chatbox_"+id).css('display') == 'none') {
			$("#chatbox_"+id).css('display','block');
			restructureChatBoxes();
		}
		$("#chatbox_"+id+" .chatboxtextarea").focus();
		return;
	}
	$(" <div />" ).attr("id","chatbox_"+id)
	.addClass("chatbox")
	.html('<div class="chatboxhead"><div class="chatboxtitle"><img src="img/tidychat.png" /></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+id+'\')"><img src="img/dynMsgMinimize.png" /></a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+id+'\')"><img src="img/dynMsgClose.png" /></a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+id+'\');"></textarea></div>')
	.appendTo($( "body" ));
	if($.browser.msie){
		$("#chatbox_"+id).css('top', ($('#chatBar').offset().top-282)+'px' );
	}else{
		$("#chatbox_"+id).css('bottom', '0px' );
	}

	chatBoxeslength = 0;
	//alert($.toJSON(chatBoxes))
	if(chatBoxes.length>0){
		for (x in chatBoxes) {var disp=$("#chatbox_"+chatBoxes[x]).css('display');		if (disp != 'none'&&typeof(disp) != 'undefined') {			chatBoxeslength++;		}	}
	}
//	if (chatBoxeslength == 0) {
//		var width=0;
//	} else {

var width=(chatBoxeslength*(270));
//	}
	$("#chatbox_"+id).css('right', width+'px');
	
	chatBoxes.push(id);

	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		if ($.cookie('chatbox_minimized')) {
			minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
		}
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == id) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			$('#chatbox_'+id+' .chatboxcontent').css('display','none');
			$('#chatbox_'+id+' .chatboxinput').css('display','none');
		}
	}

	chatboxFocus[id] = false;

	$("#chatbox_"+id+" .chatboxtextarea").blur(function(){
		chatboxFocus[id] = false;
		$("#chatbox_"+id+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[id] = true;
		newMessages[id] = false;
		$('#chatbox_'+id+' .chatboxhead').removeClass('chatboxblink');
		$('#chatbox_'+id+' .chatboxcontent').removeClass('chatboxblink');
		$("#chatbox_"+id+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});

	$("#chatbox_"+id).click(function() {
		if ($('#chatbox_'+id+' .chatboxcontent').css('display') != 'none') {
			$("#chatbox_"+id+" .chatboxtextarea").focus();
		}
	});

	$("#chatbox_"+id).show();
//alert('createChatBox');
}
function playSound() {
 document.getElementById("chatBar").innerHTML=
 "<embed src=\"tidychat.m3u\" hidden=\"true\" autostart=\"true\" loop=\"false\" type=\""+getMimeType()+"\"/>";
 }
 
/*function playSound() {
    var element = document.getElementById('chatBar');
    element.innerHTML = '<embed src="tidychat.m3u" autostart="0" loop="0" height="45" width="170" type="'+getMimeType()+'"></embed>';
}
*/
function getMimeType(){
var mimeType = "application/x-mplayer2"; //default
var agt=navigator.userAgent.toLowerCase();
if (navigator.mimeTypes && agt.indexOf("windows")==-1) {
//non-IE, no-Windows
  var plugin=navigator.mimeTypes["audio/mpeg"].enabledPlugin;
  if (plugin) mimeType="audio/mpeg" //Mac/Safari & Linux/FFox
}//end no-Windows
return mimeType
}

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 = 'Tidy Chat says...';//newMessagesFrom[x]+
					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
				$('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
				$('#chatbox_'+x+' .chatboxcontent').toggleClass('chatboxblink');
			}
		}
	}
//
	$.get("jq/chat/chat.php",{action:'chatheartbeat'},
  	function(data){

		//$('#helpme').prepend(data+'<br /><br />');
		var data=$.evalJSON(data);

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				playSound();	
//alert(item.id);
				chatboxtitle = item.id;
				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(item.id);//item.name,
				}
				if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
					$("#chatbox_"+chatboxtitle).css('display','block');
					restructureChatBoxes();
				}
				/*if (item.status == 1) {
					//is ativeuser set? add auid
					item.name = activeuser;
				}*/
				if (item.status == 2) {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.msg+'</span></div>');
				} else {
					if (item.status == 1) {					item.name='SENT';			}else{item.name='RECD';}
					newMessages[chatboxtitle] = true;
					newMessagesWin[chatboxtitle] = true;
					//newMessagesFrom[chatboxtitle]=item.name;
					//'+unescape(item.name)+':&nbsp;&nbsp;
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.name+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.msg+'</span></div>');
				}
$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				itemsfound += 1;
			}
});

//alert($.toJSON(data));
if(data.chatDate>10&&chatOff==false){
	chatOff=true;
	$(".chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">Tidy:&nbsp;&nbsp;</span><span class="chatboxmessagecontent">OFFLINE</span></div>');
	$(".chatboxinput").html('<a href="#" onclick="aSk(\'ASKemailUs\',{}); return false;"><p class="red">All Tidy operators are currently offline, click here to send us an email.</p></a>');
//<div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+id+'\');"></textarea></div>

}else if(data.chatDate<10&&chatOff==true){
	chatOff=false;
	
	
	$(".chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">Tidy:&nbsp;&nbsp;</span><span class="chatboxmessagecontent">ONLINE</span></div>');	


	$.each(chatBoxes, function(i,id){
		$("#chatbox_"+id+" .chatboxinput").html('<textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+id+'\');"></textarea>');
	});
//	'#chatbox_'+id+'
	
//'+id+'
}


chatHeartbeatCount++;
	if (itemsfound > 0) {
	chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;
	} else if (chatHeartbeatCount >= 10) {
		chatHeartbeatTime *= 2;
		chatHeartbeatCount = 1;
		if (chatHeartbeatTime > maxChatHeartbeat) {
			chatHeartbeatTime = maxChatHeartbeat;
		}
	}
//alert(chatHeartbeatTime);		
	setTimeout('chatHeartbeat();',chatHeartbeatTime);
	});
//alert('end');
}

function closeChatBox(chatboxtitle) {
	$('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes();

	$.post("jq/chat/chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){	
	});

}

function toggleChatBoxGrowth(chatboxtitle) {
	if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if ($.cookie('chatbox_minimized')) {
			minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		$.cookie('chatbox_minimized', newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if ($.cookie('chatbox_minimized')) {
			newCookie += '|'+$.cookie('chatbox_minimized');
		}


		$.cookie('chatbox_minimized',newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
	}
	
}

function checkChatBoxInputKey(event,chatboxtextarea,id) {
	
	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = $(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");

		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		$(chatboxtextarea).css('height','44px');
		if (message != '') {
			$.post("jq/chat/chat.php?action=sendchat", {to: id, message: message} , function(data){
			if(data.length>0){ alert(data);}
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				//'+unescape(activeuser)+'
				$("#chatbox_"+id+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">SENT:&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
				$("#chatbox_"+id+" .chatboxcontent").scrollTop($("#chatbox_"+id+" .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)
			$(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		$(chatboxtextarea).css('overflow','auto');
	}
	 
}

function startChatSession(){  
//alert('startchatsession');

	$.get("jq/chat/chat.php",{action:'startchatsession'},
  	function(data){


		var da=$.evalJSON(data);

$.each(da['items'], function(i,item){
	//		alert($.toJSON(item))
			if (item)	{ // fix strange ie bug
				chatboxtitle = item.id;//item.name,
				if ($("#chatbox_"+chatboxtitle).length <= 0) {					createChatBox(item.id,1);				}
//				if (item.status == 1) {					item.name=activeuser;			}
				if (item.status == 2) {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.msg+'</span></div>');
				} else {
					//'+unescape(item.name)+'
					if (item.status == 1) {					item.name='SENT';			}else{item.name='RECD';}
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.name+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.msg+'</span></div>');
				}
			}
		});

for (i=0;i<chatBoxes.length;i++) {
			chatboxtitle = chatBoxes[i];
			$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			setTimeout('$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
		}		
		
		setTimeout('chatHeartbeat();',chatHeartbeatTime);	
	});

}

/**
 * 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;
    }
};
