
//Frequently checks to see if a pending chat request exists for the user. If it does we display the chat request box. 

//////////////////////////////////////////////////////////
// used in showImPopup(), set true onClick of Red-X and IM-Requests text button
var D = false;

var globImWinClosedByUsr = false;

// Saves names of members that have sent IM Requests
var globCRs = new Array();

// used in showImPopup()
var globWeHaveANewReq = false;
var globLastNumRequestors = -1;

// whether or not there are requests in teh window, don't persist
var globWeHaveReqs = false;

// used in fetchChatDt() (loads the cookie)
var globDtLded = false;

var G_SECONDS_STALE = 130;

var globCookNeedsSaving = false;
var globSavedAnEmpty = false;

// load up from the cookie
fetchChatDt();
//////////////////////////////////////////////////////////


function packUpChatDt() {
	if (D) console.log('packUpChatDt called ************************************************************');
	if (!globCookNeedsSaving) {
		if (D) console.log('in packUpChatDt, NOT SAVING COOKIE.  globCookNeedsSaving is false.');
		return false;
	}
	
	var myData = new Object();
	var sliceGlobCRs = globCRs.slice(0);
	if (!isArray(globCRs)) {
		myData.globCRs = new Array();
	} else {
		myData.globCRs = globCRs.slice(0);
	}
	if (D) console.log('in packUpChatDt: globCRs is: ' + myData.globCRs.toSource());
	
	myData.globImWinClosedByUsr = globImWinClosedByUsr;
	if (D) console.log('in packUpChatDt: globImWinClosedByUsr is: ' + myData.globImWinClosedByUsr.toSource());
		
	myData.globWeHaveANewReq = globWeHaveANewReq;
	if (D) console.log('in packUpChatDt: globWeHaveANewReq is: ' + myData.globWeHaveANewReq.toSource());
	
	myData.globLastNumRequestors = globLastNumRequestors;
	if (D) console.log('in packUpChatDt: globLastNumRequestors is: ' + myData.globLastNumRequestors.toSource());
	
	var pckd = serialize(myData);
	if (D) console.log('in packUpChatDt(), packUpChatDt is : ' + pckd); //////////////////
	
	if (pckd) {
		jQuery.cookie('pkcChtDt',pckd,{path: '/'});
	}
	if (D) console.log('packUpChatDt ENDED ************************************************************');
	
	globCookNeedsSaving = false;
}

function fetchChatDt(force) {
	if (D) console.log('fetchChatDt called.');
	if (!globDtLded || force) {
		var myDataSr = jQuery.cookie('pkcChtDt');

		if (D) console.log('unpckdChtDt!! -> ' + myDataSr); //////////////////
		if (myDataSr) {
			if (D) console.log('in fetchChatDt, myData had data (retrieved from cookie.)');
			if (D) console.log('in fetchChatDt, myData is' + myDataSr);

			myData = eval('('+myDataSr+')');
			globCRs = myData.globCRs.slice(0);
			
			if (D) console.log('in fetchChatDt, globCRs is' + globCRs.toSource());
			
			globImWinClosedByUsr = myData.globImWinClosedByUsr;
			globWeHaveANewReq = myData.globWeHaveANewReq;
			globLastNumRequestors = myData.globLastNumRequestors;
		}
		globDtLded = true;
	}
}

function emptyChatDt() {
	globCRs = new Array();
	globCookNeedsSaving = true;
	if (!globSavedAnEmpty) {
		packUpChatDt();
	}
	globSavedAnEmpty = true;
}

function chatAccept(tuid, reqid, ouid, curl) {
	if (D)
		console.log('chatAccept called.');
	
	var durl = url_for("upchat/ajaxChatAccept");
	
	jQuery.get(durl, {"did":tuid, "rid":reqid}, function(data2) {
		checkChatRequest(ouid, curl, 2000, true);
	}); 
}

