﻿/// <reference path="jquery.intellisense.js"/>
// REFACTOR: convert all userid to use document.getElementById("hidCurrentUserIdVal").value
// global vars
var loginReturn;
var eventfulEventCatsLoaded=false; // used to indicate wether eventful categories have loaded
var tagWatermark='Enter comma separated tags';
// =====================
// Spry Carousel Functions
// =====================
function ShowCarouselNext() {
  sprySP.showNextPanel();
  document.getElementById('imgCarouselNext').src='/img/arrow_right_disabled.png';
  document.getElementById('imgCarouselNext').alt='';
  document.getElementById('imgCarouselPrev').src='/img/arrow_left_more.png';
  document.getElementById('imgCarouselPrev').alt='more Scouts';
}
function ShowCarouselPrevious() {
  sprySP.showPreviousPanel();
  document.getElementById('imgCarouselNext').src='/img/arrow_right_more.png';
  document.getElementById('imgCarouselNext').alt='more Scouts';
  document.getElementById('imgCarouselPrev').src='/img/arrow_left_disabled.png';
  document.getElementById('imgCarouselPrev').alt='';
}
// =====================
// Toggle Public/Private
// =====================
function TogglePrivateStatus(alertsettingid, checked) { 
    BNAlerts.Services.ToggleAlertPublicStatus(alertsettingid, checked);
};
// =====================
// Toggle Item Read    
// =====================
//function ToggleIsReadStatus() { 
function ToggleIsReadStatus(alertsettingid, alertsettingtype, itemid) { 
  divMAN = "divMANotiLine" + itemid;
  chkMA = "chkMA" + alertsettingid + "-" + alertsettingtype + "-" + itemid;
  if (document.getElementById(divMAN).className=="notificationTitle_read dmyCollapsibleItem notification_selected") {
      document.getElementById(divMAN).className="notificationTitle_read dmyCollapsibleItem notification_deselected";
  }
  else {
      document.getElementById(divMAN).className="notificationTitle_read dmyCollapsibleItem notification_selected";
  }
  checkbox = document.getElementById(chkMA);
  checkbox.checked = true;
  BNAlerts.Services.ToggleIsReadStatus(alertsettingtype, itemid, checkbox.checked);
  // update the page dirty flag
  $('#hidDirtyPage'+alertsettingid).attr('value','1');
  // update the unread count
  BNAlerts.Services.GetUnreadNotificationCount(alertsettingid,MarkReadReturn,null,alertsettingid); 
  // reset the session timer
  StartSessionTimer()
};    
function MarkReadReturn(result,alertsettingid) {
  // updates the unread count for an alert setting
  var count=document.getElementById('spanMACount'+alertsettingid);
  if (result>0) {
    count.innerHTML=result;
  }
  else {
    count.innerHTML='';
  }
}
// =====================
// Toggle Enable/Disable    
// =====================
function ToggleStatus(alertsettingid) { 
    var tempObj = document.getElementById("aEnable" + alertsettingid);
    var command = tempObj.innerHTML;
    //Call the service to change the status
    BNAlerts.Services.ToggleAlertStatus(alertsettingid, command);
    // update the displayed command text
    var newCmd;
    if (command=="Enable") {
        newCmd = "Disable";
        //set the alert message
        SetAlertMsg('Scout has been enabled');
    }
    else {
        newCmd = "Enable";      
        //set the alert message
        SetAlertMsg('Scout has been disabled');
    }                    
    tempObj.innerHTML = newCmd;
};    
// =====================
// Set item read checkbox    
// =====================
function ViewClicked(checkboxid) {
    //check the checkbox for the item
    document.getElementById(checkboxid).checked = true;
};
// =====================
// Mark All Items Read    
// =====================
function MarkAllAsRead(alertsettingid,visibleonly,nuke) {
    //check the checkbox for the notifications under the alert setting
    var myForm = document.forms[0];
    var chkprefix = "chkMA" + alertsettingid;
    var count=parseInt(document.getElementById('spanMACount'+alertsettingid).innerHTML);
    // determine whether to show "panic" dialog
    if ((count>50)&&(visibleonly==false)&&(nuke==false)){
      //show the panic dialog
      ShowPanicDialog(alertsettingid,count)
    }
    else {
      for (i=0;i<myForm.length;i++) {
          var tempobj=myForm.elements[i];
          if (tempobj.name.match(chkprefix)==chkprefix) {
              // check the item
              tempobj.checked=true;
              // call the web service to mark the item read                            
              BNAlerts.Services.MarkAsRead(tempobj.name);
              // mark all div styles unread                            
          }
      }
      //change all visible divs to read 
      $('.divMANoti'+alertsettingid).removeClass("notificationTitle_unread").addClass("notificationTitle_read");
      // update the page dirty flag
      $('#hidDirtyPage'+alertsettingid).attr('value','1');
      if (nuke==true){
        // nuke 'em all
        NukeUnread(alertsettingid);
      }
      else{
        //set the alert message
        SetAlertMsg('Reports have been marked read');
        // update the unread count
        BNAlerts.Services.GetUnreadNotificationCount(alertsettingid,MarkReadReturn,null,alertsettingid); 
      }
    }
};
// =====================
//Nuke Unread Notifications
// =====================
function NukeUnread(alertsettingid) {
  // call web service to mark all unread
  BNAlerts.Services.MarkAllAsRead(alertsettingid,NukeReturn,null,alertsettingid); 
}
function NukeReturn(result,alertsettingid) {
  if(result==true){
    // set the alert message
    SetAlertMsg('All reports for this scout have been marked read');  
  }
  else {
    // set the alert message
    SetAlertMsg('Sorry, we could not mark all reports read at this time');  
  }
  // update the notification cound
  BNAlerts.Services.GetUnreadNotificationCount(alertsettingid,MarkReadReturn,null,alertsettingid); 
}
// =====================
// Unread Panic Dialog    
// =====================
function ShowPanicDialog(alertsettingid,count){
  var dOffset = $('#dialogContent').offset();
  // set the unread count
  $('#nukeUnread').html(count);
  $('#dialogContent').dialog({
    modal: true,
    height: 150,
    width: 325,
    title: 'You have a lot of unread Scout Reports...',
    overlay: {
      opacity: 0.5,
      background: 'black'
    },
    buttons: {
      'Yes': function() { 
                MarkAllAsRead(alertsettingid,false,true);
                $(this).dialog('close');
             },
      'Nope, just the ones shown': function() {
          MarkAllAsRead(alertsettingid,true,false);
          $(this).dialog('close');
          }
    }
  });
  //window.scrollTo(0,0);
}
// =====================
// Close Accordian    
// =====================
function CloseAccPanels(id) {
  // change the classes
  document.getElementById('divHideShow'+id).style.visibility='hidden';
  document.getElementById('a'+id).className='arrow_closed';
  document.getElementById('aHead'+id).className='contents_headline_closed';
  $find('cpe'+id).collapsePanel();
  var hidState = document.getElementById('hid'+id);
  hidState.value = 'close';
  // handle hiding of filters
  if (id=='MAAcc') {
    document.getElementById('divMAFilters').style.display='none';
  }
  // reset the session timer
  StartSessionTimer()
};
// =====================
// Accordian Event Processing    
// =====================
function SetAccordians(panelid) {
	// panelid e.g MAAcc, PopAcc, FriendsAcc
	// "Disabled" means ignore the click and show message
	if (panelid=='Disabled'){
	  // simply show a message that the user needs to be logged in
	  SetAlertMsg('You need to be logged in to view these scouts');
	}
	else{
	  // clear any messages
	  ClearAlertMsg();
	  // process the request
    var obj = $find('cpe'+panelid);
    var hidState;
	  hidState=document.getElementById('hid'+panelid)
    if (hidState.value=='open') {
      CloseAccPanels(panelid);
	  }	
	  else {		
		  // open the panel
      // set the display style for the panel
      document.getElementById('divHideShow'+panelid).style.visibility='hidden';
      document.getElementById('divHideShow'+panelid).style.display='block';
      //expand the panel
      obj.expandPanel();
      hidState.value = 'open';        
      document.getElementById('divHideShow'+panelid).style.visibility='visible';
      // change the class
      document.getElementById('a'+panelid).className='arrow_open';
      document.getElementById('aHead'+panelid).className='contents_headline_open';
      
      // special panel handling
      if (panelid=='MAAcc') {
	      // show the filter options
	      document.getElementById('divMAFilters').style.display='';
      } 
	  }
  }
  // reset the session timer
  StartSessionTimer()
};
// =====================
// Show Tag Edit    
// =====================
function ShowTagEditPanel(elid, itemtype, itemid, userid) {
  // clear the alert message window
  ClearAlertMsg();
  var tags;
  var heading;
  // set the hidden field values of the panel
  document.getElementById('hidUserId').value = userid;
  document.getElementById('hidItemId').value = itemid;
  document.getElementById('hidItemType').value = itemtype;
  // get the current tags
  if (itemtype=='noti') {
    tags = document.getElementById('hidNotiTags'+itemid).value;
    heading='Report tags';
  }
  else if (itemtype=='alert') {
    tags = document.getElementById('hidAlertTags'+itemid).value;
    heading='Scout tags';
  }
  // set the heading
  document.getElementById('spanTagPanelHeading').innerHTML=heading; 
  // set the textbox value
  var tbId = document.getElementById('hidTagsTextBox').value;
  var tb = document.getElementById(tbId)
  if (tags.length!=0) {
    // set the tags value
    tb.value=tags;
    tb.className='tagTextInput';
  }
  else {
    // set the watermark
    tb.value=tagWatermark;
    tb.className='tagTextInputWatermarked';
  }
  // set the location of the panel
  yuiTagPanel.cfg.setProperty("context", [elid, "tr", "br"]);
  // show the panel
  yuiTagPanel.show();
  // swap the static marketing content
  SwapMarketingFlash('static');     
  // reset the session timer
  StartSessionTimer()
};

