var IBC="na",canCloseWaitDlg=0,procdone=0,imgpath="";
var eventID=0,uID=0,uip=0;inviterid=0,crID=0,currentusertype="guest",bEventOwner=false,bGuestsShown=true,pid=0; //these vars get values comes from dynamic pages
var Guests = new Array(), arrCompanions = new Array(), allContacts=new Array(), collection=new Array();
var bLocUIsel = true, bAddBookRendered=false;
var bListsAreAJAX = true,
  bProcCompanions=false,
  numUnamedCompanions=0,
  numUnamedCompanionsInit=0;
  numNamedCompanions=0,
  cntCompanions=0,
  bIsComp=false,
  inviterPos=-1,
  iTotalYes=0,
  iTotalNo=0,
  iTotalMaybe=0;
  iTotalNotResp=0;  
var cpsv="",avgCnt=0;

function LTrim( value ) {return value.replace(/^\s+/,"");}
function RTrim( value ) {return value.replace(/\s+$/,"");}
function trim( value ) {return value.replace(/^\s+|\s+$/g,"");}

function SetSelectValue(SelectId, Value) {
  eval('SelectObject = document.getElementById("' + SelectId + '");');
  if(Value){
    for(var index = 0; index < SelectObject.length; index++) {
     if(SelectObject[index].value.toLowerCase() == Value.toLowerCase())
       SelectObject.selectedIndex = index;
    }
    return index;
  }else{
    SelectObject.selectedIndex = 0;return 0;
  }
}

function initHostpage(datestr) {
  getEventContactList();
  //--- Event Name ---
  $("#edit_name_btn").click(function () {$("#edit_name").show("medium");});
  $("#cancel_edit_name_btn").click(function () {$("#edit_name").hide();});
  $("#apply_edit_name_btn").click(function () {document.edit_name_form.submit();});
  //--- Event Location ---
  $("#edit_location_btn").click(function () {$("#edit_location").show("medium");});
  $("#cancel_edit_location_btn").click(function () {$("#edit_location").hide();});
  $("#save_edit_location_btn").click(function () {
      if($("#addsel").get(0).value==0){
        document.getElementById("fc_loc_option").value="";
        if(!$("#fc_loc_street").val().length){
          $("#street_lbl").css("color", "red");
          return;}
        if(!$("#fc_loc_city").val().length){
          $("#city_lbl").css("color", "red");
          return;}
        var idx = document.getElementById("addsel").selectedIndex;
        //alert("addsel.selectedIndex: "+idx);
        document.getElementById("fc_locname").value = uLoc2[idx].name?uLoc2[idx].name:"";
      }
      else if(hasAddressValsChanged()){
        document.getElementById("fc_loc_option").value="sel|update";
      }else{
        document.getElementById("fc_loc_option").value="sel";
      }
      //alert("would have submitted");
      document.edit_location_form.submit();
    });
  initNewVenueUI();
  //---Event Notes
  $("#edit_notes_btn").click(function () {$("#edit_notes").show("medium");});
  $("#cancel_edit_notes_btn").click(function () {$("#edit_notes").hide();});
  $("#apply_edit_notes_btn").click(function () {document.edit_notes_form.submit();});
  //---Event Date/Time ---
  $("#edit_datetime_btn").click(function () {
    //var d = Date.fromString(datestr);
    $('.date-pick').val(new Date(datestr).asString()).trigger('change')
    
    $("#edit_datetime").show("medium");
    });
  $("#cancel_edit_dt_btn").click(function () {$("#edit_datetime").hide();});
  $("#save_edit_dt_btn").click(function () {document.edit_datetime_form.submit();});
  //---Event Photo
  $("#addaphotobtn").click(function () {$("#Addphoto_dlg").show("medium");});
  $("#addphoto_dlg_Cancel_btn").click(function () {$("#Addphoto_dlg").hide();});
  $("#addphoto_dlg_Save_btn").click(function () {
    setEventImage(imgpath);
    $("#Addphoto_dlg").hide();
    });
  $("#removephoto_btn").click(function () {
    $(".photosec").hide();
    setEventImage('');
    });
  //--Guest pickers
  $("#fc_pickbyaddbook").change(function(){
    if(!bAddBookRendered){
      allContacts.sort(sortbyfn);
      renderAddBookPicker();
    }
    //$("#addbookpicker").show();
    document.getElementById("addbookpicker").style.display = "block";
    //$("#textpicker").hide();
    document.getElementById("textpicker").style.display = "none";
  });
  $("#fc_pickbytext").change(function(){
    //$("#textpicker").show();
    document.getElementById("textpicker").style.display = "block";
    //$("#addbookpicker").hide();
    document.getElementById("addbookpicker").style.display = "none";
  });  
  //---Send Invitations
  $("#send_invitation_btn").click(function () {
    $("#send_invitation_dlg").show("medium");
    $("#send_btn").click(function () {
      $.post('/proc.php',
             "action=sendnotification&eid="+eventID+"&body="+escape($("#embody").attr("value")));
      $("#send_invitation_dlg").hide();
      for(var x in allContacts){
        if(allContacts[x].s == "notnotified")
        allContacts[x].s = "notificationsent";}
      //renderAllLists2();
      renderNotReplied();
      $("#invitationnotsent").html("");
      });
  });
  $("#cancel_send_invitation_btn").click(function () {$("#send_invitation_dlg").hide();});
 
  Date.firstDayOfWeek = 7;
  Date.format = 'mm/dd/yyyy';
  $(function(){
    $('.date-pick').datePicker({clickInput:true});
  });
  if(bHasEndTime){
    $("#fc_EndTime").addClass("disabled");
    $("#fc_EndTime").checked = true;
    
  }else{
    disableEndtime();
  }
  $("#fc_EndTime").click(function () {
    if(this.checked) {
      enableEndtime();
    }else{
      disableEndtime();
    }
    });
  $("#addGuest_btn").click(function () {onAddGuestsClicked(0)});
  $("#gig").change(function(){
    onGIGclicked();
    });
  $("#gsg").change(function(){
    onGSGclicked();
  });
  if(pid==1){
    $("#guestsacceptedbox .emaillist_btn").click(function(e){LaunchEmailDlg(e,"accepted");});
    $("#guestsrejectedbox .emaillist_btn").click(function(e){LaunchEmailDlg(e,"rejected");});
    $("#maybebox .emaillist_btn").click(function(e){LaunchEmailDlg(e,"maybe");});
    $("#notrepliedbox .emaillist_btn").click(function(e){LaunchEmailDlg(e,"notificationsent");});
  }
}
function LaunchEmailDlg(e,targetval){
  $("#send_email_dlg").css("top", e.pageY-100);
  $("#send_email_dlg").css("left", e.pageX-50);
  $("#send_email_dlg").show("medium");
  //$("#send_email_dlg").modal();
  $("#send_email_dlg .send_btn").click(function () {
    $("#send_email_dlg").hide();
    //BEGIN: Nat's stuff:
    //$.post('/proc.php',"action=emailguests&target="+targetval+"&eid="+eventID+"&body="+escape($("#sndembody").attr("value"))+"&emsubject="+escape($("#sndemsubject").attr("value")));
    var cb_input = "false", el = document.getElementById("cb1");
    if(el)
      if (el.checked) {
        cb_input = "true";
      }
    $.post('/proc.php',"action=emailguests&target="+targetval+"&eid="+eventID+"&body="+escape($("#sndembody").attr("value"))+"&emsubject="+escape($("#sndemsubject").attr("value"))+"&copy2host="+cb_input);
    //end: Nat's stuff:
    
    $("#send_email_dlg .send_btn").unbind();
  });
  $("#send_email_dlg .cancel_send_email_btn").click(function () {
    $("#send_email_dlg").hide();
    $("#send_email_dlg .send_btn").unbind();
    var el = document.getElementById("cb1");
    if(el) el.checked = false;
  });
}
function initCreatenewPage(){
  initNewVenueUI();
  Date.firstDayOfWeek = 7;
  Date.format = 'mm/dd/yyyy';
  $(function(){
    $('.date-pick').datePicker({clickInput:true,createButton:false});
  });
  $("#send_invitation_btn").click(function(){
    if(!bLocUIsel)
      document.getElementById("p_locid").value="";
    if(!document.getElementById("fc_name").value.length) {
      alert("Please provide a name for the event.");
      document.getElementById("fc_name").focus();
      return false;
    }
    if (!document.getElementById("fc_date1").value.length) {
      alert("Please provide a date for the event.");
      document.getElementById("fc_date1").focus();
      return false;
    }
    var el = document.getElementById("fc_new");
    if(el){
      if(el.checked){
        if(!document.create_event_form.firstname.value.length && !document.create_event_form.lastname.value.length){
          alert("If you don't set your Firstname nor your Lastname, your guests won't know who the invitation is from.");
          return false;
        }
        if(!document.create_event_form.nemail.value.length){
          alert("You need to provide an email address so that you can come back to Boomguest, log-in, and see the status of your event.");
          return false;
        }
        if(!document.create_event_form.npassword.value.length){
          alert("You need to set a password so that you can come back to Boomguest and log-in to see your event.");
          return false;
        }
      }
    }
    if (submitcount == 0) {
      /*document.create_event_form.action.value = "create_event";
      if($("#fc_new").attr("checked"))
        document.getElementById("fc_createuser").value = 1;
      else
        document.getElementById("fc_createuser").value = 0;*/
      submitcount++;
      document.create_event_form.submit();
    }
    else {
      alert("This form has already been submitted.  Thank you!");
      return false;
    }
    
    //document.create_event_form.submit();
  });
}
function initEditAccountPage(){
  $("#chgpassword_btn").click(function(){
    $("#change_pword_div").show("Medium");
  });
  $("#cancel_chgpassword_btn").click(function(){
    $("#change_pword_div").hide();
  });
  
  $("#chgname_btn").click(function(){
    $("#change_name_dlg").show("Medium");
  });
  $("#cancel_change_name_dlg").click(function(){
    $("#change_name_dlg").hide();
  });
  
  $("#chgemail_btn").click(function(){
    $("#change_email_dlg").show("Medium");
  });
  $("#cancel_chgemail_btn").click(function(){
    $("#change_email_dlg").hide();
  });  
}
function initAddressBookpage(){
  $("#LaunchAddUserDlg_btn").click(function(){
    $("#AddUser_dlg").show("AddUser_dlg");
    $("#adduser_dlg_SAVE_btn").click(function(){
      $("#AddUser_dlg").hide();
      handleSaveAddUserDlg();
      return false;
    });
    $("#adduser_dlg_Cancel_btn").click(function(){
      $("#AddUser_dlg").hide();
      return false;
    });    
  });
}
function initNewVenueUI(){
  $("#new_venue_btn").click(function () {
    $("#new_venue_dlg").css("left", $(this).offset().left - 120);
    $("#new_venue_dlg").css("top", $(this).offset().top);
    $("#new_venue_dlg").show("medium");
  });
  $("#cancel_new_venue_btn").click(function () {$("#new_venue_dlg").hide();});
  $("#add_new_venue_btn").click(OnSubmitNewVenue);
  $("#newvenue_fc").keypress(function (e) {
      if (e.which == 13)
        return OnSubmitNewVenue();
    });
}
function OnSubmitNewVenue(){
  var txt = $("#new_venue_dlg input").val();
  if(txt.length){
    $("#new_venue_dlg").hide();
    var newLoc = {"id":0,"name":txt,"ownerID":uID};
    uLoc2.push(newLoc);
    var newOption = new Option(txt,0, false, true);
    $("#addsel").get(0).options.add(newOption);
    onChangeAddressSel2();
  }else{
    $("#new_venue_dlg label").css("color", "red"); 
  }
  return false;
}  

