var base = 'www.xorax.info/blog/(?:[a-z]{2,4}/)?';
var linkReg = new RegExp(base.replace(/\//g,'\\/') + '(?!feed|wp-)');
var fileReg = new RegExp(base.replace(/\//g,'\\/') + 'wp-content/', 'i');

$(document).ready(function(){
  $('#register a').click(function() {
    if (pageTracker) pageTracker._trackEvent('click', 'blog-register');
    return true;
  });

  $('a').click(addajax);
  
  $('a.track-click').mousedown(function() {
	  if (pageTracker) pageTracker._trackEvent('click', 'track-click', url.path);
	  return true;
  });
  
  setTimeout(function(){
    replaceHash(parseUri(document.location).anchor);
    $.xstory.init(function(h){
      getContent(h);
    });
  }, 200);
});

var loadingContent = function(show, scrollTo, force){
  var content = $('#content');
  
  if(content.length > 1) content = content[content.length-1];
  
  if(!show){
    content.animate({opacity: 0.1},{duration: 500});
    $('#loadingIcon').fadeIn();
  } else {
    content.animate({opacity: 1},{duration: 500});
    $('#loadingIcon').fadeOut();
  }
  
  // scrollTo => scroll to content
  // $(scrollTo) not found => scroll to content
  // $(crollTo) found => to to it!
  if (scrollTo === true || $(scrollTo).length) {
    $('html,body').each(function(){
      if(force || scrollTo || this.scrollTop > content.offset().top){
        $(this).animate({ scrollTop: $(scrollTo || content).offset().top }, 1000);
        return false;
      }
    });
  }
};

var replaceHash =  function(h){ /* path#anchor */
  /*
  var loc = (h+'').match(/^([^#]+)?(?:#(.*))?$/);
  document.location.hash = '#'+(loc[1] || '')+'#'+(loc[2] || '');
  if (loc[1]) {
    getContent(h);
  }
  /*/
  var loc = (h+'').match(/^([^#]+)?(#.*)?$/);
  if (loc[1] && !loc[2]) { // cas #anchor (externe)
    document.location.hash = '##'+loc[1];
    loadingContent(true, '#'+loc[1], true);
  } else if (!loc[1] && loc[2]) { // cas ##anchor
    document.location.hash = '#'+loc[2];
    loadingContent(true, loc[2], true);
  } else if (!loc[1] && !loc[2]) { // cas vide
    document.location.hash = '##';
  } else if (loc[1] && loc[2]) { // cas #path#anchor
    document.location.hash = '#'+loc[1]+loc[2];
    getContent(h);
  }
  /**/
};

var getContent = function(url){ // path#anchor
  $.ajax({
    type: 'get',
    url: url.replace(/#.*$/,''),
    dataType: 'text',
    data: 'ajax=1',
    success: function (txt){
      txt = txt.replace(/<script[^>]*>(?:.|\s)*?<\s*\/script\s*>/mgi, "");
      //$('#content').replaceWith(txt);
      //txt = txt.replace(/^\s*<div[^>]+id\s*=\s*"content"[^>]+>|<\/div>\s*$/i, "");
      txt = txt.match(/^\s*<div([^>]+id\s*=\s*"content"[^>]+)>((?:.|\s)*)<\/div>\s*$/i);
      try{
        $('#content').html(txt[2]);
        txt = txt[1].match(/class="([^"]+)"/i);
        if(txt[1]) $('#content')[0].className = txt[1];
        
        if (txt = $('#content .titleAjax')) {
          document.title = txt.text();
        }
        txt = null;
        loadingContent(true, url.replace(/^[^#]*(#[^#]+)?$/,'$1'));
        $('#content a').click(addajax);
        if (pageTracker) pageTracker._trackPageview(url.replace(/^[hftps]+:\/\/[^\/]+/i,''));
      } catch(e) {
        if(!$('#lastError')) $('body').append('<div id="lastError" style="display:none"></div>');
        $('#lastError').html("une erreur s'est produite.\nVoulez vous quand meme acceder a la page ?\n\nerror: "+e);
        //if(confirm(e+'')) {
        if(confirm($('#lastError').html())) {
          document.location = url;
        } else {
          loadingContent(true);
        }
      }
    },
    error: function(s, xml,status,e){
      //document.location = url;
    },
    beforeSend: function(){
      loadingContent(false);
    }
  });
  return false;
};

var addajax = function(){
  if(!this.href || (this.href+'').match(/^javascript/)) return true;
  var url = parseUri(this.href);
  try{
    if( (url.host+url.path).match(linkReg) ){
      $.xstory.load($X.Url.A2R(parseUri(document.location).path, url.path, true) + '#'+url.anchor);
      //$.xstory.load(url.path+'#'+url.anchor);
      return false;
    } else if (pageTracker && (url.host+url.path).match(fileReg)) {
      if ((url.path+'').match(/\\.(?:jpg|jpeg|gif|png)$/i)) {
        pageTracker._trackEvent('download', 'blog-image', url.path);
      } else {
        pageTracker._trackEvent('download', 'blog-file', url.path);
      }
      return true;
    }
  } catch(e){
    /*alert(e);return false;*/
  };
  return true;
};

/* urlA2R 1.0 : translate your absolute URL to relative
 * Copyright (c) 2007 Martin Panel <http://xorax.info>
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

if (!$X) var $X = {};

$X.Url = {
  /**
   * configuration variable, if all of your absolute url is only path part of url
   */
  isPath: true,
  
  _separePathRegex: new RegExp('([^:]+)://([^/]+)/?'),
  _separePath : function (url) {
    var match = (url+'').exec(this._separeRegex);
    
    if (!match) return url;
    return {path: match[2], rest: match[1]};
  },
  
	/**
	 * transform your target absolute url to relative url from base url.
	 * 
	 * @param string base absolute url, your start point
	 * @param string target absolute url, your end point
	 * @param bool skipSameDir skip current dir identifier (./) if exist
	 * @return string relative url from base to target
	 */
  A2R : function (base, target, skipSameDir) {
	  var sbase = base.split(/\//),
	    starget = target.split(/\//),
	    diffStart = 0, i;
	  
	  for (i=0; i < starget.length; i++)
	    if (sbase[i] == starget[i]) diffStart++; else break;
	  
	  var res = [];
	  for (i = diffStart; i < sbase.length; i++)
	    res[res.length] = '..';
	  
	  if (res.length == 1 && skipSameDir && diffStart >= starget.length) res[0] = '.';
	  else res.shift();
	  
	  for (i = diffStart;i < starget.length; i++)
	    res[res.length] = starget[i];
	
	  return res.length == 1 ? res[0]+'/' : res.join('/');
	},

	/**
	 * transform your target relative url to absolute url from base url.
	 *
	 * @param string base absolute url, your start point
	 * @param string target relative url, your end point
	 * @param bool skipMultiSlash replace multi-slash (//) to single slash
	 * @return string absolute url to target
	 */
	R2A : function (base, target, skipMultiSlash) {
	  var sbase = base.split(/\//),
	    starget = target.split(/\//),
	    p;
	  if(starget[0]=='') return target;
	  sbase.pop();
	  while(null != (p = starget[0])){
	    if(p == '..') sbase.pop();
	    else if(p != '.') sbase.push(p);
	    starget.shift();
	  }
	  base = sbase.join('/');
	  return skipMultiSlash ? base.replace(/\/+/g,'/') : base;
	}
};


/* parseUri 1.2; MIT License
By Steven Levithan <http://stevenlevithan.com> */
// http://stevenlevithan.com/demo/parseuri/js/

var parseUri = function (source) {
  var o = parseUri.options,
    value = o.parser[o.strictMode ? "strict" : "loose"].exec(source);
  
  for (var i = 0, uri = {}; i < 14; i++) {
    uri[o.key[i]] = value[i] || "";
  }
  
  uri[o.q.name] = {};
  uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
    if ($1) uri[o.q.name][$1] = $2;
  });
  
  return uri;
};

parseUri.options = {
  strictMode: false,
  key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  q: {
    name: "queryKey",
    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
    loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};