var contactMePanel;
var contactMeTabs;
var closeContactMePanel;
var currentContactPanel = -1;
var callSessionId;
var callWS;

function initContactMePanel() {


closeContactMePanel = function() {
    currentContactPanel = -1;
    resetContactMePanel();
  };

  contactMePanel = new YAHOO.widget.Panel("contactMePanel_YUI", 
    { width : "525px",
      height: "370px",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      close : true, 
      draggable : true,
      modal: false,
      effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3}
    } );

  contactMeTabs = new YAHOO.widget.TabView("contactMe_tabs");
  //setContactMeBody("ContactMeInvite");
  contactMePanel.render();
  contactMePanel.beforeHideEvent.subscribe(closeContactMePanel);
	removeClassName( contactMePanel.innerElement, 'displayNone' );
  return true;
}


/**
 * When the user is not logged in, show sign in dialog.
 */
function notLoggedInDialog() {
    //TODO to implement
}


/**
 * Toggle display of the contactMe Panel.
 */
function toggleContactMePanel(provider) {
  if( currentContactPanel == provider ) {
    currentContactPanel = -1;
    contactMePanel.hide();
  } else {
    if(!contactMePanel){
        initContactMePanel();
    }
    currentContactPanel = provider;
    contactMePanel.show();
    setTimeout("canShowCallTab('"+provider+"')", 100);
    contactChat(provider);
  }
}

/**
 * Reset Panel 
 */
function resetContactMePanel() {
	if (contactMePanel) {
		// reset any clicked radio buttons
		i = 0;
		while($('existing'+ i)) {
			$('existing'+ i++).checked = false;
		}

		$('inviteContent').style.display = '';
		$('inviteSuccessMessage').style.display = '';
		$('inviteFailureMessage').style.display = 'none';
	}
}

function cancelContactMe(){
	if(contactMePanel){
		currentContactPanel = -1;
		callSessionId=null;
		callWS=null;
		contactMePanel.hide();
		resetContactMePanel();
	}
}

function setContactMeBody(tab){
if(contactMePanel){
    contactMePanel.setHeader($(tab+'Header').innerHTML);
    contactMePanel.setBody($(tab+'Body').innerHTML);
}
}

function activateTab(index){
if(contactMeTabs.getTab(index))
    contactMeTabs.set('activeIndex',index);
}

//Chat related functions

var pcajax;
function contactChat(username){
    if(currentContactPanel == username){
        pcajax =  new Ajax.Updater('contactchat', '/php/myelance/main/chat.php?ctx=profile&mode=check&view_person='+username+'&t='+getDateTime(), {method:'get'});
        setTimeout("contactChat('"+username+"')", 30000);
    }
}


function chatWin( thisLink ) {
            var comwin = window.open(thisLink,'','width=815,height=615,scrollbars=0,resizable=0');
                        comwin.focus();
}

//Call related functions


function canShowCallTab(username){
 var url = "/php/myelance/main/call.php?ctx=contactMe&mode=check&view_person="+username+'&t='+getDateTime();
   new Ajax.Request(url, {
           method: 'get',
           onSuccess: callCheckSuccess,
           onFailure: callCheckFailure
       });
}

function callCheckSuccess(tspt){
    if(tspt.responseText.length==1 && tspt.responseText!=1){
        var tab = contactMeTabs.getTab(2);
        if(tab){
             contactMeTabs.removeTab(tab);
        }
        
    }
}

function callCheckFailure(){
   //do nothing, in good faith. 
}
var URL_BASE;
function connectCall(from_phone, username, url_base){
    URL_BASE = url_base;
    clearStatus();
    var result=true;
    if(callSessionId=="IN-PROGRESS"){
        result=confirm("Call in progress, making another call may disonnect the current call. Do you want to continue?");
    }
    if(result){
        if(!validatePhone(from_phone)){
            return;
        }
        from_phone = document.CallForm.from_phone.value;
        callSessionId="IN-PROGRESS";
        setCallStatus("Connecting...");
        //Connect Call, get Session ID
        var url = "/php/myelance/main/call.php?ctx=contactMe&mode=call&view_person="+username+"&from_phone="+from_phone+'&t='+getDateTime();
        new Ajax.Request(url, {
            method: 'get',
            onSuccess: callResult,
            onFailure: callFailure
        });
    }
}

