// * date 2011/10/19 *

/**
* misc
*/

// ------ TRACE ------
function trace(s,o){if(window.console && window.console.debug){arguments.length === 2 ? window.console.debug(s,o) : window.console.debug(s);}}

// ------ TIMEOUT
function Timeout(fn, interval) {
    var id = setTimeout(fn, interval);
    this.cleared = false;
    this.clear = function () {
        this.cleared = true;
        clearTimeout(id);
    };
}

// ------ HEXTORGB convert hex to rgb color ------
function HexToRGB(h){
	if(h.charAt(0)=="#"){
		var coul = h.substring(1,7);
		var r = parseInt(coul.substring(0,2),16);
		var g = parseInt(coul.substring(2,4),16);
		var b = parseInt(coul.substring(4,6),16);
		return 'rgb('+r+', '+g+', '+b+')';
	}else{
		return null;	
	}
}



// ------ PAIR check if number is pair of impair ------
function pair(n){return typeof n=='number'?(n%2==0?true:false):null;}



// ------ RANDOM ------
function random(n1,n2){
	return arguments.length === 1 && typeof n1 === 'number'? Math.random()*n1 : ( arguments.length === 2 && typeof n1 === typeof n2 && typeof n1 === 'number' ? n1 + Math.random()*(n2-n1) : NaN );
}


// ------ ROUNDED ------
function round(n,granularity){
	if(arguments.length == 1){
		n = Math.round(n);
	}else{
		granularity = granularity.toString();
		granularity = granularity.replace(/./gi, 0);
		granularity = granularity.replace(/^./gi, 1);
		granularity = parseInt(granularity);
		n = Math.round(n*granularity)/granularity;
	}
	return n;
}



// ------ FLOOR ------
function floor(n,granularity){
	if(arguments.length == 1){
		n = Math.floor(n);
	}else{
		granularity = granularity.toString();
		granularity = granularity.replace(/./gi, 0);
		granularity = granularity.replace(/^./gi, 1);
		granularity = parseInt(granularity);
		n = Math.floor(n*granularity)/granularity;
	}
	return n;
}



// ------ CEIL ------
function ceil(n,granularity){
	if(arguments.length == 1){
		n = Math.ceil(n);
	}else{
		granularity = granularity.toString();
		granularity = granularity.replace(/./gi, 0);
		granularity = granularity.replace(/^./gi, 1);
		granularity = parseInt(granularity);
		n = Math.ceil(n*granularity)/granularity;
	}
	return n;
}


/**
* String
*/

// ------ TRIM remove multiple, leading or trailing spaces ------
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/gi,"").replace(/[ ]{2,}/gi," ").replace(/\n /,"\n");
}

