/**
 * License info: http://kmi.open.ac.uk/technologies/msg/developer/licenses/ 
 */
/**
 * Initialise the page
 */
function initMSG(authConfigArr, userId, userNickName){
	conf_authConfigArr = authConfigArr;	
	if(userId){
		conf_currentUserId = userId.toString().replace(/@/g,'%') + '@' + MSGAPIconf.msg_host;
	}
	if(userNickName){
		currentUserNickName = userNickName;
	}
	myMSG = new MSGService();
}


/**
 * Displays code etc to display status for current user
 */
function displayMyStatus(){

	var msg_widget = document.getElementById('msg_widget');
	
	var msg_widget_messages = document.createElement('span');
	msg_widget_messages.setAttribute('id','msg_widget_messages');
	msg_widget.appendChild(msg_widget_messages);
	
	var msg_widget_icon = document.createElement('span');
	msg_widget_icon.setAttribute('id','msg_widget_icon');
	
	var a_link = document.createElement('a');
	a_link.setAttribute('href','javascript:launchClick();');
	a_link.setAttribute('title','Launch MSG');
	changeNodeClass(a_link,'presenceicon');
	
	
	var presence_img = document.createElement('img');
	presence_img.setAttribute('src', MSGAPIconf.imgroot + 'offline.png');
	presence_img.setAttribute('alt','Offline');
	presence_img.setAttribute('title','Offline');
	presence_img.setAttribute('height',12);
	presence_img.setAttribute('width',12);
	changeNodeClass(presence_img,'presenceicon');
	a_link.appendChild(presence_img);
	
	msg_widget_icon.appendChild(a_link);
	msg_widget.appendChild(msg_widget_icon)
	
	if(MSGAPIconf.enable_text_notifications == true){
		var msg_widget_text = document.createElement('span');
		msg_widget_text.setAttribute('id','msg_widget_text');
		msg_widget.appendChild(msg_widget_text);
	}
	

	if(MSGAPIconf.enable_popup_notifications == true){
		var msg_widget_popup = document.createElement('span');
		msg_widget_popup.setAttribute('id','msg_widget_popup');
		changeNodeClass(msg_widget_popup,'msgnewmessagepopup');
		msg_widget.appendChild(msg_widget_popup);
		
		var msg_widget_popup_content = document.createElement('span');
		msg_widget_popup_content.setAttribute('id','msg_widget_popup_content');
		msg_widget_popup.appendChild(msg_widget_popup_content);
	}
	
}


function displayMyName(showJid){
	conf_displayNickName = true;
	var show = (showJid == null) ? false: true;
	if(show){
		conf_displayJID = true;
	}
}

/**
 * Update the status text and presence icon
 */
