var maxCookies = 5;

function getRecentChatsCookiesForId(helpeeId){
    var pCOOKIES = document.cookie.split('; ');//needs the space for splitting correctly
    var oldCookies = new Array();

    for(var i = 0; i < pCOOKIES.length; i++){
        var NmeVal  = new Array();
        var NmeVal  = pCOOKIES[i].split('=');

        //find all the cookies that begin with _helperContact_helpeeId_
        if(NmeVal[0].indexOf("_helperContact_"+helpeeId+"_")>-1){
            //get only the cookies for this helpee!
            if(oldCookies.length <maxCookies){
              oldCookies.push(pCOOKIES[i]);
            }
        }
    }
    return oldCookies;
}


function setRecentChatsCookie(helpeeId, helperId, cName, value, expires){
    var oldCookies = getRecentChatsCookiesForId(helpeeId);

    if(expires){
        expires = generateExpiration(expires);
    }
    //alert(expires);
    //check if there is already a cookie for the helpee-helper combination
    //if combo exists, delete it and set a new one which will have the latest date
    var exists = false;
    if(oldCookies.length>0){
         //alert("oldCookies "+oldCookies);
        for(var i=0; i<oldCookies.length; i++){
            var ckie = oldCookies[i];
            var helperStr = getHelperIdFromRecentChatsCookie(ckie);
            //alert("helperStr "+helperStr);
            if(helperStr!=null && helperStr == helperId){
                exists = true;
                //this combo exists, delete the old version
                deleteCookie(ckie);
                oldCookies = getRecentChatsCookiesForId(helpeeId);//get them again, 1 was deleted from the array
                //alert(" EXISTING _ ALL : "+oldCookies);
                shiftRecentChatsCookieArray(oldCookies, helpeeId);

                document.cookie = cName + oldCookies.length +"=" + escape(value) + "&expires=" + expires + "; expires="+expires;//set it as the last one in the list
                //return;
            }
        }
    }
    //alert(cName + oldCookies.length +"=" + escape(value) + "&expires=" + expires + "; expires="+expires);
    if(!exists){

        if(oldCookies.length==0){
            document.cookie = cName + "0=" + escape(value) + "&expires=" + expires + "; expires="+expires;
        }else if(oldCookies.length < maxCookies){
            //alert('new--->'+cName + oldCookies.length +"=" + escape(value) + "&expires=" + expires + "; ");
            document.cookie = cName + oldCookies.length +"=" + escape(value) + "&expires=" + expires + "; expires="+expires;//if expires is set correctly, we'll never be able to get its value out again

        }else if(oldCookies.length == maxCookies){

            findAndDeleteOldestRecentChatsCookie(oldCookies);

            oldCookies = getRecentChatsCookiesForId(helpeeId);//get them again, 1 was deleted from the array
            //alert(" AFTER DELETING MAX: "+oldCookies);
            shiftRecentChatsCookieArray(oldCookies, helpeeId);//makes everyone have another name
            document.cookie = cName + oldCookies.length +"=" + escape(value) + "&expires=" + expires + "; expires="+expires;
        }

        //document.cookie += "path=/";
        //alert("AFTER EVERYTHING ----------: "+document.cookie);
        /*if(domain){
            document.cookie += "domain=" + domain + "; ";
        }*/
    }
}

function shiftRecentChatsCookieArray(oldCookies, helpeeId){
    for(var i=0; i<oldCookies.length; i++){
        var cc = oldCookies[i];

        var str = "_helperContact_"+helpeeId+"_"+i+"="+getCookieParam(cc, 1)+"="+getCookieParam(cc, 2)+"; expires="+getCookieParam(cc, 2);
        //alert("shifting --- "+str);
        deleteCookie(getCookieParam(cc, 0));
        //alert("getCookieParam(cc, 2) --- "+getCookieParam(cc, 2)+" WSSS "+str);
        document.cookie = str;
    }
}

function findAndDeleteOldestRecentChatsCookie(oldCookies){
    //loop thru the old cookies and delete the oldest one
    var oldestCookie = "";
    var currentDate = new Date();
    var currentTime = currentDate.getTime() + 2 * 24 * 60 * 60 * 1000;//currentDate + 2 days b/c that is what we are setting it to

    for(var i=0; i<oldCookies.length; i++){
        var cookieDate = getCookieParam(oldCookies[i], 2);
        cookieDate = new Date(cookieDate).getTime();
        //alert("cookieDate "+cookieDate+" currentTime: "+currentTime);
        if(cookieDate < currentTime){
            currentTime = cookieDate;//set it to the oldest date
            oldestCookie = getCookieParam(oldCookies[i], 0);
        }
    }
    //alert("oldestCookie "+oldestCookie);
    deleteCookie(oldestCookie);
}

