/* 
 * This is the global C2Call Management Class
 * The C2Call Manager contains the C2ContactManager and the PhoneManager
 * It will also dispatch global events
 */
C2CallManager = function() {
    this.phoneManager = null;
    this.contactManager = null;
    this.callBar = null;
    this.appletFrame = null;
    this.appletName = null;
    this.isInitialized = false;
    this.eventListener = new Array();
	this.displayEventSync = 0;
	this.currency = 'EUR';
	this.callerid = '';
	this.callername = '';
}

C2CallManager.prototype.setAppletInfo = function(frame, name) {
    this.appletFrame = frame;
    this.appletName = name;
}


C2CallManager.prototype.initApplet = function() {
    if (!window.frames[this.appletFrame].document.applets[this.appletName]) { 
        //alert('sipapplet not defined');
        setTimeout(this.initAppletStub(), 1000);
        return;
    }
    var isinit = null;
    try {
        isinit = window.frames[this.appletFrame].document.applets[this.appletName].isInitialized();
    } catch (exception) {
       setTimeout(this.initAppletStub(), 1000);
       return;
    }

    
    if (isinit) {
        //alert('Applet is ready to go!');
        this.phoneManager = new PhoneManager(window.frames[this.appletFrame].document.applets[this.appletName]);
        this.phoneManager.phoneApplet.setDataUpdateScript('notifyDataUpdate');
        this.phoneManager.phoneApplet.setImScript('instantMessage');
        this.phoneManager.phoneApplet.setNotifyScript('notifyCall');
        this.phoneManager.phoneApplet.setPresenceScript('doPresence');
        this.phoneManager.phoneApplet.setOnlineStatusScript('notifyOnlineStatus');
        this.phoneManager.phoneApplet.setCallInfoScript('notifyCallInfo');
        this.phoneManager.phoneApplet.refreshData();

        this.isInitialized = true;
        this.setNavi();
        this.initCallbar();
        this.initContactManager();
        this.phoneManager.handleEvents = true;
        this.phoneManager.checkUserCredits();
		this.phoneManager.addListener('C2CallManager', this);
    }
    else
    {
        setTimeout(this.initAppletStub(), 1000);
    }

}

C2CallManager.prototype.initAppletStub = function () {
    var method = this;

    // Notiere eine Function-Expression, die als Closure wirkt
    var wrapper = function () {
        method.initApplet();
    };

    // Gib die Wrapper-Funktion zurück.
    return wrapper;
}

C2CallManager.prototype.initContactManager = function () {
    if (this.contactManager != null) {
        
        try
        {
            this.contactManager.setPhoneManager(this.phoneManager);
            setTimeout(this.initContactManagerStub(this.contactManager), 500);
        }
        catch (exception) {
            var msg = '';
            for (var i in exception) {
                msg = msg + exception[i] + ' / ';
            }
            alert('Exception initContactManager 1 : ' + msg + ' : ' + exception);
        }
    }
}

C2CallManager.prototype.initContactManagerStub = function (cm) {
    var method = this;
    var contactM = cm;

    // Notiere eine Function-Expression, die als Closure wirkt
    var wrapper = function () {
        contactM.didFinishedLoading();
    };

    // Gib die Wrapper-Funktion zurück.
    return wrapper;
}

C2CallManager.prototype.setContactManager = function(cm) {
    this.contactManager = cm;

    if (this.isInitialized) {
        this.initContactManager();
    } else {
        window.frames[this.appletFrame].location.href = '../faces/callbar/Callbar_v2.jsp';
        setTimeout(this.initAppletStub(), 2000);
    }    
}

C2CallManager.prototype.unsetContactManager = function() {
    this.contactManager = null;
	if(this.phoneManager != null)
	{
		this.phoneManager.removeListener('C2ContactManager');
	}
}

C2CallManager.prototype.setCallbar = function(callbar) {
    this.callBar = callbar;

    if (this.isInitialized) {
        this.initCallbar();
    }    
}

C2CallManager.prototype.initCallbar = function () {
    if (this.callBar != null) {

        try
        {
            this.callBar.setPhoneManager(this.phoneManager);
            setTimeout(this.initCallbarStub(this.callBar), 500);
        }
        catch (exception) {
            var msg = '';
            for (var i in exception) {
                msg = msg + exception[i] + ' / ';
            }
            alert('Exception initCallbar 1 : ' + msg + ' : ' + exception);
        }
    }
}

C2CallManager.prototype.initCallbarStub = function (cb) {
    var method = this;
    var callB = cb;

    // Notiere eine Function-Expression, die als Closure wirkt
    var wrapper = function () {
        callB.didFinishedLoading();
    };

    // Gib die Wrapper-Funktion zurück.
    return wrapper;
}