function updateState(id,state){
    
    // get the collection of offline state nodes for user
    var offlineNodes = document.getElementsByName('img_msg_offline_'+id);
	
    // get no instances of node for user - will be same number for offline and online
    var noNodes = offlineNodes.length;
    
    // if this is a page with maps then update the maps markers etc
   	myMSG.curr_id = id;
   	myMSG.curr_state = state;
    myMSG.updateMarkerState();
    
    if(noNodes <=0){
    	return;
    }
    
    // only need to check if the first node has changed (if so all the others will have too) 
    var offlineNodeName = offlineNodes[0].parentNode.getAttribute('id');
    var offlineNode = document.getElementById(offlineNodeName);

    var onlineNodeName = offlineNodes[0].parentNode.getAttribute('id').replace('offline','online');
    var onlineNode = document.getElementById(onlineNodeName);
 
    if(offlineNode){
       
        if(offlineNode.className == 'show'){
            var oldSrc = offlineNode.firstChild.src;
        } else {
            var oldSrc = onlineNode.firstChild.src;
        }
		
        var newSrc = MSGAPIconf.imgroot + state +".png";

        // only need to update image if it's changed - otherwise might get a slightly flickery effect on screen
        if (oldSrc != newSrc){
        
            //update the text panels
            for(var i=0; i < noNodes; i++) {
            	var cNode = offlineNodes[i].parentNode.getAttribute('id').replace('offline','online').replace('span_msg_online','presencetextpanel');
                var textPanel = document.getElementById(cNode);
                
                if (textPanel){
                    textPanel.innerHTML = MSGAPIconf.stateText[state];
                }
            }
            
            // going from offline to one of online states
            if(offlineNode.className == 'show' && state != 'offline'){
                
                myMSG.enableMSGLinks();
                
                if (conf_currentUserId == id){
                    var newTitle = MSGAPIconf.stateText[state];
                } else {
                    var newTitle = MSGAPIconf.stateText[state] + MSGAPIconf.str_clickToChat;
                }

                // loop through for each node instance
                for(i=0; i < noNodes; i++) {
                	var cOffNode = offlineNodes[i].parentNode.getAttribute('id');
                	tempOffNode = document.getElementById(cOffNode);
                	
                	var cOnNode = cOffNode.replace('offline','online')
                    tempOnNode = document.getElementById(cOnNode);

                    var oldImg = tempOnNode.firstChild;
                    var newImg = oldImg.cloneNode(false);

                    newImg.src = newSrc;
                    newImg.title = newTitle;
					
                    tempOnNode.replaceChild(newImg,oldImg);
                    
                    if (id != conf_currentUserId){
	   					// add the click to chat node
	   					if(newImg.addEventListener){ // Mozilla, Netscape, Firefox
							newImg.addEventListener('click', clickToChat, false);
						} else { // IE
							newImg.attachEvent('onclick', clickToChat);
						}
					}
					
   					changeNodeClass(tempOffNode,'hide');  
   					changeNodeClass(tempOnNode,'show'); 
   					
   					// update clicktochat link
   					var cNode = offlineNodes[i].parentNode.getAttribute('id').replace('offline','online').replace('span_msg_online','chatlink');
   					var cToChat = document.getElementById(cNode);
   					if(cToChat){
   						changeNodeClass(cToChat,'showchatlink');
   					} 
                }
                
            // going from an online state to offline
            } else if (offlineNode.className == 'hide' && state == 'offline') {
                
                myMSG.disableMSGLinks();
                
                // loop through for each node instance
                for(i=0; i < noNodes; i++) {
                    var cOffNode = offlineNodes[i].parentNode.getAttribute('id');
                	tempOffNode = document.getElementById(cOffNode);
                	
                	var cOnNode = cOffNode.replace('offline','online')
                    tempOnNode = document.getElementById(cOnNode);
                    
                    var oldImg = tempOffNode.firstChild;
                    
                    // make a clone of existing node (to preserve onclick etc attributes)
                    var newImg = oldImg.cloneNode(false);
                    
                    newImg.src = newSrc;
                    newImg.alt = MSGAPIconf.stateText[state];
                    
                    tempOffNode.replaceChild(newImg,oldImg);
                    
                    changeNodeClass(tempOffNode,'show');  
   					changeNodeClass(tempOnNode,'hide');
   					
   					// update clicktochat link
   					var cNode = offlineNodes[i].parentNode.getAttribute('id').replace('offline','online').replace('span_msg_online','chatlink');
   					var cToChat = document.getElementById(cNode);
   					if(cToChat){
   						changeNodeClass(cToChat,'hidechatlink');
   					} 
                }
            // going from one online state to another
            } else { 
                        
                if (conf_currentUserId == id){
                    var newTitle = MSGAPIconf.stateText[state];
                } else {
                    var newTitle = MSGAPIconf.stateText[state] + MSGAPIconf.str_clickToChat;
                }
                
                // loop through for each node instance
                for(i=0; i < noNodes; i++) {
                    var cOffNode = offlineNodes[i].parentNode.getAttribute('id');
                	tempOffNode = document.getElementById(cOffNode);
                	
                	var cOnNode = cOffNode.replace('offline','online')
                    tempOnNode = document.getElementById(cOnNode);
                    
                    var oldImg = tempOnNode.firstChild;
                    
                    // make a clone of existing node (to preserve onclick etc attributes)
                    var newImg = oldImg.cloneNode(false);
                    
                    // update the src and alt attributes
                    newImg.src = newSrc;
                    newImg.alt = MSGAPIconf.stateText[state];
                    newImg.title = newTitle;
	
                    tempOnNode.replaceChild(newImg,oldImg); 
                    
                    if (id != conf_currentUserId){
	   					// add the click to chat node
	   					if(newImg.addEventListener){ // Mozilla, Netscape, Firefox
							newImg.addEventListener('click', clickToChat, false);
						} else { // IE
							newImg.attachEvent('onclick', clickToChat);
						}
					}
                }         
            }
        }
    }  
}


