var expiration = 600;
var vs=false;

function checkOffset(q)
{
	var cook = getCookie('search')
		q = (q ? q : 'null');
	//alert(q);
	//alert(cook);
	if (cook)
	{
		//wd('<li> cookie content is '+cook);
		r = cook.split('=');
		//alert(q);
		//alert(r[0]+'@'+q);
		if (r[0].toLowerCase() == q.toLowerCase())
		{
			//window.status='Page '+r[1];
			//alert(r[1]);
			return r[1];
		}

	}

	return 0;

}



function search_media(options, callback)
{
	var opt = {
		'q': '',
		'start': 0,
		'category': '',
		'media_category': '',
		'results': 10
	};
	opt = $H(opt).merge(options || {}).toObject();


	new Ajax.Request('/recherche/media_search.php',
			{
method: 'get',
parameters: opt,
//Adding a couple of retries if the service fails.
onSuccess: function(response)
{
//alert(response.responseText);
try {
//retries
callback(response.responseText.evalJSON(true));
search_media.tries = 0;
} catch(e) {
if(!search_media.tries) search_media.tries = 0;
if(search_media.tries++ < 1) {
search_media(opt, callback);
} else {
search_media.tries = 0;
}
}
}
});
}

var Gallery = {
	'galleryId': null,
	'galleryHitTemplate': null,

	'currentPage': 0,
	'totalPages': null,
	'hitsPerPage': 12,

	'nextPageActive':null,
	'nextPageInactive':null,
	'prevPageActive':null,
	'prevPageInactive':null,

	'searchTerm': null,
	'video_results': null,

	options: {
		'searchMediaType': 'images',
		'hitsPerPage': 10,
		'galleryId': 'galeriesDePhotos',
		'onSearch': function(){}
	},

opt: null,

     'init': function(options) {
	     var that = this;
	     this.opt = $H(this.options).merge(options || {}).toObject();
	     this.searchMediaType = this.opt.searchMediaType;
	     this.hitsPerPage = this.opt.hitsPerPage;
	     this.galleryId = this.opt.galleryId;

	     //alert(this.href);	

	     //initialize template
	     this.galleryHitTemplate = new Template('\r\n<li><p class="galeriesItemTheme">#{topic}</p><a href="#{href}&offset='+this.currentPage+'&context='+this.searchTerm+'" onclick="xt_click(this,\'C\',\'7\',\'Medias '+this.searchMediaType+'\',\'N\',\'\',\'\')"><img alt="Image de la galerie 1" src="#{thumbnail}"/></a><br/><p class="galeriesItemDate">#{date}</p><p class="galeriesItemTitle">#{title}</p><p class=summary>#{summary}</p></li>');
	     $('recherche_expression2').observe('focus', function() {
			     this.value = "";
			     });

	     //alert(this);

	     this.initializePages();
	     this.loadTopics();

	     /* */

	     if ( (!queryString('relation')) && (!queryString('search'))   && (!queryString('string')) )
	     {
	     
		if (this.searchMediaType != 'xvideo')
		{
			search_media({
				     'q': '',
				     'media_category': that.searchMediaType,
				     'category': '',
				     'start': checkOffset(''),
				     'results': that.hitsPerPage
				     }, function(json) {
				     that.updateGallery(json);
				     that.opt.onSearch(json);
				     });
		}
	     }
	     /* */

     },

     'loadTopics': function() {
	     var that = this;
	     search_media({
			     'q': '',
			     'media_category': that.searchMediaType,
			     'category': 'topic',
			     'start': 0,
			     'results': that.hitsPerPage
			     }, function(json) {
			     that.updateRefines(json.media.refines);
			     });
     },


     /*
	'search': function() {
	var that = this;
	var searchCategory = $F('search_category');
	this.searchTerm = $F('recherche_expression2');
	search_media({
	'q': that.searchTerm,
	'media_category': that.searchMediaType,
	'category': searchCategory == '' ? '' : ('topic/' + searchCategory),
	'start': 0,
	'results': that.hitsPerPage
	}, function(json) {
	that.updateGallery(json);
	that.opt.onSearch(json);
	});
	},

      */

     'search': function() {
	     var that=this;
	     var searchCategory = $F('search_category');
	     var searchTerm = $F('recherche_expression2');
	     var searchOffset=0;

	     that.do_search(searchTerm, searchCategory);
     },

     'do_search': function(searchTerm, searchCategory, searchOffset) {
	     var that = this;
	     this.searchTerm = searchTerm;
	     //vs = true;

	     if (searchOffset)
	     { 

	     }
	     else
	     {
		     setCookie('search',that.searchTerm+'=0',expiration);
	     }
	     search_media({
			     'q': that.searchTerm,
			     'media_category': that.searchMediaType,
			     'category': searchCategory == '' ? '' : ('topic/' + searchCategory),
			     'start': searchOffset,
			     'results': that.hitsPerPage
			     }, function(json) {
			     that.updateGallery(json);
			     that.opt.onSearch(json);
			     });
     },


     'updateGallery': function(search_data) {
	     var hits = search_data['media']['hits'], len = hits.length;
	     //if(len == 0) return;
	     //alert(this.searchTerm);	
	     var gallery = $(this.galleryId);
	     var items = gallery.childElements();
	     for (var i = 0, ilen = items.length; i < ilen; i++)
	     {
		     items[i].remove();
	     }

	     var resultList = new Element('ul');
	     for (var i = 0; i < len; i++)
	     {
		     var hit = hits[i];
		     hit['title'] = hit['title'].truncate(100);

		     // QUICK FIX FOR DEV
		     //hit['thumbnail'] = "http://www.elysee.fr" + hit['thumbnail'];
		     //hit['href'].replace('www.elysee.fr','www2.elysee.fr');
		     var hit_html = this.galleryHitTemplate.evaluate(hit);
		     resultList.insert(hit_html);
	     }

	     //hit[date].replace('-00:00:00','');	

	     var title;
	     if (this.searchTerm)
		     title=new Element('h2').update('Résultats de recherche pour <bstrong>'+this.searchTerm+'</strong>');
	     else
		     title=new Element('h2').update('Derniers contenus publi&eacute;s');
	     gallery.appendChild(title);

	     //alert(resultList);
	     gallery.appendChild(resultList);

	     this.currentPage = Math.ceil(search_data['media']['first_displayed_hit'] / this.hitsPerPage);
	     this.totalPages = Math.ceil(search_data['media']['total_hits'] / this.hitsPerPage);
	     $$('#contenuPagination2 span')[0].update(this.currentPage + "/" + this.totalPages);

	     this.checkPages(resultList);
     },

     'updateRefines': function(refines) {
	     var select = $('search_category');
	     var options = select.childElements();
	     for(var i=0, len=options.length; i<len; i++) 
	     {
		     options[i].remove();
	     }
	     for (var i=0, len=refines.length; i<len; i++)
	     {
		     var refine = refines[i];
		     var newOption = new Element('option');
		     newOption.value = refine.id;
		     newOption.update(refine.title);
		     select.appendChild(newOption);
	     }
     },

     'next': function() {
	     var that = this;
	     var offset = this.currentPage * this.hitsPerPage;
	     var searchCategory = $F('search_category');
	     setCookie('search',that.searchTerm+'='+offset,expiration);

	     search_media({
			     'q': that.searchTerm || '',
			     'media_category': that.searchMediaType,
			     'category': searchCategory == '' ? '' : ('topic/' + searchCategory),	
			     'start': offset,
			     'results': that.hitsPerPage,
			     'video_refine': that.videoRefine || ''
			     }, function(json) {
			     that.updateGallery(json);
			     });
     },

     'prev': function() {
	     var that = this;
	     if(this.currentPage > 1) {
		     var searchCategory = $F('search_category');
		     var offset = (this.currentPage -2) * this.hitsPerPage;
		     setCookie('search',that.searchTerm+'='+offset,expiration);
		     search_media({
				     'q': that.searchTerm || '',
				     'media_category': that.searchMediaType,
				     'category': searchCategory == '' ? '' : ('topic/' + searchCategory),
				     'start': offset,
				     'results': that.hitsPerPage,
				     'video_refine': that.videoRefine || ''
				     }, function(json) {
				     that.updateGallery(json);
				     });
	     }
     },

     'checkPages': function(list) {
	     if(this.currentPage === 1) {
		     this.nextPageInactive.style.display = 'none';
		     this.nextPageActive.style.display = '';

		     this.prevPageInactive.style.display = '';
		     this.prevPageActive.style.display = 'none';
	     } else {
		     this.prevPageInactive.style.display = 'none';
		     this.prevPageActive.style.display = '';
	     }

	     var gallery = $(this.galleryId);
	     var items = list.childElements();
	     if(items.length < this.hitsPerPage) {
		     this.nextPageInactive.style.display = '';
		     this.nextPageActive.style.display = 'none';
	     }
	     else {
		     this.nextPageInactive.style.display = 'none';
		     this.nextPageActive.style.display = '';
	     }
     },

     'initializePages': function() {
	     var that = this;
	     var buttons = $('contenuPagination1').childElements();

	     this.nextPageActive = buttons[0];
	     this.nextPageInactive = buttons[1];
	     this.prevPageActive = buttons[2];
	     this.prevPageInactive = buttons[3];

	     //buttons[1].style.display='';
	     //buttons[3].style.display='';
	     buttons[0].style.display='none';
	     buttons[2].style.display='none';

	     $$('#contenuPagination2 span')[0].update('');


	     this.nextPageActive.observe('click', function(e) {
			     e.stop();
			     that.next();
			     return false;
			     });


	     this.prevPageActive.observe('click', function(e) {
			     e.stop();
			     that.prev();
			     return false;
			     });


     }
};