C2CallManager.prototype.setNavi = function() {
	
	if(this.phoneManager.isUserRegistered() == false)
	{
		parent.ladeNav2Invited();
	}
	else
	{
		parent.ladeNav2Iframe();
	}
	if(this.contactManager != null)
	{
		this.contactManager.getFormHandler('leftPaneTopButtons').selectButton('C2CallContacts', true);
	}
    //parent.resize_jsp();
    setTimeout('c2callManager.setButton()', 500);
}

C2CallManager.prototype.setButton = function() {
    parent.navi1.MM_nbGroup('down','group1','addressbook','images/navi/10_addressbook/navi_05_02_adressbook.gif',1);
}

function initPage() {
//alert("initPage() : c2callManager");
}

C2CallManager.prototype.refreshCallbarHistory = function()
{
    this.callBar.refreshHistory();
}

C2CallManager.prototype.setRegistered = function(wert)
{
    this.phoneManager.registered = wert;
}

C2CallManager.prototype.handleEvent = function(eventSource, eventType, eventObject)
{
    //alert('C2CallManager : '+eventType);
    if (eventType == 'UserCredit') {
		var credit = eventObject.getAttributeValue('Credits');
		var currency = eventObject.getAttributeValue('Currency');

//		alert("Credit: "+credit);
//		alert("Curr: "+currency);

		var newCredit = 0.00;
		var newCurrency = '';

		if(credit != null && credit>0)
		{
			newCredit = credit/10000;
			newCredit = newCredit.toFixed(2);
		}

		if(currency != null && currency != '')
		{
			newCurrency = currency;
		}
		if(credit == '0' && currency == 'EUR')
		{
			this.currency = '';
		}
		else
		{
			this.currency = currency;
		}

		this.showCredits(newCredit+' '+newCurrency);
	}

	if (eventType == 'NotifyCall')
	{
		var userid = eventObject.getElementValue('Caller');
		var status = eventObject.getElementValue('NType');
		var user = eventObject.getElementValue('DisplayName');
		this.callerid = userid;
		this.callername = user;

		if(userid == user && userid.indexOf('+') != -1)
		{
			this.callername = userid;
		}

		if(user=='9bc2858f1194dc1c107')
		{
			this.callername = 'Test Call';
		}

		if(status == 'ring')
		{
			var callstatus = this.phoneManager.phoneApplet.getCallStatus();
			
			if(callstatus == 1)
			{
				// Incoming Call
				status = 'callin';
			}
			else
			{
				// Outgoing Call
				status = 'call';
			}
		}
		this.showCallStatusbar(status);
	}


    if(eventType == 'WriteMessage')
    {
        var frame = parent.iframe.document.URL;
        if (frame.indexOf("C2ContactManager.jsp") == -1)
        {
            parent.navi1.MM_nbGroup('down','group1','addressbook','images/navi/10_addressbook/navi_05_02_adressbook.gif',1);
            var userid = eventObject.getElementValue('User');
            parent.curentuserid=userid;
            parent.messagePane=1;
            parent.iframe.location.href= "../faces/contacts/C2ContactManager.jsp";
        }
        else
        {
            var userid = eventObject.getElementValue('User');
            this.contactManager.showMessagePane(userid);
        }
    }

    if(eventType == 'ShowHistory')
    {
        var frame = parent.iframe.document.URL;
        if (frame.indexOf("C2ContactManager.jsp") == -1)
        {
            if(frame.indexOf("Login_v2.jsp") ==-1)
            {
                parent.navi1.MM_nbGroup('down','group1','addressbook','images/navi/10_addressbook/navi_05_02_adressbook.gif',1);
                parent.historyList=1;
                parent.iframe.location.href= "../faces/contacts/C2ContactManager.jsp";
            }
        }
        else
        {
            this.contactManager.showHistory();
        }
    }
    
    if(eventType == 'SetPriceInfo')
    {
        var left = document.getElementById('masterdiv').offsetLeft+545;
                
        document.getElementById('pricediv').style.left=left+'px';
        
        var price = eventObject.getElementValue('Price');
        document.getElementById('pricediv').style.display='inline';
        document.getElementById('price').innerHTML=price;
        window.setTimeout('hideInfoBox()', 3000);
    }

	if(eventType == 'ShowInfoDiv' && parent.showRegisterBubble == true)
	{
		left = document.getElementById('masterdiv').offsetLeft+254;
        document.getElementById('infodiv').style.left=left+'px';
		document.getElementById('infodiv').style.display='inline';
		//window.setTimeout('hideInfoDiv()',5000);
	}

	if(eventType == 'SetCallbarStatus')
	{
		var status = eventObject.getElementValue('Status');
		if(status == 'showAktForm')
		{
			this.callBar.showAktForm();
		}
		else
		{
			this.callBar.showCallbar(status);
		}
	}

//	if(eventType == 'ShowCallBar')
//	{
//		var mode = eventObject.getElementValue('Mode');
//		if(mode == 'AktForm')
//		{
//			this.callBar.showAktForm();
//		}
//		else
//		{
//			this.callBar.showCallbar(mode);
//		}
//	}

	if(eventType == 'ShowCallStatusBar')
	{
		var mode = eventObject.getElementValue('Mode');
//
//		var frame = parent.iframe.document.URL;
//        if (frame.indexOf("C2ContactManager.jsp") != -1 || frame.indexOf("Login_v2.jsp") != -1 || frame.indexOf("InviteConfirmNotRegistered.jsp") != -1)
//        {
			if(mode == 'hide')
			{
//				this.contactManager.hideCallStatusBar();
				this.hideCallStatusBar();
			}
			else
			{
//				this.contactManager.showCallStatusbar(mode);
				this.showCallStatusbar(mode);
			}
//		}
	}

	if(eventType == 'ShowBubble')
	{
		var name = eventObject.getElementValue('Name');

		if(name == 'register')
		{
			setTimeout(this.showRegisterBubbleStub(),120000);
		}

		if(name == 'takeCall')
		{
			var left = document.getElementById('masterdiv').offsetLeft+425;
			var top = 150;
			if(navigator.appName.indexOf("Explorer") != -1)		//für IE
			{
				top = top+20;
			}
			document.getElementById('takeCall').style.top=top+'px';
			document.getElementById('takeCall').style.left=left+'px';
			document.getElementById('takeCall').style.display='inline';

			//warte dann ausblenden
			setTimeout(this.hideBubbleStub(name),6000);
		}
	}

	if(eventType == 'HideBubble')
	{
		var name = eventObject.getElementValue('Name');
		document.getElementById(name).style.display='none';
	}

	if(eventType == 'ShowCallStatus')
	{
		var ntype = eventObject.getElementValue('NType');
		var status = eventObject.getElementValue('Status');
		
//		if (this.contactManager != null)
//        {
//			this.contactManager.showCallStatus(ntype, status);
			this.showCallStatus(ntype, status);
//		}
	}
}


