/// <reference path="Globals.js">
/// <reference path="validationFunctions.js">

var hasFocus = true;
var browserTitle = document.title;
var setTitleToDefault = false;
var lastMsg = "";
var timer = null;

var active_element;
var isIE = navigator.appName.indexOf("Internet Explorer") > -1;
var isOP = navigator.appName.indexOf("Opera") > -1;
var isFF = navigator.userAgent.indexOf("fox") > -1;
var isSF = navigator.userAgent.indexOf("Safari") > -1;


var soundOn = true;

function stopTitleTimer()
{
    if(timer != null)
        window.clearInterval(timer); 
    timer = null;
    document.title = browserTitle; 
    setTitleToDefault = false;
    hasFocus = true;
}

function onWindowFocus()    
{
    hasFocus = true;
}

function onWindowBlur()    
{
    if (isIE && active_element != document.activeElement) 
    {
        active_element = document.activeElement;
        return;
    }
    hasFocus = false;
}

if (!isIE)
{
    Event.observe(window, 'load', function(){setFocusEvents();});
}

function setFocusEvents()
{	
//	if (isIE)
//	{
//      active_element = document.activeElement;
//	    document.body.onfocus 	= function() { onWindowFocus(); } // fires 'focus' :)  <--------
// 	    document.body.onblur  	= function() { onWindowBlur(); } // fires on focus !!!
//	} 
//	else 
	if(isFF)
	{
		/* Firefox */
		window.document.onblur  = function() { onWindowBlur(); } // on Mac, only fires when loosing focus to another window, not app. 
		window.document.onfocus = function() { onWindowFocus();  } // on XP, If clicked on body will fire twice.
		
	} 
	else if(isSF || isOP)
	{
		/* Safari , Opera , OmniWeb */
		window.onblur  = function() { onWindowBlur(); }
		window.onfocus = function() { onWindowFocus(); }
	}

    Event.observe(document, "click", function(){stopTitleTimer()});
    Event.observe(document, "keypress", function(){stopTitleTimer()});
    Event.observe(document, "focus", function(){stopTitleTimer()});
    Event.observe(window, "focus", function(){stopTitleTimer()});
}

////////////////////

//var im = null;
//var winServiceMessage = null;
var winIM = null;

var winArr = new Array(1);
for(var i = 0; i < winArr.length; i++)
    winArr[i] = null;
arrIndex = 0;

function showIM(recipientId, recipientUsername, myName)
{
    openIMpopup(recipientId, recipientUsername, myName);
    getMessage();
}

function checkIfBusy(recipientId, recipientUsername, myName)
{
     var pars = 'recipientId=' + recipientId + "&isAjax=true"; 
     new Ajax.Request(siteRoot + '/Community/IM/CheckIfBusy.aspx',
        {
            parameters: pars,    
            onSuccess: function(t){
                
                if(t.responseText == "Busy")
                {
                    showServiceMessage("Your recipient is busy in another conversation. Please try again later");
                }
                else
                {
                    showIM(recipientId, recipientUsername, myName);
                }
            }
        }); 
}


function soundOnOff()
{
    soundOn = !soundOn;
    var imgSound = $('imgSound');
    var title = soundOn ? "sound on" : "sound off";
    var src = fullSiteRoot + (soundOn ? "/Static/JS/lib/sound/sound_on.gif" : "/Static/JS/lib/sound/sound_off.gif");
    imgSound.title = title;
    imgSound.src = src; 
    //eraseCookie("sound");
    createCookie("sound", "" + soundOn, 100);
    var pars = 'soundOn=' + soundOn + "&isAjax=true";    
    new Ajax.Request(siteRoot + '/Community/IM/Sound.aspx',
        {
            parameters: pars        
        }); 
}