// ------ remove all accents, for sort() by example ------
var Latinise={};Latinise.latin_map={"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A","Ẳ":"A","Ẵ":"A","Ǎ":"A","Â":"A","Ấ":"A","Ậ":"A","Ầ":"A","Ẩ":"A","Ẫ":"A","Ä":"A","Ǟ":"A","Ȧ":"A","Ǡ":"A","Ạ":"A","Ȁ":"A","À":"A","Ả":"A","Ȃ":"A","Ā":"A","Ą":"A","Å":"A","Ǻ":"A","Ḁ":"A","Ⱥ":"A","Ã":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ḃ":"B","Ḅ":"B","Ɓ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ć":"C","Č":"C","Ç":"C","Ḉ":"C","Ĉ":"C","Ċ":"C","Ƈ":"C","Ȼ":"C","Ď":"D","Ḑ":"D","Ḓ":"D","Ḋ":"D","Ḍ":"D","Ɗ":"D","Ḏ":"D","ǲ":"D","ǅ":"D","Đ":"D","Ƌ":"D","Ǳ":"DZ","Ǆ":"DZ","É":"E","Ĕ":"E","Ě":"E","Ȩ":"E","Ḝ":"E","Ê":"E","Ế":"E","Ệ":"E","Ề":"E","Ể":"E","Ễ":"E","Ḙ":"E","Ë":"E","Ė":"E","Ẹ":"E","Ȅ":"E","È":"E","Ẻ":"E","Ȇ":"E","Ē":"E","Ḗ":"E","Ḕ":"E","Ę":"E","Ɇ":"E","Ẽ":"E","Ḛ":"E","Ꝫ":"ET","Ḟ":"F","Ƒ":"F","Ǵ":"G","Ğ":"G","Ǧ":"G","Ģ":"G","Ĝ":"G","Ġ":"G","Ɠ":"G","Ḡ":"G","Ǥ":"G","Ḫ":"H","Ȟ":"H","Ḩ":"H","Ĥ":"H","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ᴁ":"AE","ʙ":"B","ᴃ":"B","ᴄ":"C","ᴅ":"D","ᴇ":"E","ꜰ":"F","ɢ":"G","ʛ":"G","ʜ":"H","ɪ":"I","ʁ":"R","ᴊ":"J","ᴋ":"K","ʟ":"L","ᴌ":"L","ᴍ":"M","ɴ":"N","ᴏ":"O","ɶ":"OE","ᴐ":"O","ᴕ":"OU","ᴘ":"P","ʀ":"R","ᴎ":"N","ᴙ":"R","ꜱ":"S","ᴛ":"T","ⱻ":"E","ᴚ":"R","ᴜ":"U","ᴠ":"V","ᴡ":"W","ʏ":"Y","ᴢ":"Z","á":"a","ă":"a","ắ":"a","ặ":"a","ằ":"a","ẳ":"a","ẵ":"a","ǎ":"a","â":"a","ấ":"a","ậ":"a","ầ":"a","ẩ":"a","ẫ":"a","ä":"a","ǟ":"a","ȧ":"a","ǡ":"a","ạ":"a","ȁ":"a","à":"a","ả":"a","ȃ":"a","ā":"a","ą":"a","ᶏ":"a","ẚ":"a","å":"a","ǻ":"a","ḁ":"a","ⱥ":"a","ã":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ḃ":"b","ḅ":"b","ɓ":"b","ḇ":"b","ᵬ":"b","ᶀ":"b","ƀ":"b","ƃ":"b","ɵ":"o","ć":"c","č":"c","ç":"c","ḉ":"c","ĉ":"c","ɕ":"c","ċ":"c","ƈ":"c","ȼ":"c","ď":"d","ḑ":"d","ḓ":"d","ȡ":"d","ḋ":"d","ḍ":"d","ɗ":"d","ᶑ":"d","ḏ":"d","ᵭ":"d","ᶁ":"d","đ":"d","ɖ":"d","ƌ":"d","ı":"i","ȷ":"j","ɟ":"j","ʄ":"j","ǳ":"dz","ǆ":"dz","é":"e","ĕ":"e","ě":"e","ȩ":"e","ḝ":"e","ê":"e","ế":"e","ệ":"e","ề":"e","ể":"e","ễ":"e","ḙ":"e","ë":"e","ė":"e","ẹ":"e","ȅ":"e","è":"e","ẻ":"e","ȇ":"e","ē":"e","ḗ":"e","ḕ":"e","ⱸ":"e","ę":"e","ᶒ":"e","ɇ":"e","ẽ":"e","ḛ":"e","ꝫ":"et","ḟ":"f","ƒ":"f","ᵮ":"f","ᶂ":"f","ǵ":"g","ğ":"g","ǧ":"g","ģ":"g","ĝ":"g","ġ":"g","ɠ":"g","ḡ":"g","ᶃ":"g","ǥ":"g","ḫ":"h","ȟ":"h","ḩ":"h","ĥ":"h","ⱨ":"h","ḧ":"h","ḣ":"h","ḥ":"h","ɦ":"h","ẖ":"h","ħ":"h","ƕ":"hv","í":"i","ĭ":"i","ǐ":"i","î":"i","ï":"i","ḯ":"i","ị":"i","ȉ":"i","ì":"i","ỉ":"i","ȋ":"i","ī":"i","į":"i","ᶖ":"i","ɨ":"i","ĩ":"i","ḭ":"i","ꝺ":"d","ꝼ":"f","ᵹ":"g","ꞃ":"r","ꞅ":"s","ꞇ":"t","ꝭ":"is","ǰ":"j","ĵ":"j","ʝ":"j","ɉ":"j","ḱ":"k","ǩ":"k","ķ":"k","ⱪ":"k","ꝃ":"k","ḳ":"k","ƙ":"k","ḵ":"k","ᶄ":"k","ꝁ":"k","ꝅ":"k","ĺ":"l","ƚ":"l","ɬ":"l","ľ":"l","ļ":"l","ḽ":"l","ȴ":"l","ḷ":"l","ḹ":"l","ⱡ":"l","ꝉ":"l","ḻ":"l","ŀ":"l","ɫ":"l","ᶅ":"l","ɭ":"l","ł":"l","ǉ":"lj","ſ":"s","ẜ":"s","ẛ":"s","ẝ":"s","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ᵯ":"m","ᶆ":"m","ń":"n","ň":"n","ņ":"n","ṋ":"n","ȵ":"n","ṅ":"n","ṇ":"n","ǹ":"n","ɲ":"n","ṉ":"n","ƞ":"n","ᵰ":"n","ᶇ":"n","ɳ":"n","ñ":"n","ǌ":"nj","ó":"o","ŏ":"o","ǒ":"o","ô":"o","ố":"o","ộ":"o","ồ":"o","ổ":"o","ỗ":"o","ö":"o","ȫ":"o","ȯ":"o","ȱ":"o","ọ":"o","ő":"o","ȍ":"o","ò":"o","ỏ":"o","ơ":"o","ớ":"o","ợ":"o","ờ":"o","ở":"o","ỡ":"o","ȏ":"o","ꝋ":"o","ꝍ":"o","ⱺ":"o","ō":"o","ṓ":"o","ṑ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","õ":"o","ṍ":"o","ṏ":"o","ȭ":"o","ƣ":"oi","ꝏ":"oo","ɛ":"e","ᶓ":"e","ɔ":"o","ᶗ":"o","ȣ":"ou","ṕ":"p","ṗ":"p","ꝓ":"p","ƥ":"p","ᵱ":"p","ᶈ":"p","ꝕ":"p","ᵽ":"p","ꝑ":"p","ꝙ":"q","ʠ":"q","ɋ":"q","ꝗ":"q","ŕ":"r","ř":"r","ŗ":"r","ṙ":"r","ṛ":"r","ṝ":"r","ȑ":"r","ɾ":"r","ᵳ":"r","ȓ":"r","ṟ":"r","ɼ":"r","ᵲ":"r","ᶉ":"r","ɍ":"r","ɽ":"r","ↄ":"c","ꜿ":"c","ɘ":"e","ɿ":"r","ś":"s","ṥ":"s","š":"s","ṧ":"s","ş":"s","ŝ":"s","ș":"s","ṡ":"s","ṣ":"s","ṩ":"s","ʂ":"s","ᵴ":"s","ᶊ":"s","ȿ":"s","ɡ":"g","ᴑ":"o","ᴓ":"o","ᴝ":"u","ť":"t","ţ":"t","ṱ":"t","ț":"t","ȶ":"t","ẗ":"t","ⱦ":"t","ṫ":"t","ṭ":"t","ƭ":"t","ṯ":"t","ᵵ":"t","ƫ":"t","ʈ":"t","ŧ":"t","ᵺ":"th","ɐ":"a","ᴂ":"ae","ǝ":"e","ᵷ":"g","ɥ":"h","ʮ":"h","ʯ":"h","ᴉ":"i","ʞ":"k","ꞁ":"l","ɯ":"m","ɰ":"m","ᴔ":"oe","ɹ":"r","ɻ":"r","ɺ":"r","ⱹ":"r","ʇ":"t","ʌ":"v","ʍ":"w","ʎ":"y","ꜩ":"tz","ú":"u","ŭ":"u","ǔ":"u","û":"u","ṷ":"u","ü":"u","ǘ":"u","ǚ":"u","ǜ":"u","ǖ":"u","ṳ":"u","ụ":"u","ű":"u","ȕ":"u","ù":"u","ủ":"u","ư":"u","ứ":"u","ự":"u","ừ":"u","ử":"u","ữ":"u","ȗ":"u","ū":"u","ṻ":"u","ų":"u","ᶙ":"u","ů":"u","ũ":"u","ṹ":"u","ṵ":"u","ᵫ":"ue","ꝸ":"um","ⱴ":"v","ꝟ":"v","ṿ":"v","ʋ":"v","ᶌ":"v","ⱱ":"v","ṽ":"v","ꝡ":"vy","ẃ":"w","ŵ":"w","ẅ":"w","ẇ":"w","ẉ":"w","ẁ":"w","ⱳ":"w","ẘ":"w","ẍ":"x","ẋ":"x","ᶍ":"x","ý":"y","ŷ":"y","ÿ":"y","ẏ":"y","ỵ":"y","ỳ":"y","ƴ":"y","ỷ":"y","ỿ":"y","ȳ":"y","ẙ":"y","ɏ":"y","ỹ":"y","ź":"z","ž":"z","ẑ":"z","ʑ":"z","ⱬ":"z","ż":"z","ẓ":"z","ȥ":"z","ẕ":"z","ᵶ":"z","ᶎ":"z","ʐ":"z","ƶ":"z","ɀ":"z","ﬀ":"ff","ﬃ":"ffi","ﬄ":"ffl","ﬁ":"fi","ﬂ":"fl","ĳ":"ij","œ":"oe","ﬆ":"st","ₐ":"a","ₑ":"e","ᵢ":"i","ⱼ":"j","ₒ":"o","ᵣ":"r","ᵤ":"u","ᵥ":"v","ₓ":"x"};
String.prototype.latinise=function(){return this.replace(/[^A-Za-z0-9\[\] ]/g,function(a){return Latinise.latin_map[a]||a})};
String.prototype.latinize=String.prototype.latinise;
String.prototype.isLatin=function(){return this==this.latinise()}