C2CallManager.prototype.showCallStatus = function(ntype,status)
{
	var connection = document.getElementById('Connection');

	if (ntype == 'CONNECTIONSTATUS' && status == 'ERROR') {
		connection.style.color = 'red';
		connection.innerHTML = 'Error';
	}

	if (ntype == 'CONNECTIONSTATUS' && status == 'CONNECTED') {
		connection.style.color = '#99cc00';
		connection.innerHTML = 'Connected';
	}
}

C2CallManager.prototype.showCredits = function(displayCredit)
{
	var credits = document.getElementById('Credits');

	credits.innerHTML = displayCredit;//parent.credits+' '+this.currency;
}

C2CallManager.prototype.handleCallStatusBarButtons = function(btnName, formId)
{
	if (formId == 'callStatusbar_call')
	{
		if (btnName == 'HangUp')
		{
			//Callbar umswitchen
			this.callBar.showAktForm();

			this.phoneManager.hangUpCall();
			this.hideCallStatusBar();
		}

		if (btnName == 'Minimize')
		{
			this.hideCallStatusBar();
			this.contactManager.showBubble('TakeCall');
		}
	}

	if (formId == 'callStatusbar_callin')
	{
		if (btnName == 'Take')
		{
			//Callbar umswitchen
			this.callBar.showCallbar('Call');

			this.showCallStatusbar('call');
			this.phoneManager.takeCall();
		}

		if (btnName == 'Reject')
		{
			//Callbar umswitchen
			this.callBar.showAktForm();

			this.phoneManager.rejectCall();
			this.hideCallStatusBar();
		}

		if (btnName == 'HangUp')
		{
			//Callbar umswitchen
			this.callBar.showAktForm();

			this.phoneManager.hangUpCall();
			this.hideCallStatusBar();
		}

		if (btnName == 'Minimize')
		{
			this.hideCallStatusBar();
			this.contactManager.showBubble('TakeCall');
		}
	}
}