function openIMpopup(recipientId, recipientUsername, myName)
{
    var winWidth = 370;
    var winHeight = 338;
    
    var soundOnFromCookie = readCookie("sound");
    if(soundOnFromCookie == null)
    {
        createCookie("sound", "true", 100);
        soundOnFromCookie = "true";
    } 
    soundOn = soundOnFromCookie.toLowerCase() == "true";
    
    var onOff = soundOn ? "on" : "off";
    
    var imgMarkup = "";
    if(includeSound)
        imgMarkup = '<img id="imgSound" title="sound ' + onOff + '" onclick="soundOnOff()" style="float: right; cursor: pointer; margin-right: 5px" src="' + fullSiteRoot + '/Static/JS/lib/sound/sound_' + onOff + '.gif" />';
    
    var div = '<table style="margin: 0 auto">' +
            '<tr>' +
                '<td>' +
                    '<span style="float: left">Conversation log (with ' + recipientUsername + '): </span>' + 
                    imgMarkup +
                    '<div class="Break">' + 
                    '<div style="width: 349px; padding-top: 5px">' +
                        '<div id="showMessages" style="height: 200px; overflow: auto; border: 1px solid #CBCFD2; padding: 3px; margin-bottom: 5px; background-color: #fff"></div>' +
                    '</div>' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td>' +
                    '<form id="IMForm" action="' + fullSiteRoot + '/Community/IM/SendMessage.aspx" method="post" onsubmit="sendIM(); return false" >' +
                        'Enter your text:' +
                        '<div style="margin-top: 3px; "><textarea id="writeMessage" name="message" style="overflow: auto; width: 345px; height: 34px; border: 1px solid #CBCFD2;"></textarea></div>' +
                        '<div id="ImSendErrorContainer" class="Error Required" style="display: none; text-align: left"></div>' +
    					
                        '<div style="text-align: right; margin-top: 5px">' +
                              
                                     
                                    '<input id="imSubmit" type="submit"' + 
                                    'class="IMbutton" ' +
                                    'onmouseout="MH.changeClass(this, \'IMbutton\')" ' +
                                    'onmouseover="MH.changeClass(this, \'IMbuttonFleep\')" ' +
                                    'value="Send" ' +
                                     ' />' +
                             
                            '<input type="hidden" id="recipientId" name="recipientId" value="' + recipientId + '" />' +
                            '<input type="hidden" id="myName" name="myName" value="' + myName + '" />' +
                        '</div>' +
                       ' </form>' +
               ' </td>' +
            '</tr>' +
        '</table>' ;
   
    if(winArr[arrIndex] == null)
    { 
        
        winArr[arrIndex] = new Window
            ({className: "alphacube", 
            width:winWidth , height:winHeight, 
            title: 'Instant Messaging',
            showEffectOptions: {duration: showEffectDuration}, 
            hideEffectOptions: {duration: hideEffectDuration},
            destroyOnClose: true,
            recenterAuto:false, 
            resizable: false,
            onClose: function() { winArr[arrIndex] = null; closeConversationWindow()},
			minimizable: true,
      		maximizable: true }
            );
    }
    winArr[arrIndex].setHTMLContent(div);
    winArr[arrIndex].showCenter(); 
    setTimeout(function(){$('writeMessage').focus()}, 300);
    setTimeout(function()
        {
            Event.observe($('writeMessage'), 'keypress', sendMessage.bindAsEventListener($('writeMessage')))
        }, 350);
        
    setTimeout(function()
        {
            Event.observe($('imSubmit'), 'click', sendMessage.bindAsEventListener($('imSubmit')))
        }, 350);
    //++arrIndex;
}

function openIM(recipientId, signed, recipientUsername, myName)
{
    if(signed == false)
    {
        showLoginPopup({ registeredOnly : true });
        return;
    }
    checkIfBusy(recipientId, recipientUsername, myName);
}

