/*
 *	It is of critical importance that this file is referenced inside the <body> tag of every page 
 * 	on your site.  For example: 
 *
 *	<body>
 *	<script src="/userplane/functions.js" type="text/javascript" language="javascript"></script>
 *	
 *	!!! WE HIGHLY RECOMMEND YOU LEAVE up_bDoPresence TO true AND TO IMPLEMENT THE CODE IN ALL php 
 *	PAGES IN THIS FOLDER !!!
 *
 *	Set up_bDoPresence to false if you have your own presence detection and will check for pending WM
 *	windows and call up_launchWM on your own.  If so, you will need to call up_launchWM for every 
 *	pending WM window every time the user changes pages.  Also, you will need to implement the logic 
 *	in the wmWindowOpened.php page to let you know when requests have been denied and also when windows 
 *	have successfully popped up
 */
var up_bDoPresence = true; 
/* 
 *	If you have up_bDoPresence set to true, this is how often (in seconds) we will connect to your 
 *	server via wmLauncher.php or win_ie_pd.php
 *
 * Changed from 30 to 60 seconds 7/14/05
 */
var up_iCheckSeconds = 60; 
var xmlHttp = createXmlHttpRequestObject(); 

//added by tedr. only actually set when a person is receiving a IM request 
var get_subscr;


//TedR built this one to preface convo with chat picker
function openChatWindow(targetUserID, targetPetID, targetPetName, userID, subscr) {
	//alert('>>'+subscr+'<<')
	//open chat confirm window
	var win_width = '';
	var win_height = '';
	var resizable = '';

	//DEPRICATED. WE NO LONGER SHOW ADS SO EVERYONE SEES THE NON-AD VERSION. TEDR 7/14/08
	//if (subscr == 'y') { //at first I considered two siez of window, a bigger one for ad viewers, but now they all get the big window
	//	win_width = 360;
	//	win_height = 560;
	//	resizable = 1;
	//} else {
	//	win_width = 780;
	//	win_height = 640;
	//	resizable = 0;  // non-plus can't resize
	//}
	
	win_width = 360;
	win_height = 560;
	resizable = 1;



	var load = window.open('/im/pick_sender.php?targetID='+targetUserID+'_'+targetPetID+'&targetPetName='+targetPetName+'&targetPetID=' +targetPetID+ '&userID='+userID+'&win_width='+win_width+'&win_height=' +win_height, 'Chat_Win_'+userID+'_'+targetPetID, 'width='+win_width+',height='+win_height+',toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable='+resizable);
}



function up_launchWM( userID, destinationUserID, petID, destinationPetID, name, destinationName, subscr )
{

	var up_localUserID = userID;
	var user_info=userID.split("_");
	var just_userID = user_info[0];
	
	var win_width = '';
	var win_height = '';
	var resizable = '';

	//ADDED BY TEDR 1/17/07 to get subscriber status
	// stores the reference to the XMLHttpRequest object
	if (get_subscr == 'y') {	
		subscr = 'y';
	}
	
	//DEPRICATED. WE NO LONGER SHOW ADS SO EVERYONE SEES THE NON-AD VERSION. TEDR 7/14/08
	//if (subscr == 'y') {
	//	win_width = 360;
	//	win_height = 560;
	//	resizable = 1;
	//} else {
	//	win_width = 720;
	//	win_height = 680;
	//	resizable = 0;  // non-plus can't resize
		//win_width = 360;
		//win_height = 560;
		//resizable = 1;
		//subscr = 'y';
	//}
	win_width = 360;
	win_height = 560;
	resizable = 1;
	
	var popupWindowTest = null;
	//note the userID and destinationID are overload. they each contain the user_id and pet_id seperated by an underscore.
	if (subscr == 'y') { //subscribers get the original IM window
		popupWindowTest = window.open( "/im/wm.php?strDestinationUserID=" + destinationUserID + "&strPetID="+ petID+ "&strDestinationPetID="+ destinationPetID+ "&strUserID="+ userID+'&win_width='+win_width+'&win_height=' +win_height, "WMWindow_" + up_replaceAlpha(userID) + "_" + up_replaceAlpha(destinationUserID), 'width='+win_width+',height='+win_height+',toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable='+resizable );   //height was 397
	} else { //regular members get a framed IM window that shows ads in bottom panel
		popupWindowTest = window.open( "/im/ad_frame.php?strDestinationUserID=" + destinationUserID + "&strPetID="+ petID+ "&strDestinationPetID="+ destinationPetID+ "&strUserID="+ userID+'&win_width='+win_width+'&win_height=' +win_height, "WMWindow_" + up_replaceAlpha(userID) + "_" + up_replaceAlpha(destinationUserID), 'width='+win_width+',height='+win_height+',toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable='+resizable ); 
	}

	if( popupWindowTest == null )
	{
		//alert('show notify');
		up_showWMNotify( userID, destinationUserID, name ); //ted changed this from 'destinationName' to 'name' so IM intro rop box shows initiator's name not recipients
	}
	else
	{
		//alert('clear notify');
		up_clearWMNotify( destinationUserID, false, userID );  //ted added userID
	}
}