/**
 * adds a user id to the presences to monitor for this page
 */
function addToMonitorStates(userid){
    monitorStatesArr.push(userid);
}


/**
 * Opens pop up window
 */
function openWindow(url){
    var top = window.screenTop; //IE
    var left = window.screenLeft; //IE
    if (!top) {
        top = window.screenY; //FF
    }
    if (!left) {
        left = window.screenX; //FF
    }
    clientWindow = window.open(url, MSGAPIconf.clientWindowName, "top="+top+",left="+left+"," + MSGAPIconf.clientWindowProps);
    if (clientWindow == null) {
        alert(MSGAPIconf.str_popupBlocked);   
    } else {
        clientWindow.focus();
    }   
}

/**
 *   kills off the peek if it's still running - this fixes a problem in firefox
 *   where if another JSON command is issued, it won't be processed until Peek has completed. 
 */
function killPeek(){
    request = MSGAPIconf.msg_jabberurl + "?command=getstatus&callback=killPeekCallback";
    aObj = new JSONscriptRequest(request);
    aObj.buildScriptTag();
    aObj.addScriptTag();   
}

/**
 * Process return request from killing peek
 */
function killPeekCallback(jData){
    // do nothing at all!   
}

/**
 * Change class of node
 */
function changeNodeClass(node,newClass){
	// hack to get around fact IE won't always add class nodes
	if (node.getAttributeNode("class")){
        for (var i = 0; i < node.attributes.length; i++) {
            var attrName = node.attributes[i].name.toUpperCase();
            if (attrName == 'CLASS') {
                node.attributes[i].value = newClass;
            }
        }
    } else {
        node.setAttribute('class',newClass);
    }
}

function enableMSGLinks(){
	//do nothing
}
function disableMSGLinks(){
	//do nothing
}

/**
 * Enable a link
 */
function enableLink(id,link){

    oldLink = document.getElementById(id);
    if (oldLink != null){
        var parent = oldLink.parentNode;   
        newLink = oldLink.cloneNode(true);
        newLink.href=link;
        newLink.className=null;
        parent.replaceChild(newLink,oldLink);   
    } 
   
}

/**
 * Disable a link
 */
function disableLink(id){
   
    oldLink = document.getElementById(id);
    if (oldLink != null){
        var parent = oldLink.parentNode;   
        newLink = oldLink.cloneNode(true);
        newLink.removeAttribute('href');
        newLink.className="disabled";
        parent.replaceChild(newLink,oldLink);   
    } 
    
}

/**
 * Extract a parameter from the query string
 */
function getQueryParam( name ) {
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var tmpURL = window.location.href;
    var results = regex.exec( tmpURL );
    if( results == null ){
        return "";
    } else {
        return results[1];
    }
}

/**
 * 
 */
