/**
 * Javascript little library
 * @author AD daret@info.unicaen.fr
 * @author CT turbout@info.unicaen.fr
 * @date 2008/08/30
 */

var AJAX = "../main/ajax.php";
var IMG = "../ui/images";
var fileLoadingImage = "../ui/images/loading.gif";
var _new = '_new';
var dialog = null;

/** Return traduction for a keyword */
function _(cat,code) {
    if (typeof(i18n)!='undefined' && i18n[cat] && i18n[cat][code]) {
        return i18n[cat][code];
    }
    return code;
}

/**
 * generic function for calling ajax.Updater
 * @return void
 */
function update(id,url,params) {
    new Ajax.Updater(id, url, {method:'post',parameters: params,
		onComplete: function() {
		initLightbox();
		$('top').scrollTo();
		// bgMax.redim();
	    }});
}

/** Load the lightbox dialog */
function loadDialog(params) { dialog = new Dialog(AJAX+'?'+$H(params).toQueryString(),{'callback':$H(params).get('callback')}); }

/**
 * Set main content using params options in AJAX
 * @param event : the click action event (to stop)
 * @param params : command parameters
 */
function setMain(event, params) {
    if ($H(params).get('a') == 'theme') changeView("ptree-"+$H(params).get('ob'),true);
    update('mainContent',AJAX+"?"+$H(params).toQueryString());    
    event.stop();
}

/**
 * Set doc content using params options in AJAX
 * @param event : the click action event (to stop)
 * @param params : command parameters
 */
function loadDoc(event, params) {
    update('doc',AJAX+"?"+$H(params).toQueryString());
    event.stop();
}

/**
 * Load a Document in AJAX and move to the given link id
 * @param event : the click action event (to stop)
 * @param params : command parameters
 * @param idlink : the link to move to
 */
function loadLinkInDoc(event, params, idlink) {
    new Ajax.Updater('mainContent', AJAX+"?"+$H(params).toQueryString(), {method:'post',
		onComplete: function() {
		initLightbox();
		$(idlink).scrollTo();
	    }});
    event.stop();
}



/**
 * Get the result of a Link
 * @param anchor : the clicked anchor
 * @param link_id : the link identifier
 */
function getLinks(anchor,link_id) {
    var childs = $(anchor).childElements();
    var text = childs.length == 0 ? anchor.innerHTML : "";
    for (var i = 0; i < childs.length; i++) {
	if (Object.isString(childs[i])) text += childs[i];
	else text += childs[i].innerHTML;
    }
    new Ajax.Updater('linkContent', AJAX+"?a=link&link_id="+link_id+"&link_label="+text, {method:'get',
		onComplete: function() {
		$('links').show();
		$('linklabel').update(text);
		$('linkdocs_toggler').src="../ui/images/reduce_links.gif";
	    }});
}

/**
 * Get the doc relatively to a descriptor
 * @param label : the descriptor
 */
function getDescriptor(label) {
    new Ajax.Updater('descriptorContent',AJAX+"?a=descriptor&label="+label,
		     {method:'get', onComplete:function() {$('descriptor').show(); $('descriptor').scrollTo();}});
    $('descrdocs_toggler').src="../ui/images/reduce_links.gif";    
}

/** Set offset ... pagination.  */
function setOffset(pos){
    var ob = (pos  == null) ? "" : "&pos="+pos;
    new Ajax.Request(AJAX+"?special=offset"+ob);
}


//////////////////// FORM //////////////////////////////////////////////////////
/**
 * Form execution
 */
function execForm(form) {
    switch (form) {
    case 'searchResult':
	update('searchResultsContent',AJAX+'?a='+form,$(form).serialize());
	$('searchResults').show();
	$('resultDocs_toggler').src="../ui/images/reduce_links.gif";
	break;
    default:
	update("form"+form,AJAX+'?a='+form,$(form).serialize());
	break;
    }
}

/** trim textarea value when focus it */
function clean(textarea) {
    textarea.value = textarea.value.replace(/^\s+|\s+$/g,'');
}

/** Trim both sides of a string */
function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}

//////////////////// TREE //////////////////////////////////////////////////////

/**
 * Ajax function to toggle a child in the tree's view
 */
function toggleView(div_id){
    return changeView(div_id,false);
}

/**
 * Ajax function to toggle a child in the tree's view
 * Could force the opening by passing second parameter
 */
