/*

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.

*/

var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
var maxChatHeartbeat = 33000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;
var totPopUps = 0;
var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();
var openChatBoxes = new Array();
var ClosedChatBoxes = new Array();
var closedChatBox = 0;
var j = jQuery.noConflict(); 

 
//j(document).ready(function(){
	 
 
function restructureChatBoxes() {
	align = 0;
	
	for (var x=0;x<chatBoxes.length;x++) {
		chatboxtitle = chatBoxes[x];
		//alert('chatboxtitle '+chatboxtitle);
		if (j("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				j("#chatbox_"+chatboxtitle).css('right', '205px');
			} else {
				width = (align)*(225+7)+205;
				j("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			align++;
		}
	}
}

function chatWith(to_id, to_name, thumbnail, c_type) {
 	//alert('U r going to chatWith :' + to_name + " , to_Id : " + to_id);
	createChatBox(to_id, to_name, thumbnail, c_type);
	j("#chatbox_"+to_id+" .chatboxtextarea").focus();
	//uploadfileforsendfile(to_id,to_name);
	
}
function populateChatMessage(to_id, c_type, message){
	j.ajax({
		type: "POST",
		url: "getchat.jsp",
		data: 	"sid="+JSID+"&to="+to_id+"&MT="+c_type+"&message="+message,
		success: function(html){
			j("#chatbox_"+to_id+" .chatboxcontent").append(html);
			j("#chatbox_"+to_id+" .chatboxcontent").scrollTop(j("#chatbox_"+to_id+" .chatboxcontent")[0].scrollHeight);
		}
	});
	openChatBoxGrowth(to_id);
	//for (var x=0;x<5;x++)  
	//	j("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+chatboxtitle+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">Hi</span></div>');
}
function countChatBox(chatboxtitle){
	//alert('in force close for '+chatboxtitle);
	//alert('in force close contains '+j.inArray(chatboxtitle, openChatBoxes));
	//openChatBoxes.reverse(); 
	//var forceClosed = openChatBoxes.pop(); 
	if(j.inArray(chatboxtitle, openChatBoxes)<0)
		closeChatBox(openChatBoxes[0]);
	//openChatBoxes.reverse(); 
	//alert('forceClosed  '+forceClosed);
	 
	//alert('closedChatBox '+closedChatBox);
	
}
function createChatBox(chatboxtitle, to_name, thumbnail, c_type, minimizeChatBox) {
	
	if (j("#chatbox_"+chatboxtitle).length > 0) 
	{
		if (j("#chatbox_"+chatboxtitle).css('display') == 'none') 
		{
			j("#chatbox_"+chatboxtitle).css('display','block');
			openChatBoxes.push(chatboxtitle);
			closedChatBox--;
			restructureChatBoxes();
		}
		populateChatMessage(chatboxtitle, 'GSM','');
		//j("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		return;
	}
	j(" <div />" ).attr("id","chatbox_"+chatboxtitle)
	.addClass("chatbox")
	.html('<div class="chatboxhead">'+
	'<div class="chatboxheader">'+ 
	'<div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><img src="images/chat/min-btn.png"></a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><img src="images/chat/close-btn.png"></a></div>'+
	'<img src="assets/subscriber/'+thumbnail+'" style="position: absolute; top: 5px; left: 5px; width: 40px;">'+
	'<div style="margin-left: 50px; padding-top: 4px;"><b>'+to_name+' </b></div>'+
	'</div>'+							
	'<div class="chatboxsubheader">'+
//	'<div id="dv_sf_btn'+chatboxtitle+'" style="float:right;padding:3px;"><a href="javascript:uploadfileforsendfile('+chatboxtitle+','+ to_name+');" id="button'+chatboxtitle+'">Send File</a></div>'+
   '<div id="dv_sf_btn_'+chatboxtitle+'" style="float:right;padding:3px;"></div>'+
 //'<div id="dv_ac_btn'+chatboxtitle+'" style="float:right;padding:3px;"><a href="javascript:initvcall('+chatboxtitle+",\'"+to_name+'\',2);" ><img title="Voice Call" src="images/chat/video-call.png"/></a></div>'+
 //'<div id="dv_vc_btn'+chatboxtitle+'" style="float:right;padding:3px;"><a href="javascript:initvcall('+chatboxtitle+",\'"+to_name+'\',1);" ><img title="Video Call" src="images/chat/voice-call.png"/></a></div>'+
 //+'<a href="javascript:upload'+chatboxtitle+'();" style="background-color:#46A7E9;color:#ffffff;font-weight:bold;" id="button'+chatboxtitle+'">Send File</a>'+
	'<input style="margin: -5px 0pt 0pt -175px; padding: 0pt; position: absolute; width: 220px; height: 30px; font-size: 14px; opacity: 0; cursor: pointer; display: none; z-index: 2147483583;" name="userfile" size="10" type="file">'+
	'</div>'+
	'<div class="chatboxvideocontent" id="chatboxvideo'+chatboxtitle+'"><div id="chatvideo'+chatboxtitle+'"></div></div>'+
	'<div class="chatboxcontent"></div>'+
	'<div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></div>')
	.appendTo(j( "body" ));
			   
	j("#chatbox_"+chatboxtitle).css('bottom', '27px');
	
	populateChatMessage(chatboxtitle, 'FM','');
	chatBoxeslength = 0;
	
	for (var x=0;x<chatBoxes.length;x++) {
		if (j("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
			chatBoxeslength++;
		}
	}
	
	
	if (chatBoxeslength == 0) {
		j("#chatbox_"+chatboxtitle).css('right', '205px');
	} else {
		width = (chatBoxeslength)*(225+7)+205;
		j("#chatbox_"+chatboxtitle).css('right', width+'px');
	}
	
	chatBoxes.push(chatboxtitle);
	openChatBoxes.push(chatboxtitle);
	//alert('Af AD openChatBoxes '+openChatBoxes);
	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		if (j.cookie('chatbox_minimized')) {
			minimizedChatBoxes = j.cookie('chatbox_minimized').split(/\|/);
		}
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == chatboxtitle) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			j('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}
	
	chatboxFocus[chatboxtitle] = false;

	j("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
		chatboxFocus[chatboxtitle] = false;
		j("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[chatboxtitle] = true;
		newMessages[chatboxtitle] = false;
		j('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
		j("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});

	j("#chatbox_"+chatboxtitle).click(function() {
		if (j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
			j("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		}
	});

	j("#chatbox_"+chatboxtitle).show();
	

	
}


 

function closeChatBox(chatboxtitle) {
	j('#chatbox_'+chatboxtitle).css('display','none');
	var tt = "chatboxvideo"+chatboxtitle;
		document.getElementById(tt).innerHTML = "";
		document.getElementById(tt).style.height = "0px";
		JavaChat.CancelVChat(JSID);
		
	closedChatBox++;
	//alert(chatboxtitle);
 	//alert('index '+j.inArray(chatboxtitle, openChatBoxes));
	openChatBoxes.splice(j.inArray(chatboxtitle, openChatBoxes), 1);
	//alert('after close '+openChatBoxes);
 	
	restructureChatBoxes();

	j.post("chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){	
	});
}

function toggleChatBoxGrowth(chatboxtitle) {
	if (j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if (j.cookie('chatbox_minimized')) {
			minimizedChatBoxes = j.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		j.cookie('chatbox_minimized', newCookie);
		
		j('#chatbox_'+chatboxtitle+' .chatboxsubheader').css('display','block');
		j('#chatbox_'+chatboxtitle+' .chatboxvideocontent').css('display','block');
		j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		j('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		j("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(j("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if (j.cookie('chatbox_minimized')) {
			newCookie += '|'+j.cookie('chatbox_minimized');
		}


		j.cookie('chatbox_minimized',newCookie);
		var tt = "chatboxvideo"+chatboxtitle;
		document.getElementById(tt).innerHTML = "";
		document.getElementById(tt).style.height = "0px";
		JavaChat.CancelVChat(JSID);
		j('#chatbox_'+chatboxtitle+' .chatboxsubheader').css('display','none');
		j('#chatbox_'+chatboxtitle+' .chatboxvideocontent').css('display','none');
		j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		j('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
	}
	
}
function openChatBoxGrowth(chatboxtitle) {
	if (j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if (j.cookie('chatbox_minimized')) {
			minimizedChatBoxes = j.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		j.cookie('chatbox_minimized', newCookie);
		j('#chatbox_'+chatboxtitle+' .chatboxsubheader').css('display','block');
		j('#chatbox_'+chatboxtitle+' .chatboxvideocontent').css('display','block');
		j('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		j('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		j("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(j("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	}
	
}

function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {
	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = j(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");
		j(chatboxtextarea).val('');
		j(chatboxtextarea).focus();
		if (message != '') {
			populateChatMessage(chatboxtitle, 'SSM',message);
			setTimeout('JavaChat.sendPrivateMessage('+JSID+','+chatboxtitle+')');
		}
		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)
			j(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		j(chatboxtextarea).css('overflow','auto');
	}
	 
}

function startChatSession(){  
	j.ajax({
	  url: "chat.php?action=startchatsession",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;

		j.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxtitle = item.f;

				if (j("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle,1);
				}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					j("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					j("#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];
			j("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(j("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			setTimeout('j("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(j("#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;
    }
};
//});
