YAHOO.namespace('core');

YAHOO.namespace('core.management');
YAHOO.namespace('core.prompt');
YAHOO.namespace('core.message');
YAHOO.namespace('core.event');
YAHOO.namespace('core.formatter');
YAHOO.namespace('core.validator');
YAHOO.namespace('core.ui');


// **** GLOBAL objects ****
$ = YAHOO.util.Dom.get;
$D = YAHOO.util.Dom;
$E = YAHOO.util.Event;
$J = YAHOO.lang.JSON;

function elObj(elementId, elementIndex, elementParam, elementObject) {
   	this.elementId = elementId;
   	this.elementIndex = elementIndex;
   	this.elementParam = elementParam;
   	this.elementObject = elementObject;
}

String.prototype.lpad=function(n,s) {
	if(n<0) return;
	if(typeof s=='undefined') s=' ';
	var res=this;
	while(res.length<n) res=s+res;
		return res;
	}


String.prototype.ucFirst = function () {
	return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};



Array.prototype.contains = function (elem) {
  var i;
  for (i = 0; i < this.length; i++) {
    if (this[i] == elem) {
      return true;
    }
  }

  return false;
};

Date.prototype.toTradrzDate = function() {
	
	var year = this.getFullYear();
	var month = this.getMonth();
	var day = this.getDate();
	
	month = parseInt(month)+1;
	month = month.toString().lpad(2, '0');
	day = day.toString().lpad(2, '0');
		
	return year + '-' + month + '-' + day;
}


// **** FORMS Utilities ****
var FormUtil = new Object;

FormUtil.focusOnFirst = function () {
	if (document.forms.length > 0) {
		for (var i=0; i < document.forms[0].elements.length; i++) {
			var oField = document.forms[0].elements[i];
			if ((oField.type) && (oField.type != 'hidden')) {
				oField.focus();
				return;
			}
		}
	}
};

FormUtil.addOption = function(oListbox, sDesc, sValue, bSelected) {
	var oOption = document.createElement('option');
	oOption.appendChild(document.createTextNode(sDesc));
	if (arguments.length >= 3) {
		oOption.setAttribute('value', sValue);
	}
	// 4 paramère ajouté pour compatibilité IE6
	if (bSelected) {
		oOption.setAttribute('selected', 'selected');
	}
	oListbox.appendChild(oOption);
};

FormUtil.removeOption = function(oListbox, mValue) {
	for (var i=1; i < oListbox.options.length; i++) {
		if (oListbox.options[i].value == mValue) {
			oListbox.remove(i);
			return;
		}
	}
};

FormUtil.getOptionVal = function(selId) {
	var oSel = $(selId);
	var mVal = oSel.options[oSel.selectedIndex].value;
	
	return mVal;
};


function isValidEmail(sText) {
	var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+$/;
	return reEmail.test(sText);
}


// **** i18n functions *****
function _(s) {
	if (typeof(i18n)!='undefined' && i18n[s]) {
		return i18n[s];
	}
	return s;
}


// **** FEEDBACK functions *****
function hideFeedBack(el) {
    if (!el) {
    	el = 'feedbackManager';
    }
    // Ligne nécessaire pour le bon fonctionnement de curvyCorner
    YAHOO.util.Dom.setStyle(el, 'overflow', 'hidden');
    
    var attributes = {
    	height: { to: 0 }
    };
    var anim = new YAHOO.util.Anim(el, attributes);
    anim.animate();
    setTimeout("YAHOO.util.Dom.removeClass('"+el+"', 'okFeedBack');", 1100);
    setTimeout("YAHOO.util.Dom.removeClass('"+el+"', 'koFeedBack');", 1100);
    setTimeout("YAHOO.util.Dom.removeClass('"+el+"', 'msgFeedBack');", 1100);
    setTimeout("YAHOO.util.Dom.get('"+el+"').innerHTML = '';", 1100);
    setTimeout("YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('"+el+"'), 'height', 'auto');", 1100);
    // Ligne nécessaire pour le bon fonctionnement de curvyCorner
    setTimeout("YAHOO.util.Dom.setStyle('"+el+"', 'overflow', 'visible');", 1100);
}

