function CPH()
{
    var collaborationLocation;
    var displayCph=true;
    var peers=new HashTable();
    var CPH_PEERS_DIV_ID="CPH_PEERS_DIV_ID";
    var ACTION_IMAGE_ID_PATTERN="";
    var CPH_PEERS_DIV=document.getElementById(CPH_PEERS_DIV_ID);
    var PEER_KEY="PEERID_";
    var PEER_ROW="PEERROW_";
    var PEERS_TABLE_ID="peersTable";
    var CPH_DIV_ID="presence";
    var CPH_DIV=document.getElementById(CPH_DIV_ID);
    var PEER_COUNT_DIV_ID= "peers_count_div_id";
    var PEER_COUNT_DIV=document.getElementById(PEER_COUNT_DIV_ID);
    var PEERS_TABLE_DIV_ID ="peersTableDivID";
    var PEERS_TABLE_DIV=document.getElementById(PEERS_TABLE_DIV_ID);
    var HTML_PEER_TEMPLATE='<td align="left">NAME</td><td align="right"><a href="#" onclick="cph.removePeer(ID);return false;"><img src="/images/actions/del.gif"/></a></td>';
    
    var FIRST_ADD_COMMAND="FIRST_ADD::COLLAB_ID&&ID&&NAME";
    var ADD_COMMAND="ADD::ID&&NAME";
    var REMOVE_COMMAND="REMOVE::ID";
    var REMOVE_ALL_COMMAND="REMOVE_ALL";
    var INVITE_DONE_COMMAND="INVITE_DONE::COLLAB_ID&&ID&&NAME";
    var INVITE_COMMAND="INVITE";
    var DISABLE_ALERT_COMMAND="DISABLE_ALERT";
    
    var TYPE_FIRST_ADD="FIRST_ADD";
    var TYPE_ADD="ADD";
    var TYPE_REMOVE="REMOVE";
    var TYPE_REMOVE_ALL="REMOVE_ALL";
    var TYPE_INVITE_DONE="INVITE_DONE";
    var TYPE_INVITE="INVITE";
    var TYPE_DISABLE_ALERT="DISABLE_ALERT";
    
    var PEER_ADDED_SUCCESS ="PEER_ADDED";
    var INVITATIONS_SENT_SUCCESS="INVITATIONS_SENT";
    var successMessage='';
    
    var SIGNOUT_BUTTON_ID="header:signoutForm:signoutButton";
    var CPH_INPUT_HIDDEN_ID="header:cphForm:cphInput";
    var CPH_SUBMIT_BUTTON_ID="header:cphForm:cphSubmit";
    
    var CPH_SUCCESS_MESSAGE_ID="globalInnerMessage";
    var CPH_SUCCESS_MESSAGE_CONTORL=document.getElementById(CPH_SUCCESS_MESSAGE_ID);
    var CPH_SUCCESS_MESSAGE="Member Added Successfully";
    
    var showAlert=true;
    var SIGN_OUT=false;
    
    
    
    var DONE_CLICKED=false;
    var IS_LAST_PEER_IN_COLLABORATION_DETAILS=false;
    
    
    this.setCollaborationLocation=function (location){
        collaborationLocation=location;
    }
    
    this.displayCph=function(display){
        displayCph=display;
    }
    
    this.setActionImageIdPattern=function (pattern){
        ACTION_IMAGE_ID_PATTERN=pattern;
    }
    this.collaborateWith=collaborateWith;
    function collaborateWith(){
        if(collaborationLocation=='NULL'){
            window.location.href="/collaborations/newcollaborationdetails.html";
        }
        else{
            executeCommand(null,TYPE_INVITE);
            
        }
    }
    this.signout=function(){
        if(peers.size()>0){
            openSignoutPopup(peers.size());
        }
        else{
            document.getElementById(SIGNOUT_BUTTON_ID).click();
        }
    }
    this.refresh=function(){
        //        if(SIGN_OUT){
        //            SIGN_OUT=false;
        //            document.getElementById(SIGNOUT_BUTTON_ID).click();
        //        }
        //        if(DONE_CLICKED){
        //            DONE_CLICKED=false;
        //            collaborateWith();
        //            return;
        //        }
        //        if(IS_LAST_PEER_IN_COLLABORATION_DETAILS){
        //            IS_LAST_PEER_IN_COLLABORATION_DETAILS=false;
        //            window.location.href="/collaborations/mycollaborations.html";
        //        }
        //        if(successMessage==PEER_ADDED_SUCCESS){
        //            successMessage='';
        //            seeDialogMessage("Member Added Successfully");
        //        }
        if(successMessage==INVITATIONS_SENT_SUCCESS){
            successMessage='';
            seeDialogMessage("Invitation sent successfullty");
        }
        //        var peersCollection=peers.getValues();
        //        for (i=0;i<peersCollection.length;i++){
        //            p=peersCollection[i];
        //            changeImageIconAndLink(p,false);
        //            
        //        }
        
    }
    
    
    this.init=function(){
        //        var dataStr=document.getElementById("cphData").value;
        //        
        //        if(dataStr!=""){
        //            
        //            data=dataStr.evalJSON();
        //            collaborationLocation=data.collabId;
        //            showAlert=data.showAlert;
        //            
        //            if(data.peers!=undefined){
        //                for(i=0;i<data.peers.length;i++){
        //                    addPeerToCPH(new Peer(data.peers[i].id,data.peers[i].name));
        //                }
        //                alertPeers();
        //            }
        //            
        //        }
    }
    
    this.addPeer=function (id,name,fname,lname){
        p = new Peer(id,name,fname,lname);
        
        //alert(p.getFName());
        if(peers.size()==0){
            openCollaborationTypePopup(p);
        }
        else{
            var peerKey=PEER_KEY+p.getId();
            if(peers.contains(peerKey)){
                alert(name+' Already Added');
                return;
            }
            executeCommand(p,TYPE_ADD);
            addPeerToCPH(p);
        }   
    }
    
    function executeCommand(p,commandType){
        //        if(commandType==TYPE_FIRST_ADD){
        //            data=FIRST_ADD_COMMAND.replace("COLLAB_ID",collaborationLocation).replace("ID",p.getId()).replace("NAME",p.getName());
        //            successMessage=PEER_ADDED_SUCCESS;
        //            
        //        }
        //        else if(commandType==TYPE_ADD){
        //            data=ADD_COMMAND.replace("ID",p.getId()).replace("NAME",p.getName());            
        //            successMessage=PEER_ADDED_SUCCESS;
        //        }
        //        else if(commandType==TYPE_REMOVE){
        //            data=REMOVE_COMMAND.replace("ID",p.getId());
        //        }
        //        else if(commandType==TYPE_REMOVE_ALL){
        //            data=REMOVE_ALL_COMMAND;
        //        }
        //        else
        if(commandType==TYPE_INVITE_DONE){
            data=INVITE_DONE_COMMAND.replace("COLLAB_ID",collaborationLocation).replace("ID",p.getId()).replace("NAME",p.getName());
            successMessage=INVITATIONS_SENT_SUCCESS;
        }
        //        else if(commandType==TYPE_INVITE){
        //            data=INVITE_COMMAND;
        //            successMessage=INVITATIONS_SENT_SUCCESS;
        //            removeAllPeers();
        //        }
        //        else if(commandType==TYPE_DISABLE_ALERT){
        //            data=DISABLE_ALERT_COMMAND;
        //        }
        
        document.getElementById(CPH_INPUT_HIDDEN_ID).value=data;
        document.getElementById(CPH_SUBMIT_BUTTON_ID).click();    
    }
    
    function addPeerToCPH(p){
        var peerKey=PEER_KEY+p.getId();
        peers.put(peerKey,p);  
        var data;
        addPeerHtml(p);
        changeImageIconAndLink(p,false); 
        checkCPHDisplay();
    }
    
    function changeImageIconAndLink(p,active){
        
        //index=ACTION_IMAGE_ID_PATTERN.indexOf('-');
        //id=ACTION_IMAGE_ID_PATTERN.substring(0,index);
        //id=id+p.getId()+ACTION_IMAGE_ID_PATTERN.substring(index+1);
        id=ACTION_IMAGE_ID_PATTERN.replace("-",p.getId());
        var img=document.getElementById(id);
        if(img!=undefined){
            
            if(active==true){
                img.src="/images/actions/add_cph_peer.gif";
                img.onclick=function(){cph.addPeer(p.getId(),p.getName()); return false;};
                img.alt="Collaborate With";
            }
            else{
                img.src="/images/actions/already_cph_added.gif";
                img.onclick=function (){return false;};
                img.alt="Already Added";
                
            }
            tooltipInitForOneImg(img);
        }
    }
    
    function addPeerHtml(p){
        table=document.getElementById(PEERS_TABLE_ID);
        var row =table.insertRow(0);
        row.setAttribute('id',PEER_ROW+p.getId());
        row.setAttribute('style','height:25px');
        c1=row.insertCell(0);
        c1.innerHTML=p.getName();
        c1.setAttribute('width','100%');
        c2=row.insertCell(1);
        c2.innerHTML='<a href="#" onclick="cph.removePeer('+p.getId()+');return false;"><img src="/images/actions/del.gif"/></a>';
    }
    
    this.removePeer=function (id){
        var peerKey=PEER_KEY+id;
        p=peers.remove(peerKey);
        executeCommand(p,TYPE_REMOVE);
        if(ACTION_IMAGE_ID_PATTERN!=""){
            changeImageIconAndLink(p,true);
        }
        checkCPHDisplay();
        removePeerHtml(p);
        
    }
    //special Case fro new collaboration detils
    this.removePeerFromCollaborationDetails=function(id){
        
        var peerKey=PEER_KEY+id;
        p=peers.remove(peerKey);
        if(peers.size()==0){
            IS_LAST_PEER_IN_COLLABORATION_DETAILS=true;
        }
        data=REMOVE_COMMAND.replace("ID",id);
        
        document.getElementById("form:cphInput").value=data;
        document.getElementById("form:cphSubmit").click();
    }
    
    function removePeerHtml(p){
        
        row=document.getElementById(PEER_ROW+p.getId());
        table=document.getElementById(PEERS_TABLE_ID);
        table.deleteRow(row.rowIndex);
        
        
        
    }
    this.removeAllPeers=function(){
        if(confirm('Are you sure you want to remove all peers')){
            executeCommand(null,TYPE_REMOVE_ALL);
            removeAllPeers();
        }
    }
    
    function removeAllPeers(){
        var peersCollection=peers.getValues();
        for (i=0;i<peersCollection.length;i++){
            p=peersCollection[i];
            if(ACTION_IMAGE_ID_PATTERN!=""){
                changeImageIconAndLink(p,true);
            }
            removePeerHtml(p);
        }
        peers.removeAll();
        checkCPHDisplay();
        //removeAllPeersHtml();
    }
    //    function removeAllPeersHtml(){
    //        table=document.getElementById(PEERS_TABLE_ID);
    //        alert(table);
    //        table.innerHTML="<tbody></tbody>";
    //    }
    
    function openCollaborationTypePopup(p){
        
        
        new Ajax.Request('/collaborations/collaborationscountinvitedcanjoin.html',{
            method:'post',
            parameters: {toInviteId:p.getId()},
            onSuccess: function(transport){
                var content = transport.responseText|| "";
                var href=window.location.href;
                var backLink=href.substring(href.indexOf('/')+2);
                backLink=backLink.substring(backLink.indexOf('/'));
                
                if(content=='0'){
                    window.location.href="/collaborations/newcollaborationdetails.html?accountId="+p.getId()+'&backLink='+backLink;
                }else{
                    popupWindow=displayModalPanel('/collaborations/collaborationtypepopup.html?toInviteId='+p.getId(), 'Collaborate with '+p.getFName(), 480, 170, 'typePopup', 'iframe', 'frameborder=0,center=1,resize=0,scrolling=1');
                    popupWindow.onclose=function(){ //Define custom code to run when window is closed
                        var popupForm=this.contentDoc.forms[0] //Access first form inside iframe just for your reference
                        var clickedButton=this.contentDoc.getElementById("buttonType"); 
                        var collabId=this.contentDoc.getElementById("form:collabId"); 
            
                        if (popupForm.elements['collabType'][0].checked){ //crude check for invalid email0
                            collaborationLocation="NULL";   
                        }
                        else{
                            collaborationLocation=collabId.value;
                        }
            
                        if(clickedButton.value=='DONE'){
                            if(collaborationLocation=="NULL"){
                                DONE_CLICKED=true;
                                //var href=window.location.href;
                                //var backLink=href.substring(href.indexOf('/')+2);
                                //backLink=backLink.substring(backLink.indexOf('/'));
                                window.location.href="/collaborations/newcollaborationdetails.html?accountId="+p.getId()+'&backLink='+backLink;
                                //executeCommand(p,TYPE_FIRST_ADD);
                            }
                            else{
                                executeCommand(p,TYPE_INVITE_DONE);
                            }
                        }
                        //            else{
                        //                alert(window.location.href);
                        //            }
                        //            else if(clickedButton.value=='ADD_MORE'){
                        //                executeCommand(p,TYPE_FIRST_ADD);
                        //                addPeerToCPH(p);
                        //            }
                        return true;
                    }
                }
            },
            onFailure: function(error){
                alert("Error couldn't load editable collaborations size"+error.responseText);
            }
        })
        return false;
    } 
    
    function openSignoutPopup(){
        popupWindow=displayModalPanel('/member/signoutpopup.html', 'Before You Go', 596, 228, 'signoutPopup', 'iframe');
        //dhtmlmodal.open('signoutPopup', 'iframe', '/member/signoutpopup.html', 'Before You Go', 'width=596px,height=228px,center=1,resize=0,scrolling=1');
 
        popupWindow.onclose=function(){ //Define custom code to run when window is closed
            var popupForm=this.contentDoc.forms[0] //Access first form inside iframe just for your reference
            var clickedButton=this.contentDoc.getElementById("buttonType"); 
            
            if(clickedButton.value=='COLLABORATE_NOW'){
                collaborateWith();
            }
            else if(clickedButton.value=='KEEP_SIGNOUT'){
                SIGN_OUT=true;
                executeCommand(null,TYPE_DISABLE_ALERT);
            }
            else if(clickedButton.value=='REMOVE_SIGNOUT'){
                SIGN_OUT=true;
                executeCommand(null,TYPE_REMOVE_ALL);
            }
            
            return true;
        }
        return false;
    } 
    
    function checkCPHDisplay(){
        
        if(peers.size()!=0&&(displayCph=='true'||displayCph==true)){
            
            CPH_DIV.style.display='';
            PEER_COUNT_DIV.style.display='';
            
        }
        else{
            hideContainer();
            
            CPH_DIV.style.display='none';
            PEER_COUNT_DIV.style.display='none'
            
        }
        
        document.getElementById('strongPeersCount').innerHTML=peers.size();
        if(peers.size()<=3){
            PEERS_TABLE_DIV.className='';
        }
        else{
            PEERS_TABLE_DIV.className='peersTableDiv';
        }
    }
    this.showHideCPHWindow=function (){
        
        if(showAlert==true||showAlert=='true'){
            document.getElementById('newDivId').className="divCountStrong";
            document.getElementById('newDivId').style.display="";
            showAlert=false;
            disableLoad=true;
            executeCommand(null,TYPE_DISABLE_ALERT);
        }
        var container=document.getElementById('presence_notifications');
        if(container.style.display==''){
            hideContainer();
        }
        else{
            showContainer();
        }
        return false;
    }
    function alertPeers(){
        if(showAlert==true||showAlert=='true'){
            var countDiv=document.getElementById('newDivId');
            countDiv.className="divCountStrongAlert";
            showHideAlert();
        }
        
    }
    function showHideAlert()
    {
        if(showAlert==true||showAlert=='true'){
            var countDiv=document.getElementById('newDivId');
            if(countDiv.style.display==""){
                countDiv.style.display="none";
            }
            else{
                countDiv.style.display="";
            }
            setTimeout(function(){showHideAlert();},900);
        }
        
    }
    function showContainer(){
        var container=document.getElementById('presence_notifications');
        var buttonDiv=document.getElementById('chat_status_control_tab');
        var buttonDivSpace=document.getElementById('chat_status_control_tab_space');
        container.style.display='';
        buttonDiv.className='presence_bar_button_opened';
        buttonDivSpace.className='presence_bar_button_space_opened';
    }
    function  hideContainer(){
        var container=document.getElementById('presence_notifications');
        var buttonDiv=document.getElementById('chat_status_control_tab');
        var buttonDivSpace=document.getElementById('chat_status_control_tab_space');
        container.style.display='none';
        buttonDiv.className='presence_bar_button';
        buttonDivSpace.className='presence_bar_button_space';
    }
}