C2CallManager.prototype.repositionCallStatusbar = function()
{
	var callStatusbar_callin = document.getElementById('callStatusbar_callin');
	var callStatusbar_call = document.getElementById('callStatusbar_call');
	var top=0;
	var left=0;
	if(navigator.appName.indexOf("Explorer") != -1)
	{
		top = (document.body.clientHeight/2)-150;
		left = (document.body.clientWidth/2)-150;
	}
	else
	{
		top = (window.innerHeight/2)-75;
		left = (window.innerWidth/2)-150;
	}

	callStatusbar_callin.style.top = top+'px';
	callStatusbar_callin.style.left = left+'px';
	callStatusbar_call.style.top = top+'px';
	callStatusbar_call.style.left = left+'px';
}

C2CallManager.prototype.showCallStatusbar = function(status)
{
	var callStatusbar_callin = document.getElementById('callStatusbar_callin');
	var callStatusbar_call = document.getElementById('callStatusbar_call');

	var stStatus = document.getElementById('StStatus');
	var callMessage_callin = document.getElementById('CallMessage_callin');
	var callMessage_call = document.getElementById('CallMessage_call');
	var connection = document.getElementById('Connection');
	var credits = document.getElementById('Credits');

	//Buttons
	var hangUp = document.getElementById('HangUp');

	if(this.contactManager != null)
	{
		this.contactManager.hideBubble('All'); // Alle Bubbles ausblenden
	}
	if(status=='hangup')
	{
		hangUp.style.display = 'none';
		stStatus.style.display = 'none';

		callMessage_callin.innerHTML = 'Hung Up.';
		callMessage_call.innerHTML = 'Hung Up.';
		connection.innerHTML = '';
		credits.innerHTML = parent.credits+' '+this.currency;
		this.repositionCallStatusbar();
		callStatusbar_callin.style.display = 'none';
		callStatusbar_call.style.display = 'inline';
		setTimeout(this.hideCallStatusBarStub(this.displayEventSync),6000);
	}
	else
	{
		if(status=='busy')
		{
			hangUp.style.display = 'inline';
			stStatus.style.display = 'none';

			callMessage_callin.innerHTML = 'Busy.';
			callMessage_call.innerHTML = 'Busy.';
			connection.innerHTML = '';
			credits.innerHTML = parent.credits+' '+this.currency;
			this.repositionCallStatusbar();
			callStatusbar_callin.style.display = 'none';
			callStatusbar_call.style.display = 'inline';
			setTimeout(this.hideCallStatusBarStub(this.displayEventSync),6000);
		}
		else
		{
			if (status == 'notavailable')
			{
				hangUp.style.display = 'none';
				stStatus.style.display = 'none';

				callMessage_callin.innerHTML = 'Not available.';
				callMessage_call.innerHTML = 'Not available.';
				connection.innerHTML = '';
				credits.innerHTML = parent.credits+' '+this.currency;
				this.repositionCallStatusbar();
				callStatusbar_callin.style.display = 'none';
				callStatusbar_call.style.display = 'inline';
				setTimeout(this.hideCallStatusBarStub(this.displayEventSync),6000);
			}
			else
			{
				if (status == 'rejected')
				{
					hangUp.style.display = 'none';
					stStatus.style.display = 'none';

					callMessage_callin.innerHTML = 'Call rejected.';
					callMessage_call.innerHTML = 'Call rejected.';
					connection.innerHTML = '';
					credits.innerHTML = parent.credits+' '+this.currency;
					this.repositionCallStatusbar();
					callStatusbar_callin.style.display = 'none';
					callStatusbar_call.style.display = 'inline';
					setTimeout(this.hideCallStatusBarStub(this.displayEventSync),6000);
				}
				else
				{
					if (status == 'error')
					{
						var credit = this.phoneManager.userCredit.getAttributeValue('Credits');

						if(credit == 0)
						{
							hangUp.style.display = 'none';
							stStatus.style.display = 'none';

							callMessage_callin.innerHTML = 'Not enough credits.';
							callMessage_call.innerHTML = 'Not enough credits.';
							connection.innerHTML = '';
							credits.innerHTML = parent.credits+' '+this.currency;
							this.repositionCallStatusbar();
							callStatusbar_callin.style.display = 'none';
							callStatusbar_call.style.display = 'inline';
							setTimeout(this.hideCallStatusBarStub(this.displayEventSync),6000);
						}
						else
						{
							hangUp.style.display = 'none';
							stStatus.style.display = 'none';

							callMessage_callin.innerHTML = 'An error occured.';
							callMessage_call.innerHTML = 'An error occured.';
							connection.innerHTML = '';
							credits.innerHTML = parent.credits+' '+this.currency;
							this.repositionCallStatusbar();
							callStatusbar_callin.style.display = 'none';
							callStatusbar_call.style.display = 'inline';
							setTimeout(this.hideCallStatusBarStub(this.displayEventSync),6000);
						}
					}
					else
					{
						if (status == 'callin')
						{
							this.displayEventSync++;
							if(this.callername == '')
							{
								callMessage_callin.innerHTML = 'Incoming call.';
								callMessage_call.innerHTML = 'Incoming call.';
							}
							else
							{
								callMessage_callin.innerHTML = this.callername+' is calling.';
								callMessage_call.innerHTML = this.callername+' is calling.';
							}
							this.repositionCallStatusbar();
							callStatusbar_call.style.display = 'none';
							callStatusbar_callin.style.display = 'inline';
						}
						else
						{
							if (status == 'call')
							{
								this.displayEventSync++;
								hangUp.style.display = 'inline';
								stStatus.style.display = 'inline';

								callMessage_callin.innerHTML = this.callername;
								callMessage_call.innerHTML = this.callername;
								connection.innerHTML = '';
								credits.innerHTML = parent.credits+' '+this.currency;
								this.repositionCallStatusbar();
								callStatusbar_callin.style.display = 'none';
								callStatusbar_call.style.display = 'inline';
							}
						}
					}
				}
			}
		}
	}
}

