

jQuery.fn.reset = function () {
  $(this).each (function() { this.reset(); });
}

var settings = {
  ajax : PHPMate.URL + 'themes/' + PHPMate.THEME + '/html/ajax/gateway.php'
}

var Waxoyl = {

  init : function(){

    this.background();
    this.pageLoaded();
  },

  setLinks : function(){
    $('a').click(function(){
      var page = Waxoyl.getPage($(this).attr('href'));
      Waxoyl.loadPage(page, '#content');
      return false;
    });
  },

  /**
   * Set background for page size
   */
  background : function(){
    var bodyWidth = $(document.body).outerWidth(true);
    $.get(settings.ajax,
      {
        "mod"   : "image",
        "width" : bodyWidth,
        "file"  : "themes/"+PHPMate.THEME+"/html/images/background.jpg"
      },
     function(data){
       //console.info(data);
       if(typeof data){
         if(typeof data.image){
           $(document.body).css('background-image', 'url('+PHPMate.URL + data.image+')');
           //console.info(PHPMate.URL + data.image);
         }
       }
     }, "json");
  },

  page : 'index',
  
  getPage : function(url){
    var uri = url.split('/');
    return uri[uri.length-1].split('.')[0];
  },

  loadPage : function(page, container){
    container = container || "#content";
    if(!$(container) || this.page == page) return;
    this.loading();
    this.page = page;
    $(container).slideUp('slow', function(){Waxoyl.__loadPage(page, container)});
  },

  __loadPage : function(page, container){
    $(container).empty();
    $.get('index.php', {'page':page, 'content_only':1},
      function(data){
        $(container).html(data);
        Waxoyl.pageLoaded();
        $(container).slideDown('slow', function(){
          Waxoyl.loading(1);
        })
    });
  },

  boxRounded : function(){
   $('.box-rounded-background').css('opacity', .7);
  },

  pageLoaded : function(){
    this.setLinks();
    this.boxRounded();
    this.pageAnim();
  },

  pageAnim : function(){
    // Set initial animations

   switch(this.page){
     case 'index':
       $('.big-box, .home-boxes .grid_4').fadeOut(0);
       $('.big-box').fadeIn('slow', function(){
        $('.home-boxes .grid_4:has(a.box-1)').fadeIn('slow', function(){
         $('.home-boxes .grid_4:has(a.box-2)').fadeIn('slow', function(){
           $('.home-boxes .grid_4:has(a.box-3)').fadeIn('slow', function(){
             $('.home-boxes .grid_4:has(a.box-4)').fadeIn('slow');
           });
         });
        });
       });
       break;

       case 'contacto':
         this.sendForm();
         break;
    }
  },

  loading : function(hide){
    var el = $('.waxoyl-overlay');
    
    if(!el.length){
      $(document.body).append('<div class="waxoyl-overlay"></div>');
      el = $('.waxoyl-overlay');
      el.css({
        'width'  : $(document).width(),
        'height' : $(document).height(),
        'z-index': 10000,
        'opacity': 0.7
      });
    }

    if(hide === 1){
      el.hide();
      return;
    }

    el.show();

  },

  sendForm : function(){
    var form = $('.contact form:first')[0];
    $(form).submit(function(){
      // Search for required items
      var requireds = $(this).contents().find('*[rel=required]');
      $(requireds).removeClass('error-required');

      // Reset errors array
      var errors = [];
      // If requireds items, add error message and error class
      if(requireds.length){
        requireds.each(function(i, e){
          if(!$(e).val()){
            $(e).addClass('error-required');
            var label = $(e).parents('label:first');
            errors.push($(label).text().replace(/\s+/g, " ") + ' es requerido');
          }
        });
      }

      if(errors.length){
        var div = '<div class="status-critical">';
        $(errors).each(function(i, error){div += '<div>'+error+'</div>';})
        div += '</div>';
        $.modal(div);
        return false;
      }
      else{
        $.post(settings.ajax, $(form).serialize(), function(data){
          try{
            result = jQuery.parseJSON( data );
          }
          catch(e){
            // We report an error, and show the erronous JSON string (we replace all " by ', to prevent another error)
            result = jQuery.parseJSON( '{"sent":"error","content":"' + e.replace(/"/g, "'") + '"}' );
          }
          var str = (result.sent == 'error') ? result.content : 'Muchas gracias<br/>Su mensaje ha sido enviado satisfactoriamente.<br />Le responderemos a la brevedad.';
          $.modal(str);
          $(form).reset();
        });
      }
      
      return false;
    })
  }

}

$(document).ready(function(){
  
  // Made background
  Waxoyl.init();

});

