var Validations = {
  initialize: function(messages){
    var validators = {};
    function addValidator(el, opts){
      opts = opts || {};
      validators[el.id] = validators[el.id] || new LiveValidation(el, opts);
      return validators[el.id];
    }
    $$('.LV-date-range').each(function(el){
      var startDate = el.select('.date').first();
      var endDate = el.select('.date').last();
      addValidator(startDate, {onlyOnSubmit: true, insertAfterWhatNode: startDate.next()});
      addValidator(endDate, {onlyOnSubmit: true, insertAfterWhatNode: endDate.next()}).add(Validate.Custom, {
        failureMessage: messages.dateRange,
        against: function(value, args){ 
          return (new Date($F(startDate.previous())) < new Date($F(endDate.previous())));
        }});
    });
    $$('.LV-num-range').each(function(el){
      var start = el.select('input').first();
      var end = el.select('input').last();
      addValidator(end, {onlyOnSubmit: true}).add(Validate.Custom, {
        failureMessage: messages.numRange,
        against: function(value, args){
          var $start = parseInt($F(start)), $end = parseInt($F(end));
          if(!isNaN($start) && !isNaN($end)){
            return $start < $end;
          }
          return true;
        }});
    });
        
    $$('.LV-numericality').each(function(el){
      addValidator(el, {onlyOnSubmit: true}).add(Validate.Numericality, 
      { minimum: 1, tooLowMessage: messages.numericality,  notANumberMessage: messages.numericality});
    });
    $$('.LV-presence').each(function(el){
      addValidator(el, {onlyOnSubmit: true}).add( Validate.Presence, {failureMessage: messages.presence} );
    });
  }
}

var Search = {
  switchType: function(type){
    $('search_listing_type').value = type;
	  fields_to_hide = ['sale', 'rental', 'temporary_rental'].without(type);
		fields_to_hide.each(function(current_field) {
		  $$('.mg-field-' + current_field).each(function (item) {
        item.down('input').disable();
			  item.hide();
			});
		})						  
		$$('.mg-field-' + type).each(function (item) {
		  item.show();
      item.down('input').enable();
		});    
  }
};

var Slideshow = Class.create({
  initialize: function(id, opts){  
    this.options = Object.extend({
			xmlUrl : null,
      swfObj: '/swf/flash_image_viewer_2.swf'
		}, opts || {});
    var color = this.parseColor($(id).getStyle('background-color')) || 'ffffff';
		var xml = color ? (this.options.xmlUrl+'?config[slideshowBackgroundColor]='+color) : this.options.xmlUrl;
    var so = new SWFObject(this.options.swfObj, 'slideshow', '100%', '100%', '7', '#'+color);
    
	  so.addParam("wmode", "transparent");
    so.addParam("allowFullScreen", "true");
	  so.addVariable("showVersionInfo", "false");
    so.addVariable("showRegistration", "false");
	  so.addVariable("showLogo", "false");
	  so.addVariable("dataFile", xml);
	  so.write(id);
  },  
	parseColor: function(color){
		var match = color.match(/rgb.([0-9]*?),.*?([0-9]*?),.*?([0-9].*?)\)/); //match rgb line
		if(match){
			return match.slice(1).collect(function(item){
				return parseInt(item).toColorPart()
			}).join('');
		}else if(color.substr(0,1) == '#'){
			if(color.length == 4){
				var c1 = color.substr(1,1),
				    c2 = color.substr(2,1),
						c3 = color.substr(3,1);
				return c1+c1+c2+c2+c3+c3;
			}else{
				return color.substr(1);
			}
		}
	}
});

// Initialize slideshows
Event.observe(window, 'load', function() {
  var baseUrl = '/agent/property_image/album/'
  var regex = /prop-(\d+)/;
  var counter = 1;
  var initializer = function(container, propId){
    var id = 'pslide' + counter;
    counter++;
    container.id = id;
    new Slideshow(id, {xmlUrl: baseUrl + propId });
    $(id).addClassName('loaded');
  };
  $$('.pslide').each(function(container){
    var propClass = container.classNames().find(function(name){return regex.match(name)});
    if(propClass && !container.hasClassName('loaded')){
      var propId = propClass.match(regex)[1];
      if(propId) initializer(container, propId);
    }
  });
});