C2CallManager.prototype.hideCallStatusBar = function()
{
	var callStatusbar_callin = document.getElementById('callStatusbar_callin');
	var callStatusbar_call = document.getElementById('callStatusbar_call');
	
	callStatusbar_callin.style.display = 'none';
	callStatusbar_call.style.display = 'none';
}

C2CallManager.prototype.hideCallStatusBarStub = function (eventNumber) {
	var method = this;
	var number = eventNumber;

	// Notiere eine Function-Expression, die als Closure wirkt
	var wrapper = function (evt) {
		if (method.checkEventNumber(number)) {
			method.hideCallStatusBar();
		}
	};

	// Gib die Wrapper-Funktion zurück.
	return wrapper;
}

C2CallManager.prototype.checkEventNumber = function(number) {
	if (this.displayEventSync == number) {
		return true;
	}

	return false;
}





C2CallManager.prototype.hideRegisterBubbleStub = function()
{
	var method = this;

	// Notiere eine Function-Expression, die als Closure wirkt
	var wrapper = function (evt) {
		method.hideRegisterBubble();
	};

	// Gib die Wrapper-Funktion zurück.
	return wrapper;
}

C2CallManager.prototype.showRegisterBubbleStub = function()
{
	var method = this;

	// Notiere eine Function-Expression, die als Closure wirkt
	var wrapper = function (evt) {
		method.showRegisterBubble();
	};

	// Gib die Wrapper-Funktion zurück.
	return wrapper;
}

C2CallManager.prototype.showRegisterBubble = function()
{
	if(parent.showRegisterBubble == true)
	{
		if(this.contactManager != null)	//ggf. alle anderen bubbles ausblenden
		{
			this.contactManager.hideBubble('All');
		}

		var left = document.getElementById('masterdiv').offsetLeft+100;
		var top = 360;
		if(navigator.appName.indexOf("Explorer") != -1)		//für IE
		{
			top = top+20;
		}
		document.getElementById('registerBubble').style.top=top+'px';
		document.getElementById('registerBubble').style.left=left+'px';
		document.getElementById('registerBubble').style.display='inline';
		setTimeout(this.hideRegisterBubbleStub(),30000);
	}
	else
	{
		this.hideBubble('register');
	}
}

C2CallManager.prototype.hideRegisterBubble = function()
{
	document.getElementById('registerBubble').style.display='none';
	//setTimeout(this.showRegisterBubbleStub(),300000);
}

C2CallManager.prototype.refresCallbarCredits = function()
{
	this.phoneManager.checkUserCredits();
}

C2CallManager.prototype.hideBubbleStub = function(name)
{
	var method = this;

	// Notiere eine Function-Expression, die als Closure wirkt
	var wrapper = function (evt) {
		method.hideBubble(name);
	};

	// Gib die Wrapper-Funktion zurück.
	return wrapper;
}

C2CallManager.prototype.hideBubble = function(name)
{
	document.getElementById(name).style.display='none';
}

function hideInfoDiv()
{
    document.getElementById('infodiv').style.display='none';
}

function hideInfoBox()
{
    document.getElementById('pricediv').style.display='none';
}

C2CallManager.prototype.refreshCallbarStatus = function(vorname, nachname) {
    this.callBar.refreshUserName(vorname, nachname);
}