function defaultSuccessAction(responseText) {
	var oFeedBack = YAHOO.util.Dom.get('feedbackManager');
	var response = YAHOO.lang.JSON.parse(responseText);

	oFeedBack.innerHTML = response.message;
	
	setCssFeedBack(response.status, null, true);
	setTimeout("hideFeedBack()", 5000);
}

function setCssFeedBack(status, id, round) {
    if (!id) {
		id = 'feedbackManager';
	}
	if (round) {
		round = true;
	}
	
	var oFeedBack = YAHOO.util.Dom.get(id);
    switch (status) {
    	case 'ok':
        YAHOO.util.Dom.addClass(oFeedBack, 'okFeedBack');
      	break;

      	case 'ko':
      	YAHOO.util.Dom.addClass(oFeedBack, 'koFeedBack');
      	break;

      	case 'message':
      	YAHOO.util.Dom.addClass(oFeedBack, 'msgFeedBack');
      	break;
    }
    
    var bIsIE = false;
    
	if (isIE == '0') {
		var bIsIE = false;
	} else {
		var bIsIE = true;
	}
	
	//if (round && ieVersion != 6) {
    /*
    if (round && !bIsIE) {
    	roundCorners(id, 5);	
    } else {
    	YAHOO.util.Dom.setStyle(id, 'padding', '5px');
    }
    */ 
}

function feedBackMessage(sMessageText, round) {
	var oFeedBack = YAHOO.util.Dom.get('feedbackManager');

    oFeedBack.innerHTML = sMessageText;
    setCssFeedBack('message');
    setTimeout("hideFeedBack()", 5000);
    
    if (round) {
    	roundCorners('feedbackManager', 5);	
    } else {
    	YAHOO.util.Dom.setStyle('feedbackManager', 'padding', '5px');
    }
}


function flashField(id, color) {
	if (!color) {
		color = 'orange';
	}
	YAHOO.util.Event.onContentReady(id, function(){
		YAHOO.util.Dom.setStyle(id, 'background-color', color);
	});
}


// **** HEADER functions *****
function changeLanguage() {
	var selLang = YAHOO.util.Dom.get('selLanguage');
	var newLang = selLang.options[selLang.selectedIndex].value;
			
	location.href='/'+newLang+'/';
}


// **** IE compatibility *****
function ieHover(e, o) {
	var oEl = YAHOO.util.Dom.get(o.elementId);
	var currentBg = YAHOO.util.Dom.getStyle(oEl, 'background-color');
	
	switch (e.type) {
		case 'mouseover':
		YAHOO.util.Dom.setStyle(oEl, 'background-color', o.elementIndex);
		break;
		
		case 'mouseout':
		YAHOO.util.Dom.setStyle(oEl, 'background-color', o.elementParam);
		break;
	}
}


function registerIeHover(id, overColor, outColor) {
	YAHOO.util.Event.addListener(id, 'mouseover', ieHover, new elObj(id, overColor, outColor));
	YAHOO.util.Event.addListener(id, 'mouseout', ieHover, new elObj(id, overColor, outColor));
}


function resizeYuiImageButton(id) {
	if (!isIE) YAHOO.util.Dom.setStyle(id, 'width', '42px');
}


// **** Round corners *****
function roundCorners(id, radNb) {
	var settings = {
    	tl: { radius: radNb },
      	tr: { radius: radNb },
      	bl: { radius: radNb },
      	br: { radius: radNb },
      	antiAlias: true,
      	autoPad: false
    };

	var divObj = YAHOO.util.Dom.get(id);
    var cornersObj = new curvyCorners(settings, divObj);
    cornersObj.applyCornersToAll();
}


// **** Misceleanous *****
function removeElement(id) {
	var el = YAHOO.util.Dom.get(id);
	el.parentNode.removeChild(el);	
}

function setShowHide(divId, triggerId) {
	
	var oDiv = new YAHOO.widget.Module(divId);
	//oDiv.render();
	oDiv.hide();
	oDiv.nextAction = 'show';
	
	var oImg = YAHOO.util.Dom.get(triggerId);
	
	YAHOO.util.Event.addListener(triggerId, 'click', function(){
		
		if (oDiv.nextAction == 'show') {
			oDiv.show();
			oDiv.nextAction = 'hide';
			oImg.src = '/img/global/down.png';
		} else {
			oDiv.hide();
			oDiv.nextAction = 'show';
			oImg.src = '/img/global/next.png';
		}
		
	});
}