// =====================
// Hide Tag Edit    
// =====================
function CloseTagPanel(action) {
  if (action=='save') {
    var type, tagcmdid, hidtagsid;
    // get the hidden field values
    var userid = document.getElementById('hidUserId').value;
    var itemid = document.getElementById('hidItemId').value;
    var itemtype = document.getElementById('hidItemType').value;
    // get the textbox value
    var tbId = document.getElementById('hidTagsTextBox').value;
    var tb = document.getElementById(tbId);
    // determine the type of item being editted
    if (itemtype=='noti') {
      type = 'Notification';
      tagcmdid = 'tagNotiImage'+itemid;
      hidtagsid = 'hidNotiTags'+itemid;
    }
    else if (itemtype=='alert') {
      type = 'AlertSetting';
      tagcmdid = 'tagAlertImage'+itemid;
      hidtagsid = 'hidAlertTags'+itemid;
    }
    if (tb.value!=tagWatermark){
      // submit the changes to the ws
      // call the web service to update
      BNAlerts.Services.SaveItemTags(userid, itemid, type, tb.value);                
      // update the hidden field in the list
      document.getElementById(hidtagsid).value = tb.value;
    }
    // update the command label
    if ((tb.value=='')||(tb.value==tagWatermark)) {
      document.getElementById(tagcmdid).className = 'lightEditActionIndicator lightEditActionIndicator_off';
    }
    else {
      document.getElementById(tagcmdid).className = 'lightEditActionIndicator lightEditActionIndicator_on';
    }
    //set the alert message
    SetAlertMsg('Tags have been updated');
  }
  // close the panel
  yuiTagPanel.hide();
  // swap the static marketing content
  SwapMarketingFlash('flash');    
}
// =====================
// Show Share Panel    
// =====================
function ShowSharePanel(elid, itemtype, notiid, alertid, userid, source) {
  // clear the alert message window
  ClearAlertMsg();
  // set the hidden field values of the panel
  document.getElementById('hidShareUserId').value = userid;
  document.getElementById('hidShareAlertId').value = alertid;
  document.getElementById('hidShareNotiId').value = notiid;
  document.getElementById('hidShareType').value = itemtype;
  document.getElementById('hidShareSource').value = source;
  // set the subject textbox value
  var subj;
  var heading;
  if (userid!=""){
    if (itemtype=='alert'){
      subj=document.getElementById('hid'+source+'Desc'+alertid).value;
      heading='Share Scout';
    }
    else if (itemtype=='noti') {
      subj=document.getElementById('hid'+source+'NotiDesc'+notiid).value;
      heading='Share Scout Report';
    }
    // set the heading
    document.getElementById('spanSharePanelHeading').innerHTML=heading; 
    // set the subject
    document.getElementById('txtShareSubject').value = 'Check this out! '+subj;
    // set the location of the panel
    yuiSharePanel.cfg.setProperty("context", [elid, "tr", "br"]);
    // show the panel
    yuiSharePanel.show();
    // swap the static marketing content
    SwapMarketingFlash('static');    
  }
  else{
    //show alert message indicating need to be logged in
    alert('You must be logged in to share scouts');
  }   
  // reset the session timer
  StartSessionTimer()
} 
// =====================
// Hide Share Panel    
// =====================
function CloseSharePanel(action) {
  var tbid;
  if (action=='send') {
    // process the sharing
    var userid = document.getElementById('hidShareUserId');
    var subj = document.getElementById('txtShareSubject');
    var msg = document.getElementById('txtShareBody');
    //var chk = document.getElementById('chkShareSendMe'); // ticket:547 - suppress bcc field
    tbid = document.getElementById('hidShareEmailsTextBox').value;
    var to = document.getElementById(tbid);
    var itemtype = document.getElementById('hidShareType').value;
    var alertid = document.getElementById('hidShareAlertId').value;
    var notiid = document.getElementById('hidShareNotiId').value;
    var source = document.getElementById('hidShareSource').value;
    
    if (itemtype=='alert') {
      BNAlerts.Services.ShareAlert(userid.value, to.value, subj.value, msg.value, false, alertid, 5);
      // update the light edit icon
      if (source=='MA'){
        document.getElementById('shareAlertImage'+alertid).className = 'lightEditActionIndicator lightEditActionIndicator_on';
      }
      SetAlertMsg('Your Scout was shared');
    }
    else if (itemtype=='noti') {
      BNAlerts.Services.ShareNotification(userid.value, to.value, subj.value, msg.value, false, alertid, notiid, 5);
      // update the light edit icon
      if (source=='MA'){
        document.getElementById('shareNotiImage'+notiid).className = 'lightEditActionIndicator lightEditActionIndicator_on';
      }
      SetAlertMsg('Your Scout Report was shared');
    }    
  }
  // close the panel
  yuiSharePanel.hide();
  // swap the static marketing content
  SwapMarketingFlash('flash');    
}

function ClearSharePanelFields() {
  // reset the To and Body
  var tbid = document.getElementById('hidShareEmailsTextBox').value;
  document.getElementById(tbid).value='';
  document.getElementById('txtShareBody').value='';
}
// =====================
// hide/show alert setting details
// =====================
function ToggleAlertSetting(divid, alert, cpe) {
  // check to see what class is currently assigned to the div
  var div = document.getElementById(divid);
  var divclass = div.className;
  if (divclass=='alert_selected') {
    if (cpe=='cpeMA' || cpe=='cpeShared' || cpe=='cpeFriends' || cpe=='cpeRecent'){
      // hide the lines and light edit
      document.getElementById(divid+'Display').style.display='none';
      document.getElementById(divid+'LinksDisplay').style.display='none';
    }
    // collapse the panel
    $find(cpe+alert).collapsePanel();
    // set the class of the div
    div.className='alert_deselected';
  }
  else {
    if (cpe=='cpeMA' || cpe=='cpeShared' || cpe=='cpeFriends' || cpe=='cpeRecent') {
      // show the lines and line edit
      document.getElementById(divid+'Display').style.display='block';
      document.getElementById(divid+'LinksDisplay').style.display='block';
    }
    // expand the panel
    $find(cpe+alert).expandPanel();
    // set the class of the div
    div.className='alert_selected';
  }
  // reset the session timer
  StartSessionTimer()
}

// =====================
// hide/show notification details
// =====================
function ToggleNotification(divid, noti, cpe) {
  // check to see what class is currently assigned to the div
  var div = document.getElementById(divid);
  var divclass = div.className;
  if (divclass=='notification_selected') {
    // collapse the panel
    $find(cpe+noti).collapsePanel();
    // set the class of the div
    div.className='notification_deselected';
  }
  else {
    // expand the panel
    $find(cpe+noti).expandPanel();
    // set the class of the div
    div.className='notification_selected';
  }
  // reset the session timer
  StartSessionTimer()
}
// =====================
// Show Suggest Panel    
// =====================
function ShowSuggestPanel() {
  // clear the alert message window
  ClearAlertMsg();
  // show the panel
  yuiSuggestPanel.show();
  // swap the static marketing content
  SwapMarketingFlash('static');    
  // reset the session timer
  StartSessionTimer()
} 
// =====================
// Hide Suggest Panel    
// =====================
function CloseSuggestPanel(action) {
  if (action=='send'){
    //call the web service to send the suggestion
    var uidctrl
    uidctrl=document.getElementById('hidUniversalLoggedInUserCtrl').value;
    BNAlerts.Services.SubmitSuggestion(document.getElementById(uidctrl).value, document.getElementById('txtSuggestNotes').value, document.getElementById('txtSuggestUrl').value);
    // clear the fields
    document.getElementById('txtSuggestNotes').value='';
    document.getElementById('txtSuggestUrl').value='';
     //set the alert message
    SetAlertMsg('Thanks for your suggestion!');
    }
    // hide the panel
    yuiSuggestPanel.hide();
    // swap the static marketing content
    SwapMarketingFlash('flash');    
}

// =====================
// Show Ask Panel    
// =====================
var strAFWatermark='ask friends for suggestions/opinions/recommendations';