//carousel stuff
/*
   var carousel_hit_template = new Template('\
   <li>\
   <p class="carouselItemTheme">#{topic}</p>\
   <a href="#{href}">\
   <img alt="#{title}" src="#{thumbnail}"/>\
   </a>\
   <br/>\
   <p class="carouselItemDate">#{date}</p>\
   <p class="carouselItemTitle">\
   <a href="#{href}">#{title}</a>\
   </p>\
   <p class="carouselItemShortDescription">#{short_desc}</p>\
   <p class="carouselItemLongDescription">#{long_desc}</p>\
   </li>');

   function update_carousel(search_data)
   {
//gna = search_data;
var carousel = $('carouselul');
var items = carousel.childElements();

for (var i = 0, len=items.length; i < len; i++)
{
items[i].remove();
}

var hits = search_data['media']['hits'];
for (i = 0; i < hits.length; i++)
{
var hit = hits[i];
hit['title'] = hit['title'].truncate(100);

// QUICK FIX FOR DEV
hit['short_desc'] = hit['summary'].truncate(25);
hit['long_desc'] = hit['summary'].truncate(75);
hit['thumbnail'] = "http://elysee.fr" + hit['thumbnail'];

var hit_html = carousel_hit_template.evaluate(hit);
carousel.insert(hit_html);
}

var category_select = $('search_category');
var options = category_select.childElements();
var refines = search_data['media']['refines'];

update_refines(category_select, refines);

for (i = 0, len = options.length; i < len; i++)
{
options[i].remove();
}

for (i = 0; i < refines.length; i++)
{
var refine = refines[i];
var newOption = new Element('option');
newOption.value = refine.id;
newOption.update(refine.title);
category_select.appendChild(newOption);
}
}

function update_refines(select, refines) {
var options = select.childElements();
for(var i=0, len=options.length; i<len; i++) 
{
options[i].remove();
}
for (var i=0, len=refines.length; i<len; i++)
{
var refine = refines[i];
var newOption = new Element('option');
newOption.value = refine.id;
newOption.update(refine.title);
select.appendChild(newOption);
}
}

*/

