var gmarkers = [];  
var house_icon_letters = [];
var tmp_icon = null;
var selected_color = "#BFDBFF";
var enabled_hover_color = "#FFCC99";
var disabled_hover_color = "#B5D0F2";
var plain_color = "#F2F2F2";
var enabled_title = "Click to disable this home";
var disabled_title = "Click to enable this home";
var tmp_obj = null;

for(var i = 1; i<=52; i++){
  tmp_icon = new GIcon();
  tmp_icon.image = "/images/icons/house-icon_"+zeroPad(i,2)+".png";
  tmp_icon.shadow = "/images/house-icon_shadow.png";
  tmp_icon.iconSize = new GSize(32, 28);
  tmp_icon.shadowSize = new GSize(32, 28);
  tmp_icon.iconAnchor = new GPoint(16, 28);
  tmp_icon.infoWindowAnchor = new GPoint(5, 1);
  tmp_icon.nid = 0; //Defines whether the icon is in use, and by what node
  house_icon_letters.push(tmp_icon);
}

//Document Ready...
$(function(){

  $('.results div.more').cluetip({
    cluetipClass: 'jtip', 
    arrows: true,
    dropShadow: true,
    hoverIntent: true,
    sticky: false,
    activation: 'click',
    mouseOutClose: true,
    local:true,
    closePosition: 'title',
    closeText: '<img src="/inc/openhomes/close.png" alt="close" />'
  });
  
  $('.cluetip-close-box').click(function(){$('#cluetip').hide();});
  
  $(".route_item").corner("round 5px");
  $(".route_items_list").sortable({axis:'y'});
  $(".unmappable").click(function(){
    var addr = $(this).find('.addr').text();
    var mls = home_data[$(this).attr('id').split('_')[1]].mls;
    $.prompt('We\'re sorry, but the listing for '+addr+' is not currently mappable. <br/> <a href="/mls?mlsnum='+mls+'#directions" target="_blank">Click here to read directions provided by the MLS listing</a>', {
      prefix: 'impromptu',
      buttons: {"Close": false }
    });
  });

});


loadMap();
function loadMap(){
	$('#map').jmap('init', {mapCenter:[38.905, -121.061], mapZoom:9});
}

$('.results').hover(function(){
  var nid = this.id.split("_")[1];
  if($('#openhome_'+nid).is('.selected')){
    //$('#tab_'+mlsnum).attr('src', '/images/home_disable.gif');
  }else{
    $('#openhome_'+nid).css('background', disabled_hover_color);
    //$('#tab_'+mlsnum).attr('src', '/images/home_enable.gif');
  }
}, function() {
  var nid = this.id.split("_")[1];
  if($('#openhome_'+nid).is('.selected')){
    $('#openhome_'+nid).css('background', selected_color);
    //$('#tab_'+mlsnum).attr('src', '/images/home_enabled.gif');
  }else{
    $('#openhome_'+nid).css('background', plain_color);
    //$('#tab_'+mlsnum).attr('src', '/images/home_disabled.gif');
  }
});

$(".results").click(function() {
  var nid = this.id.split("_")[1];
  if(!$('#openhome_'+nid).is('.unmappable')){
    $('#openhome_'+nid).toggleClass("selected");
    toggle_marker(nid,$('#openhome_'+nid).is('.selected'));
  }
});


$("#route_container .day_container h2").click(function(){
  $("#route_container .day_container").each(function(){
    $(this).removeClass('day_selected');
  });
  $(this).parent().addClass('day_selected');
  check_change();
});

$('.remove_route').click(function(){
  var nid = $(this).attr('rel').split("_")[1];
  toggle_marker(nid,false);
});

$('.remove_route').hover(function(){$(this).attr('src',"/images/remove_route_hover.gif");},function(){$(this).attr('src',"/images/remove_route.gif");});


$('#filter_apply').click(function(){
  filter_group({
    range:$('#filter_range').val(),
    city:$('#filter_city').val(),
    zip:$('#filter_zip').val(),
    day:$('#filter_day').val()
  });
});

$('#filter_reset').click(function(){
  $('#filter_range').val('-1');
  $('#filter_city').val('');
  $('#filter_zip').val('');
  $('#filter_day').val('');
  filter_group({reset: true});
});

