/** Generated by js.php */
var Url = {};
var array_urlID = new Array();

Url.MAIN_CONTENT_URL_LIST_ID = 'mainContentUrlList';

// Id mustn't be changed
Url.listTemplate = new Template("#{PUBLIC_INFO}<br>#{PAGER}<ul id='"+Url.MAIN_CONTENT_URL_LIST_ID+"'></ul>#{PAGER}");
Url.itemTemplate = new Template("<li id='mainContentUrlListElement' urlId='#{URL_ID}'>"+
									"<img id='mainContentUrlImg_#{URL_ID}' src='/img/icons/crystal/16x16/actions/#{IMG_NAME}.gif' class='statusIcon' align='baseline'/> "+
									"<a id='mainContentUrlLink_#{URL_ID}' href='/pages/frameset?id=#{URL_ID}&src=#{URL_ADDRESS}' target='_blank' class='urlName'>#{LINK}</a> "+
									"#{CATEGORY}<br>"+
									"<span>#{ADDED_DATE}</span> <#{TAG_COMMENT} id='mainContentUrlNbComment_#{URL_ID}' style='color:#555'>&nbsp;- #{COMMENT}</#{TAG_COMMENT}> "+
									"<span id='mainContentUrlStarsContainer_#{URL_ID}' class='starsContainer' default='#{DEFAULT_MARK}'>"+
										"<img id='mainContentUrlMark_#{URL_ID}_1' src='/img/star#{STAR_COLOR_1}.gif' value='1' style='left:-1px'/>"+
										"<img id='mainContentUrlMark_#{URL_ID}_2' src='/img/star#{STAR_COLOR_2}.gif' value='2' style='left:-1px'/>"+
										"<img id='mainContentUrlMark_#{URL_ID}_3' src='/img/star#{STAR_COLOR_3}.gif' value='3' style='left:-1px'/>"+
										"<img id='mainContentUrlMark_#{URL_ID}_4' src='/img/star#{STAR_COLOR_4}.gif' value='4' style='left:-1px'/>"+
										"<img id='mainContentUrlMark_#{URL_ID}_5' src='/img/star#{STAR_COLOR_5}.gif' value='5' style='left:-1px'/>"+
									"</span> "+
									"<b id='mainContentUrlAverageMarkContainer_#{URL_ID}' style='display:#{DISPLAY_AVERAGE}'>( "+_mlt("AVERAGE","Moyenne")+" : <span id='mainContentUrlAverageMark_#{URL_ID}'>#{AVERAGE_MARK}</span> / 5 )</b> #{AD}"+
									"<div class='commentContainer' style='display:block'></div>"+
								"</li>");
Url.linkedCategoryTemplate = new Template("<i categoryId=#{CATEGORY_ID}><a id='mainContentCategory_#{URL_ID}' href='javascript:;'>&nbsp;(<span class='info'>#{CATEGORY}</span>)</a></i>");
Url.advertiseTemplate = new Template("<br>"+
	"<div id='advertising_block_#{URL_ID}' class='advertising_block'>#{ADVERTISING_CONTENT}</div>"+
	"<span id='mainContentUrlAd_#{URL_ID}' class='mainContentAD' onmouseover='displayAdvert(\"cadre_advertising_#{URL_ID}\")' onmouseout='hideAdvert(\"cadre_advertising_#{URL_ID}\")'>"+_mlt("DISCOVER_COOMCOOM_SERVICES",'Découvrez les services proposés par ce site')+"</span>"
);