function validatePhone(phone){
		var p = phone.replace(/[^\d\+]/g, "");
		if (p.substr(0, 3) != "011" && p.substr(0, 1) != "+") {
			if (p == "911") {
				alert("Calls to 911 emergency services cannot be completed. Please dial the number directly from your landline or cell phone");
				document.CallForm.from_phone.focus();
				return false;
			}
			if (p == "411") {
				alert("Calls to 411 directory assistance services cannot be completed. Please dial the number directly from your landline or cell phone");
				document.CallForm.from_phone.focus();
				return false;
			}
			if (!p.match(/^\+?1?[2-9]\d{2}[2-9]\d{6}$/)) {
				alert("The phone number you entered is incorrect.\n\n" +
							"Valid US phone numbers should be a total of 10-digits in length\n" +
							"and neither the area code or 7-digit phone number can start with the number \"1\".");
				document.CallForm.from_phone.focus();
				return false;
			}
		}
		if (p.substr(0, 1) == "+") p = p.substr(1);
        document.CallForm.from_phone.value = p;
	return true;
}

function cancelCall(){
    if(callSessionId){
        if(callSessionId!='IN-PROGRESS'){
        //disconnect call
        var answer = confirm("Call is in progress. Do you want to disconnect?");
        if(answer){
            var url = "/php/myelance/main/call.php?ctx=contactMe&mode=cancel&call_sk="+callSessionId+'&call_WS='+callWS+'&t='+getDateTime();
            new Ajax.Request(url, {
            method: 'get'
            });
        }else{
            return;
        }
        }
        callSessionId=null;
    }
    clearStatus();
    cancelContactMe();
}

function callResult(tspt){
   var response = tspt.responseText;
   var data = response.split(' ');
   if(data[0]=='OK'){
       callSessionId=data[1];
       callWS = data[2];
       //initiate call status
       setCallStatus("");
       getCallStatus();
       isCallInProgress();
   }else{
       //TODO - Set Error Message
    setCallStatus(response);
    callSessionId=null;
   }
}
function clearStatus(){
    setCallStatus("");
    var sframe = $('callStatusFrame');
    sframe.src="";
}
function callFailure(){
    setCallStatus("<span class='errortext'> Internal Error, cannot connect call, please try again at a later time. ");
    callSessionId=null;
}

//get call status from provider
function getCallStatus(){
    if(callSessionId!=null){
        var iframe = "https://service.ringcentral.com/ringout.asp?cmd=status&format=html&css="+escape(URL_BASE+"/styles/ringCentralStatus.css")+"&sessionid="+callSessionId+"&WS="+callWS+'&t='+getDateTime();
        var sframe = $('callStatusFrame');
        sframe.src=iframe;
        setTimeout("getCallStatus()", 5000);
    }
}

function isCallInProgress(){
    if(callSessionId){
      YAHOO.util.Connect.asyncRequest('get',
          '/php/myelance/main/call.php?ctx=contactMe&mode=status&call_sk='+callSessionId+'&call_WS='+callWS+'&t='+getDateTime(),
          {success: updCallSession, failure:updCallSession});
      setTimeout("isCallInProgress()", 30000);
    }
}

function updCallSession(tspt){
   if(!tspt.responseText || tspt.responseText!=1){
       callSessionId=null;
   }
}

function setCallStatus(statusText){
    $('callStatus').innerHTML="<div style='float:left;'><b>Call Status</b>:</div><div style='float:left'>"+statusText+"</div>";
}

//MyElance methods


function updateMyElanceChat(){
        var username = getCookie("uname");
        var d = new Date();
                YAHOO.util.Connect.asyncRequest('get',
                   '/php/myelance/main/chat.php?ctx=profile&mode=check&format=myelance&view_person='+username+'&t='+d.getTime(),
                    {success: updMyElanceChat});
}

function updMyElanceChat(tspt){
    if(tspt.responseText.length >0)
            $('EnableChat').innerHTML = tspt.responseText;
}