$('#open_route_map').click(function(){window.open(grab_route_url());});
$("#chk_use_start").change(function(){check_change();});
$("#start_addr").change(function(){check_change();});

function zeroPad(num,count){
  var numZeropad = num + '';
  while(numZeropad.length < count) {
    numZeropad = "0" + numZeropad;
  }
  return numZeropad;
}


function toggle_marker(nid,show){
  if (home_data[nid]) {
    if (show){
      var marker_id = transfer_marker(nid);
      
      //Oh no! Out of markers
      if (marker_id == -1){ return false; }
      
      $('#map').jmap('addMarker',
        {
          pointLatLng:[home_data[nid].lat, home_data[nid].lng],
          pointIcon: house_icon_letters[marker_id],
          pointHTML: home_data[nid].html,
          customID:nid
        },
        function(marker){
          home_data[nid].gmarker = marker;
        });
      
      //Ensures it has the correct class, if called elsewhere
      $('#openhome_'+nid).addClass('selected').attr('title',enabled_title).css('background', selected_color)
      .children('div').children('img.marker').attr('src','/images/icons/house-icon_'+zeroPad(marker_id+1,2)+'.gif');
      $('.route_'+nid).show("slow", function(){check_change();}).children('img.route_icon').attr('src',"/images/icons/house-icon_"+zeroPad(marker_id+1,2)+".gif");
    }else{
      if (home_data[nid].gmarker){
        $.jmap.GMap2.removeOverlay(home_data[nid].gmarker);
      }
      transfer_marker(nid);
      
      //Ensures it has the correct class, if called elsewhere
      $('#openhome_'+nid).removeClass('selected').attr('title',disabled_title).css('background', plain_color)
      .children('div').children('img.marker').attr('src','/images/icons/house-icon_00.gif');
      $('.route_'+nid).hide("slow", function(){check_change();});
    }
    return true;
  }
  return false;
}

/*HELPER function for removing or adding markers */
function transfer_marker(nid){
  var did_remove = false;
  var open_id = -1;
  
  for (i = 0; i < house_icon_letters.length; i++) { 
    if (house_icon_letters[i].nid == nid){
      house_icon_letters[i].nid = 0; 
      did_remove = true;
    }
    
    if (house_icon_letters[i].nid == 0 && open_id == -1){
      open_id = i;
    }
  }
  
  //TODO: if open_id is -1 at this point, then we're out of markers!
  
  //If we failed to remove, then we're adding
  if (!did_remove){
    house_icon_letters[open_id].nid = nid; 
    return open_id;
  }
}

check_change();


//Object Converter
function oc(a){
  var o = {};
  for(var i=0;i<a.length;i++){
    o[a[i]]='';
  }
  return o;
}  

function apply_filter_vis(arg){
  //Clear styles and add totals
  var res_total = $('.results').show().each(function(){this.style.border = '';}).length;
  var res_hidden = $('.results.filtered').hide().length;
  var res_sel_filter = $('.results.filtered.selected').show().css('border', '2px dashed red').length;
  
  if (!arg.reset){
    
    var msg='';
    
    if ((res_hidden-res_total)==0){//No results
      msg='No listings available ';
    }else{
      msg='Showing '+(res_total-res_hidden) +' out of '+res_total+' listings, ';
    }
      if (arg.city || arg.zip) msg+='in ';
      
      if (arg.city) msg+=' '+arg.city;
      
      if (!arg.city && arg.zip){
        msg+=' '+arg.zip;
      }else if (arg.city && arg.zip){
        msg+=' ('+arg.zip+')';
      }
      
      if (arg.day) msg+=' on '+arg.day;
      
      if (arg.range!=-1){
        if(arg.range==0){
          msg+=' (under $100k)';
        }else if (arg.range < 1000){
          msg+=' ($'+arg.range+'k-$'+(parseInt(arg.range) + 100)+'k)';
        }else{
          msg+=' (over $1mil)';
        }
      }

    msg+='<br/>';
    
    if (res_sel_filter)
      msg+='(with '+res_sel_filter+' selected but not matching) &mdash; ';
    
    msg+='<a id="filter_reset_link" title="Remove all filters from the list" href="#">Reset Listings</a>';
    
    $('#filter_desc').html(msg);
    $('#filter_reset_link').click(function(){filter_group({reset:true}); return false;});
  }else{
    $('#filter_desc').html('Showing '+res_total+' listings' );
  }
}