/**
*	Generate the dom of the url list
*
**/
generateUrlList = function(xhr, json) {
	try {
		json = eval('(' + xhr.responseText + ')');
		clearElements();
		var publicInfo = "";
		var urlList = null;
		
		User.isLogged = json.infos.user.logged;
		if((json.errors) && (json.errors.urls)) {
			urlList = {PUBLIC_INFO: json.errors.urls };
			new Insertion.Bottom($('bookmarksContainer'),  Url.listTemplate.evaluate(urlList));
		} 
		else {
			var pager = '';
			if (json.infos.urls) {
				if (json.infos.urls.categoryInfo) publicInfo += json.infos.urls.categoryInfo;
				
				if (json.infos.urls.search_tag_only) publicInfo += "<br>"+json.infos.urls.search_tag_only;
				if (json.infos.categories) {
					publicInfo += "<br><br>"+json.infos.categories.summary;
					for(var i=0;i<json.infos.categories.list.length;i++)
					{
						if (i >0)
						{
							publicInfo += ", ";
						}
						publicInfo += "<a href='javascript:;' class='categoryName' onclick='searchByCategory("+json.infos.categories.list[i].id+")'>"+json.infos.categories.list[i].name+"</a>";
					}
				}
				if ((json.infos.urls.nb_matches) && (json.infos.urls.nb_matches > 20)) {
					pager = Common.getPager("searchUrls('"+json.infos.criteria+"')",json.infos.urls.nb_matches);
				}
			}
			
			urlList = {PUBLIC_INFO: publicInfo, PAGER: pager };
			new Insertion.Bottom($('bookmarksContainer'),  Url.listTemplate.evaluate(urlList));
			json.urls.each(generateUrlListElement);
		}
		
	} catch (e) { 
		if (console) console.error(e);
	}
}

generateUrlListElement = function(url) {
try {
	// Image part
	var imgName = 'bookmark';
	if ((!url.isBookmarked || url.isBookmarked == "") && (User.isLogged == true)) {
		imgName = 'bookmark_add';
	}
	
	// Link Part
	var titleText = url.title || url.address
	if(titleText.length > 60)
	{
		titleText = titleText.substring(0,60)+'...';
	}
	
	// Category Part
	var categoryEvaluated = '';
	if (url.category && url.search)
	{
		var category = {CATEGORY_ID:url.category_id,URL_ID:url.id,CATEGORY:url.category};
		categoryEvaluated = Url.linkedCategoryTemplate.evaluate(category);
	}
	
	// Comments Part
	var commentTag = 'span';
	if(url.nb_comments > 0 || User.isLogged == true)
	{
		commentTag = "a href='javascript:;'";
	}
	
	// Marks Part
	var starColorArray = new Array(5);
	var defaultMark = url.mark;
	if(User.isLogged == true) {
		for(var j=1;j<6;j++)
		{
			if(j <= url.mark) {
				starColorArray[j] = 'Blue';
			} else {
				starColorArray[j] = 'Gray';
			}
		}
	}
	else {
		defaultMark = url.average_mark;
		for(var j=1;j<6;j++)
		{
			if(j <= url.average_mark) {
				starColorArray[j] = 'Blue';
			} else {
				starColorArray[j] = 'Gray';
			}
		}
	}
	
	// Average mark
	var displayAverage = 'inline';
	if(url.average_mark == null) displayAverage = 'none';
	var average = ''+url.average_mark;
	average = average.substring(0,4);
	
	// AD
	var adEvaluated = '';
	if (url.actived_advertising == 1) {
	
		var adv = Advert(url.id,url.advertising,url.model_advertising,url.url_advertising);
		var ad = {URL_ID:url.id,ADVERTISING_CONTENT:adv};
		adEvaluated = Url.advertiseTemplate.evaluate(ad);
		
		//on stock les URL_ID dans un tableau pour etre gerer plus tard
		array_urlID.push(url.id);
	}
	
	// We generate the element
	
	var urlListElement = {URL_ID: url.id, IMG_NAME: imgName, URL_ADDRESS: url.address , LINK: titleText,CATEGORY: categoryEvaluated, ADDED_DATE: url.created, TAG_COMMENT:commentTag,COMMENT: getCommentsLabel(url.nb_comments), DEFAULT_MARK: defaultMark,STAR_COLOR_1: starColorArray[1],STAR_COLOR_2: starColorArray[2],STAR_COLOR_3: starColorArray[3],STAR_COLOR_4: starColorArray[4],STAR_COLOR_5: starColorArray[5], DISPLAY_AVERAGE:displayAverage,AVERAGE_MARK: average, AD: adEvaluated }; 
	new Insertion.Bottom($(Url.MAIN_CONTENT_URL_LIST_ID),Url.itemTemplate.evaluate(urlListElement));
	 
	// Manage Events
	// Img
	if ((!url.isBookmarked || url.isBookmarked == "") && (User.isLogged == true)) {
		Event.observe('mainContentUrlImg_'+url.id,"click",addToBookmarks);
	}
	// Link
	Event.observe('mainContentUrlLink_'+url.id,"focus",function(event) {Event.element(event).blur()})
	Event.observe('mainContentUrlLink_'+url.id,"click",function() {hitUrl(url.id,'public')})
	
	// Category
	if (url.category && url.search) {
		Event.observe("mainContentCategory_"+url.id,"click",function() {searchByCategory(url.category_id);})
	}
	// Comments
	if(url.nb_comments > 0 || User.isLogged == true)
	{
		Event.observe('mainContentUrlNbComment_'+url.id,"click",togglePublicComments)
		Event.observe('mainContentUrlNbComment_'+url.id,"focus",function(event) {Event.element(event).blur()})
	}
	// Marks
	if(User.isLogged == true) {
		Event.observe('mainContentUrlStarsContainer_'+url.id,'mouseout',resetMark);
		for(var j=1;j<6;j++)
		{
			Event.observe('mainContentUrlMark_'+url.id+'_'+j,"click",function(event){ setMark(event);updateAverageMark(event);})
			Event.observe('mainContentUrlMark_'+url.id+'_'+j,"mouseover",overMark)
		}
	}
	
	} catch (e) { if (console) console.info(e)}
}