function disableEndtime(){
  $("#endtimesection SELECT").addClass("disabled");
  $("#endtimesection SELECT").each(function(){
      this.disabled = true;
    }); 
}
function enableEndtime(){
  $("#endtimesection SELECT").removeClass("disabled");
  $("#endtimesection SELECT").each(function(){
      this.disabled = false;
    }); 
}
//---------- Email Dialog handlers ----------
function ShowEmailDlg() {
  if(uip){
    alert("You need to confirm your email address before sending your invitation. Click the URL in the email that Boomguest has sent you. Don't worry: all the information on this page is always saved.");
  }else{
    YAHOO.container.emaildlg.show();
    YAHOO.util.Dom.setStyle('emaildlg', 'display', 'block');
  }
}
var handleSubmitEmailDlg = function() {
    this.cancel();
    var emdata="subject="+escape($("#emsubject").attr("value"))+
      "&body="+escape(document.getElementById('embody').value);
    var cbo={success:handleSuccessEmailDlg,failure:handleFailureEmailDlg};
    postActionWithWait(200,"Sending the intivation to your guests","emailguests",eventID,emdata,cbo);
};
var handleCancelEmailDlg = function() {
	this.cancel();
};
var handleSuccessEmailDlg = function(o) {
    procdone = 1;
    if(canCloseWaitDlg)
        YAHOO.container.wait.hide();
    var resp = eval( '(' + o.responseText + ')' );
    if (parseInt(resp.status)){
        for(var x in allContacts){
            if(allContacts[x].s == "notnotified")
                allContacts[x].s = "notificationsent";
        }
        renderAllLists2();
    }else { //since there was an error, let's blow away our local data and get a fresh copy from the DB.
            getEventContactList();
            renderAllLists2();
    }
};
var handleFailureEmailDlg = function(o) {
  alert("There was an error when asking the server to send the invitation to your guests. Please try again later. Error code is: " + o.status);
  YAHOO.container.wait.hide();    
};
//----------------------------------------
function onSaveAddPhotoDlg(){
  onHideAddPhotoDlg();
  setEventImage(imgpath);
  return false;
}
function setEventImage(path){
  el = document.getElementById("eventimage");
  if(el) el.src = path;
  el = document.getElementById("photocont");
  el2 = document.getElementById("add_photo");
  if(el){
    if(path.length){
      el.style.display = "block";
      $("#photocont img").attr("src",path);
      if(el2) el2.style.display = "none";
      $("#cardinfo").addClass("fright")
    }else{
      el.style.display = "none";
      $("#photocont img").attr("src","");
      if(el2) el2.style.display = "block";
      $("#cardinfo").removeClass("fright")
    }
  }
  postJSONProc(parseInt(eventID), '{"name":"seteventimage","eventimage":{"path":"'+path+'"}}');  
}
//----------------------------------------
function ShowQuickGuestPicker() {
	document.getElementById("quickguestinvite").style.display = "block";
	document.getElementById("sh_gp").innerHTML = "hide guest picker tools";
	document.getElementById("sh_gp").onclick = HideQuickGuestPicker;
}
function HideQuickGuestPicker() {
    var qgi = document.getElementById("quickguestinvite");
    var gp = document.getElementById("sh_gp");
    if(qgi)
        qgi.style.display = "none";
    if(gp) {
        gp.innerHTML = "Add Guests";
        gp.onclick = ShowQuickGuestPicker;
    }
}
function ShowGuestPicker() {
  $("#quickguestinvite").css("display", "block");
  $("#quickguestinvite_small").css("display", "none");
}
function HideGuestPicker(){
  $("#quickguestinvite").css("display", "none");
  $("#quickguestinvite_small").css("display", "block");
}