function displayUserStatus(userid,instance){
	
	// if it contains an '@' then already full JID, if not then add on the msg_host to make it full JID
	if(userid.indexOf('@') < 0){
		userid = userid + '@'+ MSGAPIconf.msg_host;
	}
	
	// add to monitor states array
	addToMonitorStates(userid);
	
	var instance = (instance == null) ? 1: instance;

	//create the relevant nodes
    var userSpan = document.getElementById("presencenode_"+userid);
    
    var offlineSpan = document.createElement("span");
    offlineSpan.setAttribute('id','span_msg_offline_'+userid + '_'+instance);
    changeNodeClass(offlineSpan,'show');
    
    var offlineImg = document.createElement("img");
    offlineImg.setAttribute('src',MSGAPIconf.imgroot + 'offline.png');
    offlineImg.setAttribute('name','img_msg_offline_'+ userid);
    offlineImg.setAttribute('id','img_msg_offline_' + userid);
    offlineImg.setAttribute('alt','offline');
    offlineImg.setAttribute('title','offline');
    offlineImg.setAttribute('height',12);
    offlineImg.setAttribute('width',12);
    changeNodeClass(offlineImg,'presenceicon_offline');
    
    offlineSpan.appendChild(offlineImg);
    
    userSpan.appendChild(offlineSpan);
    
    var onlineSpan = document.createElement("span");
    onlineSpan.setAttribute('id','span_msg_online_'+ userid + '_'+instance);
    changeNodeClass(onlineSpan,'hide');
    
    var onlineImg = document.createElement("img");
    onlineImg.setAttribute('src',MSGAPIconf.imgroot + 'offline.png');
    onlineImg.setAttribute('name','img_msg_online_'+userid);
    onlineImg.setAttribute('id','img_msg_online_'+userid);
    onlineImg.setAttribute('alt','online');
    onlineImg.setAttribute('title','online');
    onlineImg.setAttribute('height',12);
    onlineImg.setAttribute('width',12);
    changeNodeClass(onlineImg,'presenceicon');
     
    onlineSpan.appendChild(onlineImg);
    
    userSpan.appendChild(onlineSpan);
    
    if(onlineImg.addEventListener){ // Mozilla, Netscape, Firefox
		onlineImg.addEventListener('click', clickToChat, false);
	} else { // IE
		onlineImg.attachEvent('onclick', clickToChat);
	} 
       
}

/**
 * Loads the legend & text depending on current Zoom level
 */
function loadLegend(){
	for(var i=0; i<4; i++){
		var myText = document.getElementById("LegendText"+i);
		myText.innerHTML = "";
		var legendText = document.createTextNode(zoomIcons[getZoomLevel()].threshold[i].text);
		myText.appendChild(legendText);
		
		var legImg = document.getElementById("LegendImage"+i);
		if(legImg){
			legImg.alt = "Icon for " + zoomIcons[getZoomLevel()].threshold[i].text;
			legImg.title = "Icon for " + zoomIcons[getZoomLevel()].threshold[i].text;
		}
	}
}

/**
 *	get the zoom level
 *  (to account for zoom levels outside 0-13 - Google defaults)
 */
 function getZoomLevel(){
 	if(map){
	 	if(map.getZoom() >= 13){
	 		return 13;
	 	}else{
	 		return map.getZoom();
	 	}
 	} else {
 		return zoomLevel;
 	}
 
}
 
/**
 * to toggle sections (show/hide)
 */
 
function toggle(sectionId, toggleTextId, showTitle, hideTitle){
	var currSection = document.getElementById(sectionId);
	var currToggleText = document.getElementById(toggleTextId);
	
	if(currSection.className == 'show'){
		changeNodeClass(currSection,'hide');
		currToggleText.title = showTitle;
		currToggleText.innerHTML = "";
		var newText = document.createTextNode(str_showLabel);
		currToggleText.appendChild(newText);
	} else {
		changeNodeClass(currSection,'show');
		currToggleText.title = hideTitle;
		currToggleText.innerHTML = "";
		var newText = document.createTextNode(str_hideLabel);
		currToggleText.appendChild(newText);
	}
}

// to check if disconnected
function isConnected(retData){
	if(retData.children[0]){
		if(retData.children[0].attributes.code == '2003'){
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	}
	
}

// from: http://homepage.ntlworld.com/bobosola/index.htm
// correctly handle PNG transparency in Win IE 5.5 & 6.
function correctPNG() 
{
   var arVersion = navigator.appVersion.split("MSIE");
   var version = parseFloat(arVersion[1]);
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for (var i=0; i < document.images.length; i++)
      {
         var img = document.images[i];
         var imgName = img.src.toUpperCase();
         var imagepart = imgName.substring(imgName.length-11, imgName.length);
         if (imagepart == "01-ICON.PNG" || imagepart == "02-ICON.PNG" || imagepart == "03-ICON.PNG" || imagepart == "04-ICON.PNG")
         {
   
            var imgID = (img.id) ? "id='" + img.id + "' " : "";
            var imgNameAttr = (img.name) ? "name='" + img.name + "' " : "";
            var imgClass = (img.className) ? "class='" + img.className + "' " : "";
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "";
			var imgAlt = (img.alt) ? "alt='" + img.alt + "' " : "";
            var imgStyle = "vertical-align:top; display:inline-block;" + img.style.cssText; 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle;
            if (img.align == "right") imgStyle = "float:right;" + imgStyle;
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
            var strNewHTML = "<span " + imgNameAttr + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\');"
			+ "\"></span>";
            img.outerHTML = strNewHTML;
            i = i - 1; // since we have now removed the current img
         }
      }
   }    
}