// **** Element Management *****



YAHOO.core.management.newElement = function(elName) {
	location.href='/'+i18n.USER_LANGUAGE+'/'+elName+'/index/id/new';
}


YAHOO.core.management.cbDelete = {
	success: function(o) {
		defaultSuccessAction(o.responseText);
		var oSel = YAHOO.util.Dom.get('selElementList');
		oSel.remove(oSel.selectedIndex);
			
		for (var i=0; i < oSel.length; i++) {
			if (oSel[i].value == elementId) {
				oSel[i].selected == true;
			}
		}
		
	},
	
	failure: function(o) {
		YAHOO.util.Dom.get("feedbackManager").innerHTML = _('Error in the function')+' deleteElement';
	},
	
	cache:false
};


YAHOO.core.management.deleteElement = function(elName) {
	
	var oSel = YAHOO.util.Dom.get('selElementList');
	if (oSel) {
		var sName = oSel.options[oSel.selectedIndex].text;
		var iId = oSel.options[oSel.selectedIndex].value;
	
		if (confirm(_('Are you sure you want to delete the ')+_(elName)+' "'+ sName +'" ?')) {
			if (iId == 0) {
				location.href='/'+i18n.USER_LANGUAGE+'/'+elName+'/index/id/0/';
			} else if (iId == elementId) {
				// Si le portfolio est le même que celui affiché on recharge la page
				location.href='/'+i18n.USER_LANGUAGE+'/'+elName+'/delete/id/'+iId+'/';				
			} else {
				var url = '/'+i18n.USER_LANGUAGE+'/'+elName+'/delete/id/' + iId + '/';
				var connectionObject = YAHOO.util.Connect.asyncRequest('GET', url, YAHOO.core.management.cbDelete);
				YAHOO.util.Dom.get('feedbackManager').innerHTML = "<img src='/img/global/ajaxBusy.gif'>";
			}
		} else {
			return;
		}
	} else {
		var message = {"message":_('You can delete an element only if it has been saved before.'),"status":"ko"};
		defaultSuccessAction(YAHOO.lang.JSON.stringify(message));
	}
}


YAHOO.core.management.copyElement = function(elName) {
	
	var oSel = YAHOO.util.Dom.get('selElementList');
	if (oSel) {
		var sName = oSel.options[oSel.selectedIndex].text;
		var iId = oSel.options[oSel.selectedIndex].value;
	
		if (confirm(_('Are you sure you want to copy the ')+_(elName)+' "'+ sName +'" ?')) {
			if (iId == 0) {
				alert(_('You can copy an element only if it has been saved before'));
				return;
			} else {
				var url = '/'+i18n.USER_LANGUAGE+'/'+elName+'/copy/id/' + iId + '/';
				var connectionObject = YAHOO.util.Connect.asyncRequest('GET', url, YAHOO.core.management.cbCopy);
				YAHOO.util.Dom.get('feedbackManager').innerHTML = "<img src='/img/global/ajaxBusy.gif'>";
			}
		} else {
			return;
		}
	} else {
		var message = {"message":_('You can copy an element only if it has been saved before.'),"status":"ko"};
		defaultSuccessAction(YAHOO.lang.JSON.stringify(message));
	}
}


YAHOO.core.management.cbCopy = {
	success: function(o) {
		defaultSuccessAction(o.responseText);
		response = YAHOO.lang.JSON.parse(o.responseText);
		var oListbox = YAHOO.util.Dom.get('selElementList');
		FormUtil.addOption(oListbox, response.name, response.id, true);
		oListbox.selectedIndex = (oListbox.length)-1;
	},
	
	failure: function(o) {
		YAHOO.util.Dom.get("feedbackManager").innerHTML = _('Error in the function')+' copyElement';
	},
	
	cache:false
};


var originalStateChanged = false;

function applyStateChangeToButton(targetName, targetStatus) {
	if (YAHOO.util.Dom.inDocument(targetName)) {
		// La méthode appelante veut mettre le flag à true
		if (targetStatus) {
			// Le flag est déjà à true
			if (originalStateChanged) {
				return;
			// Le flag était à false
			} else {
				originalStateChanged = targetStatus;
				var oSpan = YAHOO.util.Dom.get(targetName);
				YAHOO.util.Dom.setStyle(oSpan, 'border', '2px solid red');
			}
		// La méthode appelante veut mettre le flag à false
		} else {
			// Le flag est à true
			if (originalStateChanged) {
				originalStateChanged = targetStatus;
				var oSpan = YAHOO.util.Dom.get(targetName);
				YAHOO.util.Dom.setStyle(oSpan, 'border', '');
			// Le flag était déjà à false
			} else {
				return;
			}
		}
	} else {
		return;
	}
}