function checkChatRequest(uid, url, interval, skipRerun, isInitPageLoad){
//	var tempTr = jQuery('tr.trnone');
    uts = get_unix_timestamp();
    
    if (skipRerun == undefined)
    	skipRerun = false;

	jQuery.get(url, {"uid":uid, "uts":uts}, function(data){   
        // attempt to evaluate JSON data
		try {
			var json_data = eval(data);
		} catch (e) {
		    window.IMCount = 0;
		    
           if (!skipRerun) {
	           setTimeout(function() {
	               checkChatRequest(uid, url, interval);
	           }, interval);
           }
            return false;
		}

		var requestorsThisTime = new Array();
		var requestorsThisTimeReqTimes = new Array();
		
		// if targetId is an actual userId then show chat invitation
		if (json_data.targetId != -1) {
			globWeHaveANewReq = false;
			
		    var wholeTr = jQuery('#trtpl');
		    var trId = wholeTr.html();

		    var tdTime = wholeTr.children('td').get(0);
		    var tdUname = wholeTr.children('td').get(1);
		    var tdImages = wholeTr.children('td').get(2);

		    var outerTable = jQuery('#im-requests');
			outerTable.empty();

			// set the link text on the bottom bar:  im-link
			var imReqLinkTxt = jQuery('#defBtnTxt').html();
			imReqLinkTxt = imReqLinkTxt + " (" + json_data.length + ")";
			jQuery('#im-link').html(imReqLinkTxt);
			
			// now make the link red
			jQuery('#im-link').attr('class','im-link-act');
            
			if (window.IMCount != json_data.length) {
                if (json_data.length > 0)
                    playSound('/assets/manhunt/audio/chatding.mp3');
			
			    window.IMCount = json_data.length;
			}

			for (var i = 0; i < json_data.length; i++) {
			    var newTR = jQuery('<tr></tr>');
				var tuid = json_data[i][0];
				var tunam = json_data[i][1];
				var reqid = json_data[i][2];
				var reqtime = json_data[i][3];
				var host = json_data[i][4];

				var timeTD = jQuery(tdTime).clone();
				
				var xDate = String(reqtime).replace(/\-/g, '/');
				var myDate = new Date(xDate);
				var dateStr = myDate.toLocaleTimeString();
				
				if (D)
					console.log('in checkChatReq ajax: user ' + tunam + ' time is ' + dateStr);
				
				var myEpoch = myDate.getTime()/1000.0;
				
				if (D)
					console.log('in checkChatReq ajax: myEpoch is ' + myEpoch);
				
				// getTimezoneOffset()  js Date object method
				
				// put him in the global list of names	
				requestorsThisTime.push(tunam);
				requestorsThisTimeReqTimes.push(myEpoch);
				
				var timeSpan = "<span class='LocalTime' gmt_time='" + myEpoch + "'>" + reqtime + "</span>";
				var jTimeSpan = jQuery(timeSpan);
				jTimeSpan.localTime('en','timeOnly');
				timeTD.html(jTimeSpan.outerHTML());
				newTR.append(timeTD);
				
				var nameTD = jQuery(tdUname).clone();
				var profLnk = 'profile/' + tunam;
				var tuLink = '<a href="#" onClick="setWindow(\'' + profLnk + '\',\'profile\')">' + tunam + '</a>';
				nameTD.html(tuLink);
				newTR.append(nameTD);
				
				// accept link
				var actionsTdName = reqid + tunam;
				var btnsTD = jQuery(tdImages).clone();
				btnsTD.attr('id',actionsTdName);
				
				var acLink = btnsTD.find('a.chtAccLnk');
				acLink = jQuery(acLink);
				var acceptUrl = 'acceptChatInv(' + reqid + ',' + tuid + ',\'' + tunam + '\', '+ uid + ', \'' + url + '\')';
				acLink.attr('href','#');
				acLink.unbind('click');
//				acLink.attr('click',acceptUrl);

				var acOH = acLink.outerHTML();

				// decline link
				var decLink = btnsTD.find('a.chtDecLnk');
				decLink = jQuery(decLink);
				var declineURL = 'decChatInv(' + reqid + ',' + tuid + ',\'' + tunam + '\', '+ uid + ', \'' + url + '\')';	
				decLink.attr('href','#');
				decLink.unbind('click');
				
				var decOH = decLink.outerHTML();
				decOH = decOH.replace('onclick','test');
				
				var something = " onClick=\"" + declineURL + "\" ";
				
				decOH = decOH.replace('href=',something + 'href=');
				
				btnsTD.html(acOH + " | " + decOH);
				newTR.append(btnsTD);
				outerTable.append(newTR);
				
				// get the "actions" td again, get each <a>
				var foundTrName = '#' + actionsTdName;
				
				//jQuery(foundTrName + ' a.chtAccLnk').unbind('click');
				jQuery(foundTrName + ' a.chtAccLnk').each(function (index, element) {
					element.reqid = reqid;
					element.tuid = tuid;
					element.tunam = tunam;
					element.hostip = host;
				}).bind("click", function(e) {
			      acceptChatInv(this.reqid, this.tuid, this.tunam, this.hostip, uid, url); // use THIS request's information
			    });
			} // end for loop
/*

If you get a new request with freshness=good (req. is not new, but it's < 2min.
don't pop up the window again if the IM Request div is empty (meaning, if this new+fresh request 
is 

*/
			for (var i=0; i<requestorsThisTime.length; i++) {
				var tnm = requestorsThisTime[i];
				
				//var tm = get_unix_timestamp();
				var tm = requestorsThisTimeReqTimes[i];
				var thisRequestor = new chatRequestor(tnm,tm);
if (D) console.log('a');
				/* check if he exists, but the request time now is later than the recorded request time.
					if this is the case, we want to update the request time in the cookie, but NOT pop 
					up the window again if the user has closed it. */
				checkForCurrWFreshness = true;
				callAddRequestor = false;
				if (reqExistsButCurReqIsNew(thisRequestor, checkForCurrWFreshness)) {
if (D) console.log('in checkChatRequest, ' + tnm + ' is in the cookie, but his freshness is good.');
					callAddRequestor = true;
					if (globLastNumRequestors == 0) {
						/* don't pop up the window. globImWinClosedByUsr was set to false when the 
							request div became empty, but because this guy is fresh, don't repop the div. */
						globImWinClosedByUsr = true;  
					}
				} else if (!requestorExists(thisRequestor)) {
if (D) console.log('if '+tnm+' freshness is good, we should never get here.');
if (D) console.log('b');
					globWeHaveANewReq = true;
					globImWinClosedByUsr = false;
					callAddRequestor = true;
				}
				if (callAddRequestor) {
					addRequestor(thisRequestor);
				}
if (D) console.log('c');
			}
			
//			packUpChatDt();
			showImPopup(isInitPageLoad);
			globWeHaveReqs = true;
			globSavedAnEmpty = false;
			globLastNumRequestors = json_data.length;
		// there are no chat requests
		} else {
		    window.IMCount = 0;
		    
			jQuery('#trtpl').hide();
			var newTR = jQuery('tr.trnone:first').clone();
		    var outerTable = jQuery('#im-requests');
			outerTable.empty();
			
			var origTxt = jQuery('#defBtnTxt').html();
			jQuery('#im-link').html(origTxt);
			jQuery('#im-link').removeClass('im-link-act');
			jQuery('#im-link').addClass('im-link-inact');
			
			try {
				outerTable.empty();
				outerTable.append(newTR);
			} catch (e) {
			}
			
			checkShouldCloseImDisplay();
			
			var cookExists = jQuery.cookie('pkcChtDt');
			
			if (!cookExists) {
				if (D) console.log('no cookie exists, so create it empty.');
				emptyChatDt();
			}
			
			globWeHaveReqs = false;
			globImWinClosedByUsr = false;
			globLastNumRequestors = 0;
		}
		
		// re-run itself in the specified interval
		if (!skipRerun) {
	        setTimeout(function() {
	           checkChatRequest(uid, url, interval);
	        }, interval);
		}
	}); // END jQuery.get()
}