/**
 * to determine if a return key was pressed
 */
function keyPressed(event){
	if(event.keyCode == 13){
		return true;
	} else {
		return false;
	}	
}

/**
 * update the username & Jid
 */
function showUserName(name,jid){
	
	var nameTag = document.getElementById("msg_widget_name");
	var html=name;
	
	if (conf_displayJID){
		html += " (" + jid + ")";
	}
	
	if (nameTag){
		nameTag.innerHTML  = html;
	}
}


/**
 * open notification window/text etc
 */
function openMessageNotification(message){

	var popup = document.getElementById('msg_widget_popup');
	if(popup && MSGAPIconf.enable_popup_notifications){
		messageNotificationSlideUp(message);
	}
		
	var textNotif = document.getElementById('msg_widget_text');
	
	if(textNotif && MSGAPIconf.enable_text_notifications){
		textNotif.innerHTML = "";
		var rLink = document.createElement("a");
		if(messagesUnread == 1){
			rLink.setAttribute("href","javascript:readMessageClick();");
		} else {
			rLink.setAttribute("href","javascript:launchClick();closeMessageNotification();");
		}
		var text = document.createTextNode(message);
		rLink.appendChild(text);
		changeNodeClass(rLink,"msgnewmessagetextlink");
		textNotif.appendChild(rLink);
	}
}

/**
 * close popup notification window
 */
function closeMessageNotification(){
	var obj = document.getElementById('msg_widget_popup');
	if(obj){
		messageNotificationSlideDown();
	}
	var textNotif = document.getElementById('msg_widget_text');
	if(textNotif){
		textNotif.innerHTML = "";
	}
	 
}

function resetNoUnread(){
	messagesUnread=0;
	updatePresenceIcon(currentStatus);
}

function messageNotificationSlideUp(message){
	popup = document.getElementById('msg_widget_popup');
	var popupContent = document.getElementById('msg_widget_popup_content');
	if(popupContent){
			popupContent.innerHTML = "";
			
			var image = document.createElement("img");
			image.setAttribute("src",MSGAPIconf.imgroot + "/launch.png");
			popupContent.appendChild(image);
			popupContent.appendChild(document.createTextNode(" "));
			var t = document.createTextNode(message); 
			popupContent.appendChild(t);
			
			var menudiv = document.createElement("div");
			menudiv.setAttribute("id","msg_widget_popup_menu");
			var rLink = document.createElement("a");
			if(messagesUnread == 1){
				rLink.setAttribute("href","javascript:readMessageClick();");
			} else {
				rLink.setAttribute("href","javascript:launchClick();");
			}
			changeNodeClass(rLink,"popuplink");
			var text = document.createTextNode(MSGAPIconf.str_popupRead);
			rLink.appendChild(text);
			menudiv.appendChild(rLink);
			
			menudiv.appendChild(document.createTextNode(" | "));
			
			var cLink = document.createElement("a");
			cLink.setAttribute("href","javascript:closeMessageNotification();resetNoUnread();");
			changeNodeClass(cLink,"popuplink");
			var text = document.createTextNode(MSGAPIconf.str_popupClose);
			cLink.appendChild(text);
			menudiv.appendChild(cLink);
			popupContent.appendChild(menudiv);
			slideUp();
	}	
		
	
}

function slideUp(){
	layer = document.getElementById('msg_widget_popup');
	layer.style.display = "block";

}

function messageNotificationSlideDown(){
	var layer = document.getElementById("msg_widget_popup");
	if(layer){
		layer.style.display = "none";
	}
}


