
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());

// place any jQuery/helper plugins in here, instead of separate, slower script files.

$(document).ready(function() {
	
	var BGImageArray = ["bg.jpg","bg2.jpg"];
	var BGImage = BGImageArray[Math.floor(Math.random()*BGImageArray.length)]

	$("body").ezBgResize({
		img     : "/img/" + BGImage, // Relative path example.  You could also use an absolute url (http://...).
		opacity : 1, // Opacity. 1 = 100%.  This is optional.
		center  : true // Boolean (true or false). This is optional. Default is true.
	});
	
	$('#slidepisos').cycle({ 
	    fx:     	'fade', 
	    speed:       200, 
    	timeout:     0,
    	next:   	'#next',
        prev:   	'#prev',
    	pager:      '#nav', 
    	pagerEvent: 'mouseover',  
	    pagerAnchorBuilder: function(idx, slide) { 
	        // return selector string for existing anchor 
	        return '#nav li:eq(' + idx + ') a'; 
	    } 
	});
	
	$('.detalles_imagen').hover(
        function() { $('#controls').fadeIn(); },
        function() { $('#controls').fadeOut(); }
    );
	
	$(".fancybox").fancybox({
		fixed      : true,
		beforeClose: function() { $('#contact').each(function() { this.reset(); }); }
	});
	
	// Cerramos la ventana de la pagina pisos.php
	$('.close').click(function() {
	  $('.filtros').fadeOut("slow");
	});
	
	//Borrar texto de formularios
	$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
	
	//Placeholder en dos colores
	$.fn.placeholder = function(options) {
    return this.each(function() {
      if ( !("placeholder"  in document.createElement(this.tagName.toLowerCase()))) {
        var $this = $(this);
        var placeholder = $this.attr('placeholder');
        $this.val(placeholder).data('color', $this.css('color')).css('color', '#aaa');
        $this
          .focus(function(){ if ($.trim($this.val())===placeholder){ $this.val('').css('color', $this.data('color'))} })
          .blur(function(){ if (!$.trim($this.val())){ $this.val(placeholder).data('color', $this.css('color')).css('color', '#aaa'); } });
      }
    });
  };
  
  //Validation Form
  /**
   * Form Validators
   */
  // Regular Expression to test whether the value is valid
  $.tools.validator.fn("[type=time]", "Please supply a valid time", function (input, value) {
      return(/^\d\d:\d\d$/).test(value);
  });

  $.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function (input) {
      var name = input.attr("data-equals"),
      field = this.getInputs().filter("[name=" + name + "]");
      return input.val() === field.val() ? true : [name];
  });

  $.tools.validator.fn("[minlength]", function (input, value) {
      var min = input.attr("minlength");

      return value.length >= min ? true : {
          en : "Please provide at least " + min + " character" + (min > 1 ? "s" : "")
      };
  });

  $.tools.validator.localizeFn("[type=time]", {
      en : 'Please supply a valid time'
  });
	
	//Error Form
  var target = "#main";

  $('input[placeholder]', target).placeholder();

  $("input[type=date]", target).dateinput();

  $("input:checkbox,input:radio,select,input:file", target).uniform();
    
	/**
	 * setup the validators
	 */
	$(".has-validation", target).validator({
	    position : 'bottom left',
	    offset : [5, 0],
	    messageClass : 'form-error',
	    message : '<div><em/></div>'// em element is the arrow
	}).submit(function(e)  { 
   
   	// when data is valid 
  	if (!e.isDefaultPrevented()) {
	      
	      // tell user that everything is OK
	      $.ajax({
					type: 'POST',
					url: $(this).attr('action'),
					data: $(this).serialize(),
					// Mostramos un mensaje con la respuesta de PHP
					success: function(data) {
				  	$('#result').html(data);
				  	$('html, body').animate({ scrollTop: 0 }, 0);
				  	$('#contact').fadeOut('Slow');
				  	$('#gracias').fadeIn();
					}
				})      
				return false;

	      
	      // prevent the form data being submitted to the server
	      e.preventDefault();
	   } 
	   
	});

	//Error Form
  var target2 = "#inline1";

  $('input[placeholder]', target2).placeholder();

  $("input[type=date]", target2).dateinput();

  $("input:checkbox,input:radio,select,input:file", target2).uniform();
    
	/**
	 * setup the validators
	 */
	$(".has-validation", target2).validator({
	    position : 'bottom left',
	    offset : [5, 0],
	    messageClass : 'form-error',
	    message : '<div><em/></div>'// em element is the arrow
	}).submit(function(e)  { 
   
   	// when data is valid 
  	if (!e.isDefaultPrevented()) {
	      
	      // tell user that everything is OK
	      $.ajax({
					type: 'POST',
					url: $(this).attr('action'),
					data: $(this).serialize(),
					// Mostramos un mensaje con la respuesta de PHP
					success: function(data) {
				  	$('#result').html(data);
				  	$('html, body').animate({ scrollTop: 0 }, 0);
				  	$('#contact').fadeOut('Slow');
				  	$('#gracias').fadeIn();
					}
				})      
				return false;

	      
	      // prevent the form data being submitted to the server
	      e.preventDefault();
	   } 
	   
	});
	
	//form submit ajax
	$('#contact').ajaxStart(function() {
		$('#loader').show();
	}).ajaxStop(function() {
		$('#loader').hide();
		$('.info').fadeIn('slow');
	});
  // Interceptamos el evento submit

});