function ShowAskPanel(elid,alertid,channel) {
  // clear the alert message window
  ClearAlertMsg();
  var userid=$('#hidCurrentUserIdVal')[0].value;
  if (userid!=""){
    // set the location of the panel
    yuiAskPanel.cfg.setProperty("context", [elid, "tl", "bl"]);
    yuiAskPanel.render();
    // set the pop-up params
    document.getElementById('txtPostTitle').value='Help Me Find This';
    document.getElementById('hidAskUserId').value=userid;
    document.getElementById('hidAskAlertId').value=alertid;
    var msg=document.getElementById('txtPostDesc');
    msg.value=strAFWatermark;
    msg.className='watermarkAF';
    // check to see if we need to retrieve the alert settings for the user
    var popScouts=$('#popAskScoutId');
    if (popScouts[0].options.length<=1) {
      // go query for the user alerts
      //Public Function GetUserAlerts(ByVal inUserId As String, ByVal inASFilter As String, ByVal inNotifFilter As String, ByVal inTag As String) As DataSet
      BNAlerts.AjaxData.GetUserAlerts(userid,'all','unread','',GetAskAlertsReturn,null,alertid);
    }
    else {
      // select the alert setting if necessary
      SelectOptionByValue(popScouts,alertid);
      // show the panel
      FinalizeShowAskPanel();
    }
    if (channel != '') {
      var popChan = $('#popPostTo');
      // set the selected pop-menu in the channel pop
      // set the channel display value
      SelectOptionByValue(popChan, channel);
      SelectAskNetwork();
    }
  }
  else{
    //show alert message indicating need to be logged in
    SetAlertMsg('You must be logged in to ask friends');
  }   
  // reset the session timer
  StartSessionTimer()
}
function GetAskAlertsReturn(result,alertid){
  // add the alerts to the pop-menu
  var popScouts=$('#popAskScoutId');
  // get the dataset using jQuery
  var xmlTables = $(result).find("Table1");
  if($(xmlTables).length >0){
    $(xmlTables).each(function(){
      val=$($(this).children("AlertSettingId").get(0)).text();
      text=$($(this).children("Description").get(0)).text();
      AddSelectOption(popScouts,val,text);
    });
  }  
  // select the alert in the popmenu
  SelectOptionByValue(popScouts,alertid);
  // show the panel
  FinalizeShowAskPanel();
}
function FinalizeShowAskPanel() {
  // show the panel
  yuiAskPanel.show();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
function SetAskFriendButtonStatus(enabled) {
  var btn=document.getElementById("btnAskFriend");
  var img=document.getElementById("imgAskFriend");
  if (enabled==true){
    btn.disabled=false;
    btn.className='positive';
    img.src='/img/tick.png';
  }
  else {
    btn.disabled=true;
    btn.className='disabled';
    img.src='/img/tick-disabled.png';
  }
};
function SelectAskNetwork() {
  var nw=document.getElementById('popPostTo')[document.forms[0].popPostTo.selectedIndex].text;
  if (nw=='FriendFeed') {
    $('#divAskShowFFAuth').show();
    $('#divAskNetwork')
        .removeClass()
        .addClass('askFF');
    SetAskFriendButtonStatus(true);
  }
  else if (nw=='Facebook') {
    $('#divAskShowFFAuth').hide();
    $('#divAskNetwork')
        .removeClass()
        .addClass('askFB');
    SetAskFriendButtonStatus(true);
  }
  else {
    $('#divAskShowFFAuth').hide();
    $('#divAskNetwork')
        .removeClass()
        .addClass('askY');
    SetAskFriendButtonStatus(false);
  }
}
// =====================
// Close Ask Panel    
// =====================
function CloseAskPanel(action) {
  var index;
  var network;
//  index=document.forms[0].popPostTo.selectedIndex;
//  network=document.getElementById('popPostTo')[index].text;
  network=GetSelectedOptionValue($('#popPostTo'));
  var t=document.getElementById('txtPostTitle').value;
  var c=document.getElementById('txtPostDesc').value;
  alertid=GetSelectedOptionValue($('#popAskScoutId'));  
  // save the post info to the database
  if (c == strAFWatermark) {
    c = '';
  }
  if ((network!='')&&(alertid!='')){
    BNAlerts.Services.SaveAskFriendDetails(alertid, document.getElementById('hidAskUserId').value, t, c, network);
    var u='http://www.yotify.com/a/ar.aspx?id='+alertid;
    if (network=='Facebook') {
      // open the Facebook panel
      var u='http://www.yotify.com/a/ar.aspx?id='+alertid+'&nw=Facebook';
      window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
      // hide our panel
      yuiAskPanel.hide();
      // swap the static marketing content
      SwapMarketingFlash('flash');    
    }
    else if (network=='FriendFeed') {
      var n=document.getElementById('txtAskFriendFeedUsername').value;
      var rk=document.getElementById('txtAskFriendFeedRemotekey').value;
      if ((n=='')||(rk=='')) {
        //show alert message indicating need to enter a nickname and remotekey
        SetAlertMsg('You must enter your FriendFeed nickname and remote key');        
      }
      else {
        // submit the request
        //SaveFriendFeedAskFriend(ByVal inAlertSettingId As String, ByVal inUserId As String, ByVal inUsername As String, ByVal inRemoteKey As String, ByVal inTitle As String, ByVal inDescription As String, ByVal inNetwork As String) As Boolean
        BNAlerts.Services.SaveFriendFeedAskFriend(alertid,document.getElementById("hidCurrentUserIdVal").value,n,rk,t,c,network,GetAskFriendReturn,null,network); 
      }
    }
  }
  else {
    // show an alert message
    SetAlertMsg('You must select a channel and scout');        
  }
}
function GetAskFriendReturn(result,network) {
  if (result==true) {
    SetAlertMsg('You request has been posted to '+network);        
  }
  else {
    SetAlertMsg('There was a problem posting your request to '+network);        
  }
  // hide our panel
  yuiAskPanel.hide();
  // swap the static marketing content
  SwapMarketingFlash('flash');    
}
// =====================
// Show GoogleMe Panel    
// =====================
function ShowGoogleMePanel(userid) {
  // hide the progress indicator
  document.getElementById('spanGoogleMeProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  // set the hidden field values of the panel
  document.getElementById('hidGoogleMeUserId').value = userid;
  //show the panel
  yuiGoogleMePanel.show();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// =====================
// Hide GoogleMe Panel    
// =====================
function CloseGoogleMePanel(action) {
  var name=document.getElementById('txtGoogleMe').value;
  var userid=document.getElementById("hidCurrentUserIdVal").value;
  if (name!="") {
    if (userid!=""){
      // show the progress indicator
      document.getElementById('spanGoogleMeProgress').style.display='block';
      // call the webservice
      BNAlerts.Services.AddGoogle1ClickAlert(userid,name,"","me",document.getElementById('chkSearchMePrivacy').checked,Get1ClickReturn,null,yuiGoogleMePanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='GoogleMe';
      yuiGoogleMePanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need to be logged in
    SetAlertMsg('You must enter your name');  
  }
}
// =====================
// Show SearchThis Panel    
// =====================
function ShowSearchThisPanel() {
  // hide the progress indicator
  document.getElementById('spanSearchThisProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  //show the panel
  yuiSearchThisPanel.show();
  // set the focus to the textbox
  document.getElementById('txtSearchThis').focus();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// =====================
// Hide Search This Panel    
// =====================
function CloseSearchThisPanel(action) {
  var userid = document.getElementById('hidCurrentUserIdVal').value;
  var phrase = document.getElementById('txtSearchThis').value;
  if (userid!="") {
    if (phrase!="") {
      // show the progress indicator
      document.getElementById('spanSearchThisProgress').style.display='block';
      // call the webservice
      BNAlerts.Services.AddGoogle1ClickAlert(userid,phrase,"","this",document.getElementById('chkSearchThisPrivacy').checked,Get1ClickReturn,null,yuiSearchThisPanel);
    }
    else {
      //show alert message indicating need to be logged in
      SetAlertMsg('You must enter a search phrase');  
    }
  }
  else {
    // show the login / registration dialog
    // set the global var for the method to call on successful login/registration
    loginReturn='SearchThis';
    yuiSearchThisPanel.hide();
    ShowLoginPanel();
  }  
}
// =====================
// Show TrackRss Panel    
// =====================
function ShowTrackRssPanel() {
  // hide the progress indicator
  document.getElementById('spanTrackRssProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  //show the panel
  yuiTrackRssPanel.show();
  // set the focus to the textbox
  document.getElementById('txtFeedUrl').focus(); // this causes some screen refresh issues
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// =====================
// Hide Track Rss Panel    
// =====================
function CloseTrackRssPanel(action) {
  var index = document.forms[0].popTrackRssCat.selectedIndex;
  var cat = document.getElementById('popTrackRssCat')[index].value;
  var userid = document.getElementById("hidCurrentUserIdVal").value;
  var url = document.getElementById('txtFeedUrl').value;
  var phrase = document.getElementById('txtTrackRss').value;
  if (url!="") {
    if (userid!=""){
      // show the progress indicator
      document.getElementById('spanTrackRssProgress').style.display='block';
      // call the webservice
      BNAlerts.Services.AddRssFeedAlert(userid,phrase,url,cat,document.getElementById('chkTrackRssPrivacy').checked,Get1ClickReturn,null,yuiTrackRssPanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='TrackRss';
      yuiTrackRssPanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need to be logged in
    SetAlertMsg('You must enter a feed url');  
  }
}
// =====================
// Show TrackLinkedIn Panel    
// =====================
function ShowTrackLinkedInPanel() {
  // hide the progress indicator
  document.getElementById('spanTrackLinkedInProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  //show the panel
  yuiTrackLinkedInPanel.show();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// =====================
// Hide Track LinkedIn Panel    
// =====================
function CloseTrackLinkedInPanel(action) {
  var userid = document.getElementById("hidCurrentUserIdVal").value;
  var url = document.getElementById('txtTrackLinkedInUrl').value;
  if (url!="") {
    if (userid!=""){
      // show the progress indicator
      document.getElementById('spanTrackLinkedInProgress').style.display='block';
      // call the webservice
      //     Public Function AddLinkedIn1ClickAlert(ByVal inUserId As String, ByVal inProfileUrl As String, ByVal inIsPrivate As Boolean) As Boolean
      BNAlerts.Services.AddLinkedIn1ClickAlert(userid,url,document.getElementById('chkTrackLinkedInPrivacy').checked,Get1ClickReturn,null,yuiTrackLinkedInPanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='TrackLinkedIn';
      yuiTrackLinkedInPanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need to be logged in
    SetAlertMsg('You must enter a website url');  
  }
}
// =====================
// Show TrackWebsite Panel    
// =====================
function ShowTrackWebsitePanel() {
    // hide the progress indicator
    document.getElementById('spanTrackWebsiteProgress').style.display = 'none';
    // clear the alert message window
    ClearAlertMsg();
    //show the panel
    yuiTrackWebsitePanel.show();
    // swap the static marketing content
    SwapMarketingFlash('static');
}
// =====================
// Hide TrackWebsite Panel    
// =====================
function CloseTrackWebsitePanel(action) {
    //var index = document.forms[0].popTrackWebsiteCat.selectedIndex;
    //var cat = document.getElementById('popTrackWebsiteCat')[index].value;
    var cat = "2"; //set to track blog
    var userid = document.getElementById("hidCurrentUserIdVal").value;
    var url = document.getElementById('txtTrackWebsiteUrl').value;
    var phrase = document.getElementById('txtTrackWebsite').value;
    if (url != "") {
        if (userid != "") {
            // show the progress indicator
            document.getElementById('spanTrackWebsiteProgress').style.display = 'block';
            // call the webservice
            BNAlerts.Services.AddWebsiteAlert(userid, phrase, url, cat, document.getElementById('chkTrackWebsitePrivacy').checked, Get1ClickReturn, null, yuiTrackWebsitePanel);
        }
        else {
            // show the login / registration dialog
            // set the global var for the method to call on successful login/registration
            loginReturn = 'TrackWebsite';
            yuiTrackWebsitePanel.hide();
            ShowLoginPanel();
        }
    }
    else {
        //show alert message indicating need to be logged in
        SetAlertMsg('You must enter a website url');
    }
}
// =====================
// Show TrackPrice Panel    
// =====================
function ShowTrackPricePanel() {
  // hide the progress indicator
  document.getElementById('spanTrackPriceProgress').style.display='none';
  // clear the search terms
  var terms;
  terms=document.getElementById('txtTrackPriceKeywords');
  terms.value='enter specific product and click search >';
  terms.className='watermark';
  // clear the price
  document.getElementById('txtTrackPriceAmount').value='';
  // clear the best price field
  document.getElementById('txtTrackPriceDisplay').value='';
  // disable the save button
  SetSavePriceButtonStatus(false);
  // reset the popmenu options
  var pop=$('#popTrackPriceProducts');
  ClearSelectOptions(pop);
  AddSelectOption(pop,'','enter search terms above');
  // clear the alert message window
  ClearAlertMsg();
  //show the panel
  yuiTrackPricePanel.show();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// ==========================
// TrackPrice Search Products    
// ==========================
function SearchProducts() {
  // clear the alert message window
  ClearAlertMsg();
  // clear the price field
  document.getElementById('txtTrackPriceAmount').value='';
  document.getElementById('txtTrackPriceDisplay').value='';
  // disable the save button
  SetSavePriceButtonStatus(false);
  // process the request
  var searchTerms=document.getElementById("txtTrackPriceKeywords").value;
  if (searchTerms!="") {
    // show the progress indicator
    var prog=document.getElementById('spanTrackPriceProgress');
    prog.innerHTML='Searching&nbsp;&nbsp;';
    prog.style.display='block';
    // call the webservice to get matching products
    BNAlerts.AjaxData.ProductSearch(searchTerms,ProductSearchReturn);
  }
  else {
    //show alert message indicating need slect a product
    SetAlertMsg('You must enter product information');    
  }
};
function ProductSearchReturn(result) {
  // hide the progress indicator
  document.getElementById('spanTrackPriceProgress').style.display='none';
  // clear the popmenu
  var pop=$('#popTrackPriceProducts');
  ClearSelectOptions(pop);  
  // process the results and add them to the popmenu
  var i=0;
  var val, text;
  // get the dataset using jQuery
  var xmlTables = $(result).find("Table1");
  if($(xmlTables).length >0){
    $(xmlTables).each(function(){
      val=$($(this).children("ProductId").get(0)).text()+'|'+$($(this).children("MinPrice").get(0)).text();
      text=$($(this).children("ProductTitle").get(0)).text();
      AddSelectOption(pop,val,text);
      i+=1;
      if(i==1){
        // set the price field
        SetProductPriceField(val);
      }          
    });
  } else {
    val='0|0';
    text='No products found';
    AddSelectOption($('#popTrackPriceProducts'),val,text);          
  }  
};
function SetProductPriceField(val) {
  var arr=val.split("|");
  var id,price;
  if (arr.length==2){
    id=arr[0];
    price=arr[1];
    if (id==0) {
      // disable the save button
      SetSavePriceButtonStatus(false);
    }
    else {
      // set the price field
      document.getElementById("txtTrackPriceAmount").value=price;
      document.getElementById('txtTrackPriceDisplay').value=price;
      //enable the save button
      SetSavePriceButtonStatus(true);
    }
  }
  else {
  // disable the save button
  SetSavePriceButtonStatus(false);
  }
};
function SetSavePriceButtonStatus(enabled) {
  var btn=document.getElementById("btnSavePriceAlert");
  var img=document.getElementById("imgSavePriceAlert");
  if (enabled==true){
    btn.disabled=false;
    btn.className='positive';
    img.src='/img/tick.png';
  }
  else {
    btn.disabled=true;
    btn.className='disabled';
    img.src='/img/tick-disabled.png';
  }
}
// =====================
// Select Product
// =====================
function SelectPriceAlertProduct(){
  var index = document.forms[0].popTrackPriceProducts.selectedIndex;
  var val = document.getElementById('popTrackPriceProducts')[index].value;
  SetProductPriceField(val);
}
// =====================
// Hide TrackPrice Panel    
// =====================
function CloseTrackPricePanel(action) {
  var index = document.forms[0].popTrackPriceProducts.selectedIndex;
  var val = document.getElementById('popTrackPriceProducts')[index].value;
  var price = document.getElementById("txtTrackPriceAmount").value;
  var arr=val.split("|");
  var userid = document.getElementById("hidCurrentUserIdVal").value;
  if ((arr[0] != 0) && (price != "")) {
    if (userid!=""){
      // show the progress indicator
      var prog=document.getElementById('spanTrackPriceProgress');
      prog.innerHTML='Sending scout';
      prog.style.display='block';
      // call the webservice
      BNAlerts.Services.AddPriceAlert(userid,arr[0],price,document.getElementById('chkTrackPricePrivacy').checked,Get1ClickReturn,null,yuiTrackPricePanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='TrackPrice';
      yuiTrackPricePanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need slect a product
    SetAlertMsg('Invalid price parameters');  
  }
}
// =====================
// Show Track Auctions Panel    
// =====================
function ShowTrackAuctionsPanel() {
  // hide the progress indicator
  document.getElementById('spanTrackAuctionsProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  //show the panel
  yuiTrackAuctionsPanel.show();
  // set the focus to the textbox
  document.getElementById('txtTrackAuctions').focus();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// =====================
// Close Track Auctions Panel    
// =====================
function CloseTrackAuctionsPanel(action) {
  var userid = document.getElementById("hidCurrentUserIdVal").value;
  var phrase = document.getElementById('txtTrackAuctions').value;
  if (phrase!="") {
    if (userid!=""){
      // show the progress indicator
      document.getElementById('spanTrackAuctionsProgress').style.display='block';
      // call the webservice
      BNAlerts.Services.AddEBay1ClickAlert(userid,phrase,document.getElementById('chkTrackAuctionsPrivacy').checked,Get1ClickReturn,null,yuiTrackAuctionsPanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='TrackAuctions';
      yuiTrackAuctionsPanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need to be logged in
    SetAlertMsg('You must enter a search phrase');  
  }
}
// =====================
// Show Track Events Panel    
// =====================
function ShowTrackEventsPanel() {
  // hide the progress indicator
  document.getElementById('spanTrackEventsProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  // clear the search terms
  document.getElementById('txtEventKeywords').value='';
  //show the panel
  yuiTrackEventsPanel.show();
  // set the focus to the textbox
  document.getElementById('txtEventZip').focus();
  // swap the static marketing content
  SwapMarketingFlash('static');    
  if (eventfulEventCatsLoaded==true){
    // categories loaded so enable the save alert
    SetSaveEventButtonStatus(true);
  }
  else {
    //need to laod the categories so disable the save alert button
    SetSaveEventButtonStatus(false);
    GetEventCategories();
  }
};
function GetEventCategories() {
  // clear the alert message window
  ClearAlertMsg();
  var prog=document.getElementById('spanTrackEventsProgress');
  prog.innerHTML='Retrieving categories&nbsp;&nbsp;';
  prog.style.display='block';
  // call the webservice to get matching products
  BNAlerts.AjaxData.GetEventfulCategories(EventCategoriesReturn);
};
function EventCategoriesReturn(result) {
  // hide the progress indicator
  document.getElementById('spanTrackEventsProgress').style.display='none';
  // clear the popmenu
  var pop=$('#popTrackEventCats');
  ClearSelectOptions(pop);  
  // process the results and add them to the popmenu
  var i=0;
  var val, text;
  // add a generic first item option
  AddSelectOption(pop,'','Select an event category');  
  // get the dataset using jQuery
  var xmlTables = $(result).find("category");
  if($(xmlTables).length >0){
    $(xmlTables).each(function(){
      val=$($(this).children("id").get(0)).text();
      text=$($(this).children("name").get(0)).text();
      AddSelectOption(pop,val,text);
    });
  };
  // indicate events loaded and enable the save button
  eventfulEventCatsLoaded=true;
  SetSaveEventButtonStatus(true);
};
function SetSaveEventButtonStatus(enabled) {
  var btn=document.getElementById("btnSaveEventAlert");
  var img=document.getElementById("imgSaveEventAlert");
  if (enabled==true){
    btn.disabled=false;
    btn.className='positive';
    img.src='/img/tick.png';
  }
  else {
    btn.disabled=true;
    btn.className='disabled';
    img.src='/img/tick-disabled.png';
  }
};
// =====================
// Close Track Events Panel    
// =====================
function CloseTrackEventsPanel(action) {
  var userid = document.getElementById('hidCurrentUserIdVal').value;
  var phrase = document.getElementById('txtEventKeywords').value;
  var zip = document.getElementById('txtEventZip').value;
  var index = document.forms[0].popTrackEventCats.selectedIndex;
  var cat = document.getElementById('popTrackEventCats')[index].value;
  var catTitle = document.getElementById('popTrackEventCats')[index].innerHTML;
  // keywords or zip is required
  if (zip!="") {
    if (userid!=""){
      // show the progress indicator
      var prog=document.getElementById('spanTrackEventsProgress');
      prog.innerHTML='Sending scout';
      prog.style.display='block';
      // call the webservice
      //AddEvent1ClickAlert(ByVal inUserId As String, ByVal inSearchString As String, ByVal inLocation As String, ByVal inCategoryId As String, ByVal inCategoryTitle As String, ByVal inIsPrivate As Boolean)
      BNAlerts.Services.AddEvent1ClickAlert(userid,phrase,zip,cat,catTitle,document.getElementById('chkTrackEventsPrivacy').checked,Get1ClickReturn,null,yuiTrackEventsPanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='TrackEvents';
      yuiTrackEventsPanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need to enter a search phrase and zip code
    SetAlertMsg('You must enter your zip code');  
  }
}
// =====================
// Show Track FriendFeed Panel    
// =====================
function ShowTrackFriendFeedPanel() {
  // hide the progress indicator
  document.getElementById('spanTrackFriendFeedProgress').style.display='none';
  // clear the alert message window
  ClearAlertMsg();
  // clear the search terms
  document.getElementById('txtTrackFriendFeed').value='';
  //show the panel
  yuiTrackFriendFeedPanel.show();
  // set the focus to the textbox
  document.getElementById('txtTrackFriendFeed').focus();
  // swap the static marketing content
  SwapMarketingFlash('static');    
}
// =====================
// Close Track FriendFeed Panel    
// =====================
function CloseTrackFriendFeedPanel(action) {
  var userid = document.getElementById('hidCurrentUserIdVal').value;
  var phrase = document.getElementById('txtTrackFriendFeed').value;
  var username = document.getElementById('txtFriendFeedUsername').value;
  var remotekey = document.getElementById('txtFriendFeedRemotekey').value;
  if ((username!="")&&(remotekey!="")) {  
    if (userid!=""){
      // show the progress indicator
      var prog=document.getElementById('spanTrackFriendFeedProgress');
      prog.innerHTML='Sending scout';
      prog.style.display='block';
      // call the webservice
      BNAlerts.Services.AddFriendFeed1ClickAlert(userid,phrase,username, remotekey,document.getElementById('chkTrackFriendFeedPrivacy').checked,Get1ClickReturn,null,yuiTrackFriendFeedPanel);
    }
    else{
      // show the login / registration dialog
      // set the global var for the method to call on successful login/registration
      loginReturn='TrackFriendFeed';
      yuiTrackFriendFeedPanel.hide();
      ShowLoginPanel();
    }   
  }
  else {
    //show alert message indicating need to enter a nickname and remotekey
    SetAlertMsg('You must enter your FriendFeed nickname and remote key');  
  }
}

// ===========================
// Callback for 1-Click Alerts    
// ===========================
// This is the callback routine used by the 1-click alerts
function Get1ClickReturn(result, panel) {
  if (result==true) {
    // Force a refresh of the alerts
    RefreshMyAlerts();
  }
  else {
    // close the panel
    panel.hide();
    // hide the login panel in case it was displayed
    yuiLoginPanel.hide();
    // if the flash marketing message is visible then swap the static graphic to the flash graphic
    SwapMarketingFlash('flash');
    if (panel.id=='pnlTrackWebsite') {
    //show alert message indicating no feeds on site
    SetAlertMsg('The web page you entered does not contain any feeds');
    }
    else if (panel.id=='pnlTrackLinkedIn') {
    //show alert message indicating invalid profile
    SetAlertMsg('The profile url is invalid');
    }
    else {
    //show alert message indicating need to be logged in
    SetAlertMsg('Your Scout was not saved');
    }
  }
}
// =======================
// Page-Specific Login Pop-Up Methods    
// =======================
function LoginReturn(result) {
  // set the local user id
  document.getElementById("hidCurrentUserIdVal").value=result;
  // call the appropriate method to complete alert saving  
  var progress=document.getElementById('spanLoginProgress');
  var regprogress=document.getElementById('spanRegProgress');
  if (result!='') {
    var n = loginReturn;
    loginReturn=''; // clear this variable so it does not cause problems later
    // update the progress indicator
    progress.innerHTML='Sending scout';
    regprogress.innerHTML='Sending scout';
    switch(n)
    {
    case 'GoogleMe':
      // finish saving the alert
      CloseGoogleMePanel('login');
      break;    
    case 'SearchThis':
      // finish saving the alert
      CloseSearchThisPanel('login');
      break;    
    case 'TrackRss':
      // finish saving the alert
      CloseTrackRssPanel('login');
      break;    
    case 'TrackLinkedIn':
      // finish saving the alert
      CloseTrackLinkedInPanel('login');
      break;
  case 'TrackWebsite':
      // finish saving the alert
      CloseTrackWebsitePanel('login');
      break;
  case 'TrackPrice':
      // finish saving the alert
      CloseTrackPricePanel('login');
      break;    
    case 'TrackAuctions':
      // finish saving the alert
      CloseTrackAuctionsPanel('login');
      break;    
    case 'TrackEvents':
      // finish saving the alert
      CloseTrackEventsPanel('login');
      break;    
    case 'TrackFriendFeed':
      // finish saving the alert
      CloseTrackFriendFeedPanel('login');
      break;    
    default:
      // tbd what to do here
    }
  }
  else {
    // show an error message in the pop-up
    document.getElementById('spanLoginError').innerHTML='Login attempt failed';
    document.getElementById('spanLoginError').style.display='block';
    document.getElementById('spanRegError').innerHTML='Registration failed. Try a different username.';
    document.getElementById('spanRegError').style.display='block';
    // hide the progress indicator
    progress.style.display='none';
    regprogress.style.display='none';
  }
}
// =======================
// Force My Alerts Refresh    
// =======================
function RefreshMyAlerts() {
  // Right now we are simply forcing a page refresh
  // add querystring params to show alert message that alert was saved
  var url = document.location.pathname + '?r=true&a=0';
  window.location.href=url;
  // TODO: Add logic to force a refresh of the contents of my alerts
}
// =====================
// JQuery Startup
//  CAC 25 March 2008    
// =====================
var xmlMyAlerts;
var yuiGoogleMePanel;
var yuiRelevancePanel;
var yuiTrackRssPanel;
var yuiTrackWebsitePanel;
var yuiTrackLinkedInPanel;
var yuiTrackPricePanel;
$(function(){
    $(".dmyCollapsiblePanel").bind("click",runCollapsiblePanelToggle);//call runCollapsiblePanelToggle on click
    $("#flashContentPlaceholder").hide();//hide the flash placeholder
    $("#flashOpen").hide();//hide the flash open button
    $(".feedback_top").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            //if the flash container does not have a class or the class attribute does not contain the class "hideMe"...
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    //Bind clicks to all the buttons that bring up a 1-Click panel
    $("#A1").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A2").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A3").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A4").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A5").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A6").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A7").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A8").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A9").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A10").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A11").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $("#A12").bind("click", function(){
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").hide();
            $("#flashContentPlaceholder").show();
            $(".closeFlash").css("visibility","hidden");
        }
    });
    $(".closeFlash").bind("click", function(){
        $("#flashContainer").hide();
        $("#flashContentPlaceholder").hide();
        $(".openFlash").show();
        $("#flashContainer").addClass("hideMe");//add the class hideMe to be used for showing and hiding of the flash close button
        $(this).css("visibility","hidden");
        //reset the YUI panels to take into account the new XY coordinates of their anchors
        yuiGoogleMePanel.cfg.queueProperty("context", ["p1", "tl", "tl"]);
        yuiGoogleMePanel.render();
        
        yuiSearchThisPanel.cfg.queueProperty("context", ["p2", "tl", "tl"]);
        yuiSearchThisPanel.render();
        
        yuiTrackRssPanel.cfg.queueProperty("context", ["p3", "tl", "tl"]);
        yuiTrackRssPanel.render();
        
        yuiTrackWebsitePanel.cfg.queueProperty("context", ["p4", "tl", "tl"]);
        yuiTrackWebsitePanel.render();

        yuiTrackLinkedInPanel.cfg.queueProperty("context", ["p5", "tl", "tl"]);
        yuiTrackLinkedInPanel.render();
        
        yuiTrackPricePanel.cfg.queueProperty("context", ["p1", "tl", "tl"]);
        yuiTrackPricePanel.render();
        
        yuiTrackAuctionsPanel.cfg.queueProperty("context", ["p2", "tl", "tl"]);
        yuiTrackAuctionsPanel.render();

        yuiTrackEventsPanel.cfg.queueProperty("context", ["p3", "tl", "tl"]);
        yuiTrackEventsPanel.render();

        yuiTrackFriendFeedPanel.cfg.queueProperty("context", ["p4", "tl", "tl"]);
        yuiTrackFriendFeedPanel.render();

    }).css("visibility", "hidden");
    $(".openFlash").bind("click",function(){
        $("#flashContainer").show();
        $("#flashContentPlaceholder").hide();
        $(".openFlash").hide();
        $("#flashContainer").removeClass("hideMe");
        var showCloseFlash = setTimeout(function(){$(".closeFlash").css("visibility","visible");},2500);
        yuiGoogleMePanel.cfg.queueProperty("context", ["p1", "tl", "tl"]);
        yuiGoogleMePanel.render();
        
        yuiSearchThisPanel.cfg.queueProperty("context", ["p2", "tl", "tl"]);
        yuiSearchThisPanel.render();
        
        yuiTrackRssPanel.cfg.queueProperty("context", ["p3", "tl", "tl"]);
        yuiTrackRssPanel.render();
        
        yuiTrackWebsitePanel.cfg.queueProperty("context", ["p4", "tl", "tl"]);
        yuiTrackWebsitePanel.render();
        
        yuiTrackLinkedInPanel.cfg.queueProperty("context", ["p5", "tl", "tl"]);
        yuiTrackLinkedInPanel.render();
        
        yuiTrackPricePanel.cfg.queueProperty("context", ["p1", "tl", "tl"]);
        yuiTrackPricePanel.render();

        yuiTrackAuctionsPanel.cfg.queueProperty("context", ["p2", "tl", "tl"]);
        yuiTrackAuctionsPanel.render();

        yuiTrackEventsPanel.cfg.queueProperty("context", ["p3", "tl", "tl"]);
        yuiTrackEventsPanel.render();

        yuiTrackFriendFeedPanel.cfg.queueProperty("context", ["p4", "tl", "tl"]);
        yuiTrackFriendFeedPanel.render();

    });
   
    var showCloseFlash = setTimeout(function(){
        $(".closeFlash").css("visibility","visible");
        //For first load, set all of the YUI 1-Click panels after the Flash has become visible.
        yuiGoogleMePanel = new YAHOO.widget.Panel("pnlGoogleMe", {visible:false});
        yuiGoogleMePanel.cfg.queueProperty("context", ["p1", "tl", "tl"]);
        yuiGoogleMePanel.cfg.queueProperty("modal", true);
        yuiGoogleMePanel.cfg.queueProperty("close", true);
        yuiGoogleMePanel.render();
        
        yuiSearchThisPanel = new YAHOO.widget.Panel("pnlSearchThis", {visible:false});
        yuiSearchThisPanel.cfg.queueProperty("context", ["p2", "tl", "tl"]);
        yuiSearchThisPanel.cfg.queueProperty("modal", true);
        yuiSearchThisPanel.cfg.queueProperty("close", true);
        yuiSearchThisPanel.render();
        
        yuiTrackRssPanel = new YAHOO.widget.Panel("pnlTrackRss", {visible:false});
        yuiTrackRssPanel.cfg.queueProperty("context", ["p3", "tl", "tl"]);
        yuiTrackRssPanel.cfg.queueProperty("modal", true);
        yuiTrackRssPanel.cfg.queueProperty("close", true);
        yuiTrackRssPanel.render();
        
        yuiTrackLinkedInPanel = new YAHOO.widget.Panel("pnlTrackLinkedIn", {visible:false});
        yuiTrackLinkedInPanel.cfg.queueProperty("context", ["p5", "tl", "tl"]);
        yuiTrackLinkedInPanel.cfg.queueProperty("modal", true);
        yuiTrackLinkedInPanel.cfg.queueProperty("close", true);
        yuiTrackLinkedInPanel.render();
        
        yuiTrackPricePanel = new YAHOO.widget.Panel("pnlTrackPrice", {visible:false});
        yuiTrackPricePanel.cfg.queueProperty("context", ["p1", "tl", "tl"]);
        yuiTrackPricePanel.cfg.queueProperty("modal", true);
        yuiTrackPricePanel.cfg.queueProperty("close", true);
        yuiTrackPricePanel.render();
        
        yuiTrackAuctionsPanel = new YAHOO.widget.Panel("pnlTrackAuctions", {visible:false});
        yuiTrackAuctionsPanel.cfg.queueProperty("context", ["p2", "tl", "tl"]);
        yuiTrackAuctionsPanel.cfg.queueProperty("modal", true);
        yuiTrackAuctionsPanel.cfg.queueProperty("close", true);
        yuiTrackAuctionsPanel.render();
        
        yuiTrackEventsPanel = new YAHOO.widget.Panel("pnlTrackEvents", {visible:false});
        yuiTrackEventsPanel.cfg.queueProperty("context", ["p3", "tl", "tl"]);
        yuiTrackEventsPanel.cfg.queueProperty("modal", true);
        yuiTrackEventsPanel.cfg.queueProperty("close", true);
        yuiTrackEventsPanel.render();

        yuiTrackFriendFeedPanel = new YAHOO.widget.Panel("pnlTrackFriendFeed", {visible:false});
        yuiTrackFriendFeedPanel.cfg.queueProperty("context", ["p4", "tl", "tl"]);
        yuiTrackFriendFeedPanel.cfg.queueProperty("modal", true);
        yuiTrackFriendFeedPanel.cfg.queueProperty("close", true);
        yuiTrackFriendFeedPanel.render();

        yuiTrackWebsitePanel = new YAHOO.widget.Panel("pnlTrackWebsite", { visible: false });
        yuiTrackWebsitePanel.cfg.queueProperty("context", ["p4", "tl", "tl"]);
        yuiTrackWebsitePanel.cfg.queueProperty("modal", true);
        yuiTrackWebsitePanel.cfg.queueProperty("close", true);
        yuiTrackWebsitePanel.render();

        $(".container-close").bind("click", function() {//bind a function to all 1-Click close buttons
        if((!$("#flashContainer").attr("class"))||($("#flashContainer").attr("class").indexOf("hideMe") < 0)){
            $("#flashContainer").show();
            $("#flashContentPlaceholder").hide();
            var showCloseFlash = setTimeout(function(){$(".closeFlash").css("visibility","visible");},2500);
            return false;
        }
    });
        
    },2500);
    
    // =====================
    // Truncate based on class assigned - uses jQueryTruncate plugin
    // http://www.reindel.com/truncate/    
    // =====================
    //Uncomment whichever one you want to see work:
    /*$(".bnTruncate30").truncate(30,{
        chars: /\s/
    });
   
    $(".bnTruncate90").truncate(90,{
        chars: /\s/
    });
    
    $(".bnTruncate30SafeEnd18").truncateSafeEnd(30,18,{
    });
    
    $(".bnTruncateMid30").truncateMid(30,{
            chars: /\s/
    });*/
    
    RunTruncate('');
    /*-- Added 13 June 2008 by CAC --*/
    assignRelevancePanelEvents($(".addRuleButton").length-1); /*wire up the initial events for relevance panel*/
});

// =====================
// Run Truncate
// =====================
function RunTruncate(action){
  action=action+'';
  if ((action=='30')||(action=='')) {
    $(".bnTruncate30").truncate(30,{
        chars: /\s/
    });
  }
  if ((action=='45')||(action=='')) {
    $(".bnTruncate45").truncate(45,{
        chars: /\s/
    });
  }
  if ((action=='100')||(action=='')) {
    $(".bnTruncate100").truncate(100,{
        chars: /\s/
    });
  }
  if ((action=='30SafeEnd18')||(action=='')) {
    $(".bnTruncate30SafeEnd18").truncateSafeEnd(30,18,{
    });
  }
  if ((action=='Mid30')||(action=='')) {
    $(".bnTruncateMid30").truncateMid(30,{
            chars: /\s/
    });
  }
}
// =====================
// Relevance Panel Methods
// =====================
function ShowFilterPanel(id) {
  ResetRelevancePanel(); // reset the filter panel lines
  // position the dialog 
  yuiRelevancePanel.cfg.setProperty("context", ["spanRel"+id, "tl", "bl"]);
  // show the dialog 
  yuiRelevancePanel.show(); 
  $('#hidFilterId').val(id);// set the alert id
  // set the progress indicator and disable the save button
  var prog=$('#spanSavingRelevanceRules').get(0);
  $(prog).text('Loading rules...');
  $(prog).css('visibility','inherit');
  SetSaveRulesetButtonStatus(false); // disable the save button  
  var div=$('.bdRuleLine').get(0);
  $(div).css('visibility','hidden');// hide the first row
  // clear alert message  
  ClearAlertMsg();
  // get the filter rules for the alert setting 
  BNAlerts.AjaxData.GetAlertRuleSet($('#hidCurrentUserIdVal').val(),id,GetRulesReturn);
  // swap the static marketing content
  SwapMarketingFlash('static');    
  // reset the session timer
  StartSessionTimer()
}

function GetRulesReturn(result){
  // loop through the rules and add lines
  // process the results and add them to the popmenu
  var i=1;
  var val, text;
  // get the dataset using jQuery
  var xmlTables = $(result).find("Table1");
  if($(xmlTables).length >0){
    $(xmlTables).each(function(){
      index=$($(this).children("Index").get(0)).text();
      text=$($(this).children("Values").get(0)).text();
      if (i>1){
        AddRuleLine(i-1);//add a line
      }
      SetRelevanceLineValues(i,index,text); // set the values
      assignRelevancePanelEvents(i);//assign the events
      i++;
    });
  }  
  // setup the remove rule buttons
  if($(".addRuleButton").length<=1){
      $(".removeRuleButton").css("visibility","hidden");
  }
  else {
      $(".removeRuleButton").css("visibility","inherit");
  }
  $('.bdRuleLine').css('visibility','inherit')// show all of the lines
  $('#spanSavingRelevanceRules').css('visibility','hidden');// hide the progress indicator
  SetSaveRulesetButtonStatus(true); // enable the save button
}
function SetSaveRulesetButtonStatus(enabled) {
  var btn=$("#btnSaveRuleset").get(0);
  var img=$("#imgSaveRuleset").get(0);
  if (enabled==true){
    btn.disabled=false;
    btn.className='positive';
    img.src='/img/tick.png';
  }
  else {
    btn.disabled=true;
    btn.className='disabled';
    img.src='/img/tick-disabled.png';
  }
};
function ResetRelevancePanel() {
  // this method resets the relevance panel to a defautl state (1 row and nothing selected)
  // delete the lines > line 1
  var len=$(".addRuleButton").length;
  var line;
  for (i=1;i<len;i++) {
    line=$(".addRuleButton").get(len-i);
    $(line).parent().parent().remove();
  }            
  assignRelevancePanelEvents(1);//setup the binding, etc
//  $($(".addRuleButton").hide().get(0)).show();// show the add button on the first row
//  $(".removeRuleButton").css("visibility","hidden");// hide the remove button
  // reset the value of line 1  
  SetRelevanceLineValues(1,0,'');
}
function SetRelevanceLineValues(line,selval,txtval) {
  var pop=$(".selRuleAction").get(line-1);
  pop.selectedIndex=selval;
  var txt=$(".selRuleText").get(line-1);
  txt.value=txtval;
}
function AddRuleLine(lineIndex) {
  var parent=$(".addRuleButton").get(lineIndex-1);
  $(parent).parent().parent().clone(true).insertAfter($(parent).parent().parent());
  
  if (lineIndex>=1) {
    // remove the add from previous line    
    $($(".addRuleButton").get($(".addRuleButton").length-2)).hide();//hide the add button  
  }
  if($(".addRuleButton").length>=5){//If the newly created div has made more than 5...
    $($(".addRuleButton").get($(".addRuleButton").length-1)).hide();//hide the add button
  }
}
function CloseFilterPanel() {
  // show the progress indicator
  var prog=$('#spanSavingRelevanceRules').get(0);
  $(prog).text('Saving rules...');
  $(prog).css('visibility','inherit');
  // build the return string
  var pop,txt;
  var rules,sep,type;
  rules='';
  sep='';
  for (i=0;i<=$(".selRuleAction").length-1;i++) {
    pop=$(".selRuleAction").get(i);
    txt=$(".selRuleText").get(i);
    if ($(txt).val()!='') {
      index=pop.selectedIndex;
      type=pop[index].value;
      rules=rules+sep+type+'='+$(txt).val();
      sep='|';
    }
  }
  if (rules.length>0) {
    // save it to the db
    BNAlerts.Services.UpdateRuleSet($('#hidCurrentUserIdVal').val(), $('#hidFilterId').val(),rules,SaveRulesReturn);
  }
  else {
    // no rules to save
    SetAlertMsg('No rules were configured');
    SaveRulesReturn(false);
  }
}
function SaveRulesReturn(result) {
  if (result==true) {
    //show alert message indicating problem saving
    SetAlertMsg('Your scout rules were saved');
  }
  else {
    //show alert message indicating problem saving
    SetAlertMsg('Your scout rules were not saved');
  }
  // close the panel
  yuiRelevancePanel.hide();
  // if the flash marketing message is visible then swap the static graphic to the flash graphic
  SwapMarketingFlash('flash');
}
// =====================
// assignRelevancePanelEvents
//  CAC 13 June 2008    
// =====================
assignRelevancePanelEvents = function(count){
    /*This is to hide the remove button when there is only one div*/
    if($(".addRuleButton").length<=1){
        $(".removeRuleButton").css("visibility","hidden");
    }
    /*This function binds one click function to the addRuleButtons*/
//    $($(".addRuleButton").get(count)).one("click",AddRuleLine());
    $($(".addRuleButton").get(count)).one("click",function(){
        if($(".addRuleButton").length<5){//Check to see if there are less than 5 divs. If they are, continue*/
            $(".removeRuleButton").css("visibility","inherit");//Show the remove button for all panels. This is to keep remove buttons from disappearing
            $(this).parent().parent().clone(true).insertAfter($(this).parent().parent());//Clone the current div and add it to the panel
            $($(".addRuleButton").hide().get($(".addRuleButton").length-1)).show();//Show only the bottom add button
            if($(".addRuleButton").length>=5){//If the newly created div has made more than 5...
                $($(".addRuleButton").get($(".addRuleButton").length-1)).hide();//hide the add button
            }
            $(this).unbind();//remove the click function from the current add button. If you don't do this, when you do the recursion, the click event is still in place and it goes bezerk
            assignRelevancePanelEvents($(".addRuleButton").length-1);//Iterate the recursion
        }
        return false;//cancel the bubble
    });
    /*This button binds one click function to the removeRuleButtons*/
//    $($(".removeRuleButton").get(count)).one("click",RemoveRuleLine());
    $($(".removeRuleButton").get(count)).one("click",function(){
        if($(".addRuleButton").length>1){//Make sure there are at least 2 divs
            $(this).parent().parent().remove();//remove the current div
            $($(".addRuleButton").hide().get($(".addRuleButton").length-1)).show();//show the addRuleButton on the next div up the stack
            if($(".addRuleButton").length==1){//If there is only one div now...
                $(".removeRuleButton").css("visibility","hidden");//hide the delete button
            }
            assignRelevancePanelEvents($(".addRuleButton").length-1);//Iterate the recursion
        }
        
        return false;
    });
    return false;
};
 
// =====================
// runCollapsiblePanelToggle
//  CAC 25 March 2008    
// =====================
runCollapsiblePanelToggle = function(){
    //var xmlMyNotifications;
    var newID = $(this).attr("id").replace(/divMALine_/,"");
    //var newFilter = document.getElementById("hidMANotiFilterVal").value;
    //var newTag = document.getElementById("hidMATagSearchVal").value;
    //var userid = document.getElementById("hidCurrentUserIdVal").value;
    
    var imgOpenUrl="../img/collapse.gif";
    var imgCloseUrl="../img/expand.gif";
    
    var imgOpenAlt="Collapse";
    var imgCloseAlt="Expand";

    var objImg = $(this).children(".showhide");
    var objThis = $(this).next(); // assigned pnlMANoti to objThis
    
    var objNotiDiv = $(objThis).children(".li_notifications");
    var bShown=objThis.css("display")=="none"?false:true;
    if(bShown){//Panel is visible
      objImg.attr("src",imgCloseUrl);        
      objImg.attr("alt",imgCloseAlt);        
      // toggle the hide show of light edits and notifications  
      $(this).toggleClass("alert_deselected").toggleClass("alert_selected");
      // clear out the contents of the notification area
      objNotiDiv.empty();
      objThis.slideUp("fast");
    } else {//Panel is invisible
        // swap the triangle 
        objImg.attr("src",imgOpenUrl);
        objImg.attr("alt",imgOpenAlt);        
        // slide the panel down
        objThis.slideDown(10);
        // toggle the hide show of light edits and notifications
        $(this).toggleClass("alert_deselected").toggleClass("alert_selected");        
        // get the notifications
        refreshNotifications(newID,'');
      objThis.slideDown("fast");
    }
};

function refreshNotifications(alertsettingid,direction) {
  // reset the session timer
  StartSessionTimer()
  var objPageNum = $('#hidPage'+alertsettingid);
  var pagenum = parseInt(objPageNum.attr('value'));
  var objMA = $('#divMALine_'+alertsettingid); 
  var objThis = $(objMA).next(); // assigned pnlMANoti to objThis
  var objNotiDiv = $(objThis).children(".li_notifications");
  // clear the contents
  objNotiDiv.empty();
  // show a status indicator
  objNotiDiv.append('<ul id="lvMANoti"><li><img src="/img/yBlue-small-loader.gif" class="retreivingReports"/>Retrieving Scout Reports...</li></ul>');
  // retrieve the notifications
  var xmlMyNotifications;
  var newFilter = document.getElementById("hidMANotiFilterVal").value;
  var newTag = document.getElementById("hidMATagSearchVal").value;
  var userid = document.getElementById("hidCurrentUserIdVal").value;
  var strHTML="";
  if (direction=='next') {
    if (($('#hidDirtyPage'+alertsettingid).attr('value')=='1')&&((newFilter=='recentunread')||(newFilter=='unread'))){
      pagenum=pagenum; // do not increment the pagenum just refresh current page
    }
    else{
      pagenum=pagenum+1; // increment the pagename
    }
  }
  else if (direction=='prev') {
    pagenum=pagenum-1;
  }
  else {
    pagenum=1;
  }
  if (pagenum<=1) {
    pagenum=1;
    $('#spanRefreshPrev'+alertsettingid).hide();
  }  
  else {
    $('#spanRefreshPrev'+alertsettingid).show();
  }
  objPageNum.attr('value',pagenum);
  // update the page dirty flag
  $('#hidDirtyPage'+alertsettingid).attr('value', '0');
  $.ajax({
      url: "../ws/AjaxData.asmx/GetUserAlertNotifications",
      type: "POST",
      data: { inUserId: userid, inFilter: newFilter, inTag: newTag, inAlertSettingId: alertsettingid, inPageNum: pagenum },      // input data
      processData: true,
      dataType: "xml",
      success: function(result) {
          xmlMyNotifications = result;
          xmlTables = $(xmlMyNotifications).find("Table");

          strHTML += '        <ul id="lvMANoti">';

          if ($(xmlTables).length > 0) {
              if (pagenum == 1) {
                  if ($(xmlTables).length < 10) {
                      // hide the "next" light edit if on first page and <10
                      $('#spanRefreshNext' + alertsettingid).hide();
                  }
                  else {
                      // show the "next" light edit if on first page and = 10
                      $('#spanRefreshNext' + alertsettingid).show();
                  }
              }
              $(xmlTables).each(function() {

                  ID = $(this).attr("diffgr:id");
                  rowOrder = $(this).attr("msdata:rowOrder");

                  iRowNum = $($(this).children("rownum").get(0)).text();
                  dCreateDate = $($(this).children("CreateDate").get(0)).text();
                  strDescription = $($(this).children("Description").get(0)).text();
                  strAlertType = $($(this).children("AlertType").get(0)).text();
                  strAlertSource = $($(this).children("AlertSource").get(0)).text();
                  strFavIcon = $($(this).children("FavIcon").get(0)).text();
                  iItemId = $($(this).children("ItemId").get(0)).text();
                  strTitle = $($(this).children("Title").get(0)).text();
                  strCommandName = $($(this).children("CommandName").get(0)).text();
                  strNotificationUrl = $($(this).children("NotificationUrl").get(0)).text();
                  strSourceUrl = $($(this).children("PreviewUrl").get(0)).text();
                  iAlertSettingId = $($(this).children("AlertSettingId").get(0)).text();
                  iNotificationId = $($(this).children("NotificationId").get(0)).text();
                  strFilter = $($(this).children("Filter").get(0)).text();
                  strUserId = $($(this).children("UserId").get(0)).text();
                  bIsPrivateChecked = $($(this).children("IsPrivateChecked").get(0)).text();
                  bIsReadChecked = $($(this).children("IsReadChecked").get(0)).text();
                  iAlertSettingType = $($(this).children("AlertSettingType").get(0)).text();
                  strEnableCommand = $($(this).children("EnableCommand").get(0)).text();
                  strTagCommand = $($(this).children("TagCommand").get(0)).text();
                  strAlertTagCommand = $($(this).children("AlertTagCommand").get(0)).text();
                  strTags = $($(this).children("Tags").get(0)).text();
                  strAlertTags = $($(this).children("AlertTags").get(0)).text();
                  strPrimaryEmail = $($(this).children("PrimaryEmail").get(0)).text();
                  dFriendlyCreateDate = $($(this).children("FriendlyCreateDate").get(0)).text();
                  strPreviewClass = $($(this).children("PreviewClass").get(0)).text();
                  strShareClass = $($(this).children("ShareClass").get(0)).text();
                  strPriorityClass = $($(this).children("PriorityClass").get(0)).text();
                  strPreviewUrl = '';
                  if (strPriorityClass == '') {
                      strPriorityClass = 'priority_0';
                  }
                  intPriority = $($(this).children("Priority").get(0)).text();
                  if (intPriority == '') {
                      intPriority = '0';
                  }
                  var readclass; // need to determine the read/unread state of the line to apply the correct css class
                  if (bIsReadChecked == 'checked') {
                      readclass = 'notificationTitle_read';
                  }
                  else {
                      readclass = 'notificationTitle_unread';
                  }

                  if (strSourceUrl.toString().substring(0, 22) == 'http://www.youtube.com') {
                      strPreviewUrl = strSourceUrl;
                  }
                  else {
                      strPreviewUrl = '/misc/nvr.aspx?a=' + iNotificationId;
                  }
                  strHTML += '            <li>';
                  strHTML += '                <div id="divMANotiLine' + iNotificationId + '" class="divMANoti' + iAlertSettingId + ' notification_deselected ' + readclass + ' dmyCollapsibleItem" onclick="ToggleIsReadStatus(' + iAlertSettingId + ', ' + iAlertSettingType + ', ' + iItemId + ')">'; //<!--//onclick="ToggleIsReadStatus('iAlertSettingId + ', ' + iAlertSettingType + ', ' + iItemId')"';//<!--//onclick="ToggleNotification('divMANotiLine<%#Eval("NotificationId")%>','<%#Eval("NotificationId")%>', 'cpeMANotiEdit')"//--> //onclick="ToggleNotification(\'divMANotiLine'+iNotificationId+'\','+iNotificationId+', \'cpeMANotiEdit\')" 
                  strHTML += '                    <div class="' + strPriorityClass + '" title="Priority ' + intPriority + ' Report"></div>';
                  strHTML += '                    <input id="chkMA' + iAlertSettingId + "-" + iAlertSettingType + "-" + iItemId + '" name="chkMA' + iAlertSettingId + "-" + iAlertSettingType + "-" + iItemId + '" class="readcheckbox" type="checkbox" ' + bIsReadChecked + ' style="visibility: hidden;" />'; //<!--//onclick="ToggleIsReadStatus('+iAlertSettingType+', '+iItemId+', this.checked)" //<!--//onclick="ToggleIsReadStatus(<%# Eval("AlertSettingType") %>, <%# Eval("ItemId") %>, this.checked)"-->                                                                
                  strHTML += '                    <span class="notificationTitle">' + strTitle + '</span>';
                  strHTML += '                    <span class="friendlydate_h">' + dFriendlyCreateDate + '</span>';
                  strHTML += '                    <input id="hidMANotiDesc' + iNotificationId + '" type="hidden" value="' + strTitle + '" />';
                  strHTML += '                </div>';
                  strHTML += '                <div id="divMANotiDesc" style="display:none"></div>';
                  strHTML += '                <div id="pnlMANotiEdit" class="li_content2" style="display:none">';
                  strHTML += '                    <span id="tagNotiImage' + iNotificationId + '" class="lightEditActionIndicatorTag ' + strTagCommand + '" onclick="ShowTagEditPanel(\'aTag' + iNotificationId + '\', \'noti\', ' + iNotificationId + ', \'' + strUserId + '\')">&nbsp;&nbsp;&nbsp;&nbsp;</span>'; //<!--//onclick="ShowTagEditPanel('aTag<%# Eval("NotificationId") %>', 'noti', '<%# Eval("NotificationId") %>', '<%# Eval("UserId") %>')"-->
                  strHTML += '                    <span class="lightEditActionTag" id="aTag' + iNotificationId + '" onclick="ShowTagEditPanel(\'aTag' + iNotificationId + '\', \'noti\', ' + iNotificationId + ', \'' + strUserId + '\')">Tag</span>'; //<!--//onclick="ShowTagEditPanel('aTag<%# Eval("NotificationId") %>', 'noti', '<%# Eval("NotificationId") %>', '<%# Eval("UserId") %>')"//-->
                  strHTML += '                    <input id="hidNotiTags' + iNotificationId + '" type="hidden" value="' + strTags + '"/>';
                  strHTML += '                    <span id="shareNotiImage' + iNotificationId + '" class="lightEditActionIndicatorShare lightEditActionIndicator_off" style="visibility:' + strShareClass + '">&nbsp;&nbsp;&nbsp;&nbsp;</span>'; //<!--//onclick="ShowSharePanel('aNotiShare<%# Eval("NotificationId") %>', 'noti', '<%# Eval("NotificationId") %>', '<%# Eval("AlertSettingId") %>', '<%# Eval("UserId") %>', 'MA')"//-->
                  strHTML += '                    <span class="lightEditAction" id="aNotiShare' + iNotificationId + '" onclick="ShowSharePanel(\'aNotiShare' + iNotificationId + '\', \'noti\', ' + iNotificationId + ', ' + iAlertSettingId + ', \'' + strUserId + '\', \'MA\')" style="visibility:' + strShareClass + '">Share</span>'; //<!--//onclick="ShowSharePanel('aNotiShare<%# Eval("NotificationId") %>', 'noti', '<%# Eval("NotificationId") %>', '<%# Eval("AlertSettingId") %>', '<%# Eval("UserId") %>', 'MA')"//-->
                  strHTML += '                    <span class="' + strPreviewClass + '" id="aPreview' + iNotificationId + '" onclick="ShowPreviewPanel(\'aPreview' + iNotificationId + '\',\'' + strPreviewUrl + '\');">Preview</span>'; //<!--//onclick="ShowPreviewPanel('aPreview<%# eval("NotificationId") %>','<%# eval("PreviewUrl") %>');"//-->
                  strHTML += '                    <a class="linkOut" href="' + strPreviewUrl + '" target="_blank">&nbsp;</a>'; //<!--//At load of notification, change the href to the NotificationUrl//-->
                  strHTML += '                </div>';
                  strHTML += '            </li>';
              });

          } else {
              strHTML += '<li>No reports at this time</li>';
              if (pagenum == 1) {
                  // hide the "next" light edit if page=1
                  $('#spanRefreshNext' + alertsettingid).hide();
              }
          }
          strHTML += '        </ul>';
          objNotiDiv.empty();
          objNotiDiv.append(strHTML); //inject new HTML into DOM as child of panel

          // I am concerned about the performance hit of binding to every single notification
          $(".dmyCollapsibleItem").bind("click", toggleNotification);
      },
      error: function(xhr, message, ex)
      { alert("Ajax Error: " + message); }
  });
}
// =====================
// toggleNotification
//  CAC 25 March 2008    
// =====================
toggleNotification = function(){
   // $(this).toggleClass("notification_deselected").toggleClass("notification_selected");
    $(this).next().toggle().next().toggle();
};
// =====================
//Add autocomplete to tags
// =====================
$(document).ready(function() {
if ($('#hidTagSearch')[0] != null) {
        $('#' + $('#hidTagSearch')[0].value).autocomplete(
        "/ws/tagsautocomplete.aspx",
        {
            minChars: 2,
            extraParams: { cid: $('#hidCurrentUserIdVal')[0].value },
            cacheLength: 10
        });
    }
});

$(document).ready(function() {
if ($('#hidTagsTextBox')[0] != null) {
        $('#' + $('#hidTagsTextBox')[0].value).autocomplete(
        "/ws/tagsautocomplete.aspx",
        {
            minChars: 2,
            extraParams: { cid: $('#hidCurrentUserIdVal')[0].value },
            cacheLength: 10,
            multiple: true
        });
    }
}); 

$(document).ready(function() {
    $('#' + $('#hidShareEmailsTextBox')[0].value).autocomplete(
        "/ws/contactsautocomplete.aspx",
        {
	        minChars:2,
	        extraParams: {cid: $('#hidCurrentUserIdVal')[0].value},
	        cacheLength: 10,
	        multiple: true
        }
    );
});
