var EmlxmlHttp;
var TotalContChecked = 0;

// Ajax object to get connection
function GetEmlXmlHttpObject()
{
    var EmlxmlHttp=null;
    try
      {
      // Firefox, Opera 8.0+, Safari
      EmlxmlHttp=new XMLHttpRequest();
      }
    catch (e)
      {
      // Internet Explorer
      try
        {
        EmlxmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
      catch (e)
        {
        EmlxmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
    return EmlxmlHttp;
}

function UpdateCheckedName(ListItemID, FullName)
{
    var Start = "";
    var Finish = "";

    if(!document.all['li' + ListItemID].checked)
    {
        Start = "<span class=smtext><font color=#808080>";
        Finish = "</font></span>";
    }
    //alert(ListItemID + " - " + FullName + " - " + document.all['li' + ListItemID].checked);

    document.all['dvli' + ListItemID].innerHTML = Start + FullName + Finish;

    return true;
}

function CancelEmailer(dvName)
{
    document.all[dvName].innerHTML = "";
    document.all[dvName].display = "none";

    return false;
}

function ShowEmailer(dvName, Params)
{
    var EmlURL = "/app/blitz/ajx_emailer.php"

    var AllParams = "dvname=" + dvName + "&";

    if(document.all.CUR_JID) AllParams += "jid=" + document.all.CUR_JID.value + "&";
    if(document.all.CUR_GID) AllParams += "gid=" + document.all.CUR_GID.value + "&";

    AllParams += Params;

    EmlxmlHttp=GetEmlXmlHttpObject()
    if (EmlxmlHttp==null)
    {
      alert ("Your browser does not support AJAX!");
      return false;
    }
   // alert (AllParams);
    EmlxmlHttp.onreadystatechange=ShowEmailerReturn;
    EmlxmlHttp.open("Post",EmlURL,true);
    EmlxmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    EmlxmlHttp.setRequestHeader("Content-length", AllParams.length);
    EmlxmlHttp.setRequestHeader("Connection", "close");
    EmlxmlHttp.send(AllParams);

    return false;
}

function ShowEmailerReturn()
{
    var FrmHTML = "";

    // Wait until we get to ready state before processing
    if(EmlxmlHttp.readyState == 4)
    {
        var ParmsSplit = EmlxmlHttp.responseText.split("|");

        FrmHTML = "<table border=0 width=410 cellpadding=1 cellspacing=1 bgcolor=#064265><tr><td valign=top>";
        FrmHTML += "<table border=0 width=408 bgcolor=#ffffff cellspacing=2 cellpadding=2><td valign=top>";

        FrmHTML += ParmsSplit[1];

        //FrmHTML += "<br> <span style='font-size: 6px'> <br></span><center><a href=# onClick=\"CancelEmailer('" + ParmsSplit[0] + "');\">Cancel</a>";

        //alert(ParmsSplit[1]);

        document.all[ParmsSplit[0]].display = "";
        document.all[ParmsSplit[0]].innerHTML = FrmHTML;

        //if(document.all.ListItemIDs)
        //    alert(document.all.AllSelected.value + "\n\n" + document.all.ListItemIDs.value + "\n\n" + document.all.ListItemValues.value);

    }
    return false;
}

function PreviewEmail(dvName, UseFirefox)
{
    var url = "/app/blitz/ajx_previewemail.php?width=620&height=450&EmailBlock=" + dvName + "&showmessage=true&welcome=" + urlencode(document.all[dvName + 'Welcome'].value);
    url += "&subject=" + urlencode(document.all[dvName + 'Subject'].value);

    if(document.all.CUR_JID) url += "&jid=" + document.all.CUR_JID.value;
    if(document.all.CUR_GID) url += "&gid=" + document.all.CUR_GID.value;

    if(!UseFirefox)
    {
        document.all.EmlLink.href = url;
        document.all.EmlLink.title = document.all[dvName + 'Subject'].value;
        document.all.EmlLink.click();
    }
    else
        window.open(url, "_blank", "width=640,height=500,status=no,resizable=yes,toolbar=no,scrollbars=1,left=25,top=25");

    return false;
}

function SendEmail(dvName, Params)
{
    var TotalContacts;
    var Plural = "s";
    var AllParams = Params;
    var Emails = "";

    // Verify user wants to send
    if(document.all.ChooseType.value == "l")
        TotalContacts = document.all.TotalSelected.value;
    else
        TotalContacts = TotalDirectEmails(dvName);

    if(TotalContacts == 1) Plural = "";

    if(!confirm("Send Message to " + TotalContacts + " contact" + Plural + "?")) return false;

    AllParams += "&dosend=t&welcome=" + urlencode(document.all[dvName + 'Welcome'].value) + "&subject=" + urlencode(document.all[dvName + 'Subject'].value);

    if(document.all.ChooseType.value == "d")
    {
        AllParams += "&totaldirect=" + document.all[dvName + '_totaldirect'].value;

        Emails = ParseDirectEmails(dvName, -1);
        if(Emails != "") AllParams += "&" + Emails;
    }

    // If this is a list, add list of selected by using CancelSelected function (yeah, that's right)
    if(document.all.ChooseType.value == "l" && document.all.AllSelected.value == "F")
        return CancelSelected(dvName, AllParams);
    else
        ShowEmailer(dvName, AllParams);

    return false;
}

function SelectAll(dvName, Params)
{
    var i;

    if(!confirm('Select all Recipients?')) return false;

    return ShowEmailer(dvName, Params);
}

function UnselectAll(dvName, Params)
{
    var i;

    if(!confirm('UnSelect all Recipients?')) return false;

    return ShowEmailer(dvName, Params);
}

function SelectContacts(dvName, Params)
{
    // If all not selected, get actual list now
    if(document.all.AllSelected.value == 'F')
        return CancelSelected(dvName, Params);
    else
        return ShowEmailer(dvName, Params);
}

function ChooseSelected(dvName, Params)
{
    var AllParams = Params + "&listitems=t";
    var AllIDs = document.all.ListItemIDs.value.split("-");
    var i;

    for(i=0;i<AllIDs.length;i++)
        if(document.all['li' + AllIDs[i]].checked) AllParams += "&li" + AllIDs[i] + "=t";

    //alert(AllParams);

    return ShowEmailer(dvName, AllParams);
}

function SaveSelectedAs(dvName, Params)
{
    if(document.all[dvName + '_SaveAsName'].value == "")
    {
        alert("To save the selections as a new list, please select a name for the list.\n\nOtherwise simply click 'Choose Selected' to choose without saving a new list.");
        return false;
    }

    var AllParams = Params + "&saveasname=" + urlencode(document.all[dvName + '_SaveAsName'].value) + "&listitems=t";
    var AllIDs = document.all.ListItemIDs.value.split("-");
    var i;

    for(i=0;i<AllIDs.length;i++)
        if(document.all['li' + AllIDs[i]].checked) AllParams += "&li" + AllIDs[i] + "=t";

    //alert(AllParams);

    return ShowEmailer(dvName, AllParams);
}

function CancelSelected(dvName, Params)
{
    var AllParams = Params + "&listitems=t";
    var AllIDs = document.all.ListItemIDs.value.split("-");
    var AllValues = document.all.ListItemValues.value.split("-");
    var i;

    // Get list of items from original page input
    for(i=0;i<AllIDs.length;i++)
        if(parseInt(AllValues[i])) AllParams += "&li" + AllIDs[i] + "=t";

    //alert(AllParams);

    return ShowEmailer(dvName, AllParams);
}

function ShowListUpload(dvName)
{
    return ShowEmailer(dvName, "choose=l&showupload=t");
}

function DeleteList(dvName, ListCode)
{
    if(!confirm('Permanently Delete this List?')) return false;

    return ShowEmailer(dvName, "choose=l&dellist=" + ListCode);
}

function UpdateList(dvName, ListCode)
{
    return ShowEmailer(dvName, "choose=l&showupdate=" + ListCode);
}

function CancelUploadList(dvName)
{
    return ShowEmailer(dvName, "choose=l");
}

function ValidateCreateList(dvName)
{
    var ErrList = "";

    if(document.all[dvName + "_ListName"].value == "")
        ErrList += "Enter a name for the list (so you can use it in the future). It will remain private - only you can see or use the list.\n\n";

    if(document.all[dvName + "_PastedEmails"].value == "")
        ErrList += "Enter email addresses (one per line) to create your new list.\n";

    if(ErrList != "")
    {
        alert("Please fix the following inputs:\n\n" + ErrList);
        return false;
    }
    return true;
}

function ValidateListUpload(dvName)
{
    var ErrList = "";

    // Don't look for name if we are replacing a list
    if(!document.all.ReplaceList)
    {
        if(document.all[dvName + "_ListName"].value == "")
            ErrList += "Enter a name for the list (so you can use it in the future). It will remain private - only you can see or use the list.\n\n";
    }

    if(document.all[dvName + "_ListFile"].value == "")
        ErrList += "Choose a .CSV file to upload (and ensure it has columns named 'First Name', 'Last Name', and 'Email'\n";

    if(ErrList != "")
    {
        alert("Please fix the following inputs:\n\n" + ErrList);
        return false;
    }
    return true;
}

function ShowEmailerDirectAddLine(dvName)
{
    var Params = "choose=d";

    // Add 1 to current total direct lines and send back
    Params += "&totaldirect=" + (parseInt(document.all[dvName + '_totaldirect'].value) + 1);

    Emails = ParseDirectEmails(dvName, -1);
    if(Emails != "") Params += "&" + Emails;

    //alert(Params);

    return ShowEmailer(dvName, Params);
}

function ShowEmailerDirectRemoveLine(dvName, RemoveNum)
{
    var Params = "choose=d";

    // Remove 1 from total direct
    Params += "&totaldirect=" + (parseInt(document.all[dvName + '_totaldirect'].value) - 1);

    Emails = ParseDirectEmails(dvName, RemoveNum);
    if(Emails != "") Params += "&" + Emails;

    //alert(Params);

    return ShowEmailer(dvName, Params);
}

function ParseDirectEmails(dvName, SkipNum)
{
    var i;
    var MaxEmails = document.all[dvName + '_totaldirect'].value;
    var Params = "";

    // Get all email addresses for the given dvName, and convert into a param block
    for(i=0;i<MaxEmails;i++)
    {
        if(i != SkipNum)
        {
            CurName = trim(document.all[dvName + '_DirectName' + i].value);
            CurEmail = trim(document.all[dvName + '_DirectEmail' + i].value)

            if(CurName != "") Params += "DirectName" + i + "=" + urlencode(CurName) + "&";
            if(CurEmail != "") Params += "DirectEmail" + i + "=" + urlencode(CurEmail) + "&";
        }
    }

    return Params;
}

function TotalDirectEmails(dvName)
{
    var i;
    var MaxEmails = document.all[dvName + '_totaldirect'].value;
    var TotalDirect = 0;

    // Get all email addresses for the given dvName, and convert into a param block
    for(i=0;i<MaxEmails;i++)
    {
            CurEmail = trim(document.all[dvName + '_DirectEmail' + i].value)
            if(CurEmail != "") TotalDirect++;
    }

    return TotalDirect;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    var histogram = {}, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}
/*
function ShowSendInvite()
{
    var FrmHTML = "";

    document.all.InpShowSendInvite.value = document.all.ShowSendInvite.innerHTML;

    FrmHTML = "<b>Send a Single Invite:</b><form method=post action=viewgroup.php><input type=hidden name=SendGroupInvite value=true>";
    FrmHTML += "<b>Full Name:</b> &nbsp;&nbsp;<input type=textbox class=textbox name=invite_fullname size=25> <br>";
    FrmHTML += "<b>Email:</b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=textbox class=textbox name=invite_email size=25><br>";
    FrmHTML += "<input type=submit class=submit name=SingleInvite id=SingleInvite value=\"Send Single Invite\">";

    FrmHTML += " <input type=button class=submit value=Cancel onClick=\"return CancelShowSendInvite();\">";
    FrmHTML += "</form>";

    document.all.ShowSendInvite.innerHTML = FrmHTML;

    return false;
}

function CancelShowSendInvite()
{
    document.all.ShowSendInvite.innerHTML = document.all.InpShowSendInvite.value;
    document.all.InpShowSendInvite.value = "";

    return false;
}

function ShowSendWelcome()
{
    var FrmHTML = "";

    document.all.InpShowSendWelcome.value = document.all.dvShowSendWelcome.innerHTML;

    FrmHTML = "<b>Send a Single Welcome:</b><form method=post action=viewgroup.php><input type=hidden name=SendGroupWelcome value=true>";
    FrmHTML += "<b>Full Name:</b> &nbsp;&nbsp;<input type=textbox class=textbox name=invite_fullname size=20> <br>";
    FrmHTML += "<b>Email:</b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=textbox class=textbox name=invite_email size=20><br>";
    FrmHTML += "<input type=submit class=submit name=SingleInvite id=SingleInvite value=\"Send Single Welcome\">";

    FrmHTML += " <input type=button class=submit value=Cancel onClick=\"return CancelShowSendWelcome();\">";
    FrmHTML += "</form>";

    document.all.dvShowSendWelcome.innerHTML = FrmHTML;
    return false;
}

function CancelShowSendWelcome()
{
    document.all.dvShowSendWelcome.innerHTML = document.all.InpShowSendWelcome.value;
    document.all.InpShowSendWelcome.value = "";

    return false;
}

function CancelInviteMembers()
{
    if(!confirm('Are you sure you want to cancel?'))
        return false;

    document.all.InviteGroupMembers.innerHTML = "";

    return false;
}

function ShowConfirmList()
{
    var HdrHTML = "";
    var ButtonsHTML = "";
    var i;

    // Store step 2 in case user cancels
    document.all.InpShowInviteStep.value = document.all.ShowInviteStep.innerHTML;
    document.all.InpShowInviteButtons.value = document.all.ShowInviteButtons.innerHTML;

    TotalContChecked = document.all.ContSize.value; // Start with total and deduct unchecked ones
    for(i=0;i<document.all.ContSize.value;i++)
        if(!document.all['InvRecip' + i].checked)
        {
            document.all['ShowCont' + i].style.display = "none";
            TotalContChecked--;
        }

    HdrHTML = "<b>Send Multiple Invites (Step 3 of 3):</b><br><span class=smtext>Please confirm that you want to invite the following contacts, then click \"Send Invites\" below.</span>";
    ButtonsHTML = "<input type=submit class=submit name=SendInvites id=SendInvites value=\"Send " + TotalContChecked + " Invites\">";
    ButtonsHTML += " <input type=button class=submit value=Back onClick=\"return CancelConfirmList();\">";
    ButtonsHTML += " <input type=submit class=submit name=CnclInvites id=CnclInvites value=\"Cancel\">";

    // Swap out text and buttons
    document.all.ShowInviteStep.innerHTML = HdrHTML;
    document.all.ShowInviteButtons.innerHTML = ButtonsHTML;

    return false;
}

function CancelConfirmList()
{
    var i;

    document.all.ShowInviteStep.innerHTML = document.all.InpShowInviteStep.value;
    document.all.ShowInviteButtons.innerHTML = document.all.InpShowInviteButtons.value;

    document.all.InpShowInviteStep.value = "";
    document.all.InpShowInviteButtons.value = "";

    for(i=0;i<document.all.ContSize.value;i++)
        document.all['ShowCont' + i].style.display = "";

    return false;
}

function PreviewInvite()
{
    // If no email addresses, return
    if(document.all.InviteEmails.value == "")
    {
        alert("Please enter at least 1 email address.");
        return false;
    }

    // If no welcome message, return
    if(document.all.InviteWelcome.value == "")
    {
        alert("Please enter a welcome message.");
        return false;
    }

    // Package params and post to server
    var Params;
    var ViewURL = "/app/blitz/viewgroup_ajx_invites.php";
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
      alert ("Your browser does not support AJAX!");
      return false;
    }

    var InviteWelcome = document.all.InviteWelcome.value.replace(/"/g, "'");
    var InviteSubject = document.all.InviteSubject.value.replace(/"/g, "'");

    Params = "previewinvite=true&inviteemails=" + escape(document.all.InviteEmails.value) + "&invitewelcome=" + escape(InviteWelcome);
    Params += "&invitesubject=" + escape(InviteSubject);

    xmlHttp.onreadystatechange=ShowInviteMembersReturn;
    xmlHttp.open("POST",ViewURL,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", Params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(Params);

    return false;
}

function ShowPreviewInvite()
{
    var url = "/app/blitz/viewgroup_ajx_invites.php?showmessage=true&gid=" + document.all.GroupID.value + "&invitewelcome=" + escape(document.all.InviteWelcome.value);
    url += "&invitesubject=" + escape(document.all.InviteSubject.value);

    window.open(url, "_blank", "width=640,height=600,status=no,resizable=yes,toolbar=no,scrollbars=1,left=25,top=25");
}

function SendInvites()
{
    var Plural = "s";

    if(document.all.TotalInvites.value < 2) Plural = "";

    if(!confirm('Are you sure you want to send out ' + document.all.TotalInvites.value + ' invite' + Plural + '?'))
        return false

    return true;
}
*/