function up_showWMNotify( userID, destinationUserID, destinationName )
{
	up_localUserID = userID;
	//alert('localUserID ' +up_localUserID);	
	var bAdd = true;
	//alert('showNotify ' +up_launchArray.length);
	for( var i = 0 ; i < up_launchArray.length ; i++ )
	{
		if( up_launchArray[i].destID == destinationUserID )
		{
			if( destinationName != undefined )
			{
				up_launchArray[i].destName = "<strong>" + destinationName + "</strong>";
			}
			bAdd = false;
		}
	}
	destinationName = destinationName == undefined ? "A website member" : "<strong>" + destinationName + "</strong>";
	
	if( bAdd )
	{
		var userObj = new Object();
		userObj.destID = destinationUserID;
		userObj.destName = destinationName;
		//alert(userObj.destID + userObj.destName);
		up_launchArray.push( userObj );
	}
	up_showNotification();
}

function up_clearWMNotify( clearDestIDs, bForceClear, userIDs )
{
  //added by tedr
	var clearDestID_info=clearDestIDs.split("_");
	var clearDestID = clearDestID_info[0];

	var userID_info=userIDs.split("_");
	var userID = userID_info[0];

	//alert('dest: ' +clearDestID+' user: '+userID);


	var tempArray = up_launchArray;
	up_launchArray = new Array();
	var bRemoved = false;
	//alert('1' + bForceClear+ ' > ' +tempArray.length);
	while( tempArray.length > 0 )
	{
		var userObj = tempArray.pop();
		//alert(userObj.destID + clearDestID);
		if( userObj.destID != clearDestIDs )
		//if( userObj.destID != userIDs )
		{
			up_launchArray.push( userObj );
		}
		else
		{
			bRemoved = true;
		}
	}
	//alert('2' + bRemoved);
	if( bRemoved || !bForceClear )
	{
		if( bForceClear )
		{
			//alert('bForceClear:' +  userID);
			frames['up_wmReject'].location.href = "/im/cmd.php?strDestinationUserID=" + userID + "&refresh=" + Math.floor( Math.random() * 100000000000 );
		}
		//alert('bRemoved:' +  userID);
		frames['up_wmLauncher'].location.href = "/im/wmWindowOpened.php?destinationUserID=" + userID + "&doPresence=" + ( up_bDoPresence && !up_is_win_ie ? "true" : "false" ) + "&forceClear=" + ( bForceClear ? "true" : "false" ) + "&iRefreshInterval=" + up_iCheckSeconds + "&refresh=" + Math.floor( Math.random() * 100000000000 );
	} else {
		alert('neither');
	}
	up_showNotification();
}