/**
* Array
*/

// ------ UNIQUE reduces duplicates ------
array_unique = function(ar){
	var r = new Array();
	o:for(var i = 0, n = ar.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==ar[i])
			{
				continue o;
			}
		}
		r[r.length] = ar[i];
	}
	return r;
};

/*	
		SHUFFLE Add a shuffle function to Array object prototype
		author: Stephane Roucheray
		src: http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/
		found 2011/09/08.
*/
array_shuffle = function(ar){
    var i = ar.length, j, temp;
    if ( i == 0 ) return;
    while ( --i ) {
        j = Math.floor( Math.random() * ( i + 1 ) );
        temp = ar[i];
        ar[i] = ar[j];
        ar[j] = temp;
    }
    return ar;
};


// ------ CONTAINS ------
array_contains = function(ar, obj) {
    var i = ar.length;
    while (i--)
        if (ar[i] === obj)
            return true;
    return false;
};



// ------ REMOVE ------
// /!\	Found on the Internet, not sure of efficiency.
// Array.prototype.remove = function(v) {
//     var x, _i, _len, _results;
//     _results = [];
//     for (_i = 0, _len = this.length; _i < _len; _i++) {
//         x = this[_i];
//         if (x !== v) {
//             _results.push(x);
//         }
//     }
//     return _results;
// };