function filter_group(arg){
  $(sort_data).each(function(){
    //Default Clear
    var city_check = true;
    var price_check = true;
    var zip_check = true;
    var day_check = true;
    if (!arg.reset){
      
      if (arg.range == -1){ //All Prices
        price_check = true;
      }else if (arg.range==0){
        price_check = (this.price < 100000);
      }else if(arg.range < 1000){ //100k to 900k
        price_check = (this.price >= (arg.range*1000) && this.price <= ((parseInt(arg.range)+100)*1000));
        //console.log(this.mls + ' -- ' + this.price + ' -- ' + (arg.range*1000) + ' -- ' + (parseInt(arg.range)+100)*1000);
      }else{ //1 Mill
        price_check = (this.price > (arg.range*1000));
      }
      
      //Cities
      if (arg.city) city_check = (this.city==arg.city);
      
      //Zip Codes
      if (arg.zip) zip_check = (arg.zip == this.zip);
      
      //Day of the week
      if (arg.day) day_check = arg.day in oc(this.days);
      
    }
    
    //console.log('mls: ' + this.mls + ' P:' + price_check+' C:' + city_check+' Z:' + zip_check+' D:' + day_check+' Final:'+(price_check && city_check && zip_check && day_check));
    //Apply all filters using binary compare - if any fails, it won't show up
    if(price_check && city_check && zip_check && day_check){
      $('#openhome_'+this.nid).removeClass('filtered');
    }else{
      $('#openhome_'+this.nid).addClass('filtered');
    }

  });
  
  apply_filter_vis(arg);
}


function check_day_select(){
  //No day selected! Select the next visible day
  if (!$(".day_selected").length){
    $(".day_container:visible:first").addClass('day_selected');
    check_change();
  }
}

function check_change(){
  //Start Addr as end addr-----------------------------
  if($("#chk_use_start:checked").length){
    $("#route_end").css("opacity", 1);
    if ($.trim($("#start_addr").val())){
      $("#end_addr").html($.trim($("#start_addr").val()));
    }else{
      $("#end_addr").html('<em>[None Given]</em>');
    }
  }else{
    $("#route_end").css("opacity", .4);
    $("#end_addr").html("<em>[Using Last Home Address]</em>");
  }
  
  //Day Container visibility
  $(".day_container").each(function(){
    if($(this).children("ul").children("li:visible").length){
      if (!$(this).is(":visible")) $(this).show("slow",check_day_select);
    }else{
      if ($(this).is(":visible")) $(this).removeClass('day_selected').hide("slow",check_day_select);
    }
  });
  
  //Item Count
  if (!($("#route_container .day_selected .route_item:visible").length) || !($.trim($("#start_addr").val()))){
    //All out of items
    var msg="No Items To Map";
    
    if (!($.trim($("#start_addr").val()))) msg="No Starting Address";
          
    $("#open_route_map").attr("disabled", true).html(msg);
    
  }else{
    $("#open_route_map").attr("disabled", false).html("Map the route for "+$(".day_selected h2").text());
  }
  
  var hnum = $(".results.selected").length;
  if (!hnum) hnum="0";
  $("#home_count strong").html(hnum);
  
}

function grab_route_url(){
  var g = [];
  var i = 0;
  var s = "http://maps.google.com/maps?f=d&hl=en";
  
  $("#route_container .day_selected .route_item:visible span").each(function(){
    g.push(escape($(this).html()));
  });
  
  $(g).each(function(){
    i++;
    if (i==1){
      s+='&saddr='+escape($("#start_addr").val())+'&daddr='+g[i-1];
    }else{
      s+='+to:'+g[i-1];
      if(i==g.length && $("#chk_use_start:checked").length) s+='+to:'+escape($("#start_addr").val());
    }
  });
  
  return s;
} 