function up_showNotification()
{
	var elem = document.getElementById( "up_wmNotifications" );
	if( up_launchArray.length > 0 )
	{

		//ADDED BY TEDR 1/17/07 to get subscriber status. I put here so it has time to get the value.
		//stores the reference to the XMLHttpRequest object
		//the important part is that set's the get_subscr value which is reference in up_launchWM
		getSessionVar();


		//alert('n:  '+up_launchArray[0].destID);
		if( up_displayedNotificationID != up_launchArray[0].destID )
		{
			//alert('local:  '+up_localUserID + 'dest:  '+up_launchArray[0].destID);
			elem.innerHTML = '<div class="up_mbox"><div class="up_mbox1"><div class="up_mbox2"></div></div><div class="up_mboxgut" style="text-align:center">' + ( up_is_win_ie ? '' : '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td align="center">' ) + '<table border="0" cellpadding="2" cellspacing="5"><tr><td nowrap align="center"><strong style="font-size:larger;">Incoming IM Message</strong></td></tr><tr><td align="center">' + unescape(up_launchArray[0].destName) + ' wants to chat.<br>Would you like to accept?</td></tr><tr><td nowrap align="center"><a style="font-size:larger;" href="" onClick="javascript: up_launchWM( \'' + up_localUserID + '\', \'' + up_launchArray[0].destID + '\' ); return false;">Yes</a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a style="font-size:larger;" href="" onClick="javascript: up_clearWMNotify( \'' + up_launchArray[0].destID + '\', true, \'' + up_localUserID + '\' ); return false;">No</a></td></tr></table>' + ( up_is_win_ie ? '' : '</td></tr></table>' ) + '</div><div class="up_mbox3"><div class="up_mbox4"></div></div></div>';
			up_displayedNotificationID = up_launchArray[0].destID;
			up_animate( 30 );
		}
	}
	else
	{
		//alert('r:  '+elem.innerHTML);
		up_displayedNotificationID = "";
		up_animate( -200 );
	}
}

function up_animate( iWhereTo )
{
	var elem = document.getElementById( "up_wmNotifications" );
	if( up_iDivCurrentY != iWhereTo || up_launchArray.length > 0 )
	{
		if( up_iDivCurrentY != iWhereTo )
		{
			up_iDivCurrentY += iWhereTo < up_iDivCurrentY ? -10 : 10;
		}
		
		elem.style.top = up_iDivCurrentY + document.body.scrollTop;
		
		clearTimeout( up_animate_timeoutID );
		up_animate_timeoutID = setTimeout( "up_animate(" + iWhereTo + ")", 33 );
	}
	else
	{
		elem.style.top = iWhereTo;
	}
}

function up_replaceAlpha( strIn )
{
	var strOut = "";
	for( var i = 0 ; i < strIn.length ; i++ )
	{
		var cChar = strIn.charAt(i);
		if( ( cChar >= 'A' && cChar <= 'Z' )
			|| ( cChar >= 'a' && cChar <= 'z' )
			|| ( cChar >= '0' && cChar <= '9' ) )
		{
			strOut += cChar;
		}
		else
		{
			strOut += "_";
		}
	}
	
	return strOut;
}

function up_checkWM()
{
	if( up_is_win_ie )
	{
		up_wmCheckImage = new Image();
		up_wmCheckImage.onLoad = up_onImageLoad();
		up_wmCheckImage.src = "/im/win_ie_pd.php?refresh=" + Math.floor( Math.random() * 100000000000 );
		clearTimeout( up_checkWM_timeoutID );
		up_checkWM_timeoutID = setTimeout("up_checkWM()", 1000 * up_iCheckSeconds);
	}
	else
	{
		frames['up_wmLauncher'].location.href = "/im/wmLauncher.php?iRefreshInterval=" + up_iCheckSeconds + "&refresh=" + Math.floor( Math.random() * 100000000000 );
	}
}

function up_onImageLoad()
{
	if (!up_wmCheckImage.complete)
	{
		clearTimeout( up_onImageLoad_timeoutID );
		up_onImageLoad_timeoutID = setTimeout("up_onImageLoad()", 250);
	}
	else
	{
		if( up_wmCheckImage.height == 2 )
		{
			frames['up_wmLauncher'].location.href = "/im/wmLauncher.php?iRefreshInterval=0&refresh=" + Math.floor( Math.random() * 100000000000 );
		}
		else
		{
			//alert( "Nothing to launch" );
		}
		
		clearTimeout( up_checkWM_timeoutID );
		up_checkWM_timeoutID = setTimeout("up_checkWM()", 1000 * up_iCheckSeconds);
	}
}