array_remove= function(ar){
    var what, a= arguments, L= a.length, ax;
    while(L && ar.length){
        what= a[--L];
        while((ax= ar.indexOf(what))!= -1){
            ar.splice(ax, 1);
        }
    }
    return ar;
};

// for IE
// if(!Array.prototype.indexOf){
//     Array.prototype.indexOf= function(what, i){
//         i= i || 0;
//         var L= this.length;
//         while(i< L){
//             if(this[i]=== what) return i;
//             ++i;
//         }
//         return -1;
//     };
// }

array_indexOf= function(ar, what, i){
    i= i || 0;
    var L= ar.length;
    while(i< L){
        if(ar[i]=== what) return i;
        ++i;
    }
    return -1;
};


// ------ SUBSTRACT substract two array ------
function array_subtract(ara1,ara2) {
  var aRes = new Array() ;
  for (var i = ara1.length-1; i >= 0; i--)
    if( !ara2.contains(ara1[i]) )
      aRes.push(ara1[i]);
  return aRes ;

};


/**
* Objects
*
*/
// ------ OBJECTSIZE get the length of objects ------
function objectSize(o) {
	var len = o.length ? --o.length : 0;
	for (var k in o)
		len++;
	return len;
}
// Object.prototype.size = function () {
// 	// var len = this.length ? --this.length : -1; // POURQUOI NE FONCTIONNE PAS?
// 	var len = this.length ? --this.length : -2;
// 	for (var k in this)
// 		len++;
// 	return len;
// }

