// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


// All ajax requests will trigger the format.xml block
// of +respond_to do |format|+ declarations

function sfHover() {
  var sfEls = document.getElementById('main_menu1').getElementsByTagName("li");
  
  for (var i=0; i<sfEls.length; i++) {
    sfEls[i].onmouseover = function() {
      this.className += " sfhover";
    }

    sfEls[i].onmouseout = function() {
      this.className = this.className.replace(" sfhover", "");
    }
  }
}

if (window.attachEvent) window.attachEvent("onload", sfHover);


String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.endsWith = function (a) {
    return this.substr(this.length - a.length) === a;
}

String.prototype.startsWith = function (a) {
    return this.substr(0, a.length) === a;
}


jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

jQuery(document).ready(function() {
  mark1 = new Date();
  $("ul.sub_menu").bgIframe({left:30});
  
  mark2 = new Date();
  // Initialize history plugin.
  hash = location.href.replace(/^.*#/, '');
  hash = (hash.length > 0 ? hash : null);
	$.historyInit(pageload, hash);
	
	// Initialize ellipsis controls
	//$('.ellipsis').livequery(function() {
	//  $(this).ThreeDots({max_rows:2}) 
	//});
	
	propagateSessionId();
  
  mark3 = new Date();
  initializeAjaxLinks();
  mark4 = new Date();
  
  initSharePropertyButtons();
  mark5 = new Date();
  
  initPersonalizationBarButtons();
  mark6 = new Date();
    
  initPersonalizationBarFoatingPanels();
  mark7 = new Date();
  
  initFloatingPanels();
  mark8 = new Date();
    
  initTooltips();
  mark9 = new Date();
  
  //startAdRotator(2, null);
  //startAdRotator(3, null);
  
  openDialogBox();
  mark10 = new Date();
  
  initializeSubmitOnEnter();
  mark11 = new Date();
  
  stats = "Performance Stats\n";
  stats += "History Plugin              " + (mark3 - mark2) +" msec\n";
  stats += "AJAX Links                  " + (mark4 - mark3) +" msec\n";
  stats += "Share Property Buttons      " + (mark5 - mark4) +" msec\n";
  stats += "Personalization Bar Buttons " + (mark6 - mark5) +" msec\n";
  stats += "Personalization Bar Panels  " + (mark7 - mark6) +" msec\n";
  stats += "Floating Panels             " + (mark8 - mark7) +" msec\n";
  stats += "Tooltips                    " + (mark9 - mark8) +" msec\n";
  stats += "Dialogbox                   " + (mark10 - mark9) +" msec\n";
  stats += "Submit On Enter Events      " + (mark11 - mark10) +" msec\n";
  stats += "Total                       " + ((new Date()) - mark1) +" msec\n";
  
  //alert(stats);
});

function pageload(hash) {
  
	// alert("pageload: " + hash);
	// hash doesn't contain the first # character.
	if(hash) {
	  hash = hash.replace('3F', '?');
	  
		// restore ajax loaded state
		if($.browser.msie) {
			// jquery's $.load() function does't work when hash include special characters like aao.
			// hash = encodeURIComponent(hash);
		}

		$.get(hash, null, null, "script");
	} else {
	  if(location.href.match(/#.*/) == "#") {
	    location.href = location.href.replace(/#.*/, '');
    } else {
      location.reload();
    }
	}
}

//adding AJAX form submitting function
jQuery.fn.submitWithAjax = function() {
  
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

function startAdRotator(block_id, timer) {
  if (timer == null) {
    timer = $("#ad_block_"+block_id).find('.front_canvas').find('a:first').attr('duration') * 1000;
  }
  
  $("#ad_block_" +block_id+ ".rotate").everyTime(timer, function() { rotateAd(block_id) }, 0);
}

function rotateAd(block_id) {
  block = $("#ad_block_" +block_id);
  ads = block.find('.ads');
  current_ad = block.find('.front_canvas').find('a:first').attr('ad_id');
  
  if(ads.length > 0) {
    block.find('.back_canvas').html(block.find('.front_canvas').find('a'))

    block.find('.front_canvas').hide();
    block.find('.front_canvas').html(ads.find('a:first'));

    block.find('.front_canvas').fadeIn(2000, function() { ads.append(block.find('.back_canvas').find('a')) });

    stopAdRotator(block_id);
    startAdRotator(block_id);
  } else {
    $.get('ads.js?block='+block_id+"&current_ad="+current_ad, null, null, "script");
  }
}

function stopAdRotator(block) {
  $("#ad_block_" +block+ ".rotate").stopTime();
}

function initializeAjaxLinks() {
  // Unbind event bindings
  $("a.ab_test").unbind();
  
  // All A tags with class 'ajax_get', 'ajax_post', 'ajax_put' or 'ajax_delete' will perform an ajax call
  $('a.ajax_get').unbind();
  $('a.ajax_get').livequery('click', function() {
    var link = $(this);
    
    hash = link.attr('href');
    hash = hash.replace(/^.*#/, '');
    ga_tracker_url = hash;
    
    hash = hash.replace(/\?/, '3F');
    
		$.historyLoad(hash);
		
    pageTracker._trackPageview(link.attr(ga_tracker_url));
    return false;
  }).attr("rel", "nofollow");
  
  $('a.ajax_get_popup, a.ajax_get_without_history').unbind();
  $('a.ajax_get_popup, a.ajax_get_without_history').livequery('click', function() {
    var link = $(this);
    
    $.get(link.attr('href'), function(data) {
      if (link.attr('ajaxtarget'))
        $(link.attr('ajaxtarget')).html(data);
    }, null, "script");
    
    pageTracker._trackPageview(link.attr('href'));
    return false;
  }).attr("rel", "nofollow");


  $('input.use_photo_selection').livequery('click', function() {
    var form = $(this).parents('form:first');
    form.attr('action', 'upload_photo_use');
    var action_url = form.attr('action');
    form.attr('action', action_url);

    $.post(form.attr('action'), form.serialize(), null, 'script');
    
    if ($(this).is(":checked")) {
       $(this).value(1);
      }
     else
      {
       $(this).value(0);
      }
    return false;
  }).attr("rel", "nofollow");


  $("input[name='listing[primary]']").click(function() {

    if ($(this).is(":checked")) {
      value = 1;
       $(this).attr('primary', value);
    }
    else {
      value = 0 ;
       $(this).attr('primary', value);
    }

    var form = $(this).parents('form:first');
    form.attr('action', 'update');
    var action_url = form.attr('action');
    $("input[name='listing[primary]']:checked").val(value);
    $(this).attr('primary', value);
    form.attr('action', action_url);
    $.post(form.attr('action'), form.serialize(), null, 'script');
    $(this).value(value);
    return false;
 }).attr("rel", "nofollow");

  
  $('a.ajax_submit').unbind('click');
  $('a.ajax_submit').livequery('click', function() {
    var form = $(this).parents('form:first');
    var link = $(this);

  
    var linkUrl = link.attr('href')
    if(linkUrl.charAt(linkUrl.length - 1) != "#") {
      form.attr('action', link.attr('href'));
    }

    if(link.attr('value')) {
      var action_url = form.attr('action');
      if(action_url.indexOf('?') > 0) {
        action_url += "&";
      } else {
        action_url += "?";
      }
      action_url += link.attr('value');
      form.attr('action', action_url);
    }

    $.post(form.attr('action'), form.serialize(), null, 'script');
    return false;
  }).attr("rel", "nofollow");

  $('a.submit').unbind('click');
  $('a.submit').livequery('click', function() {
    var form = $(this).parents('form:first');
    var link = jQuery(this);

    var linkUrl = link.attr('href')
    if(linkUrl.charAt(linkUrl.length - 1) != "#") {
      form.attr('action', link.attr('href'));
    }

    if($(this).attr('value')) {
      var action_url = form.attr('action');
      if(action_url.indexOf('?') > 0) {
        action_url += "&";
      } else {
        action_url += "?";
      }
      action_url += $(this).attr('value');
      form.attr('action', action_url);
    }

    form.submit();
    return false;
  }).attr("rel", "nofollow");

  $('a.submit_dialog_box').unbind('click');
  $('a.submit_dialog_box').livequery('click', function() {
    var form = $('#dialog_box form');
    form.submit();
    return false;
  }).attr("rel", "nofollow");
  
  $('a.ajax_submit_dialog_box').unbind('click');
  $('a.ajax_submit_dialog_box').livequery('click', function() {
    var form = $('#dialog_box form');
    var link = $(this);

    var linkUrl = link.attr('href')
    if(linkUrl.charAt(linkUrl.length - 1) != "#") {
      form.attr('action', link.attr('href'));
    }

    if(link.attr('value')) {
      var action_url = form.attr('action');
      if(action_url.indexOf('?') > 0) {
        action_url += "&";
      } else {
        action_url += "?";
      }
      action_url += link.attr('value');
      form.attr('action', action_url);
    }
    
    $.post(form.attr('action'), form.serialize(), null, 'script');
    return false;
  }).attr("rel", "nofollow");
  
  $("form.ajax_submit").unbind('submit');
  $("form.ajax_submit").livequery('submit', function() { 
    var form = $(this);
    $.post(form.attr('action'), form.serialize(), null, 'script');
    return false;  
  });
  
  initABTestingLinks();

  //jQuery('a.ajax_get, a.ajax_post, a.ajax_put, a.ajax_delete').removeAttr('onclick');
/*  
  $('.pagination a').unbind();
  $('.pagination a').livequery('click', function() {
    hash = $(this).attr('href');
    hash = hash.replace(/^.*#/, '');
    hash = hash.replace(/\?/, '3F');
		$.historyLoad(hash);
		
    return false;
  }).attr("rel", "nofollow");
*/
}

var enterEvent;
function initializeSubmitOnEnter() {
  $('input.submit_on_enter, form.submit_on_enter input').livequery('keypress', function(e) {
    enterEvent = e;
    // If user clicked on an item in an autocomplete list, we need to allow for some time in order for that
    // value to be populated into the text field.
    setTimeout("submitFormOnEnter()", 200);
    
    // This prefents IE from beeping
    if(e.which == 13) {
      return false;
    }
  });
}

function submitFormOnEnter(e, action) {
  var keycode;
  
  if(!e) {
    e = enterEvent;
  }
  
  if (window.event)
    keycode = window.event.keyCode;
  else if (e)
    keycode = e.which;
  else
    return true;

  if (keycode == 13) {
    target = e.target || e.srcElement;
    
    if(action) {
      target.form.action = action;
    }

    var form = $(target.form);
    if(form.hasClass('ajax_submit')) {
      $.post(form.attr('action'), form.serialize(), null, 'script');
    } else {
      target.form.submit();
    }
    return false;
  }

  return true;
}

function initTooltips() {
  // Initialize tooltips
	$('a.tooltip, img.tooltip').tooltip({
	  showURL: false
	});
}

function openDialogBox() {
  var dialogBox = $('#dialog_box_wrapper #dialog_box');
  if(dialogBox.length > 0) {
    dialogBox.modal({
      minWidth: 100,
      onShow: function (d) {
        var popup_height = $('#simplemodal-container .dialog_box_panel').outerHeight();
        var window_height = $(window).height();
        if(popup_height >= window_height) {
          d.wrap.css('overflow','visible');
        
          dw = $('#simplemodal-container');
          dw.css('position','absolute');
          dw.css('top','0');
          
          $(window).scrollTop(0);
        }
      },
      onClose: function (dialog) {
				$.modal.close(); // must call this!
				$('#dialog_box_wrapper').html('');
      }
    });
  }
}

function closeDialogBox() {
  $.modal.close();
}

function displayVirtualTour(url) {
  if(!url.startsWith("http://")) {
    url = "http://" + url;
  }
 
  openPopupWindow(url, 'VirtualTour', 860, 600, 'location=no,menubar=no,titlebar=no,toolbar=no,scrollbars=yes');
  return false;
}

function openPopupWindow(url, title, width, height, options) {
  if(options == null) options = "scrollbars=yes";
  newWindow = window.open(url, title, 'height='+ height +',width=' + width + ',' + options);
  if (window.focus) { newWindow.focus() }
  return false;
}

function log(msg) {
  if (console != undefined && console != null) {
    console.log(msg);
  }
}

function replaceAllUrls(match, replacement, qualifier) {
  var re = new RegExp(match, 'g');
  
  if(qualifier == undefined) {
    qualifier = "a";
  }
  
  $(qualifier).each(function(index) {
    var href = $(this).attr('href');
    var match = re.exec(href);
    if(href) {
      var new_href = $(this).attr('href').replace(re, replacement);
      $(this).attr('href', $(this).attr('href').replace(re, replacement));
    }
  });
  
  $('form').each(function(index) {
    $(this).attr('action', $(this).attr('action').replace(re, replacement));
  });
}

function ajaxRedirect(uri) {
  var current_uri = window.location.pathname + window.location.search;
  current_uri = current_uri.replace(/^.*#/, '');
  current_uri = current_uri.replace(/\?/, '3F');
  
  //$.historyLoad(current_uri);
  window.location = uri;
}

function initABTestingLinks() {
  $("a.ab_test").livequery('click', function() {
    var conversion = $(this).attr('conversion');
    if (conversion) {
      var url = "http://" + window.location.host + "/ab_test_conversion/" + conversion;
      $.get(url);
    }
  });
}

function initSharePropertyButtons() {
  
  $('a.share_property').unbind();
  $('a.share_property').livequery('click', function() {
    var panel = $("#share_property_" + $(this).attr('listing') + " .floating_panel");
    
    if(panel.css('display') == 'none') {
      $(this).addClass('hover')
      panel.show();
    } else {
      $(this).removeClass('hover')
      panel.hide();
    }
    
    return false;
  }).attr("rel", "nofollow");
  
  $('a.share_property').livequery('hover',
    function() {
      $(this).addClass('hover');
    },
    function() {
      var panel = $("#share_property_" + $(this).attr('listing') + " .floating_panel");
      if(panel.css('display') == 'none') {
        $(this).removeClass('hover')
      }
    }
  );
  
  initABTestingLinks();
  
  initSharePropertyPanels();
}

function initSharePropertyPanels() {
  $('div.share_property_wrapper').hoverIntent(
    {
      sensitivity: 1,
      interval: 200,
      over: function() {},
      timeout: 500,
      out: function() {
        $("#share_property_" + $(this).attr('listing') + " a:first-child").removeClass('hover');
        $("#share_property_" + $(this).attr('listing') + " .floating_panel").hide();
      }
    }
  );
}

function initFloatingPanels() {  
  $('a.floating_panel_close_button').unbind();
  $('a.floating_panel_close_button').livequery('click', function() {
    $(this).parents('.floating_panel').hide();
    return false;
  }).attr("rel", "nofollow");
}

function initPersonalizationBarButtons() {
  $('a.floating_panel_link').unbind();
  $('a.floating_panel_link').livequery('click', function() {
    var panel = $(this).parent().find('.floating_panel');
    if(panel.css('display') == 'none') {
      $(this).parent().find('.floating_panel h1 span').each(function() {
        $(this).html('');
      });
      
      $(this).parent().find('.floating_panel .list').each(function() {
        $(this).html('');
        $(this).addClass('loading');
      });
      
      $(this).parent().find('.floating_panel').show();
      
      var link = $(this);

      $.get(link.attr('href'), function(data) {
        if (link.attr('ajaxtarget'))
          $(link.attr('ajaxtarget')).html(data);
      }, null, "script");
      
    } else {
      $(this).parent().find('.floating_panel').hide();
    }
    
    return false;
  }).attr("rel", "nofollow");
}

function initPersonalizationBarFoatingPanels() {
  $('#personalization_bar div.my_searches, #personalization_bar div.my_properties').hoverIntent(
    {
      sensitivity: 1,
      interval: 200,
      over: function() {},
      timeout: 500,
      out: function() {
        $(this).find('.floating_panel').hide();
      }
    }
  );
}

function refreshMyPropertiesPanel(action) {
  
  my_properties_panel = $('#personalization_bar .my_properties_panel .floating_panel')
  if(my_properties_panel.length < 1 || my_properties_panel.css('display') != 'block') {
    return;
  }
  
  var saved_xpos = $('#personalization_bar .saved_properties .list').scrollTop();
  var recent_xpos = $('#personalization_bar .recent_properties .list').scrollTop();
  
  if(action == 'save') { saved_xpos = 0; }
  if(action == 'view_listing') { recent_xpos = 0; }
  
  var link = $('#personalization_bar .my_properties .floating_panel_link')
  $.get(link.attr('href') + "?saved_xpos="+saved_xpos+"&recent_xpos="+recent_xpos+"&original_action="+action, function(data) {
    if (link.attr('ajaxtarget'))
      $(link.attr('ajaxtarget')).html(data);
  }, null, "script");
}

function clearErrorFields() {
  $('.form_row_compact.error, .form_row_expanded.error').each(function(index) {
      $(this).removeClass('error');
  });
}

function tagErrorField(fieldId, css_selector) {
  if (css_selector == null){
    css_selector = "";
  }
  
  $(css_selector + ' #'+fieldId).parent('div').addClass('error');
}

function propagateSessionId() {
  sessionId = getUrlVars()['_sid'];
  
  if(!sessionId) {
    return;
  }
  
  $('a').each(function(){
    var link = $(this);
    var href = link.attr('href');
    if(href && !href.match(/^http\:\/\//) && !href.match(/\_sid/) && !href.match(/^\#/) && !href.match(/^javascript/)) {
      
      if(!href.match(/\?/)) {
        href += "?";
      } else {
        href += "&";
      }
      
      href += "_sid=" + sessionId;  
    }
    
    link.attr('href', href);
  });
}

function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}

$(document).ready(function() {
  $('select.change_sort_order').livequery('change', function() {
    var form = $(this).parents('form:first');
    form.submit();
    return false;
 }).attr("rel", "nofollow");
});