/*
* Effectue une recherche
*/
searchUrls = function(criteria,start,searchFromTag)
{
	if(start == null) start = 0;	
	
	if (!searchFromTag) searchFromTag = 0;

	new Ajax.Request('/urls/search/'+encodeURIComponent(criteria)+'/'+start+'/null/'+searchFromTag,{
		method:'post',
		postBody:'searchTagOnly=1',
		onComplete:generateUrlList
	});
	
	// mise � jour du critere de recherche (si elle est lanc�e depuis les tags)
	criteria = decodeURIComponent(criteria);
	$('mainContentCriteria').value =criteria; 
}

searchByCategory = function(id) {
	switchToPublic(true);
	new Ajax.Request('/categories/searchUrlByCategory/'+id,{
		method:'post',
		onComplete: function(xhr,json) {
			activeSwitchLink();
			generateUrlList(xhr,json);
			json = eval('(' + xhr.responseText + ')');
			
			var infoPathCompleteArray = '';
			if ((json.infos.categories) && (json.infos.categories.infoPath)) {
				infoPathCompleteArray = json.infos.categories.infoPath;
			}
			PathInfo.generatePath(infoPathCompleteArray,'searchByCategory',true);
			
			//on met le portlet contenant les categories
			new Ajax.Updater('categoryPortlet','/categories/getInPortlet/'+id+'/1', {onComplete: function(){
				PathInfo.generatePath(infoPathCompleteArray,'searchByCategory',true);
			}});
		}
	});
}

/**
*	Fonction qui met a jour la moyenne des notes pour une url
*/

updateAverageMark = function(event)
{
	// �toile cliqu�e
	star = Event.element(event)
	url_id = Element.up(star,'li').getAttribute('urlId')
	boldContainer = $('mainContentUrlAverageMarkContainer_'+url_id)
	new Ajax.Updater("mainContentUrlAverageMark_"+url_id,"/marks/getAverage/"+url_id,{asynchronous:false});
	boldContainer.style.display = "inline"
}

opened_public_comment = null;

togglePublicComments = function(event)
{
    li = Event.findElement(event,'LI')
    
    if($('adv_'+li.getAttribute('urlId'))){
        $('adv_'+li.getAttribute('urlId')).style.display = 'block';
        $('adv_'+li.getAttribute('urlId')).style.width = '100%';
    }
    
    commentContainer = Element.down(li,'div.commentContainer');

    try {
        if (commentContainer.innerHTML.length == 0)
        {
            // surbrillance du bloc complet de l'url
            li.className = 'selected_url'

            // on rapatrie les commentaires
            new Ajax.Updater(commentContainer,'/comments/display/'+li.getAttribute('urlId'))
            commentContainer.style.display = 'block'

            commentContainer.style.width = '100%'

            if (opened_public_comment)
            {
                opened_public_comment.innerHTML = ''
                opened_public_comment.style.display = 'none'
                opened_public_comment.up('li').className = 'unselected_url'
            }
            opened_public_comment = commentContainer;
        }
        else{
            // retour à l'affichage normal
            li.className = 'unselected_url'

            commentContainer.innerHTML = ''
            commentContainer.style.display = 'none'
            opened_public_comment = null;
        }
    }
    catch(e) { if(console) console.info(e); else alert(e)}
}