function Peer(id,name,fname,lname){
    this.id=id;
    this.name=name;
    this.fname=fname;
    this.lname=lname;
    
    this.setId=function (value){
        id=value;
    };
    this.setName=function (value){
        name=value;
    };
    
    this.setFName=function (value){
        fname=value;
    };this.setLName=function (value){
        name=value;
    };
    
    this.getId=function (){
        return id;
    }
    this.getName=function (){
        return name;
    }
    this.getFName=function (){
        return fname;
    }
    this.getLName=function (){
        return lname;
    }
    
}
function HashTable(){
    this.hash = new Array();
    this.keys = new Array();
    
    this.put = function (key, value){
        if (value == null)
            return;
        
        if (this.hash[key] == null)
            this.keys[this.keys.length] = key;
        
        this.hash[key] = value;
    }
    
    /**
     * get
     * Return an element
     * param: key - String, key name
     * Return: object - The requested object
     */
    this.get = function (key){
        return this.hash[key];
    }
    
    /**
     * remove
     * Remove an element
     * param: key - String, key name
     */
    this.remove = function (key){
        for (var i = 0; i < this.keys.length; i++){
            //did we found our key?
            if (key == this.keys[i]){
                //remove it from the hash
                p=this.hash[this.keys[i]];
                this.hash[this.keys[i]] = null;
                //and throw away the key...
                this.keys.splice(i ,1);
                return p;
            }
        }
        return null;
    }
    
    /**
     * size
     * Return: Number of elements in the hashtable
     */
    this.size = function (){
        return this.keys.length;
    }
    
    
    this.contains = function(key) {
        for (var i = 0; i < this.keys.length; i++){
            //did we found our key?
            if (key == this.keys[i]&&this.hash[this.keys[i]] != null){
                return true;
            }
        }
        return false;
    }
    
    this.removeAll=function(){
        this.keys = new Array();
        this.hash = new Array();
        
    }
    
    /**
     * next
     * Return: true if theres more items
     */
    
    this.getValues = function() {
        var values = new Array();
        for (var i = 0; i < this.keys.length; i++){
            values[i]=this.hash[this.keys[i]] ;
        }
        return values;
    }    
}