function objectIsEmpty(obj){
	for (var prop in obj) {
		if (obj.hasOwnProperty(prop))
			return false;
	}
	return true;
};



// ------ OBJECTGETKEY get key of index ------
function objectGetKey(o,index){
	var i = 0;
	for (var k in o){
		if (k === 'length' || !o.hasOwnProperty(k)) 
			continue;
		if(i == index) 
			return k;
		i ++;
	}
}
// Object.prototype.getKey = function(index){
// 	var i = 0;
// 	for (var key in this){
// 		if (key === 'length' || !this.hasOwnProperty(key)) 
// 			continue;
// 		if(i == index) 
// 			return key;
// 		i ++;
// 	}
// }

// ------ OBJECTSORT sort object ------
function objectSort(o,value) {
    var connection = new Array();
	for (var i = objectSize(o) - 1; i >= 0; i--){
		var k = objectGetKey(o,i);
		for (var j = objectSize(o[k].wit) - 1; j >= 0; j--){
			var k2 = objectGetKey(o[k].wit,j);
			if (k2==value) {
				var the_wit = parseFloat(o[k].wit[k2]);
				connection.push( {wit:the_wit,nid:k} );
			};
		};
	};

	connection.sort(function(a,b){
		// return (a.wit - b.wit);//ascending
		return (b.wit - a.wit);//descending
	});

	var o_sort = {};
	for (var i = connection.length - 1; i >= 0; i--){
		// o_sort[connection[i].wit+'-'+connection[i].nid] = o[connection[i].nid];
		o_sort[connection[i].nid] = o[connection[i].nid];
	};

	return o_sort;
}


/**
* trigo
*/
// -------- TRIGO ----------
// L'angle 0 correspond au nord (vers le haut)
// Exemple : getElementAngle(posElementX, posElementY, posSourisX, posSourisY)
//			 Ceci retournera l'angle de l'élément par rapport à la position de la souris
function getElementAngle(x1, y1, x2, y2) {
	var adj = x2 - x1;
	var opp = y2 - y1;
	
	var angle = Math.abs(Math.atan(opp/adj) * 180/Math.PI);
	
	if (adj > 0 && opp < 0 ) {
		angle = 90 - angle;
	}
	else if (adj >= 0 && opp >= 0) {
		angle += 90;
	}
	else if (adj < 0 && opp >= 0) {
		angle = 180 + (90 - angle);
	}
	else {
		angle += 270;
	}
	
	return angle;
}





/* **********************************************
     Begin materio_search_api_ajax.js
********************************************** */

// @codekit-prepend "gui.js"