function changeView(div_id, force){
    $$('.tree-children .tree-icon').each(function(img){
	    img.src = IMG+'/tree/folder' + (img.src.include('disabled') ? 'disabled' : '') + '.png';
	});
    var childs = $$('#' + div_id +' > .tree-children');   
    var image = $$('#'+div_id+' .tree-expand-icon');
    image[0].src = IMG+'/tree/'+ (image[0].src.include('L') ? 'L' : 'T') + (childs[0]!=null ? ((!childs[0].visible() || force) ? 'minus' : 'plus') : '') +".png";
    var folder = $$('#'+div_id+' .tree-icon')[0];
    var disabled = folder.src.include('disabled') ? 'disabled' : '';
    folder.src = IMG+'/tree/folder' + disabled + ((force || !$$('#'+div_id+' .tree-children')[0].visible()) ? '_open' : '') + '.png';
    if (force) childs.invoke('show');
    else childs.invoke('toggle');
}

//////////////////// SEARCH RESULT TOGGLER /////////////////////////////////////

function displaySearchResult(lang){
    $$("#resultDocs a.lang").each(function(elem){
	    if (elem.getAttribute("alt") == lang) {
		elem.addClassName("selected");
	    } else {
		elem.removeClassName("selected");
	    }
	});
    $$("#resultDocs ul").each(function(elem){
	    elem.addClassName("hidden");
	});
    $('resultDoc_'+lang).removeClassName("hidden");
}

//////////////////// IMAGE RESIZING /////////////////////////////////////

// window.onresize = resizeImages;

function resizeImages() {
    log("Start resizeImages");
    if (!document.getElementsByTagName){ return; }
    var imgs = $$('a[rel] img');
    var contentWidth = $('mainContent').getWidth();
    // loop through all img tags
    for (var i=0; i<imgs.length; i++){
	var img = imgs[i];
	$(img).style.width = "auto";
	if (img.getAttribute("src")){
	    // img.onclick = function () {showLightbox(this,false); return false;}
	    $(img).style.width = $(img).width > contentWidth || $(img).width == 0 ? (contentWidth-10)+"px" : $(img).width+"px";
	}
    }
    log("End resizeImages");
}

function resizeImage(event) {
    var width = $('leftMenu').getWidth();
    var arrayPageSize = getPageSize();
    var contentWidth = arrayPageSize[2] - width;
    var image = event.element();
    if (image.width > contentWidth) image.style.width = (contentWidth-100)+"px";
    if (eval(image.width) == 0) image.style.width = "auto";
    log("image.width="+image.width);
    event.stop();
}

function log(str) {
    if (typeof(console) != "undefined") console.log(str);
}

//
//  getPageSize()
//
function getPageSize() {

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
	xScroll = window.innerWidth + window.scrollMaxX;
	yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	xScroll = document.body.scrollWidth;
	yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	xScroll = document.body.offsetWidth;
	yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) {	// all except Explorer
	if(document.documentElement.clientWidth){
	    windowWidth = document.documentElement.clientWidth;
	} else {
	    windowWidth = self.innerWidth;
	}
	windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	windowWidth = document.documentElement.clientWidth;
	windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
	windowWidth = document.body.clientWidth;
	windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
	pageHeight = windowHeight;
    } else {
	pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
	pageWidth = xScroll;
    } else {
	pageWidth = windowWidth;
    }

    return [pageWidth,pageHeight,windowWidth,windowHeight];
}

//////////////////// GLOSSARY /////////////////////////////////////

function loadGlossary(){ updateGlossary({'idx':'A'}); dialog.centerBox.defer(); }

function updateGlossary(params) {
    var idx = $H(params).get('idx');
    $$(".glossary").each(function(elem){
	    var label = elem.select("label").first();
	    elem.style.display= label.innerHTML.startsWith(idx) ? 'block': 'none';
	});
    updateIndexer(idx,'updateGlossary');
    $('dialog').setStyle({'width':'700px'});
}

function updateIndexer(idx,fct) {
    $$("#indexer *").each(function(elem){
	    if (elem.innerHTML.startsWith(idx)) elem.replace('<span class="selec">['+idx+']</span>');
	    else if (elem.innerHTML.startsWith('[')) {
		var letter = elem.innerHTML.substring(1,2);
		if (letter != idx) elem.replace('<a href="#" onclick="'+fct+'({\'idx\':\''+letter+'\'})">'+letter+'</a>');
	    }
	});
}

//////////////////// TABS /////////////////////////////////////
function showTab(container, id) {
    $$('#'+container+'_tabs li').invoke('removeClassName', 'selected');
    $(id+'_tab').addClassName('selected');
    $$('#'+container+' .toggable').invoke('removeClassName', 'selected');
    $(id).addClassName('selected');
}

//////////////////// LEFT MENU PANELS ////////////////////////
function togglePanel(id) {
    $(id).toggle();
    var src = $(id+'_toggler').src;
    if (src.endsWith('reduce_links.gif'))
	$(id+'_toggler').src = "../ui/images/grow_links.gif";
    else $(id+'_toggler').src = "../ui/images/reduce_links.gif";
}