function hideImDisplay() {
	var lst = jQuery("#im-list");
	var isDispl = jQuery(lst).css('display');
	
	if (isDispl == 'block')
		lst.slideToggle(700);
}

function checkShouldCloseImDisplay () {
	var noCRs = ""; 
	var hasCRs = "";
	
	try {
		noCRs = jQuery('#im-requests .trnone').html();
	} catch (e) {
	}
	
	if (noCRs != null)
		hideImDisplay();
}

function acceptChatInv (myId, remId, remName, host, ouid, curl) {
	chatAccept(remId, myId, ouid, curl);
	hideImDisplay();
	launchChatWindow(myId, remId, remName, host, true);
}

function decChatInv (myId, remId, remName, ouid, curl) {
	chatAccept(remId, myId, ouid, curl);
	
	var timeStp = 1;
	
	try {
		timeStp = get_unix_timestamp();
	} catch (e) {
	}
	
	var thisRequestor = new chatRequestor(remName,timeStp);
	
	checkShouldCloseImDisplay();
}

function showImPopup (isInitPageLoad) {
	var pp = $("#im-list");
	
	if (!globImWinClosedByUsr || globWeHaveANewReq) {
		if (!imWindowIsOpen()) {
			var toggleSpeed = 700;
			
			if (isInitPageLoad)
				toggleSpeed = 0;
			
			jQuery(pp).slideToggle(toggleSpeed);
		}
		
		globImWinClosedByUsr = false;
	}
}