// **** Common dialogs ****
YAHOO.core.prompt.simplePromptValidateInput = function() {
	// Placeholder to allow custom validation by redifining the function
}

YAHOO.core.prompt.simplePromptOkHdl = function() {
	YAHOO.core.prompt.simplePromptValidateInput();
	this.submit();
}
YAHOO.core.prompt.simplePromptCancelHdl = function() {
	this.cancel();
}
YAHOO.core.prompt.simplePromptButtons = [ 
	{ text:"OK", handler:YAHOO.core.prompt.simplePromptOkHdl, isDefault:true },
	{ text:"Cancel", handler:YAHOO.core.prompt.simplePromptCancelHdl } 
];
YAHOO.core.prompt.oSimplePrompt;

YAHOO.core.prompt.simplePrompt = function(question, cbSuccess, cbFailure, width) {

	// Init question and answer
	YAHOO.util.Dom.get('dlgSimplePromptQuestion').innerHTML = question;
	if (width) YAHOO.util.Dom.setStyle('dlgSimplePrompt', 'width', width.toString()+'px');
	if (width) YAHOO.util.Dom.setStyle('dlgSimplePrompt-nameParam', 'width', (width-100).toString()+'px');
	
	// Initialisation du dialogue d'ajout de paramètre
	var oDlg = new YAHOO.widget.Dialog('dlgSimplePrompt', {modal: true, fixedcenter: true, visible: false});
	oDlg.cfg.queueProperty('buttons', YAHOO.core.prompt.simplePromptButtons);
	oDlg.callback.success = cbSuccess; 
	oDlg.callback.failure = cbFailure;
		
	oDlg.render();
	oDlg.hide();
	
	YAHOO.core.prompt.oSimplePrompt = oDlg;
}

YAHOO.core.message.oSimpleMessage;

YAHOO.core.message.simpleMessage = function(msg, title) {
	oDialog = new YAHOO.widget.SimpleDialog("dlg", { 
		width: "40em",
		effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25}, 
		fixedcenter:true,
		modal:true,
    	visible:false,
		draggable:false
	});
	oDialog.setHeader(title);
	oDialog.setBody(msg);
	oDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_INFO);
	
	var handleOk = function() {
		this.hide();
	}
	
	var myButtons = [ { text:"Ok", handler:handleOk } ];
	oDialog.cfg.queueProperty("buttons", myButtons);
	
	oDialog.render(document.body);
	oDialog.show();
	
	YAHOO.core.message.oSimpleMessage = oDialog;
}


YAHOO.core.message.loadingPanel = function(conf){
    conf = conf == undefined ? new Array() : conf;
    conf.id = conf.id == undefined ? 'yuiLoadingPanel':confi.id;
    conf.header = conf.header == undefined ? 'Loading, please wait...':conf.header;
    conf.width = conf.width == undefined ? '240px':conf.width;
    this.conf = conf;
    this.cancelEvent = new YAHOO.util.CustomEvent("cancelEvent", this);
    this.init();
	
};

YAHOO.core.message.loadingPanel.prototype = {
    init:function(){
        var loadingPanel = new YAHOO.widget.Panel(this.conf.id,{
            width:this.conf.width,
	    	fixedcenter:true,
            close:false,
            draggable:false,
            modal:true,
            visible:false
        });
    
       loadingPanel.setBody(this.conf.header + 
               '<img src="/img/rel_interstitial_loading.gif" />');
               loadingPanel.render(document.body);
               $D.addClass(loadingPanel.id, 'tcc_lightboxLoader');
               $D.setStyle(loadingPanel.body, 'text-align', 'center');
               $D.addClass(document.body, 'yui-skin-sam');
        this.loadingPanel = loadingPanel;
    },
    show:function(text, idToHide){

        if(text != undefined){
            this.loadingPanel.setHeader(text);
        }else{
            this.loadingPanel.setHeader(this.conf.header);
        }
        this.loadingPanel.show();

        // In IE, the flash chart will *always* be over the loading panel.
        // NO MATTER WHAT!! So we hide it while the loading panel is deployed
        if (idToHide != undefined) {
            if ($D.inDocument(idToHide)) {
                var oHidden = $(idToHide);

                var oModuleHidden = new YAHOO.widget.Module(oHidden);
                oModuleHidden.hide();
            }
        }
    },
    hide:function(idToHide){
        if (idToHide != undefined) {
            if ($D.inDocument(idToHide)) {
                var oHidden = $(idToHide);
                
                var oModuleHidden = new YAHOO.widget.Module(oHidden);
                oModuleHidden.show();
            }
        }

        this.loadingPanel.hide();
    }
};