function generateExpiration(cookieLife){
    var today = new Date();
    var expr = new Date(today.getTime() + cookieLife * 24 * 60 * 60 * 1000);
    return  expr.toGMTString();
}

function callSetRecentChatsCookie(helperId, firstName, lastName, imageUrl, helpeeId){
    var cookieValue = 'scnName='+helperId+'&helpeeId='+helpeeId+'&firstName='+firstName+'&lastName='+lastName+'&imageUrl='+imageUrl;
    setRecentChatsCookie(helpeeId, helperId, "_helperContact_"+helpeeId+"_", cookieValue, 180);
}

function getCookieParam(cookie, index){
   var splitValues=cookie.split("=");
   return splitValues[index];
}

function getHelperIdFromRecentChatsCookie(cookie){
    var str = getCookieParam(cookie, 1);
    var data = str.split("=");

    var data1 = (data.toString().substring(0, data.toString().indexOf("%26")));
    var helperId = data1.split("%3D")[1];

    return helperId;
}

function getAnyParam(str, name){
    /*%3D
    %26 or &
    firstName
    lastName
    imageUrl*/
    var begin = str.indexOf(name);
    if(begin>-1){
        str = str.substring(begin);
        var end = str.indexOf("%26");
        if(end==-1) end = str.indexOf("%3F");//get the img url

        var data = str.substring(0, end);
        return data.split("%3D")[1];
    }
    return "";

}

function showRecentChats(cookieNumber){
    var div = document.getElementById("recentChatsDiv");
    if(div.style.display == "none"){
        div.style.display = "block";
        div.style.height = cookieNumber*62+"px";
    }else{
        div.style.display = "none";
    }
}

function writeRecentChatsCookies(helpeeId, helpeeCookies){

    //writeRecentChatsDiv();

    if(helpeeCookies.length>0){
        var str = "";
        for(var i=0; i<helpeeCookies.length; i++){
            var cc = helpeeCookies[i];
            var helperId = getHelperIdFromRecentChatsCookie(cc);
            var origStr = getCookieParam(cc, 1);
            var img;
            if(getAnyParam(origStr, 'imageUrl')==undefined){
                img = "/img/ai_0t.jpg";
            }else{
                img = "/"+getAnyParam(origStr, 'imageUrl')+"";
            }

            str += " <div style='height:40px; clear:both; margin:3px; padding-bottom:3px; border-bottom:1px solid #F1F1F0;'><div style='width:40px; margin-right:3px; float:left;'><img src='"+img+"'/></div> <a href='"+helperId+"?src=recent_chats'>"+getAnyParam(origStr, 'firstName')+" "+getAnyParam(origStr, 'lastName')+"</a> <br style=''></div> ";
        }
        document.write(str);
    }
}

function writeRecentChatsDiv(){
    document.write('<div id="recentChatsDiv" style="position:fixed; bottom:0; right:0; width:158px; height:350px; display:none; text-align:left; padding-left:5px; padding-top:5px; background-image:url(/images/chat/recent_contacts_background.gif); background-repeat:no-repeat;">');
}

function writeRecentChatsButton(helpeeCookieLength){
    if(helpeeCookieLength>0){
        document.write('<div id="recentChatsButton" onclick="showRecentChats('+helpeeCookieLength+');" style="position:fixed; bottom:0; right:0; width:163px; height:21px; padding-top:8px; font-size:13px;color:#4F4F2F;background-image:url(/images/chat/recent_contacts_button.gif); background-repeat:no-repeat; cursor:pointer; text-align:center;font-family:Arial,Helvetica,sans-serif;font-size:12px;">Recent chats</div');
    }
}

/* ------------------------  Generic cookie functions ------------------------ */

function writeCookie(name, value, expDays) {
    var expires = generateExpiration(1);
    if(expDays) {
        expires = generateExpiration(expDays);
    }
    document.cookie = name + "=" + escape(value) + "&expires=" + expires + "; expires=" + expires;//set it as the last one in the list
}

function deleteCookie(name){
    var cookie_date = new Date ();  // current date & time
    cookie_date.setTime ( cookie_date.getTime() - 3 * 24 * 60 * 60 * 1000);
    document.cookie = name + "=; expires=" + cookie_date.toGMTString()+"; ";
}

function getCookie(name){
    var allcookies = document.cookie.split('; ');//needs the space for splitting correctly

    for(var i = 0; i < allcookies.length; i++){
        var NmeVal  = new Array();
        NmeVal  = allcookies[i].split('=');

        //find all the cookies that begin with _helperContact_helpeeId_
        if(NmeVal[0] == name)
            return unescape(NmeVal[1]);
    }
    return false;
}