/**
 * 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;
/**
 * generic function for calling ajax.Updater
 * @return void
 */
function update(id,url,params) {
    new Ajax.Updater(id, url, {method:'post',parameters: params, 
		onLoading: $('load').show(), 
		onComplete: function() {		
		$('load').hide();
		initLightbox();
	    }});
}

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

/**
 * Get a Board AND set the status Bar
 * @param action : one of the seePJ, userBoard, modWG action
 * @param obj : obj identifier or null if no one given
 * @param menu1 : the main tab menu to display
 * @param menu2 : the admin tab menu to display
 */
function getBoard(action, obj, menu1, menu2) {
    var ob = (obj   == null) ? "" : "&ob="+obj;
    var m1 = (menu1 == null) ? "" : "&m1="+menu1;
    var m2 = (menu2 == null) ? "" : "&m2="+menu2;
    if (action == 'thema') changeView("ptree-"+obj,true);
    //update('status',AJAX+"?special=status&a="+action+ob+m1+m2);
    update('mainContent',AJAX+"?a="+action+ob+m1+m2);
}

/**
 * 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',
		onLoading: $('load').show(),
		onComplete: function() {		
		$('load').hide();
		$('links').show();
		$('linklabel').update(text);
	    }});    
}

/**
 * Get the doc relatively to a descriptor
 * @param label : the descriptor
 */
function getDescriptor(label) {
    update('descriptorContent',AJAX+"?a=descriptor&label="+label, 
	   {method:'get', onComplete:$('descriptor').show()});
}

/**
 * Get a Document
 * @param doc_id : document identifier
 * @param lang : the language of the document to display
 */
function getDocument(doc_id, lang) {
    // log("Start getDocument");
    var doc_id = (doc_id   == null) ? "" : "&ob="+doc_id;
    var lang = (lang == null) ? "" : "&m1="+lang;
    update('doc',AJAX+"?a=document"+doc_id+lang);
    // log("End getDocument");
}

/** 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 'document' :
    case 'newVR' :
    case 'firstVR' :
	$(form).action = "index.php";
	$(form).submit();
	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');
}

/////////// DOCUMENT VERSION TREE //////////////////////////////////////////////

/**
 * Ajax function to toggle a child in the document version tree's view
 */
function changeVersionView(div_id){
    var childs = $$('#' + div_id +' > .version-tree-children');
    var image = $$('#'+div_id+' .tree-expand-icon');
    image[0].src = IMG+'/tree/'+ (image[0].src.include('L') ? 'L' : 'T') + ((!childs[0].visible()) ? 'min' : 'pl') + 'us.png';
    childs.invoke('toggle');
}

/**
 * Ajax function to toggle all child of the document version tree view
 */
function expandTree(deploy) {    
    $('version-tree-root').src = IMG+'/tree/i'+((deploy)?'min':'pl')+'us.png';
    $('version-tree-root').writeAttribute('onclick', 'expandTree('+!deploy+');');
    var childs = $$('#version-tree > .version-tree-children');
    var descendants = $$('#version-tree .version-tree-children');
    var image = $$('#version-tree .tree-expand-icon');
    image.each(function(img) {
	    sign = img.src.include('L') ? 'L' : 'T';
	    img.src = IMG+'/tree/'+ sign + ((deploy) ? 'min' : 'pl') + 'us.png';
	});
    if (deploy) descendants.invoke('show'); else descendants.invoke('hide');
    childs.invoke('show');
}

//////////////////// ALTERNATIVE SELECT /////////////////////////////////////////

function checkAll(id) { selectOption(id,true); }

function uncheckAll(id)  { selectOption(id,false); }

function selectOption(id,booleen) {
    var select = document.getElementById(id);
    for (var j=0, m=select.length; j<m; j++)
        select.options[j].selected = booleen;
}

//////////////////// SEARCH POPUP /////////////////////////////////////

function openSearchPopup(lang){
    var msg = "";
    switch(lang) {
    case "fr":
	msg = "\nLa recherche avancée n'est pas encore disponible...\n";
	break;
    case "es":
	msg = "\nBúsqueda no está disponible todavía...\n";
	break;

    case "en":
    default:
	msg = "\nAdvanced search is not yet avalaible...\n";
	break;
    }    
    alert(msg);
}

//////////////////// 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');
}