// **** Events management ****
YAHOO.core.event.fire = function (element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}


// **** Core datatable formatters
YAHOO.core.formatter.currency = function(elCell, oRecord, oColumn, oData)
{
	if (oData === null) {
		elCell.innerHTML = '';
		return;
	}

	elCell.innerHTML = YAHOO.util.Number.format(oData, {
		prefix: i18n.LOCAL_MONETARY_PREFIX,
		decimalPlaces: i18n.LOCAL_DECIMAL_PLACES,
		decimalSeparator: i18n.LOCAL_DECIMAL_SEPARATOR,
		thousandsSeparator: i18n.LOCAL_THOUSAND_SEPARATOR,
		suffix: i18n.LOCAL_MONETARY_SUFIX
	});

	YAHOO.util.Dom.setStyle(elCell, 'text-align', 'right');
};

YAHOO.core.formatter.currencyChange = function(elCell, oRecord, oColumn, oData)
{
	if (oData === null) {
		elCell.innerHTML = '';
		return;
	}

	fMoney = parseFloat(oData);

	if (fMoney < 0) {
		YAHOO.util.Dom.setStyle(elCell, 'color', 'red');
	} else {
		YAHOO.util.Dom.setStyle(elCell, 'color', 'green');
	}

	elCell.innerHTML = YAHOO.util.Number.format(oData, {
		prefix: i18n.LOCAL_MONETARY_PREFIX,
		decimalPlaces: i18n.LOCAL_DECIMAL_PLACES,
		decimalSeparator: i18n.LOCAL_DECIMAL_SEPARATOR,
		thousandsSeparator: i18n.LOCAL_THOUSAND_SEPARATOR,
		suffix: i18n.LOCAL_MONETARY_SUFIX
	});

	YAHOO.util.Dom.setStyle(elCell, 'text-align', 'right');
};

YAHOO.core.formatter.integer = function(elCell, oRecord, oColumn, oData)
{
	if (oData === null) {
		elCell.innerHTML = '';
		return;
	}

	elCell.innerHTML = YAHOO.util.Number.format(oData, {
		thousandsSeparator: i18n.LOCAL_THOUSAND_SEPARATOR
	});

	YAHOO.util.Dom.setStyle(elCell, 'text-align', 'right');
}

YAHOO.core.formatter.floatNum = function(elCell, oRecord, oColumn, oData)
{
	if (oData === null) {
		elCell.innerHTML = '';
		return;
	}

	elCell.innerHTML = YAHOO.util.Number.format(oData, {
		thousandsSeparator: i18n.LOCAL_THOUSAND_SEPARATOR,
		decimalSeparator: i18n.LOCAL_DECIMAL_SEPARATOR
	});

	YAHOO.util.Dom.setStyle(elCell, 'text-align', 'right');
}

YAHOO.core.formatter.percentageChange = function(elCell, oRecord, oColumn, oData)
{
	if (oData == 'skip') {
		elCell.innerHTML = '';
		return;
	}

	fPct = parseFloat(oData);

	if (fPct < 0) {
		YAHOO.util.Dom.setStyle(elCell, 'color', 'red');
	} else {
		YAHOO.util.Dom.setStyle(elCell, 'color', 'green');
	}

	elCell.innerHTML = YAHOO.util.Number.format(oData, {
		prefix: '',
		decimalPlaces: i18n.LOCAL_DECIMAL_PLACES,
		decimalSeparator: i18n.LOCAL_DECIMAL_SEPARATOR,
		thousandsSeparator: i18n.LOCAL_THOUSAND_SEPARATOR,
		suffix: '%'
	});

	YAHOO.util.Dom.setStyle(elCell, 'text-align', 'right');
};