function imWindowIsOpen() {
	var pp = $("#im-list");
	var shown = jQuery(pp).css('display');
	
	return (shown == 'block');
}

function get_unix_timestamp(){
	return parseInt(new Date().getTime().toString().substring(0, 10));
}

function chatRequestor(name,time) {
	this.name = name;
	this.dateAdded = time;
	
	return this;
}

function dumpGlobCrsArray() {
	var myGlobCRs = globCRs.slice(0);

	alert(globCRs.length);
	if (isArray(myGlobCRs)) {
		myGlobCRs.forEach(function(x){
			if (D) {
				var debstr = 'in dumpGlobCrsArray() ONE: name: ' + x.name + ", dateAdded: " + x.dateAdded;
				if (jQuery.browser.mozilla)
					console.log(debstr);
				else
					alert(debstr);
			}
		});
	}
}

function reqExistsButCurReqIsNew(r,checkForCurrWFreshness) {
	return requestorExists(r,checkForCurrWFreshness);
}

function requestorExists(r,checkForCurrWFreshness) {
	if (D) console.log('requestorExists called.');
	var targName = r.name;
	var foundMatch = false;
	var myGlobCRs = globCRs.slice(0);
	
	for (var j=0; j<myGlobCRs.length; j++) {
		var x = myGlobCRs[j];
		var thisName = x.name;
		
		if (thisName == targName) {
			var cookRecordAddedOn = x.dateAdded;
			var newReqAddedOn = r.dateAdded
			var diff = newReqAddedOn - cookRecordAddedOn;
			if ((diff == 0) && !checkForCurrWFreshness) {
				if (D) console.log('in requestorExists, timeDiff is 0, this is the request that we have already added.');
				foundMatch = true;
			} else if (diff != 0) {
				if (D) console.log('in requestorExists, timeDiff is NOT 0, we should update: newReqAddedOn: ' + newReqAddedOn + ", cookRecordAddedOn: " + cookRecordAddedOn + ", (diff: " + diff + ")");
				/* this would be if the guy IS in the array, AND his recorded addDate is less than the 
					current requests's addDate, but the diff is within the G_SECONDS_STALE limit.  
					Here, we want to update his request time, but not call him "new" so that he would re
					-pop-up the notification window.
				*/
				if(D) console.log('in requestorExists, checkForCurrWFreshness is ' + checkForCurrWFreshness); 
//				if (checkForCurrWFreshness) { // i don't think this is required here
	if(D) console.log('in requestorExists, diff is ' + diff + ' and G_SECONDS_STALE is ' + G_SECONDS_STALE);
	
					if (diff <= G_SECONDS_STALE) // 2:10 minutes:seconds
						foundMatch = true;
//				}
			}
		}
	}
	
	return foundMatch;
}


