(function($){

var ns = 'Site';

window[ns] = function ( title ) {
  this.title = title;
  this.completeContent = {
    archive: false,
    navigator: false
  };
  
  this.body = $('body');
//  this.body.removeClass('no-js');
  if ( appleDevice() ) {
    this.body.addClass('apple-device');
  }
};

window[ns].prototype = {
  
  set: function ( page, slug, category, title ) {
    this.page = page;
    this.slug = slug || "";
    this.category = category || "";
    
    var url = '#/';
    var pagename = "";
    if ( page == 'category' || page == 'page' ) {
      url += slug + '/';
      pagename = category || "";
    } else if ( page == 'project' ) {
      url += category + '/' + slug + '/';
      pagename = title || "";
    }
    
    if ( page == 'project' ) {
      this.noFill();
    } else {
      this.fill();
    }
    
    window.location.href = url;
    document.title = this.page == 'home' ? this.title : pagename + " - " + this.title;
  },
  
  fill: function () {
    $('#filler').addClass('fill');
  },
  
  noFill: function () {
    $('#filler').removeClass('fill');
  },
  
  loadComplete: function ( string ) {
    this.completeContent[string] = true;
    
    for ( key in this.completeContent ) {
      if ( ! this.completeContent[key] ) return;
    }
    
    /* all complete */
    this.completeCallback();
  },
  
  complete: function ( callback ) {
    this.completeCallback = callback || $.noop;
  },
  
  redirect: function ( base ) {
    var path = window.location.href.split('#')[0];
    var query = "";
    
    if ( (new RegExp(base)).test( path ) ) {
      query = path.replace( base, "" );
      if ( query != "" ) {
        window.location.href = base + "#/" + query;
      }
    }
  },

  analyze: function () {
    var url = window.location.href;
    var para = url.split('#');
    
    if ( para.length >= 2 ) {
      para = para[1];
    } else {
      // home
      para = "";
    }
    
    
    // level 1 : page
    var match = para.match(/^\/(about|contact)\/?$/);
    if ( match && match[1] ) {
      var id = getPageID( match[1] );
      this.set('page', match[1], getPageTitle( id ) );
      return;
    }
    
    // level 1' :  category
    var match = para.match(/^\/([\w\d-]+)\/?$/);
    if ( match && match[1] ) {
      var id = getCatID( match[1] );
      if ( id ) {
        this.set('category', match[1], getCategoryTitle( id ) );
        return;
      }
    }
    
    // level 2 : project
    var match = para.match(/^\/([\w-]+)\/([\w\d-]+)\/?$/);
    if ( match && match[1] && match[2] ) {
      var id = getProjectID( match[2] );
      if ( id ) {
        this.set('project', match[2], match[1], getProjectTitle( id ) );
        return;
      }
    }
    
    // nothing found : home
    this.set('home');
    
  }
}

})(jQuery);