function getIM()
{

    new Ajax.Request(siteRoot + '/Community/IM/GetIM.aspx',
        {
            onSuccess: function(t){
                if(t.responseText.indexOf("open") == 0)
                {
                    if(winArr[arrIndex] == null)
                    {
                        var tokens = t.responseText.split(":");
                        var id = tokens[1]; 
                        var recipientUserName = tokens[2];
                        var myName = tokens[3];
                        showIM(id, recipientUserName, myName); 
                    }
                }
            }
        });
    var t = setTimeout("getIM()",4000)            
}

function closeConversationWindow()
{
    var recipientId = $('recipientId').value;
    var pars = 'recipientId=' + recipientId + "&isAjax=true";    
    new Ajax.Request(siteRoot + '/Community/IM/CloseConversationWindow.aspx',
        {
            parameters: pars          
            
        }); 
}

function getMessage()
{    
    if(winArr[arrIndex] == null)
        return;

    var recipientId = $('recipientId').value;
    var pars = 'recipientId=' + recipientId + "&isAjax=true"; 
    new Ajax.Request(siteRoot + '/Community/IM/GetMessage.aspx',
        {
            parameters: pars,          
            onSuccess: function(t){
                if(t.responseText != "fail")
                {
                    var showMessages = $('showMessages');
                    var message = t.responseText;
                    var date = new Date();
                    var time = "[" + date.getHours() + ":" + date.getMinutes() + "] ";
                    new Insertion.Bottom(showMessages, "<div class='You'>" + time + message + "</div")
                    showMessages.scrollTop = showMessages.scrollHeight;
                    if(soundOn && includeSound)
                        soundManager.play('oncommingMsg');
                    if(!isIE && !hasFocus)
                    {
                        lastMsg = message;
                        changeBrowserTitleTo();    
                    }
                    
                    var writeMessage = $('writeMessage');
                    if(writeMessage.disabled)
                    {
                        writeMessage.value = "";
                        writeMessage.disabled = false;
                        var imSubmit = $('imSubmit');
                        imSubmit.disabled = false;
                    }
                }
            }
        });    
    var t = setTimeout("getMessage()",2000)    
}

function sendMessage(event)
{
     if(event.keyCode == Event.KEY_RETURN) 
     {   
    
        sendIM()
        event.stop();
    }
}

function sendIM()
{ 
        var Error = {};
        Error.elementToFocus = null;
        Error.found = false;
        
        var myName = $('myName').value;
        var message = $('writeMessage');
        var recipientId = $('recipientId').value;
        var showMessages = $('showMessages');
        
        messageValid = validateNotEmpty(message, 'ImSendErrorContainer', "Please enter a message", Error);
        if(!messageValid)
        {
            message.focus();  
            return false;
        }
        
        new Insertion.Bottom(showMessages, "<div class='MySelf'>" + myName + ": " +  message.value + "</div>");  
        showMessages.scrollTop = showMessages.scrollHeight;
        
        var messageSerialized = encodeURIComponent(message.value);
        var pars = 'recipientId=' + recipientId + "&message=" + messageSerialized + "&isAjax=true"; 
        message.value = ""; 
        message.focus();   
        new Ajax.Request(siteRoot + '/Community/IM/SendMessage.aspx',
            {
                parameters: pars,
                onFailure: function(t){
                    
                },
                onSuccess: function(t){
                    if(t.responseText == "Busy")
                    {
                        message.value = "Your recipient is busy with another user";
                        message.disabled = true;
                        var imSubmit = $('imSubmit');
                        imSubmit.disabled = true;
                    }
                }
            }); 
}

function changeBrowserTitleTo()
{
    if(timer != null)
        window.clearInterval(timer);
    timer = window.setInterval(changeBrowserTitleToWithTimer, 1000);
}  
    
function changeBrowserTitleToWithTimer()
{
    if(setTitleToDefault)
    {
        document.title = browserTitle;
    }
    else
    {
        document.title = lastMsg;
    }
    setTitleToDefault = !setTitleToDefault;
}  