function addRequestor(r) {
	globCookNeedsSaving = false;
	var doPush = false;
	
	if (D) console.log('addRequestor called: ' + r.name);
	
	var targName = r.name;
	var myGlobCRs = globCRs.slice(0);
	var myOutGlobCRs = new Array();
	var foundRequestor = false;
	for (var j=0; j<myGlobCRs.length; j++) {
		var x = myGlobCRs[j];
		var thisName = x.name;
		if (thisName != targName) {
			myOutGlobCRs.push(x);
		} else {
			foundRequestor = true;
			myOutGlobCRs.push(r);
			globCookNeedsSaving = true;
/*			// check if it's expired
			foundRequestor = true;
			var nnow = get_unix_timestamp();
			var thisAddedOn = x.dateAdded;
			var diff = nnow - thisAddedOn;
			if (diff > G_SECONDS_STALE) { 
				if (D) console.log('in addRequestor: guy to add already existed, but was stale.');
				myOutGlobCRs.push(r);
				globCookNeedsSaving = true;
			} else {
				if (D) console.log('in addRequestor: guy to add already exists, NOT ADDING AGAIN.');
				myOutGlobCRs.push(x);
			}*/
		}
	}

	// if he wasn't found in the existing list, we still need to add him
	if ((myOutGlobCRs.length == 0) || !foundRequestor) {
		myOutGlobCRs.push(r);
		globCookNeedsSaving = true;
	}
	
	if (globCookNeedsSaving) {
		globCRs = myOutGlobCRs.slice(0);
		if (D) console.log('in addRequestor, globImWinClosedByUsr is ' + globImWinClosedByUsr);
		packUpChatDt();
	} else {
		// we didn't change anything, so just ignore myOutGlobCRs, it's the same as globCRs
	}
	// MAYBE TO A COOKIE SAVE HERE ???
}

function delRequestor(reqObj, skipPackUp) {
	if (D) console.log('delRequestor called.');
	if (D) console.log("dump before delRequestor: ");
	if (D) dumpGlobCrsArray();
	
	var targName = reqObj.name;
	var myGlobCRs = globCRs.slice(0);
	var myOutGlobCRs = new Array();
	
	for (var j=0; j<myGlobCRs.length; j++) {
		var x = myGlobCRs[j];
		var thisName = x.name;
		if (thisName != targName) {
			myOutGlobCRs.push(x);
		}
	}
	
	globCRs = myOutGlobCRs.slice(0);
	
	if (!skipPackUp) {
		globCookNeedsSaving = true;
		packUpChatDt();
	}
	
	if (D)
		console.log("dump after delRequestor: ");
	
	if (D)
		dumpGlobCrsArray();
}


function serialize(_obj) {
   if (_obj == null) {
      return false;
   }
   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
      return _obj.toSource();

   // Other browsers must do it the hard way
   switch (typeof _obj) {
      // numbers, booleans, and functions are trivial:
      // just return the object itself since its default .toString()
      // gives us exactly what we want
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;
      // for JSON format, strings need to be wrapped in quotes
      case 'string':
         return '\'' + _obj + '\'';
         break;
      case 'object':
         var str;
         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined') {
            str = '[';
            var i, len = _obj.length;
            for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
            str += serialize(_obj[i]) + ']';
         } else {
            str = '{';
            var key;
            for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
            str = str.replace(/\,$/, '') + '}';
         }
         return str;
         break;
      default:
         return 'UNKNOWN';
         break;
   }
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1) {
      return false;
   } else {
      return true;
   }
}