YAHOO.core.formatter.percentage = function(elCell, oRecord, oColumn, oData)
{
	if (oData == 'skip') {
		elCell.innerHTML = '';
		return;
	}

	elCell.innerHTML = YAHOO.util.Number.format(oData, {
		prefix: '',
		decimalPlaces: i18n.LOCAL_DECIMAL_PLACES,
		decimalSeparator: i18n.LOCAL_DECIMAL_SEPARATOR,
		thousandsSeparator: i18n.LOCAL_THOUSAND_SEPARATOR,
		suffix: '%'
	});

	YAHOO.util.Dom.setStyle(elCell, 'text-align', 'right');
};


// **** Core UI components
YAHOO.core.ui.yuiImgButton = function(id, imgSrc, label, callback) {
    var oBtn = new YAHOO.widget.Button(id, {label:'<span><img src="'+imgSrc+'"  class="yuiBtnImage" alt="'+label+'"><span class="yuiBtnText">'+label+'</span></span>'});
    if (callback) {
        oBtn.addListener('click', callback);
    }
}

YAHOO.core.ui.tourAnim = function(id) {
    animTryUs = function() {
        YAHOO.util.Event.onAvailable(id, function() {
            // Get handle on the target div
            var oDiv = YAHOO.util.Dom.get(id);

            //define the points object
            var moveObjRight = {
                points: {by: [20, 0]}
            };
            var moveObjLeft = {
                points: {by: [-40, 0]}
            };
            var moveObjBack = {
                points: {by: [20, 0]}
            };

            //define and run the animations
            var animLeft = new YAHOO.util.Motion(oDiv, moveObjLeft, 0.5, YAHOO.util.Easing.backBoth);
            var animRight = new YAHOO.util.Motion(oDiv, moveObjRight, 0.5, YAHOO.util.Easing.backBoth);
            var animBack = new YAHOO.util.Motion(oDiv, moveObjBack, 0.5, YAHOO.util.Easing.backBoth);

            animRight.animate();
            animRight.onComplete.subscribe(function(){
                animLeft.animate();
                animLeft.onComplete.subscribe(function(){
                    animBack.animate();
                });
            });
        });
    }

    setTimeout("animTryUs();", 300);
}


// **** Inline Edition ****

function editTitle(e, o) {
	var oMain = YAHOO.util.Dom.get(o.elementObject);
	var oTitle = YAHOO.util.Dom.get(o.elementId);
	var sOrgTitle = oTitle.innerHTML;
	
	// Remove org title
	oTitle.parentNode.removeChild(oTitle);
	
	// Add input for the new title
	var oInput = document.createElement('input');
	oInput.type = 'text';
	oInput.id = 'inputTitleId';
	oInput.value = sOrgTitle;
	YAHOO.util.Dom.addClass(oInput, 'inlineEditor');
	oMain.appendChild(oInput); 
	
	// Add save button
	var oSaveBtn = document.createElement('button');
	oSaveBtn.innerHTML = _('Save');
	YAHOO.util.Dom.addClass(oSaveBtn, 'inlineEditorSaveBtn');
	oMain.appendChild(oSaveBtn);
	
	// Add separation text between 2 buttons
	var oSeparator = document.createElement('span');
	YAHOO.util.Dom.addClass(oSeparator, 'inlineEditorSeparator');
	var sOr = document.createTextNode(' '+_('or').toUpperCase()+' ');
	oSeparator.appendChild(sOr);
	oMain.appendChild(oSeparator);
	
	// Add cancel button
	var oCancelBtn = document.createElement('button');
	oCancelBtn.innerHTML = _('Cancel');
	YAHOO.util.Dom.addClass(oCancelBtn, 'inlineEditorCancelBtn');
	oMain.appendChild(oCancelBtn);
	
	// Add Listeners
	YAHOO.util.Event.addListener(oSaveBtn, 'click', o.elementIndex);
	YAHOO.util.Event.addListener(oCancelBtn, 'click', o.elementParam, new elObj(oMain, null, sOrgTitle));
}