/**
* Fonction Ajax qui retourne les commentaires suivants
*/

displayPublicComments = function(url_id,start)
{
    new Ajax.Updater(opened_public_comment,"/comments/display/"+url_id+"/"+start)
}

/**
* Fonction qui affiche la div permettant d'ajouter son commentaire
*/

displayMyPublicComment = function(url_id)
{
    new Ajax.Updater(opened_public_comment,'/comments/display/'+url_id,{
        onComplete:function(){
            $('public_div_mycomment_'+url_id).style.display = 'block';
            $('public_div_allcomments_'+url_id).style.display = 'none';
        }
    });

}

/**
* Fonction qui cache la div permettant d'ajouter son commentaire et affiche les commentaires public
*/

closeMyPublicComment = function(url_id)
{
    $('public_div_mycomment_'+url_id).style.display = 'none';
    $('public_div_allcomments_'+url_id).style.display = 'block';
}

/**
* Fonction qui permet d'ajouter son commentaire sur une URL donnée
*/

addPublicComment = function(url_id,start,nb_comments)
{
    comments = $('public_textarea_'+url_id).value;
    new Ajax.Request("/comments/add/"+url_id,{
        asynchronous:false,
        method:'post',
        postBody: 'comment='+encodeURIComponent(comments)
    });
    new Ajax.Updater(opened_public_comment,"/comments/display/"+url_id+"/"+start,{asynchronous:false});
    nb_comments++;

    $('mainContentUrlNbComment_'+url_id).innerHTML = '&nbsp;-&nbsp;'+getCommentsLabel(nb_comments)+'&nbsp;-&nbsp;';
    $('public_div_mycomment_'+url_id).style.display = 'none';
    opened_public_comment.style.display = 'block';
}

/**
* Fonction qui permet d'ajouter son commentaire sur un URL donné
*/

updateMyPublicComment = function(url_id,indice,comment_id,user_id)
{

    comments = $('public_textarea_'+url_id).value
    new Ajax.Request("/comments/update/"+url_id+"/"+comment_id,{
        asynchronous:false,
        method:'post',
        postBody: 'commentName='+encodeURIComponent(comments)
    });

    $('public_div_mycomment_'+url_id).style.display = 'none';
    $('public_div_allcomments_'+url_id).style.display = 'block';
    if (user_id != -1){
        //var exp = new RegExp('\r\n','<br />');
        $('div_user_comment_'+url_id+'_'+user_id).innerHTML = comments.gsub("\n","<br />")
    }
}


/**
*  Suppression d'un commentaire
*/
deleteMyComment = function(url_id)
{
    new Ajax.Request('/urls/delete_user_comment/'+url_id,{asynchronous:false,onComplete:deleteMyCommentReturn})
}

deleteMyCommentReturn = function(xhr,json)
{
    try {
        new Ajax.Updater(opened_public_comment,'/comments/display/'+json.url_id,{asynchronous:false})
        $('mainContentUrlNbComment_'+json.url_id).innerHTML = '&nbsp;-&nbsp;'+getCommentsLabel(json.nb_comments)+'&nbsp;-&nbsp;';
    }
    catch(e) { if(console) console.info(e)}
}

/**
* Ajoute l'url dans la partie privée de l'utilisateur
*/

addToBookmarks = function(event)
{
    // élément de liste d'où provient le click
    li = Event.element(event).up("LI");
    dialog('addBookmarkToPrivate',{size:'450,350',source:'/bookmarks/toPrivate/'+li.getAttribute('urlId')}).display(false);
}