//constructor for an item in the Guests array. Could have more fields here (like fn, ln, email...)
function guest(fn_ln_email, id) {
	this.fn_ln_email = fn_ln_email;
	this.id = id;
}
//function called by the interpreter as it's executing sort: NOT USED
function sortGuests(a, b) {
	var x = a.fn_ln_email.toLowerCase();
	var y = b.fn_ln_email.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function inviteGuest(idx,em,fn,ln,bNotify){
	if(cpsv.length) 
		cpsv+='|';
    var s = bNotify ? "notificationsent" : "inviting";
	//since I'm drawing before actually knowing if the invitation succeeded, if notify is set, I just pretend the notif was sent.
	if( (allContacts.length) && (idx < allContacts.length) && (idx != -1) ){
		allContacts[idx].s = s;
		cpsv+='old,'+allContacts[idx].id+','+idx+','+bNotify;
	}else{
		l = allContacts.length;
		allContacts[l] = {"id":0,"fn":fn,"ln":ln,"em":em,"cnt":0,"s":s,"vd":"","rd":""};
		cpsv+='new,'+em+','+l+','+bNotify;
	}
}

function writeActionInvite(em,fn,ln,type,bNotify){
  var idx = getGuestIndex(em);
  var outtxt= '{"name":"invite","type":"'+type+'","notify":'+bNotify+',"iid":';
  outtxt += (currentusertype == "companion") ? inviterid : uID;
  outtxt += ',"user":{';
  if(idx != -1)
    outtxt += '"id":'+allContacts[idx].id+',"idx":'+idx+',';
  outtxt += '"em":"'+em+'","fn":"'+fn+'","ln":"'+ln+'"}}';    
  return outtxt;
}
function onAddGuestsClicked(bNotify) {
  var b = document.getElementById("fc_guestnames");
  if($("#fc_pickbyaddbook").attr("checked") == true)
    onAddGuestsFromAB();
  else
    onAddGuestsClicked3(bNotify, b.value);
  b.value = "";
}
function onAddGuestsFromAB() {
  var x=0,actiontxt="";
  for(x=0; x<allContacts.length; x++ ){
    if(allContacts[x].s == "preinviting"){
      allContacts[x].s = "inviting";
      if(actiontxt.length) actiontxt += ",";
      actiontxt += writeActionInvite(allContacts[x].em,allContacts[x].fn,allContacts[x].ln,"guest",false);
    }
  }
  postJSONProc(parseInt(eventID), actiontxt);
  renderNewGuestList();
  renderAddBookPicker();
}
function onAddGuestsClicked3(bNotify, str) {
	var arrNameEmail = str.split(',');
	var x=0,y=0,i,j,item,actiontxt="",s="";
  var ns = new NameString("");
	try	{
		j = arrNameEmail.length;
		cpsv="";
		for(x=0;x<j;x++){
			item = trim(arrNameEmail[x]);
      ns.setInput(item);
      if(ns.em.length){
        //First, let's insert this user in the local collection
        //I really should build a wait dialog and wait to see if the email was really sent before setting the status... 
        i = getGuestIndex(ns.em);
        s = bNotify ? "notificationsent" : "inviting";
        if(i != -1)
          allContacts[i].s = s;
        else
          allContacts[allContacts.length] = {"id":0,"fn":ns.fn,"ln":ns.ln,"em":ns.em,"cnt":0,"s":s,"vd":"","rd":"","msg":"","numchildren":0,"numcomps":0}; //can push actually take a JSON block in all arrays?
        //Second, let's get write the JSON text that we need to send to the server 
        if(actiontxt.length)
          actiontxt += ",";
        actiontxt += writeActionInvite(ns.em,ns.fn,ns.ln,"guest",bNotify);
        //Pretending that it's already been done... great user experience when it works!!!
        remFromTypeAssist(ns.em);
      }else{
          if(x+1<j)
              alert("No valid email address was seen in the entry '"+item+"'. This item will be ignored.");
      }
		}
    postJSONProc(parseInt(eventID), actiontxt);
    if(bNotify)
      renderNotReplied();
    else
      renderNewGuestList();
		return false;
	}catch (e) { alert(e); return false}
}
function reloadThePage(){
    window.location = window.top.location;
}
function onclickMRUGuest(el,idx) {
	el.className="MFUNameSeled";
	el.onclick="";
	inviteGuest(idx,"","","",0);
  remFromTypeAssist(allContacts[idx].em);
	renderNewGuestList();
	postGLChanges(cpsv);
}
// finds the index of the Guest in the allContacts array
function getGuestIndex(email) {
	if(allContacts.length) {
		for (var x in allContacts) {
			if(allContacts[x].em == email)
				return x;
		}
	}
	return -1;
}
function getIndexByParam(arr, param, value) {
	if(arr.length) {
		for (var x in arr) {
			if(arr[x][param] == value)
				return x;
		}
	}
	return -1;
}
//---------- Submit (invite) new Guests for the event ----------
function postGLChanges(cpsvID) {
	var qs="action=inviteGuests&eid="+parseInt(eventID)+"&gid="+cpsvID;
	YAHOO.util.Connect.asyncRequest('POST', '/proc.php', IGCallback, qs);
}
function postJSONProc(eventID, actions) {
	var jsout='{"eID" : '+parseInt(eventID)+',"actions":['+actions+']}';
  var data = "format=json&jso="+escape(jsout);
	//YAHOO.util.Connect.asyncRequest('POST', '/proc.php?format=json', IGCallback, "jso="+escape(jsout));
  $.ajax({
    type: "POST",
    url: "/proc.php",
    success: handleJSONSuccess,
    error: handleJSONFailure,
    timeout: 10000,
    data:data});
}
function handleJSONSuccess(data, textStatus){
	var updatedUsers = eval( '(' +data+ ')' );
	var string;
  if(updatedUsers.length && allContacts.length) {
    for(var x in updatedUsers){
      if(parseInt(updatedUsers[x].idx) != -1)
          allContacts[parseInt(updatedUsers[x].idx)] = updatedUsers[x];
    }
  }
}
function handleJSONFailure(XMLHttpRequest, textStatus, errorThrown) {
  if(XMLHttpRequest.status == "403")
    alert("Sorry, you don't seem to be logged-in. Perhaps something happened to your cookies. Go to the home page and log-in. "+XMLHttpRequest.status);
  else
    alert("Sorry, there was an error. Please try again. "+XMLHttpRequest.status);  
}
//------------------------------------------------------------

//---------- Get the list of Contacts for the event ----------
//function handleECLSuccess(o){
function handleECLSuccess(data, textStatus){
  var el,cID;
	el = document.getElementById("autocompletestatus");
  if(el) el.style.display = "none";
	//if( (o.status == "204") || (o.status==204) ||(o.statusText.match(/No Content/i)) ){
  if( !data.length) {
    handleHasNoContacts();
	}else{
		allContacts = eval( '(' + data + ')' );
		var string, iNotNull=0,t=0,c=0;
      if(bProcCompanions){
        cID=uID;
        if(currentusertype == "companion")
          cID = inviterid;
      }
		//loop for fill type assist collection and to compute the cnt average and to fill the array of companions
		for(var x in allContacts){
			collection[x] = allContacts[x].fn + " "+ allContacts[x].ln + " <"+ allContacts[x].em + ">";
			if(allContacts[x].cnt > 0){
				iNotNull++;
				t+=parseInt(allContacts[x].cnt);
			}
			if(allContacts[x].s != "ni")
        c++;
      if(bProcCompanions){
        if((allContacts[x].type == "companion") && (allContacts[x].inviterID == cID) && (allContacts[x].id != uID)){
           arrCompanions.push(allContacts[x]);
           numNamedCompanions++;
        }
        if((currentusertype == "companion") && (allContacts[x].id == inviterid)){
          numUnamedCompanions = allContacts[x].numcomps;
          numUnamedCompanionsInit = numUnamedCompanions;
          inviterPos = x;
        }
        if((currentusertype != "companion") && (allContacts[x].id == uID))
          numUnamedCompanions = allContacts[x].numcomps;
          numUnamedCompanionsInit = numUnamedCompanions;
      }
		}
    if(bListsAreAJAX)
        renderAllLists2();
		if(iNotNull) {
			avgCnt = t/iNotNull;
		}
    if(window.redrawAddBookPicker){
      allContacts.sort(sortbyfn);
      renderAddBookPicker();
    }
		else avgCnt=0;
		if(!avgCnt){
			el = document.getElementById("PickMRUG_btn");
            if(el) el.style.display = "none";
        }
    if(pid==1){
      if(c) HideGuestPicker();
      else ShowGuestPicker();
    }
	}
	el = document.getElementById("waitforlistarea");
    if(el) el.style.display = "none";
	el = document.getElementById("guestlist");
    if(el) el.style.display = "block";
  if(pid==1){
    //var selidx = $("#addsel").attr("selectedIndex");
    var el = document.getElementById("addsel");
    if(el){
      selidx = el.selectedIndex;
    }
    setTimeout('showMap(uLoc2['+selidx+'])', 100);
  }else{
    setTimeout('showMap(uLoc2[0])', 100);
    //showMap(uLoc2[0]);
  }
}
function handleECLFailure (XMLHttpRequest, textStatus, errorThrown) {
  alert("There was a glitch when trying to retreive the guest list. Click 'reload' in your browser or try again later.");
  var el = document.getElementById("waitforlistarea");
  if(el) el.style.display = "none";  
}
function handleHasNoContacts(){
    $("#importareacont").css("display", "block");
    $("#PickMRUG_btn").css("display", "none");
    $("#launchAddBook_dlg_btn").css("display", "none");
    ShowGuestPicker();
}
function getEventContactList() {
	var reqstr = "action=req_contacts4event&eid="+parseInt(eventID);
  $.ajax({
    type: "POST",
    url: "/proc.php",
    success: handleECLSuccess,
    error: handleECLFailure,
    timeout: 5000,
    data:reqstr});
};
//-------------------------------------------------------------------
var gotContactsSuccess = function(o){
	if( (o.status == "204") || (o.status==204) ||(o.statusText.match(/No Content/i)) ){
        showGuestAddGuestPicker();
    }else{
        allContacts = eval( '(' + o.responseText + ')' );
        //loop for fill type assist collection and to compute the cnt average
        for(var x in allContacts){
            collection[x] = allContacts[x].fn + " "+ allContacts[x].ln + " <"+ allContacts[x].em + ">";
        }
        showGuestAddGuestPicker();
    }
};
function showGuestAddGuestPicker(){
    try{
    document.getElementById("guestpickerwait").style.display = "none";
    document.getElementById("guestpickercontainer").style.display = "block";
    }catch (e){
        alert("caught an error");
    }    
}
var gotContactsFailure = function(o){
	document.getElementById("footer").innerHTML = "Get Contacts failed";
	o.statusText;
	YAHOO.container.wait4csv.hide();
};
var getContactsCallback = {
	success:gotContactsSuccess,
	failure:gotContactsFailure,
	argument:""
};
function getContactList() {
	var reqstr = "action=req_contacts&contacttype=partier"; 
	YAHOO.util.Connect.asyncRequest('POST', '/proc.php', getContactsCallback, reqstr);
};
//-------------------------------------------------------------------

//---------Remove Guests Stuff---------------------------------------
function onRemoveGuest(id) {
	for(var x=0; x<allContacts.length; x++ ){
		if(allContacts[x].id == id) {
			allContacts[x].s = "ni";
			break;
		}
	}
  var actiontxt = '{"name":"uninvite","user":{"id":'+id+',"em":"'+allContacts[x].em+'"}}';
  postJSONProc(parseInt(eventID), actiontxt);	
	renderAllLists2();
}
//-------------------------------------------------------------------
function AddressBookCheckAll(bCheck) {
	var el;
	for(var x in allContacts) {
		tname = "tn"+x;
		try{
			el = document.getElementById(tname);
			el.checked = bCheck;
		}catch(e){};
	}		
}
//-------------------------------------------------------------------
function onClickAddChecked() {
	var el,actiontxt="",bF=0;
	cpsv="";
	for(var x in allContacts) {
		tname = "tn"+x;
		try{
			el = document.getElementById(tname);
			if(el.checked){
        bF=1;
				//inviteGuest(x,"","","",0);
        //remFromTypeAssist(allContacts[x].em);
        allContacts[x].s = "notnotified";
        if(actiontxt.length)
          actiontxt += ",";
        actiontxt += writeActionInvite(allContacts[x].em,allContacts[x].fn,allContacts[x].ln,"guest",0);
        //Pretending that it's already been done... great user experience when it works!!!
        remFromTypeAssist(allContacts[x].em);
			}
		}catch(e){};
	}
  YAHOO.container.AddBook_dlg.hide();
  renderNewGuestList();
  postJSONProc(parseInt(eventID), actiontxt);
}
//-------------------Edit Event Properties -------------------
//-- Begin ---
function ShowWait(sec, relEl){
  $("#wait_dlg").css({"left":($("#"+relEl).offset().left-75)+"px","top":($("#gig").offset().top-50)+"px"});
  $("#wait_dlg").show();
  setTimeout("donewait()",sec)
}
var init_wait_dlg = function() {
    YAHOO.container.wait = new YAHOO.widget.Panel("wait_dlg",
        {   width:"30em", 
            fixedcenter:true, 
            close:false, 
            draggable:true, 
            modal:true,
            visible:false} );
    YAHOO.container.wait.setHeader("Submitting your change");
    YAHOO.container.wait.render(document.body);
    YAHOO.util.Event.addListener("close_wait_dlg_btn", "click", YAHOO.container.wait.hide, YAHOO.container.wait, true);
    
    YAHOO.container.wait.showEvent.subscribe(onShowWaitDlg);
    YAHOO.container.wait.hideEvent.subscribe(onHideWaitDlg);
    function onShowWaitDlg(){
        YAHOO.util.Dom.setStyle('wait_dlg', 'display', 'block');
    }
    function onHideWaitDlg(){YAHOO.util.Dom.setStyle('wait_dlg', 'display', 'none');}
  }
  function donewait() {
    canCloseWaitDlg = 1;
    //if(procdone)
      $("#wait_dlg").hide();
  }

  function onOKclicked() {
    YAHOO.container.wait.hide();
  }
  function postActionWithWait(timeout,header,action,namevaluepairs,cb) {
    IBC = action;
    if(timeout){
      setTimeout("donewait()",timeout)
      $("#wait_dlg").show();
    }
  }
  function onGIGclicked() {
    ShowWait(2000, "gig");
    var postData = "action=process_gig&eid="+eventID+"&guests_invite_guests="; 
    if(document.getElementById("gig").checked)
      postData += "on"; 
    else
      postData += "off"; 
    $.ajax({type: "POST",url: "/proc.php", data:postData});
    //var request = YAHOO.util.Connect.asyncRequest('POST', sURL, waitDlgcallback, postData);
  }
  function onGSGclicked() {
    ShowWait(2000, "gsg");
    //IBC = "GSG";
    var postData = "action=process_gsg&eid="+eventID+"&guests_see_guests="; 
    if(document.getElementById("gsg").checked)
      postData += "on"; 
    else
      postData += "off"; 
    $.ajax({type: "POST",url: "/proc.php", data:postData});
  }
function onSaveReminder(){
  var el = document.getElementById('reminder');
  if(el){
    var idx = el.selectedIndex;
    //alert(el[idx].value);
    $.ajax({type: "POST",url: "/proc.php", data:"action=setreminder&eid="+eventID+"&ndays="+el[idx].value});
    if(parseInt(el[idx].value) == 0)
      var outtxt = "You have not set a reminder.";
    else if(parseInt(el[idx].value) == 1)
      var outtxt = "You are set to receive an email 1 day before the event.";
    else
      var outtxt = "You are set to receive an email "+el[idx].value+" days before the event.";
    $("#setreminderbox .status").html(outtxt);
  }  
}
//-- END ---
//-------------------Edit Event Properties -------------------

//-------- RENDERING FUNCTIONS ----------
function renderNewGuestList() {
	var strHTML = " ";
  var el = document.getElementById("invitationnotsent");
  if(el){
    for(var x in allContacts) {
      if( (allContacts[x].s == "inviting") || (allContacts[x].s == "notnotified") ) {
        strHTML += renderUnsentGuest(x);
      }
    }
    el.innerHTML = strHTML;
    var el2 = document.getElementById("invitationnotsentbox");
    if(el2) el2.style.display = "block";
	}
}

function renderGuestName(x) {
  return renderGuestName2(allContacts[x]);
}
function renderGuestName2(item) {
	var outHTML="";
	if( item.fn.length && item.ln.length )
		return item.fn+' '+item.ln;
	if( item.fn.length && item.em.length)
		return outHTML += item.fn+' &lt;'+item.em+'&gt;';
	if( item.ln.length && item.em.length)
		return outHTML += item.ln+' &lt;'+item.em+'&gt;';
	return outHTML += item.em;
}
function renderGuest(pos){
  var strout="";
  if(parseInt(allContacts[pos].numchildren) || parseInt(allContacts[pos].numcomps))
    strout += "<li class='two' ";
  else{
    if(allContacts[pos].s == "slave")
      strout += "<li class='one child' ";
    else
      strout += "<li class='one' ";
  }
  if(bEventOwner){
    strout+="onmouseover='onentergli(this)' onmouseout='onexitgli(this)'";
  }
  strout+=">";

  strout += renderGuestName(pos);
  if(bEventOwner){
    strJSCB = "'onRemoveGuest(allContacts["+pos+"].id);'";
    strout+='<a style="display: none" onclick='+strJSCB+' href="#"/>&nbsp;&nbsp;[ x ]</a>';
    //strout+='<img style="position: absolute; top: -1px; right: 0px; display: none" onclick='+strJSCB+' title="Remove this guest" src="/i/icons/cancel.png" alt="remove"/>';
  }
  var bWD = 0;
  if(allContacts[pos].rd){
    if(allContacts[pos].rd.length && allContacts[pos].rd.indexOf("0000",0) == -1){
      strout += "<em>("+allContacts[pos].rd+")</em>";
      bWD = 1;
    }
  }
  if(!bWD && allContacts[pos].vd){
    if(allContacts[pos].vd.length && allContacts[pos].vd.indexOf("0000",0) == -1)
      strout += "<em>("+allContacts[pos].vd+")</em>";
  }
  if(allContacts[pos].msg.length)
    strout += "<span class='rep'>\""+allContacts[pos].msg+"\"</span>";
    
  strout +="</li>";
  //strJSCB = "'onRemoveGuest(allContacts["+pos+"].id);'";
  //strout+='<img style="position: absolute; top: -1px; right: 0px; display: none" onclick='+strJSCB+' title="Remove this guest" src="http://yui.yahooapis.com/2.2.2/build/container/assets/close12_1.gif" alt="remove"/>';
  return strout;
}
function renderUnsentGuest(pos){
  var strout='<p><span class="name">';
  strout += renderGuestName(pos);
  strJSCB = "'onRemoveGuest(allContacts["+pos+"].id);'";
  strout += '</span><a href="#" onclick='+strJSCB+'>[x]</a></p>';
  return strout;
}
function renderAllLists2() {
  if(!bGuestsShown)
    return;
	var el,outAcc="",outRej="",outMay="",outSent="",outNotR="",outAddBook="",iCompBuf,sBuf="",iPPos=0,iTempCnt=0,bWTR=0,bR=0,cs="",bIsP=0,bIsC=0;
  var lastParent = {"pos":0,"s":"","cnt":0,"comp":0};
	iTotalYes=0;iTotalNo=0;iTotalMaybe=0;iTotalNotResp=0;  
    var l = allContacts.length;
	for(var x in allContacts) {
    if(allContacts[x].id == crID)
      continue; //don't render the creator in the guest lists. 
    cs = allContacts[x].s;
    if(cs != "ni"){
      if(lastParent.cnt)
          lastParent.cnt--;
      else{
          lastParent = {"pos":x,"s":cs,"cnt":(parseInt(allContacts[x].numchildren)),"comp":parseInt(allContacts[x].numcomps)};
      }
      if((cs == "accepted") || ((cs == "slave") && (allContacts[lastParent.pos].s == "accepted"))){
        outAcc += renderGuest(x);
        iTotalYes++;
      }else if ((cs == "rejected") || ((cs == "slave") && (allContacts[lastParent.pos].s == "rejected"))){
        outRej += renderGuest(x);
        iTotalNo++;
      }else if ((cs == "maybe") || ((cs == "slave") && (allContacts[lastParent.pos].s == "maybe"))){
        outMay += renderGuest(x);
        iTotalMaybe++;
      }else if ((cs == "notificationsent") || ((cs == "slave") && (allContacts[lastParent.pos].s == "notificationsent"))){
        outSent += renderGuest(x);
        iTotalNotResp++;
      }else if ((cs == "notnotified") || ((cs == "slave") && (allContacts[lastParent.pos].s == "notnotified"))){
        outNotR += renderUnsentGuest(x);
      }

      if(!lastParent.cnt && lastParent.comp){
          if(lastParent.s == "accepted"){
              outAcc += renderPlusLine(lastParent.comp);
              iTotalYes+=lastParent.comp;
          }else if (lastParent.s == "rejected"){
              outRej += renderPlusLine(lastParent.comp);
              iTotalNo+=lastParent.comp;
          }else if (lastParent.s == "maybe"){
              outMay += renderPlusLine(lastParent.comp);
              iTotalMaybe+=lastParent.comp;
          }else if (lastParent.s == "notificationsent"){
              outSent += renderPlusLine(lastParent.comp);
              iTotalNotResp+=lastParent.comp;
          }else if (lastParent.s == "notnotified"){
              outNotR += renderPlusLine(lastParent.comp);
          }
      }
    }
	}
	document.getElementById("guestsaccepted").innerHTML = outAcc;
	document.getElementById("guestsrejected").innerHTML = outRej;
	document.getElementById("guestsmaybe").innerHTML = outMay;
	document.getElementById("guestsnotreplied").innerHTML = outSent;

	document.getElementById("numYes").innerHTML = "("+iTotalYes+" guests)";
	document.getElementById("numNo").innerHTML = "("+iTotalNo+" guests)";
	document.getElementById("numMaybe").innerHTML = "("+iTotalMaybe+" guests)";
  document.getElementById("numNotRep").innerHTML = "("+iTotalNotResp+" guests)";
  if(pid==1){
    /*if(outAddBook)
      document.getElementById("addbook").innerHTML = outAddBook;*/
    var dispstyle = iTotalYes ? "block" : "none";
    $("#guestsacceptedbox .emaillist_btn").css("display",dispstyle);
    dispstyle = iTotalNo ? "block" : "none";
    $("#guestsrejectedbox .emaillist_btn").css("display",dispstyle);
    dispstyle = iTotalMaybe ? "block" : "none";
    $("#maybebox .emaillist_btn").css("display",dispstyle);
    dispstyle = iTotalNotResp ? "block" : "none";
    $("#notrepliedbox .emaillist_btn").css("display",dispstyle);
  }
  el = document.getElementById("invitationnotsent");
  if(el){
    el.innerHTML = outNotR;
  }
  RenderCompanions();
}
function renderNotReplied(){
  if(!bGuestsShown)
    return;
	var el,outSent="";
	for(var x in allContacts) {
    if(allContacts[x].id == crID)
      continue; //don't render the creator in the guest lists. 
    cs = allContacts[x].s;
    if (cs == "notificationsent"){
      outSent += renderGuest(x);
      iTotalNotResp++;
    }
	}
	document.getElementById("guestsnotreplied").innerHTML = outSent;
  document.getElementById("numNotRep").innerHTML = "("+iTotalNotResp+" guests)";
  var dispstyle = iTotalNotResp ? "block" : "none";
  $("#notrepliedbox .emaillist_btn").css("display",dispstyle);
  
}

function renderPlusLine(num){
  return '<li class="one child">+ '+num+' more</li>';
}

function remFromTypeAssist(em){
	for (y=0;y<collection.length;y++) {
		if(collection[y].match(em)) 
			collection.splice(y,1);
	}  
}
function onentergli(el){
    var mylist=el.getElementsByTagName("a");
    mylist[0].style.display='inline';
}
function onexitgli(el){
    var mylist=el.getElementsByTagName("a");
    mylist[0].style.display='none';
}
function renderMFUList() {
	var outHTML="",cnt=0;
	cpsv=""; //if you don't understand what this does, don't remove it!!
	for(var x in allContacts) {
		if(allContacts[x].cnt > avgCnt){
			if(allContacts[x].s == "ni"){
				cnt++;
				outHTML += '<li><span class="MFUName" onclick="onclickMRUGuest(this,'+x+');">'+renderGuestName(x)+'</span></li>'
			}else
				outHTML += '<li><span class="MFUNameSeled" onclick="onclickMRUGuest(this,'+x+');">'+renderGuestName(x)+'</span></li>'
			if(cnt>30) break;
		}		
	}
	document.getElementById('MFUNames').innerHTML = outHTML;
}
function renderAddBookEl(i){
  var out ="",idstr="cb_"+i;
  
  if(allContacts[i].s != "ni"){
    out += '<span><input id="'+idstr+'" name="check" checked disabled="disabled" class="checkset" type="checkbox" onclick="onCheckedABP(this);">&nbsp;';
    out += "<strong>";
  }else{
    out += '<span><input id="'+idstr+'" name="check" class="checkset" type="checkbox" onclick="onCheckedABP(this);">&nbsp;';
  }
  if(allContacts[i].fn.length) out += allContacts[i].fn+" ";
  if(allContacts[i].ln.length) out += allContacts[i].ln+" ";
  out += '&lt;'+allContacts[i].em+'&gt;</span>';
  if(allContacts[i].s != "ni") out += "</strong>";
  return out;
}
function renderAddBookPicker() {
	var out="",el=document.getElementById('addbook'), lastLetter='', bTO=false;
  if(el){
    el.innerHTML = '<IMG SRC="/i/wait.gif" WIDTH="16" HEIGHT="16" BORDER="0" ALT="">';
    for(var x in allContacts) {
      if(allContacts[x].fn.length){
        if(lastLetter != allContacts[x].fn.charAt(0).toUpperCase()){
          lastLetter = allContacts[x].fn.charAt(0).toUpperCase();
          //if(bTO) out += '';
          out  += '</div><span class="letter">'+lastLetter+'</span><div class="letterlist">';
          //bTO=true;
        }
      }
      out += renderAddBookEl(x);
    }
    out += '</div><div id="impaddbook" style="display: none"><span class="letter">END</span><a href="#" onclick="myshowPlaxoABChooser(); return false;">[ import an address book ]</a></div>';
    el.innerHTML = out;
    initPlaxo();
    bAddBookRendered = true;
  }
}
function myshowPlaxoABChooser(){
  if(self.showPlaxoABChooser)
    showPlaxoABChooser('plaxoaddbook', '/s/plaxo_import.html');
  else
    alert("Plaxo provides an awesome address book import tool that Boomguest users. Unfortunately, there seems to be an issue contacting Plaxo right not. Perhaps you can try again later or from an other network.");
  return false;
}
function initPlaxo(){
  if(!window.plaxo1)
    $.getScript("http://www.plaxo.com/css/m/js/util.js", function(){ window.plaxo1 = 1; showPlaxoLink();});
  if(!window.plaxo2)
    $.getScript("http://www.plaxo.com/css/m/js/basic.js", function(){ window.plaxo2 = 1;showPlaxoLink();});
  if(!window.plaxo3)
    $.getScript("http://www.plaxo.com/css/m/js/abc_launcher.js", function(){ window.plaxo3 = 1;showPlaxoLink();});
}
function showPlaxoLink(){
  if(window.plaxo1 && window.plaxo2 && window.plaxo3){
    $("#impaddbook").css("display", "block");
  }
}
function onCheckedABP(el){
  var idstr = el.id;
  var arr = idstr.split("_", 2);
  if(el.checked)
    allContacts[arr[1]].s = "preinviting";
  else
    allContacts[arr[1]].s = "ni";
}
//------------------- UI helper functions -------------------
function IsInputInCol(str, col){
    try{
        ns = new NameString(str);
        for(var x in col){
            if(ns.em == col[x].em)
                return x;
        }
        return false;
    }catch (e){
        return false;
    }    

}
function onChangeAddressSel2() {
  var idx = document.getElementById("addsel").selectedIndex;
  document.getElementById("fc_locname").value = uLoc2[idx].name?uLoc2[idx].name:"";
  document.getElementById("fc_loc_street").value = uLoc2[idx].street?uLoc2[idx].street:"";
  document.getElementById("fc_loc_city").value = uLoc2[idx].city?uLoc2[idx].city:"";
  SetSelectValue("fc_loc_state", uLoc2[idx].state);
  document.getElementById("fc_loc_zip").value = uLoc2[idx].zip?uLoc2[idx].zip:"";
}
function hasAddressValsChanged(){
  try {
    var idx = document.getElementById("addsel").selectedIndex;
    if(document.getElementById("fc_loc_street").value != uLoc2[idx].street) return true;
    if(document.getElementById("fc_loc_city").value != uLoc2[idx].city) return true;
    if(document.getElementById("fc_loc_zip").value != uLoc2[idx].zip) return true;
    var sel = document.getElementById("fc_loc_state");
    var i = sel.selectedIndex;
    if(sel.options[i].text.toLowerCase() != uLoc2[idx].state.toLowerCase()) return true;
    return false;
  }catch (e) { return false}
}
// --------------------- BEGIN: Guest Page ---------------------
var nOtherComps = 0;
var strTempCompRem = "";
var bResponseChanged = false;

function initGuestpage() {
  if(bListsAreAJAX)
    getEventContactList();

  //--- Event Name ---
  $("#showCompanionDlgBtn").click(function (e) {
    RenderCompDlg();
    $("#edit_companions_dlg").css({"left":(e.pageX-150)+"px","top":(e.pageY-180)+"px","right":"auto","z-index":"2000"});
    $("#edit_companions_dlg").show("medium");
    });
  $("#cancel_edit_companions_btn").click(function () {$("#edit_companions_dlg").hide();});
  $("#save_edit_companions_btn").click(function () {
    if(onCompanionDlgOK())
      $("#edit_companions_dlg").hide();
    });
  $("#gag_save_btn").click(function () {
    onAddGuestsClicked3(true, $("#fc_gagnames").attr('value'));
    $("#fc_gagnames").attr('value', "");
    });
  $("#btn_toggleSetReminder").click(function(){
    if($("#plusminus").html() == "+")
      $("#plusminus").html("-");
    else
      $("#plusminus").html("+");
    $("#setreminderbox").slideToggle( "medium")
  });
  $("#save_reminder_btn").click(onSaveReminder);
}
function RenderCompDlg() {
  var out = "",x=0;
  numNamedCompanions=arrCompanions.length;
  var totalcnt = numNamedCompanions+parseInt(numUnamedCompanions);
	//get the dropdown of companions and set it to the right number.
  el = document.getElementById("fc_numcompanions");
  if(el) el.value = totalcnt;
  //draw the correct number of names and name places
  for(x=0; x<numNamedCompanions; x++){
    out += '<li class="companion">'+
          //'<INPUT autocomplete="off" class="wickEnabled:TypeAssistWinComp nocomma" TYPE="text" NAME="comp_'+x+'" value="'+ arrCompanions[x].fn+' '+arrCompanions[x].ln+' '+arrCompanions[x].em+'">'+
          '<INPUT autocomplete="off" class="nocomma" TYPE="text" NAME="comp_'+x+'" value="'+ arrCompanions[x].fn+' '+arrCompanions[x].ln+' '+arrCompanions[x].em+'">'+
          '&nbsp;&nbsp;<a class="remove_btn" href="#" onclick="removeCompanionBox(this);">[ x ]</a>'+
          '</li>';
  }
  for(var y=0; y<numUnamedCompanions;y++){
    out += '<li class="companion">'+
          //'<INPUT onfocus="javascript: this.nextSibling.nextSibling.style.display=\'none\';" autocomplete="off" class="wickEnabled:TypeAssistWinComp nocomma" TYPE="text" NAME="comp_'+(y+x)+'" value="">'+
          '<INPUT autocomplete="off" class="nocomma" TYPE="text" NAME="comp_'+(y+x)+'" value="">'+
          '&nbsp;&nbsp;<a class="remove_btn" href="#" onclick="removeCompanionBox(this);">[ x ]</a>'+
          '<span class="invisbleerror">Must contain an email address (or just leave blank)</span>'+
          '</li>';    
  }
  el = document.getElementById("edit_complist");
  if(el) el.innerHTML = out;
}
function removeCompanionBox(el){
  RemoveMyParent(el);
  document.getElementById('fc_numcompanions').value--;
  numUnamedCompanions--;
}
function removeEmptyCompanionBox(){
  numUnamedCompanions--;
  RenderCompDlg()
}
//---------- Companion Dialog handlers ----------
function onCompanionDlgOK() {
	var n = document.companionnames.length;
  var ns = new NameString("");
  var arrNewCompanions = new Array(), out="";
  numUnamedCompanions = 0;
  for(i=0; i<document.companionnames.elements.length; i++)
  {
    if( trim(document.companionnames.elements[i].value).length == 0){
      numUnamedCompanions++;
    }else{
      ns.setInput(trim(document.companionnames.elements[i].value));
      if(ns.em.length) {
        l = arrNewCompanions.length;
        arrNewCompanions[l] = {"id":0,"fn":ns.fn,"ln":ns.ln,"em":ns.em,"cnt":0,"s":"inviting","vd":"","rd":""};
      }else{
        var eq = "#edit_complist li:eq("+i+") span";
        $(eq).css("display", "block");
        //document.companionnames.elements[i].nextSibling.nextSibling.style.display='inline';
        return false;
        //handle the error of not having found an email.
      }
    }
  }
  //1.Look for companions that are no longer there
  var removed,newtocomplist,idx=-1;
  for(var x in arrCompanions){
    removed=true;
    for(var y in arrNewCompanions){
      if(arrNewCompanions[y].em == arrCompanions[x].em){
        removed=false;
        break;
      }
    }
    if(removed){
      idx = getGuestIndex(arrCompanions[x].em);
      if (out.length) out += ",";
      out += '{"name":"uninvite","user":{"id":'+arrCompanions[x].id+',"idx":'+idx+',"em":"'+arrCompanions[x].em+'"}}';
      allContacts[idx].s = "ni";
    }
  }
  //2.Find new companions
  for(var y in arrNewCompanions){
    newtocomplist=true;
    for(var x in arrCompanions){
      if(arrNewCompanions[y].em == arrCompanions[x].em){
        newtocomplist=false;
        break;
      }
    }
    if(newtocomplist){
      idx = getGuestIndex(arrNewCompanions[y].em);
      if(idx != -1){
        //Is this user already a guest?
        if(allContacts[idx].s != "ni") {
          alert('"'+renderGuestName(idx)+'" is already a guest of this event.');
          return false;
        }
        arrNewCompanions[y].id = allContacts[idx].id;
      }else
        arrNewCompanions[y].id = 0;
      arrNewCompanions[y].idx = idx;

      //Now that we know what we are doing, let's add new users to the main guest list.
      var theguest;
      if(idx != -1){
        //first, companions that exist must be removed from allContacts so that they can be reinserted after it's inviter
        theguest = allContacts[idx];
        allContacts.splice(idx, 1);
      }else{
        theguest = arrNewCompanions[y];
      }
      theguest.s = "accepted";
      theguest.rd = "";
      theguest.msg = "";
      var posI = getIndexByParam(allContacts, "id", (currentusertype=="companion")?inviterid:uID);
      posI = parseInt(posI)+1; 
      allContacts.splice(posI, 0, theguest);
      //Write the JSON action request
      if (out.length) out += ",";
      out += writeActionInvite(arrNewCompanions[y].em,arrNewCompanions[y].fn,arrNewCompanions[y].ln,"companion",1);
    }
  }
  if(out.length)
    arrCompanions = arrNewCompanions;
  
  if(numUnamedCompanionsInit != numUnamedCompanions){
    var gID=uID;
    if(currentusertype == "companion")
      gID = inviterid;
    if (out.length) out += ",";
    out += '{"name":"setnumcomp","num":'+numUnamedCompanions+',"user":{"id":'+gID+'}}';
    numUnamedCompanionsInit = numUnamedCompanions;
  }
  if(out.length)
    postJSONProc(parseInt(eventID), out);
  
  arrCompanions = arrNewCompanions;
  
	if(bResponseChanged)
		onChangedResponse();
	UpdateGuestCounters();
  renderAllLists2();
  return true;
}
var onCompanionDlgCancel = function() {
	numUnamedCompanions = numUnamedCompanionsInit;
  this.cancel();
};
var onConvertDlgOK = function() {
  YAHOO.container.convcompaniondlg.hide();
  var out="";
  for(var x in arrCompanions){
    el = document.getElementById("cur_"+arrCompanions[x].id);
    if(el){
      if(el.checked){
        if (out.length) out += ",";
        out += '{"name":"uninvite","user":{"id":'+arrCompanions[x].id+',"em":"'+arrCompanions[x].em+'"}}';
      }else{
        arrCompanions[x].s = "removed";
        if (out.length) out += ",";
        out += '{"name":"comp2guest","user":{"id":'+arrCompanions[x].id+',"em":"'+arrCompanions[x].em+'","s":"accepted"}}'; //todo: set the state of the inviter
      }
    }
  }
  arrCompanions.length = 0;
  if (out.length) out += ",";
  out += encodeResponse();
  if(out.length){
    postJSONProc(parseInt(eventID), out);
    RenderCompanions();
    document.getElementById('totalcompanions_cnt').innerHTML = "0";
    document.getElementById('fc_hNumCompanions').value = "0";
    el = document.getElementById('compcntlist');
    if(el) el.innerHTML = "";
  }
}

var onConvertDlgCancel = function() {
  YAHOO.container.convcompaniondlg.hide();
  if(currentResponse == "YES")
      el = document.getElementById('fc_yes');
  if(currentResponse == "MAYBE")
      el = document.getElementById('fc_maybe');
  if(el)
      el.checked = true;
}

var handleSuccessCompDlg = function(o) {
	alert("success received after saving companion dlg");
};
var handleFailureCompDlg = function(o) {alert("Submission failed: " + o.status);};

function encodeResponse(){
  el = document.getElementById('fc_respmsg');
  var notes="";
  if(el)
    notes = escape(el.value);
  return '{"name":"response","value":"'+getSelectedResponse()+'","notes":"'+notes+'"}';
}

function getSelectedResponse(){
  el = document.getElementById('fc_yes');
  if(el && el.checked == true)
    return "YES";
  el = document.getElementById('fc_no');
  if(el && el.checked == true)
    return "NO";
  return "MAYBE";  
}
//formats the string in this format [del],[userID],[intPassedBack]|
function onRemoveCompanion(el) {
    el = el.parentNode;
	//if the item has an id, it means that it exists in the DB, so it must be scheduled for deletion.
    if(el.id.length){
		if(strTempCompRem.length)
			strTempCompRem += '|';
		strTempCompRem += "del,"+el.id.substring(4)+",0";
		//alert("removing item id. posting: "+fcrem.value);
	}
    //remove the item from the Companions array
    //var pos = el.getAttribute('pos');
    //if(pos) arrCompanions.splice(pos,1);
	
    if (el.parentNode) {
	  el.parentNode.removeChild(el);
	}
    UpdateGuestCounters();
    RenderCompanions();
	bResponseChanged = true;
	return false;
}

//When the number of companions change:
// 1. Update the number of 
function onChangeNumComp(el) {
  if(el.value >= arrCompanions.length){
    numUnamedCompanions = el.value - arrCompanions.length;
  }else{
    numUnamedCompanions = 0;
    //for(var x=0; x < (arrCompanions.length-el.value); x++)
      //arrCompanions.pop();
  }
  RenderCompDlg();  
}
function AddTextToList(list, text, clname) {
	var newNode = document.createElement("li");
	newNode.className = clname;
	newNode.innerHTML = text;
	list.appendChild(newNode);
}
function UpdateGuestCounters(){
    var el = document.getElementById("totalcompanions_cnt");
    if(el) {
        var cnt = arrCompanions.length+parseInt(numUnamedCompanions);
        if(currentusertype == "companion") cnt++;
        el.innerHTML = cnt;
    }
    el = document.getElementById("othercompcnt");
    if(el) el.innerHTML = numUnamedCompanions;    
    
}
function DisplayCounts() {
	alert("read from select: "+document.getElementById('fc_numcompanions').value);
	alert("number of children: " + document.getElementById("edit_complist").childNodes.length)
}
function removeChildrenFromNode(node)
{
  if(node == undefined || node == null)
    return;
  var len = node.childNodes.length;
	while (node.hasChildNodes())
	  node.removeChild(node.firstChild);
}
function onChangedResponse(el){
  var strout="";
  var oel = document.getElementById("convertcomptbl");
  if(oel && numNamedCompanions>0 && (currentResponse!='NO') && el.value=="NO") {
    for(var x in arrCompanions){
      if(arrCompanions[x].s != "removed") {
        strout += 
          '<tr>'+
          '    <td class="name">'+renderGuestName2(arrCompanions[x])+'</td>'+
          '    <td><input type="radio" id="cur_'+arrCompanions[x].id+'" name="cu_'+arrCompanions[x].id+'" value="remove" checked="checked"/><label for="cur_'+arrCompanions[x].id+'">uninvite</label></td>'+
          '    <td><input type="radio" id="cui_'+arrCompanions[x].id+'" name="cu_'+arrCompanions[x].id+'" value="invite"/><label for="cui_'+arrCompanions[x].id+'">still going</label></td>'+
          '</tr>';
      }
    }
    oel.innerHTML = strout;
    YAHOO.container.convcompaniondlg.show();
  }
	document.getElementById("submitbtn").disabled = false;
}
function onKeyPressAddComp(e) {
	var key;
	if(window.event)
		key = window.event.keyCode;     //IE
	else
		key = e.which;     //firefox
	if (key == 13) {
		var btn = document.getElementById("fc_invitecompbtn");
		if (btn != null) {
			btn.click();
			if(window.event) event.keyCode = 0;
		}
	}
}
// ----- Name descrambler Object -----
function NameString(str){
    this.userStr = "";
    this.emxpr = /\b[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/;
    this.fn = "";
    this.ln = "";
    this.em = "";
    if(str.length)
        this.setInput(str);
}
//NameString.method('setInput', function (str) {
NameString.prototype.setInput = function (str) {
    this.userStr = str;
    this.fn = "";
    this.ln = "";
    this.em = "";
    str = trim(str);
    r = this.emxpr.exec(str);
    if(r){
        this.em = r[0];
        var tempregex = "("+this.em+"|\\(|\\)|<|>|\"|')"
        str = str.replace( new RegExp( tempregex, "g" ), "" );
    }
    if(str.length){
        pos = str.indexOf(",");
        if(pos != -1) {
            alert("found a comma at pos:"+pos+ "in string:"+str);
            this.ln = str.slice(0,pos);
            alert("ln is now:"+this.ln);
            this.fn = LTrim((str.slice(pos+1)));
            alert("fn is now:"+this.fn);
        }else{
          pos = str.indexOf(" ");
          if(pos != -1) {
              this.fn = str.slice(0,pos);
              this.ln = LTrim(str.slice(pos+1));
          }
        }
    }
}/*)*/;

// ----- Guest Add Guest UI -----
var bGAGSeen = false;
function onShowGAG() {
	if(!bGAGSeen) {
		//document.getElementById('guestpickerwait').style.display='block';
		//getContactList();
        showGuestAddGuestPicker();
		bGAGSeen = true;
	}
}
var getContactsCB = function(){ 
}
function RenderCompanions() {
    var el = document.getElementById("complist");
    //var el2 = document.getElementById("edit_complist");
    var el2 = 0;
    if(el || el2){
        var strout="",strout2="";
        if(inviterPos != -1)
            strout += "<li class='compname'>"+allContacts[inviterPos].fn+" "+allContacts[inviterPos].ln+"</li>"
        for(var x in arrCompanions){
            if(arrCompanions[x].s != "removed")
                if(el)
                    strout += "<li class='compname'>"+renderGuestName2(arrCompanions[x])+"</li>"
                if(el2){
                    if(arrCompanions[x].id)
                        strout2 +="<li pos='"+x+"'class='companion' id='diuk"+arrCompanions[x].id+"' name='companionname'>"+renderGuestName2(arrCompanions[x])+"&nbsp;<a href='#' onclick='javascript: onRemoveCompanion(this);'>remove</a></li>";
                    else
                        strout2 +="<li pos='"+x+"'class='companion' name='companionname'>"+renderGuestName2(arrCompanions[x])+"&nbsp;<a href='#' onclick='javascript: onRemoveCompanion(this);'>remove</a></li>";
                }
        }
        if(el) el.innerHTML = strout;
        if(el2) el2.innerHTML = strout2;
    }
    UpdateGuestCounters()
    el = document.getElementById("totalcompanions");
    if(el) el.style.display = (arrCompanions.length || numUnamedCompanions) ? "block" : "none";
    el = document.getElementById("unnamedcompanions");
    if(el) el.style.display = parseInt(numUnamedCompanions) ? "block" : "none";
}
//-------------------------------------------------------------------
//BEGIN------------Addressbook page --------------------
function RenderAddBook(sortby) {
    el = document.getElementById('addbooklist');
    var outStr = "<span id='abcnt'>( "+allContacts.length+" contacts)</span>&nbsp;Sort by:<a href='#' onclick='handleRenderByLN();'>Last Name</a>&nbsp;<a href='#' onclick='handleRenderByFN();'>First Name</a>&nbsp;<a href='#' onclick='handleRenderByEM();'>Email</a><br/>";
    var prevchar = "",str;
    for(var x in allContacts){
        if(!sortby || (sortby == "fn") || (sortby == ""))
            str = allContacts[x].fn;
        else if(sortby == "ln")
            str = allContacts[x].ln;
        else if(sortby == "em")
            str = allContacts[x].em;
        if(str && (str.length) && (prevchar.toUpperCase() != str.charAt(0).toUpperCase())) {
            outStr += '<span class="dividingletter">=== '+str.charAt(0).toUpperCase()+' ===</span>';
            prevchar=str.charAt(0);
        }
        str = (allContacts[x].ln.length || allContacts[x].fn.length) ? allContacts[x].fn+" "+allContacts[x].ln : allContacts[x].em
        outStr +=
        '<div name="abitem" class="item">'+
        '<div class="action">'+
        '<IMG class="abcloseimg" SRC="/i/close12_1.gif" title="remove" ALT="remove" onclick="onclickedremove(this,'+allContacts[x].id+',\''+str+'\');"/>';
        //enable the code below to display the "edit user" button.
        /*if(parseInt(allContacts[x].addedbyid) == uID && allContacts[x].status == "autocreated"){
          outStr += '<IMG SRC="/i/icons/user_edit.png" title="edit" ALT="edit" onclick="handleShowEditUserDlg('+allContacts[x].id+');"/>';
        }*/
        outStr += '</div>';
        if(sortby == "ln"){
            if(allContacts[x].ln && allContacts[x].fn)
                outStr += '<div class="name" name="abname">'+allContacts[x].ln+', '+allContacts[x].fn+'</div>';
            else
                outStr += '<div class="name" name="abname">'+allContacts[x].ln+allContacts[x].fn+'</div>';
            outStr += '<div class="email" name="abemail">&nbsp;'+allContacts[x].em+'</div>'+
            '</div>';
        }
        else if(sortby == "em"){
            outStr +=
            '<div class="email" name="abemail">'+allContacts[x].em+'</div>'+
            '&nbsp;<div class="name" name="abname">'+allContacts[x].fn+' '+allContacts[x].ln+'</div>'+
            '</div>';
        }
        else{
            outStr += '<div class="name" name="abname">'+allContacts[x].fn+' '+allContacts[x].ln+'</div>';
            outStr += '<div class="email" name="abemail">&nbsp;'+allContacts[x].em+'</div>'+
            '</div>';
        }
    }
    el.innerHTML = outStr;    
}
var gotABSuccess = function(o){
	if( (o.status == "204") || (o.status==204) ||(o.statusText.match(/No Content/i)) ){
        //alert("sorry, your address can't be found right now");
    }else{
        allContacts = eval( '(' + o.responseText + ')' );
        RenderAddBook("fn");
    }
};
var gotABFailure = function(o){
	document.getElementById("footer").innerHTML = "Get Contacts failed";
};
var getABCallback = {
	success:gotABSuccess,
	failure:gotABFailure,
	argument:""
};
function getContactListForAB() {
	var reqstr = "action=req_contacts&contacttype=partier"; 
	YAHOO.util.Connect.asyncRequest('POST', '/proc.php', getABCallback, reqstr);
};
function handleSaveAddUserDlg(){
  var fn = document.getElementById("fc_nufname").value;
  var ln = document.getElementById("fc_nulname").value;
  var em = document.getElementById("fc_nuemail").value;
  var reqstr = "action=process_userimport&contacts="+fn+" "+ln+" "+em;
  $.ajax({type: "POST",url: "/proc.php", data:reqstr});
  var abItem = {"fn":fn,"ln":ln,"em":em};
  allContacts[allContacts.length] = abItem;
  allContacts.sort(sortbyfn);
  RenderAddBook("fn");
}
function handleSaveEditUserDlg(){
  var fn = document.getElementById("fc_eufname").value,
      ln = document.getElementById("fc_eulname").value,
      em = document.getElementById("fc_euemail").value,x,
      id = document.getElementById("fc_euid").value;  
  for(x in allContacts){if(allContacts[x].id == id) break;}
  allContacts[x].fn = fn;
  allContacts[x].ln = ln;
  allContacts[x].ln = ln;
  allContacts[x].em = em;
  RenderAddBook("fn");
  var action = '{"name":"edituser","user":{"id":'+id+',"fn":"'+fn+'","ln":"'+ln+'","em":"'+em+'"}}';
  postJSONProc(0, action);
  return false;
}

function handleRenderByLN(){
  allContacts.sort(sortbyln);
  RenderAddBook("ln");
}
function handleRenderByFN(){
  allContacts.sort(sortbyfn);
  RenderAddBook("fn");
}
function handleRenderByEM(){
  allContacts.sort(sortbyem);
  RenderAddBook("em");
}
function sortbyfn(a, b) {
    var x = a.fn.toLowerCase();
    var y = b.fn.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortbyln(a, b) {
    var x = a.ln.toLowerCase();
    var y = b.ln.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortbyem(a, b) {
    var x = a.em.toLowerCase();
    var y = b.em.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function RemoveMyParent(el){
  var myparent = el.parentNode;
  if (myparent.parentNode) {
	  myparent.parentNode.removeChild(myparent);
  }
}

//END------------Addressbook page --------------------
//BEGIN------------create_event page --------------------
function onUserType(t){
  elog=document.getElementById('ce_login');
  enew=document.getElementById('ce_newuser');
  if(!elog || !enew){
    return false; //coding error
  }
  if(t=='n'){
    elog.style.display = "none";
    enew.style.display = "block";
 }else{
    elog.style.display = "block";
    enew.style.display = "none";
 }
 return true;
}
//END------------Addressbook page --------------------

//---------- Google Maps stuff ----------
var map = null;
var geocoder = null;
function load(address) {
  if (GBrowserIsCompatible()) {
	/*map = new GMap2(document.getElementById("map"));
	//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	map.addControl(new GSmallMapControl());*/
	geocoder = new GClientGeocoder();
	showAddress(address);
  }
}
function showAddress(address) {
  if (geocoder) {
	geocoder.getLatLng(
	  address,
	  function(point) {
		if (!point) {
		  //alert(address + " not found");
      document.getElementById("map").innerHTML = "Couldn't find this address on a map.";
		} else {
		  //map.setCenter(point, 13);
      
      map = new GMap2(document.getElementById("map"));
      map.setCenter(point,13);
      map.addControl(new GSmallMapControl());
      
		  var marker = new GMarker(point);
      marker.title = "Click to get directions from Google maps";
		  map.addOverlay(marker);
      var durl = 'http://maps.google.com/?q='+address;
      GEvent.addListener(marker, "click", function (){window.open('http://maps.google.com/?q='+address,'mywindow','');});
      
		  //marker.openInfoWindowHtml("<h1>Hello</h1>"+address);
      //marker.openInfoWindowHtml(document.createTextNode("Hello, world"));
		}
	  }
	);
  }
}
function showMap(locobj){
  load(locobj.street+" "+locobj.city+" "+locobj.state+" "+locobj.zip);
  $("#map").show();
}
// ----------------------END: Guest Page -----------------------
