// Shows the login lightwindow.
// Optionally, you can pass a path to redirect to as a parameter.
//
function popLogin() {
  var redirectTo = null;

  if (arguments.length >= 1) {
    redirectTo = arguments[0];
  }

  eventTracker.loginShow();

  if (typeof(loginDialog) != "undefined") { 
    loginDialog.dialog('open')
  }
  else {
    loginDialog = $j('<div style="display:hidden"></div>').appendTo('body');

    var path = "/account/login_signup";
    if (redirectTo != null) {
      path = path + "?redirect_to=" + redirectTo;
    }

    loginDialog.load(
      path +' #loginSignupFormcontainer', 
      function (responseText, textStatus, XMLHttpRequest) {

        loginDialog.dialog({ 
          // height: 514, // removed due to display bug in IE
          width: 514, 
          modal: true, 
          closeOnEscape: true,
          draggable: false,
          dialogClass: 'loginDialog',
          beforeclose: function(event, ui) {
            // they are logged in
            if (getCookie("displet_logged_in")) return true

            // they are not on detail
            if (document.URL.indexOf('detail') == -1) return true

            return false
          },
          title: 'Login/Signup'});
      }
    );
  }

  return false
}

function updateFavorite() {
  link = this
  id = link.rel.substring(1)
  action = link.rel.substring(0,1)
  url = (action == 'a') ? '/residentials/create_favorite/'+id : '/residentials/delete_favorite/'+id

  function showFaveResult(data, xhr) {
    if (xhr.status == 401) {
      popLogin()
      return false
    }

    if (data.successful) {
      if (data.adding) {
        $j(link).addClass('favoriteOn')
        link.innerHTML = 'Remove From Favorites'
        link.writeAttribute('rel','r'+id)
      }
      else {
        $j(link).removeClass('favoriteOn')
        link.innerHTML = 'Add To Favorites'
        link.writeAttribute('rel','a'+id)
      }
    }
  }

  $j.ajax({
    url: url,
    type: 'POST',
    context: document.body, 
    dataType: "json", 
    success: function(data, textStatus, XMLHttpRequest) {
      showFaveResult(data, XMLHttpRequest) 
    }
  });

  return false
}

function showShowingRequest() {
  // we dont reuse this dialog since it is used on teh resilts list page where the url changes for each property
  requestDialog = $j('<div style="display:hidden"></div>').appendTo('body');
  requestDialog.load(
    this.href, 
    function (responseText, textStatus, XMLHttpRequest) {
      requestDialog.dialog({ height: 500, width: 500, modal: true, title: 'Request Showing'});
      $j("#showing_request_appointment1_at").datepicker();
      $j("#showing_request_appointment2_at").datepicker();
    }
  );

  return false
}
function submitShowingRequest() {
  requestDialog.dialog('close');
  $j('#requestShowingLink').html('Sending Request ...')

  $j.ajax({ url: "/showing_requests", 
            type: 'POST',
            context: document.body, 
            dataType: "json",
            data: $j('#new_showing_request').serialize(),
            success: handleShowingRequest
  });
  return false
}
function handleShowingRequest(e, r, settings) {
  if (e.successful) {
    $j('#requestShowingLink').html('Request Sent')
    $j('div#actions1 div:first-child').effect("highlight", {}, 3000);
    $j('#sendRequestButton').attr('value','Send');
  }
  else {
    // console.log('testfail')
  }

}

function showEmailDialog() {
  if (typeof(emailDialog) != "undefined") { 
    emailDialog.dialog('open')
  }
  else {
    emailDialog = $j('<div style="display:hidden"></div>').appendTo('body');
    emailDialog.load(
      this.href, 
      function (responseText, textStatus, XMLHttpRequest) {
        emailDialog.dialog({ height: 410, width: 500, modal: true, title: 'Send to a Friend'});
      }
    );
  }
  $j('#sendEmailButton').attr('value','Send');
  return false
}
function sendFriendEmail() {
  $j.ajax({ url: "/friend_notifications", 
            type: 'POST',
            context: document.body, 
            dataType: "json",
            data: $j('#new_friend_notification').serialize(),
            success: handleFriendEmail
  });
  return false
}
function handleFriendEmail(e, r, settings) {
  if (e.successful) {
    $j('#emailFriendLink').html('Message Sent')
    $j('#emailFriendLink').effect("highlight", {}, 3000);
  }
  else {
    // console.log('testfail')
  }

  // $j('#requestShowingFeedback').html(e.message)
  emailDialog.dialog('close');
}

function showSaveSearch() {
  // TODO: check for authentication
  // if (xhr.status == 401) {
  //   popLogin()
  //   return false
  // }
  
  // pop dialog for saving search
  if (typeof(saveSearchDialog) != "undefined") { 
    saveSearchDialog.dialog('open')
  }
  else {
    saveSearchDialog = $j('<div style="display:hidden"></div>').appendTo('body');
    saveSearchDialog.load(
      "/saved_searches/new", 
      function (responseText, textStatus, XMLHttpRequest) {
        saveSearchDialog.dialog({ 
          width: 514,
          modal: true,
          closeOnEscape: true,
          draggable: true,
          dialogClass: 'savedSearchDialog',
          title: 'Save Search',
          open: function(event, ui) {
            $j('#saved_search_search_criteria').val(searcher.params)
            $j('#savedSearchErrors').hide()
            $j('#savedSearchErrors span').html(null)
            $j('#savedSearchClientList li a').click(function() {
              $j('#saved_search_client_user_id').val($j(this).attr('rel'))
              $j('#selectedClientDisplay').text($j(this).text())
            })
            $j('#clearSavedSearchLink').click(function() {
              $j('#saved_search_client_user_id').val("")
              $j('#selectedClientDisplay').text("None Selected")
            })
          }
        });
      }
    );
  }
}
function submitSaveSearch(form) {
  $j.ajax({
    url: form.action,
    type: 'POST',
    context: document.body,
    data: form.serialize(),
    dataType: "json", 
    success: function(data, textStatus, xhr) {
      if (data.successful) {
        $j('#savedSearchErrors').fadeOut()
        $j('#savedSearchErrors span').html(null)

        saveSearchDialog.dialog('close')
        $j('#saveSearchLink').effect("highlight", {}, 3000);
      }
      else {
        $j('#savedSearchErrors').fadeIn()
        $j('#savedSearchErrors span').html(data.errors)
      }
    }
  });

  return false;
}

function filterUsers(ob) {
  var users_list = $j("#savedSearchClientList li");
  var user_filter = $j("#user_filter");

  users_list.each(function(i, user) {
    listedName = $j(user).text()
    if (listedName.indexOf(user_filter.val()) != -1) {
      $j(user).show()
    }
    else {
      $j(user).hide()
    }
  });
}

$j(document).ready(function() {
  // $j('#requestShowingLink').click(showShowingRequest)
  $j('.makeRequest').click(showShowingRequest)
  $j('#saveFaveLink').click(updateFavorite)
  $j('#emailFriendLink').click(showEmailDialog)

  $j('#saveSearchLink').click(showSaveSearch)
});