(function($) {

MaterioSearchApiAjax = function(){
  var _isloadingresults = false;
  var _$content = $('#content');
      // TODO:  define $content by module settings  
  /**
  * init()
  */
  function init(){
    //trace('init MaterioSearchApiAjax');

    initSearchAjax();
    initViewMode();
  };

  /**
  * searchAjax
  */
  function initSearchAjax(){
    // trace('initSearchAjax');

    $('#materio-search-api-search-form').bind('submit', function(event) {
      // trace('search submited', event);
      var $this = $(this);
      setTimeout(function(){
        loadResults(getSearchKeys());
      },10);
      return false;
    });

    // /!\ AUTOCOMPLETE SELECT EVENT need a patch http://drupal.org/node/365241#comment-5374686
    $("#edit-searchfield")
      .bind('autocompleteSelect', function(event) {
        $(this).parents('.form').trigger('submit');
      })
      .bind('focus', function(event){
        $(this).select();
      });

    $(document)
      .bind('init-scroller-pager', onInitScrollerPager)
      .bind('load-scroller-pager', onLoadScrollerPager)
      .bind('view-mode-changed', onViewModeChanged)
      .bind('history-state-change', onHistoryStateChange);
    
    // trigger updated event for direct html loading
    if( isActuality() || isExplore() ){
      setTimeout(function(){
        //trace('MaterioSearchApiAjax :: initSearchAjax :: triggering resultschanged')
        $.event.trigger({
          type : 'resultschanged',
          container : isActuality() ? '#content .actuality-items' : '#content .search-results'
        });  
      }, 10);
    }
  };
  
  function getSearchKeys(){
    return $('#materio-search-api-search-form').find('input[name*="searchfield"]').val();
  };

  function loadResults(keys){
    trace('keys', keys);
    if(keys !== undefined && keys !== ''  && keys.length >= 2){
      keys = keys.replace('/', ' ');

      var types = {}, stringTypes = [];
      $('#edit-bundles-filter', '#materio-search-api-search-form').find('input[type*="checkbox"]').each(function(i){
        $this = $(this);
        if ( $this.attr('checked') )
          stringTypes.push($this.val());
        types[$this.val()] = $this.attr('checked');
      });
      //trace('types', types);


      if(!_isloadingresults){
        $.event.trigger('loading-content');
        _isloadingresults = true;
        $('#materio-search-api-search-form').addClass('loading');
        // trace('window.location.href',window.location.href);
        // TODO:  record ajax path in a variable from materio_search_api_ajax_init
        $.getJSON(Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/search/', 
          {'types':types,'current_path':document.location.href, keys:keys},
          function(json){
            //trace('json', json);
            
            // google analytics
            $.event.trigger({
              type : "record-stat",
              categorie : 'Search',
              action : keys,
              label : 'filters : '+ stringTypes.join(' ,'),
              value : json.count
            });

            if(json.redirect){
              window.location = json.redirect;
            }else{
              $.event.trigger('loaded-content');      
              _isloadingresults = false;
              $('#materio-search-api-search-form').removeClass('loading');
              changeContent(json);  
            }
            
        });
      }
    }
  };

  function loadActuality(){
    if(!_isloadingresults){
      $.event.trigger('loading-content');
      _isloadingresults = true;
      $('#materio-search-api-search-form').addClass('loading');

      var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/actuality';
      $.getJSON(url, 
        function(json){
          //trace('json', json);
          $.event.trigger('resultsloaded');      
          _isloadingresults = false;
          $('#materio-search-api-search-form').removeClass('loading');
          changeContent(json);
      });
    }
  };

  function changeContent(json){
    trace('MaterioSearchApiAjax changeContent | json', json);

    if(json.return){
      $.event.trigger('loaded-content');
      $('.inner-content',_$content).html(json.return).find('ul.pager').hide();
      triggerContentChanged();
    }else{
      //trace('no results');
    }

    $.event.trigger({
      type : 'new-history-page',
      path : Drupal.settings.basePath + Drupal.settings.pathPrefix + json.path,
      title : json.title,
      content : json.return
    });
    
    for (language in Drupal.settings.materio_search_api_ajax.languages) {
      var l = Drupal.settings.materio_search_api_ajax.languages[language];
      $('#block-locale-language li.'+language+' a').attr('href', Drupal.settings.basePath + l.prefix+'/' + json.search_path + '/' + json.keys)        
    };
  };

  function triggerContentChanged(){
    //trace('MaterioSearchApiAjax :: triggerContentChanged');
    $.event.trigger({
      type : 'resultschanged',
      container : '#content .search-results, #content .actuality-items'
    });
  };

  function onInitScrollerPager(event){
    if(isActuality() || isExplore())
      event.pager.hide();
  };

  function onLoadScrollerPager(event){
    if(!_isloadingresults){
      if (isExplore())
        loadNextResultsPage(event.href);

      if(isActuality())
        loadNextActualityPage(event.href);
    }
  };

  function loadNextResultsPage(href){
    // trace('loadNextResultsPage');
    var keys = href.match(/explore\/([^\/|\?]+)/);
    var page = href.match(/\?page=([0-9]+)/);
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/search/'+page[1];
    
    loadNextPage(url, keys[1], $('.materiobase-results', _$content), '.search-results');
  };

  function loadNextActualityPage(href){
    // trace('loadNextActualityPage');
    var page = href.match(/\?page=([0-9]+)/);
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/actuality/'+page[1];

    loadNextPage(url, '', $('.materiobase-actuality', _$content), '.actuality-items');
  };

  function loadNextPage(url, keys, $container, target){
    //trace('MaterioSearchApiAjax :: loadNextPage()');
    _isloadingresults = true;
    $container.addClass('loading');
    $.getJSON(url, {'keys':keys}, function(json){
      //trace('json', json);
      $container.removeClass('loading');
      addNextpage(json, target);
      // addNextpageItemByItem($(json.return), target);
    });
  };

  function addNextpage(json, container_class){
    var $newcontent = $(json.return),
        $newitems = $(container_class, $newcontent).children('article'), //.addClass('just-added'),
        $newpager = $('ul.pager', $newcontent);

    $(container_class, _$content).append($newitems);
    $('ul.pager', _$content).replaceWith($newpager.hide());

    // TODO: animation, this should be on theme side
    $(container_class, _$content).children('.just-added').each(function(i){
      var $this = $(this);
      setTimeout(function(){
        $this.removeClass('just-added');
      }, 150*i);
    });

    $.event.trigger({
      type : 'resultscompleted',
      container : $(container_class, _$content)
    });
    _isloadingresults = false;
  };

  // TEST not used 
  function addNextpageItemByItem($newcontent, container_class){
    //trace('MaterioSearchApiAjax :: addNextpageItemByItem()');
    $('ul.pager', _$content).remove();
    $(container_class, _$content).append($(container_class, $newcontent).children('article').eq(0));

    if($(container_class, $newcontent).children('article').length){
      setTimeout(function(){
        addNextpageItemByItem($newcontent, container_class);
      }, 200);
    }else{
      _isloadingresults = false;
      $('ul.pager', _$content).replaceWith($('ul.pager', $newcontent).hide());
      $.event.trigger({
        type : 'resultscompleted',
        container : $(container_class, _$content)
      });  
    }
  };  

  /**
  * viewmode
  */
  function initViewMode(){
    $('.viewmode-link').click(function(event){
      event.preventDefault();
      
      if(!$(this).is('.active'))
        changeViewMode($(this).attr('rel'), $(this));

      return false;
    });
  };

  function changeViewMode(vm, $btn){
    if(!_isloadingresults){
      _isloadingresults = true;
      $.getJSON(Drupal.settings.basePath+'materio_search_api_ajax/viewmode/change/'+vm, function(json){
        //trace('viewmode json', json);
      _isloadingresults = false;
        if (json.statut == "saved"){
          
          // google analytics
          $.event.trigger({
            type : "record-stat",
            categorie : 'Viewmode',
            action : vm,
            label : isActuality() ? 'Actualities' : 'Search results'
          });

          $.event.trigger('view-mode-changed');
          $('.viewmode-link, .viewmode-link i').removeClass('active');
          $btn.addClass('active').find('i').addClass('active');
        }
          
      });
    }
  };

  function onViewModeChanged(event){
    if (isExplore())
      loadResults(getSearchKeys());

    if(isActuality())
      loadActuality();
  };

  /**
  * history
  */
  function onHistoryStateChange(event){
    if(isExplore() || isActuality())
      triggerContentChanged();
    // TODO:  pushstate trogger state change, so we have a retriggerring here on loading new results … how to avoid this  
  };

  /**
  * helpers
  */
  function isExplore(){
     return $('.search-results', '#content').length;
  };

  function isActuality(){
    return $('.actuality-items', '#content').length;
  };
    
  init();
};

  var materiosearchapiajax = new MaterioSearchApiAjax();
  
})(jQuery);