inlineEditor = function(id, paramName, module, controller, action) {
	
	function applyHover(id) {
		YAHOO.util.Event.addListener(id, 'mouseover', function(){
			el = YAHOO.util.Dom.get(this);
			YAHOO.util.Dom.setStyle(el, 'background-color', 'yellow');
		});
		YAHOO.util.Event.addListener(id, 'mouseout', function(){
			el = YAHOO.util.Dom.get(this);
			YAHOO.util.Dom.setStyle(el, 'background-color', '');
		});
	}
		
	function handleInline(e, o) {
		oMain = YAHOO.util.Dom.get(o.elementId);
		YAHOO.util.Event.purgeElement(oMain);
		YAHOO.util.Dom.setStyle(oMain, 'background-color', '');
		sOrgText = oMain.innerHTML;
		oMain.innerHTML = '';
		
		// Add input for the new title
		var oInput = document.createElement('input');
		oInput.type = 'text';
		oInput.id = 'input'+o.elementId;
		oInput.value = sOrgText;
		YAHOO.util.Dom.addClass(oInput, 'inlineEditor');
		oMain.appendChild(oInput); 
		
		// Add save button
		var oSaveBtn = document.createElement('button');
		oSaveBtn.innerHTML = _('Save');
		YAHOO.util.Dom.addClass(oSaveBtn, 'inlineEditorSaveBtn');
		oMain.appendChild(oSaveBtn);
		
		// Add separation text between 2 buttons
		var oSeparator = document.createElement('span');
		YAHOO.util.Dom.addClass(oSeparator, 'inlineEditorSeparator');
		var sOr = document.createTextNode(' '+_('or').toUpperCase()+' ');
		oSeparator.appendChild(sOr);
		oMain.appendChild(oSeparator);
		
		// Add cancel button
		var oCancelBtn = document.createElement('button');
		oCancelBtn.innerHTML = _('Cancel');
		YAHOO.util.Dom.addClass(oCancelBtn, 'inlineEditorCancelBtn');
		oMain.appendChild(oCancelBtn);
		
		// Add Listeners
		YAHOO.util.Event.addListener(oSaveBtn, 'click', handleInlineSave, new elObj(oMain));
		YAHOO.util.Event.addListener(oCancelBtn, 'click', handleInlineCancel, new elObj(oMain, null, sOrgText));
		
		
		// Subfunctions
		function restoreNode(oldNode, oldText) {
			newNode = document.createElement('span');
			newId = YAHOO.util.Dom.generateId(newNode);
			txtNewNode = document.createTextNode(oldText);
			newNode.appendChild(txtNewNode);
			oldNode.parentNode.replaceChild(newNode, oldNode);
			
			YAHOO.util.Event.purgeElement(oldNode);
			applyHover(newId);
		}
		
		function handleInlineSave(e, o) {
			sMainId = o.elementId.id;
			oIput = YAHOO.util.Dom.get('input'+sMainId);
			
			var url = '/'+module+'/'+controller+'/'+action+'/paramName/'+ paramName + '/paramVal/' + encodeURIComponent(oInput.value) + '/';
			var connectionObject = YAHOO.util.Connect.asyncRequest('POST', url, cbInlineSave);
		}
		
		var cbInlineSave = {
			success: function(o) {
				alert(YAHOO.lang.JSON.stringify(o));
			},
			
			failure: function(o) {
				alert('failure');
			},
			
			cache:false
			
		};
		
		function handleInlineCancel(e, o) {
			restoreNode(o.elementId, o.elementParam); 
			YAHOO.util.Event.addListener(newId, 'click', handleInline, new elObj(newId));
		}
		
	}
	
	YAHOO.util.Event.addListener(id, 'click', handleInline, new elObj(id));
	applyHover(id);
}


// **** COre validators
YAHOO.core.validator.standardDate = function (dateToTest) {
    var regex= '[0-9]{4}-(0[1-9]|1[0-2])-[0-3][0-9]';

    var rtn = dateToTest.match(regex);
    if (!rtn) {
        return false;
    } else {
        return true;
    }
}


// **** brower and OS detection ****
var isOpera = YAHOO.env.ua.opera,
	isSafari = YAHOO.env.ua.webkit, 
	isGecko = YAHOO.env.ua.gecko,
	isIE = YAHOO.env.ua.ie;

var ieVersion = YAHOO.env.ua.ie;

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