document.write( '<style type="text/css">' );
document.write( '.up_mbox { background: #ffffff url(/userplane/images/fbox.gif) repeat-y top right; border: 0; margin: 2px 0 6px 0; padding: 0; }' );
document.write( '.up_mbox1 { background: url(/userplane/images/fbox1.gif) no-repeat top right; height: 8px; font: normal 0px/0px Sans-serif; margin: 0; padding: 0; }' );
document.write( '.up_mbox2 { display: block; background: url(/userplane/images/fbox2.gif) no-repeat top left; height: 8px; width: 8px; font: normal 0px/0px Sans-serif; margin: 0; padding: 0; }' );
document.write( '.up_mbox3 { background: url(/userplane/images/fbox3.gif) no-repeat bottom right; height: 8px; font: normal 0px/0px Sans-serif; margin: 0; padding: 0; }' );
document.write( '.up_mbox4 { display: block; background: url(/userplane/images/fbox4.gif) no-repeat bottom left; height: 8px; width: 8px; font: normal 0px/0px Sans-serif; margin: 0; padding: 0; }' );
document.write( '.up_mboxgut { background: url(/userplane/images/fboxgut.gif) repeat-y top left; font: 11px/18px Verdana, Geneva, Arial, Helvetica, Helve, Sans-serif; margin: 0; padding: 0 10px 0 10px; word-wrap: break-word; }' );
document.write( '</style>' );
document.write( '<iframe name="up_wmLauncher" id="up_wmLauncher" style="position:absolute; top: -200px; z-index:9998; width:100px; height:100px; border: 0px" src=""></iframe>' );
document.write( '<iframe name="up_wmReject" id="up_wmReject" style="position:absolute; top: -200px; z-index:9999; width:100px; height:100px; border: 0px" src=""></iframe>' );
document.write( '<div id="up_wmNotifications" style="position:absolute; width:250px; z-index:9997; left: 30px; top: -200px;"></div>' );
var up_iDivCurrentY = -200;

var up_launchArray = new Array();
var up_localUserID = "";
var up_displayedNotificationID = "";

var up_wmCheckImage = null;
var up_checkWM_timeoutID = null;
var up_onImageLoad_timeoutID = null;
var up_animate_timeoutID = null;

// determine if is Windows IE (up_is_win_ie)
var up_agt 			= navigator.userAgent.toLowerCase();
var up_appVer 		= navigator.appVersion.toLowerCase();
var up_is_mac 		= up_agt.indexOf('mac') != -1;
var up_is_safari 	= up_agt.indexOf('safari') != -1 && up_is_mac;
var up_is_khtml  	= up_is_safari || up_agt.indexOf('konqueror') != -1;
var up_is_ie  	 	= up_appVer.indexOf('msie') != -1 && up_agt.indexOf("opera") == -1 && !up_is_khtml;
var up_is_win   	= up_is_mac ? false : (up_agt.indexOf("win") != -1 || up_agt.indexOf("16bit") != -1);
var up_is_win_ie 	= up_is_win && up_is_ie; 

if( up_bDoPresence )
{
	up_checkWM();
}



// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() 
{	
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // if running Internet Explorer
  if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try 
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
   // alert("Error creating the XMLHttpRequest object.");
	alert("Bummer, there was a problem and IM may not work properly right now");

  else 
  return xmlHttp;
}

function getSessionVar()
{          
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
		xmlHttp.open("GET", "http://www.dogster.com/im/get_subscr_status.php", true);                 
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;
    // make the server request
    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after one second 
    setTimeout('getSessionVar()', 1000);
}
 
// executed automatically when a message is received from the server
function handleServerResponse()
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4)
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200)
    {
      // extract the XML retrieved from the server
			 xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlDocumentElement = xmlResponse.documentElement;
      // get the text message, which is in the first child of
      // the the document element
      var itemArray = xmlDocumentElement.getElementsByTagName("item");
      // remove existing options
			get_subscr = itemArray[0].firstChild.data;
			alert('dogster test2: "'+has_subscr+'" "'+get_subscr+'"');
      return (itemArray[0].firstChild.data);
		}
    else {
      //alert("There was a problem accessing the server: " + xmlHttp.statusText);
			alert("There was a problem and IM may not work properly right now");
    }
  }
}
