var Zurple = {
  Client: {
    city_counter: 0,

    setDeleteMultipleCity: function(evt) {
      var jqmulti_city = $(this).parents('#multi_city_view').siblings('#form-element-multi_city').find('#multi_city');
      var multi_cities = jqmulti_city.val().split(/;/);
      jqmulti_city.val('');

      for( var i = 0, l = multi_cities.length; i < l; i++ ) {
        if( multi_cities[i] != $(this).parent().next().text() && multi_cities[i] != '' ) {
          jqmulti_city.val(jqmulti_city.val() + multi_cities[i] + ';')
        }
      }
      $(this).parent().parent().remove();

      return false;
    },

    setSearchMultipleEvent: function(evt) {
      var jqcity = $(this).prev().find('#city');
      var jqmulti_city = $(this).prev().prev().find('#multi_city');
      var jqmulti_city_view = $(this).next();

      var new_city = jqcity.val().replace(/(^\s+)|(\s+$)/g, "");

      if( new_city != '' ) {
        jqmulti_city.val(jqmulti_city.val() + new_city + ';');
        jqmulti_city_view.append('<div class="multi_city_item" id="multi_city_' + Zurple.Client.city_counter + '"><div class="multi_city_x"><a href="#" class="multi_city_del yellow">x</a></div><div class="multi_city_name">' + new_city + '</div></div>');
        $('#multi_city_' + Zurple.Client.city_counter).show('fast');
        jqcity.val('');          
        Zurple.Client.city_counter += 1;

        $('.multi_city_del').click(Zurple.Client.setDeleteMultipleCity);
      }
      else {
        alert('Please enter city/community or zipcode');
        jqcity.focus();
      }

      return false;
    },

    Common: function() {
      var close = true;
      var mouse_on = null;
      var questions_entered = [];
      var prop_id_q;

      if($("#city").length > 0) {
        $("#city").jSuggest( {
          url: "city",
          type: "GET",
          data: "c" ,
          autoChange: true,
          loadingImg: '',
          minchar: 1,
          delay: 100
        });
      }

      $('#address').focus(function(event) {
        if ($('#city').val() == '') {
          $("#address").jSuggest({
            url: "city/address/city/0/",
            type: "GET",
            data: "a",
            autoChange: true,
            loadingImg: '',
            minchar: 3,
            delay: 100
          });
        }
        else {
          $("#address").jSuggest({
            url: "city/address/city/" + $('#city').val() + '/',
            type: "GET",
            data: "a",
            autoChange: true,
            loadingImg: '',
            minchar: 1,
            delay: 100
          });
        }
      });

      var closePulldown = function() {
        $("#pulldown_menu_popup").hide("fast");
        close = true;
      };

      $("#topnavi_button").mouseover(function(event) {
        if (close) {
          $("#pulldown_menu_popup").show('fast');
        }

        if (mouse_on) {
          clearTimeout(mouse_on);
          mouse_on = null;
        }
      });

      $("#topnavi_button").mouseout(function(event) {
        mouse_on = setTimeout(closePulldown, 1000);
      });

      $(".question").focus(function(event) {

        // get prop_id
        prop_id_q = $(this).attr("id").replace('question-', '');

        // check if it's got focused
        for( var i = 0, t = questions_entered.length; i < t; i++ ) {
          if( questions_entered[i] == prop_id_q ) {
            return;
          }
        }

        questions_entered.push(prop_id_q);
        $(this).val('');
      });

      $(".ask_question").click(function(event)
      {
        // get prop_id
        prop_id_q = $(this).attr("id").replace('ask_question-', '');

        // check if question has been entered
        var entered = false;
        for( var i = 0, t = questions_entered.length; i < t; i++ ) {
          if( questions_entered[i] == prop_id_q ) {
            entered = true;
          }
        }

        if( !entered || $("#question-" + prop_id_q).val() == '' )
        {
          alert("please enter your question");
          $("#question-" + prop_id_q).focus();
          return false;     
        }

        // pop up the question box
        $("#ask_box_container").css({'top': event.pageY - 120 + 'px', 'left': event.pageX + 'px'});
        $("#ask_box_container").fadeIn('fast');
    
        // focus on first name
        $("#first_name").focus();
    
        return false;
      });

      $(".cancel").click(function(event)
      {
        $("#ask_box_container").fadeOut('fast');
    
        return false;
      });

      $(".close").click(function(event)
      {
        $("#advanced_filter").fadeOut('fast');
    
        return false;
      });

      $('#property_search_form').submit(function(evt) {
        var city = $('#city').val().replace(/(^\s+)|(\s+$)/g, "");
        var mcity = $('#multi_city').val().replace(/(^\s+)|(\s+$)/g, "");
        if( city == '' && mcity == '' ) {
          alert('Please enter city/community or zipcode');
          $('#city').focus();
          return false;
        }

        return true;
      });

      $('#search_multiples').click(Zurple.Client.setSearchMultipleEvent);

      if ($("#ask_question_send").length > 0) {
      
        $("#ask_question_send").validate({
          rules: {
            first_name: "required",
            phone: ($("#phone").length > 0 && $("label[for=phone]").text().indexOf('*') > 0) ? "required" : null,
            email: {
              required: true,
              email: true
            }
          },
          messages: {
            first_name: "Please enter your first name",
            phone: "Please enter your phone number",
            email: {
              required: "Please enter your email address",
              email: "Please enter a valid email address"
            }
          },
          submitHandler: function(form){
          
            var admin_id = 0;
            if (prop_id_q == 0) {
              admin_id = $('#admin_id').val();
            }
            
            var obj = $('#ask_question_send_button');
            
            obj.hide();
            obj.after('<img src="img/zurple/icon_loading.gif" class="loading3" />');
            
            $.post(form.action, {
              prop_id: prop_id_q,
              admin_id: admin_id,
              question: $("#question-" + prop_id_q).val(),
              first_name: $("#first_name").val(),
              last_name: $("#last_name").val(),
              email: $("#email").val(),
              phone: $("#phone").val()
            }, function(json){
              if (json.error == 1) // login error
              {
                location.href = $('base').attr('href') + 'login';
              }
              else 
                if (json.error != 0) // etc error
                {
                }
                else {
                  $("#ask_question_span-" + prop_id_q).html(json.message);
                  $("#ask_question_span-" + prop_id_q).addClass("white");
                }
              
              obj.show();
              $(".loading3").remove();
              
              alert(json.message);
              $("#ask_box_container").fadeOut('fast');
            }, "json");
            
            return false;
          }
        });
      }

      $('.delete_fav').click(function(event) {
        return confirm('Remove this property from favorite?');
      });

    },

    Home: function() {
      $('#advanced_filter').css({left: '148px', top: '200px'});

      $('#advanced_filter_link').click(function(evt) {

        $('#advanced_filter').show();
        $('#advanced_filter #multi_city').val($('#property_search_form #multi_city').val());
        $('#advanced_filter #city').val($('#property_search_form #city').val());
        $('#advanced_filter #multi_city_view').html($('#property_search_form #multi_city_view').html());
        $('#advanced_filter #min_price').val($('#property_search_form #min_price').val());
        $('#advanced_filter #max_price').val($('#property_search_form #max_price').val());
        $('#advanced_filter #bedrooms').val($('#property_search_form #bedrooms').val());

        $('#advanced_filter #search_multiples').click(Zurple.Client.setSearchMultipleEvent);
        $('#advanced_filter .multi_city_del').click(Zurple.Client.setDeleteMultipleCity);

        $("#advanced_filter #city").jSuggest( {
          url: "city",
          type: "GET",
          data: "c" ,
          autoChange: true,
          loadingImg: '',
          minchar: 1,
          delay: 100
        });

        return false;
      });
    },

    Insider: function() {
      var clase = true;
      var mouse_on = false;

      $(".morecity").mouseover(function(event) {
        if (close) {
          $(".morecity_pop").show('fast');
        }
      });

      $(".morecity").mouseout(function(event) {
        mouse_on = setTimeout('$(".morecity_pop").hide("fast"); close = true;', 1000);
      });

      $(".morecity").mousemove(function(event) {
        if (mouse_on) {
          clearTimeout(mouse_on);
          mouse_on = null;
        }
      });

      $(".sort").click(function(event)
      {
        // get sort type
        var sort_type = $(this).attr("id").replace('sort_', '');

        document.sort_form.sort.value = sort_type;
        $("#sort_form").submit();

        return false;
      });
    },

    Login: function() {
      $('#username').focus();
    },

    Propdetail: function() {
      var mouse_on = null;
      var close = true;
      var prop_id_q = null;

      $(".open_photo").click(function(event) {
        if ($(this).attr('src').indexOf('http://') != -1) {
          prefix = '';
        } else {
          prefix = $('base').attr('href');
        }

        window.open(prefix + $(this).attr('src'),'photo_window','width=660,height=500');
      });

      $('#slide').cycle({
        fx: 'fade',
        next: '#next', 
          prev: '#prev'
      });

      $('#pause').click(function() {
          $('#slide').cycle('pause'); 
      });

      $('#next').click(function() {
          $('#slide').cycle('pause'); 
      });

      $('#prev').click(function() {
          $('#slide').cycle('pause'); 
      });

      $('#resume').click(function() {
          $('#slide').cycle('resume'); 
      });

      $('#add_fav').click(function(event) {
        var obj = $(this);

        $(this).hide();
        $(this).after('<img src="img/zurple/icon_loading.gif" class="loading4" />');

        $.getJSON($(this).get(0).href, function(json) {
          if( json.error == 1 ) {  // error
            location.href = $('base').attr('href') + 'login';
          }
          else {
            $("#add_fav_span").html(json.message);
            $("#add_fav_span").addClass("white");
          }

          obj.show();
          $(".loading4").remove();

          alert(json.message);
        });

        return false;
      });

      $("#send_email").click(function(event) {
        var obj = $(this);

        if( $("#friend_email").val() == '' || $("#friend_email").val() == "type your friend's email here" ) {
          alert('Please enter email');
          return false;
        }

        $(this).hide();
        $(this).after('<img src="img/zurple/icon_loading.gif" class="loading1" />');

        $.getJSON($(this).get(0).href + escape($("#friend_email").val()), function(json) {
          if( json.error == 1 ) { // login error 
            location.href = $('base').attr('href') + 'login';
          }
          else if( json.error != 0 ) {  // etc error 
          }
          else {
            $("#send_email_span").html(json.message);
            $("#send_email_span").addClass("white");
          }

          obj.show();
          $(".loading1").remove();

          alert(json.message);
        });

        return false;
      });

      $("#friend_email").focus(function(event) {
        if( $("#friend_email").val() == "type your friend's email here" ) {
          $("#friend_email").val('');
        }
      });

      $(".post_comment").click(function(event) {
        var obj = $(this);

        // get prop_id
        var prop_id = $(this).attr("id").replace('post_comment-', '');

        if( $("#comment-" + prop_id).val() == '' ) {
          alert("please enter your comment");
          return false;     
        }

        $(this).hide();
        $(this).after('<img src="img/zurple/icon_loading.gif" class="loading2" />');

        $.post($(this).get(0).href, { comment: $("#comment-" + prop_id).val() }, function(json) {
          if( json.error == 1 ) { // login error
            location.href = $('base').attr('href') + 'login';
          }
          else if( json.error != 0 ) {  // etc error
          }
          else {
            $("#post_comment_span-" + prop_id).html(json.message);
            $("#post_comment_span-" + prop_id).addClass("white");
          }

          obj.show();
          $(".loading2").remove();

          alert(json.message);
        }, "json");

        return false;
      });

      $(".baloon").click(function(event) {
        // get prop_id
        var prop_id = $(this).attr("id").replace('baloon-', '');
    
        // show baloon
        $("#baloon_box-" + prop_id).removeClass("hidden");
    
        return false;
      });

      $('#pick_schedule').click(function(event) {
        var url = $(this).get(0).href;
        $("#schedulepick").show();

        $("#schedulepick").datepicker({
          showButtonPanel: true,
          minDate: 0,
          maxDate: '+3M',
          closeText: 'X',
          onClose: function(dateText, inst)
          {
            $("#schedulepick").hide();
          },
          onSelect: function(dateText, inst)
          {
            if (confirm('Would you like to schedule at ' + dateText + '?'))
            {
              var obj = $("#pick_schedule");

              $("#pick_schedule").hide();
              $("#pick_schedule").after('<img src="img/zurple/icon_loading.gif" class="loading5" />');

              $.post(url, { date: dateText }, function(json)
              {
                if( json.error == 1 ) // login error
                {
                  location.href = $('base').attr('href') + 'login';
                }
                else if( json.error != 0 )  // etc error
                {
                }
                else
                {
                  $("#schedule_span").html('scheduled at ' + dateText);
                }

                obj.show();
                $(".loading5").remove();

                alert(json.message);

              }, "json");

              $("#schedulepick").attr('disabled', 'disabled');        
            }
            else
            {
              $("#schedulepick").hide();
            }
          }
        });

        $("#schedulepick").datepicker('show');

        return false;
      });
    },

    Search: function() {
      var mouse_on = null;
      var close = true;

      $('#checkall').change(function(evt)
      {
        var checked = $(this).attr('checked');

        if (checked) {
          $('.comm_checkbox').each(function(i){
            $(this).attr('checked', 'checked');
          });
        }
        else
        {
          $('.comm_checkbox').each(function(i){
            $(this).removeAttr('checked');
          });
        }
      });

      $("#filterby").mouseover(function(event)
      {
        if (close) {
          $("#filterby_pop").show('fast');
        }
      });

      $("#filterby").mouseout(function(event)
      {
        mouse_on = setTimeout('$("#filterby_pop").hide("fast"); close = true;', 500);
      });

      $("#filterby").mousemove(function(event)
      {
        if (mouse_on) {
          clearTimeout(mouse_on);
          mouse_on = null;
        }
      });

      $('#advanced_filter_link').click(function(evt) {

        $('#advanced_filter').show();
        $('#advanced_filter #search_multiples').click(Zurple.Client.setSearchMultipleEvent);
        $('#advanced_filter .multi_city_del').click(Zurple.Client.setDeleteMultipleCity);
        $("#advanced_filter #city").jSuggest( {
          url: "city",
          type: "GET",
          data: "c" ,
          autoChange: true,
          loadingImg: '',
          minchar: 1,
          delay: 100
        });

        // check multi_city
        var multi_cities = $('#advanced_filter #multi_city').val().split(/;/);
        var city = $("#advanced_filter #city").val();
        for( var i = 0, l = multi_cities.length; i < l; i ++ ) {
          if( multi_cities[i] == '' ) {
            continue;
          }

          $("#advanced_filter #city").val(multi_cities[i]);
          $('#advanced_filter #search_multiples').click();
          $("#advanced_filter #city").val();
        }
        $("#advanced_filter #city").val(city);

        return false;
      });

      $('#advanced_filter').css({left: '220px', top: '160px'});
    },

    Register: function() {
      $("#first_name").focus();

      $("#register_form").validate({
        rules: {
          first_name: "required",
          phone: ( $("#phone").length > 0 && $("label[for=phone]").text().indexOf('*') > 0 ) ? "required" : null,
          email: {
            required: true,
            email: true
          }
        },
        messages: {
          first_name: "Please enter your first name",
          phone: "Please enter your phone number",
          email: {
            required: "Please enter your email address",
            email: "Please enter a valid email address"
          }
        }
      });

      $("#register_form").submit(function(event)
      {
        if( $("#first_name").val() == '' ) {
          alert("Please enter first name");
          $("#first_name").focus();
        }
        else if( $("#email").val() == '' ) {
          alert("Please enter email");
          $("#email").focus();
        }
        else
        {
          return true;
        }

        return false;
      });
    },

    My: function() {
      var community_id = [];
      var cur_city_id;
      community_id[$("#city_id").val()] = $("#community_id").val();

      var loadCommunity = function(data)
      {
        $('#community_id option').remove();
        $.each(data, function(i, item)
        {
          if (community_id[cur_city_id] != undefined && community_id[cur_city_id] != null && community_id[cur_city_id] == item.id)
          {
            $('#community_id').append('<option value="' + item.id + '" selected="selected">' + item.value + '</option>');
          }
          else
          {
            $('#community_id').append('<option value="' + item.id + '">' + item.value + '</option>');
          }
        });
      };

      $("#city_id").change(function(evt)
      {
        cur_city_id = $(this).val();
        $.getJSON('/city/communitiespulldown', {"city_id": $(this).val()}, loadCommunity, 'json');
      });

      $("#community_id").change(function(evt)
      {
        community_id[$("#city_id").val()] = $(this).val();
      });

      $("#change_email").click(function(event)
      {
        $("#change_email_text").addClass('hidden');
        $("#change_email_form").removeClass('hidden');
        return false;
      });

      $("#change_criteria").click(function(event)
      {
        $("#change_criteria_text").addClass('hidden');
        $("#change_criteria").hide();
        $("#change_criteria_form").removeClass('hidden');
        return false;
      });
    },

    Thankyou: function() {
      setTimeout("location.href = backpage;", 5000);
    },

    Resource: function() {
    },

    SearchCityTipText: 'Enter a city, or zip/postal code',

    SearchBasicCityTipAdd: function() {
      if ($('#property_search_form #city').val() == '') {
        $('#property_search_form #city').val(Zurple.Client.SearchCityTipText);
      }
    },
    SearchAdvancedCityTipAdd: function() {
      if ($('#advanced_filter_form #city').val() == '') {
        $('#advanced_filter_form #city').val(Zurple.Client.SearchCityTipText);
      }
    },
    SearchBasicCityTipRemove: function() {
      if ($('#property_search_form #city').val() == Zurple.Client.SearchCityTipText) {
        $('#property_search_form #city').val('');
      }
    },
    SearchAdvancedCityTipRemove: function() {
      if ($('#advanced_filter_form #city').val() == Zurple.Client.SearchCityTipText) {
        $('#advanced_filter_form #city').val('');
      }
    }
  }
};

