
function isEmpty(oArray)
{
    if (oArray && oArray[0]) {
        return false;
    }
    return true;
}



function getAdPriceInfos()
{
    var annonceId = document.getElementById('annonce');
    var publishId = document.getElementById('PFC_id');
    var oObserved = document.getElementById('AN_detail_abrege');
    
    if (!publishId || !oObserved || !annonceId) {
        return false;
    }
    var charCount = oObserved.value;
    charCount = charCount.replace("\r\n", ' ');
    charCount = charCount.length;
    
    var aOptions = getOptions();
    
    // $publishChoiceId, $CharCount, $optionsId
    var data = {};
    data['PFC_id'] = publishId.options[publishId.selectedIndex].value;
    data['charCount'] = charCount;
    data['options'] = aOptions;
    data['annonce'] = annonceId.value;
    return data;
}








function updateAdPrice(data)
{
    var oAdPriceTable = document.getElementById('myPaperAdPrice');
    var tableTemplate = document.getElementById('tableTemplate');
    if (!oAdPriceTable || !tableTemplate) {
        return false;
    }
    
    var allRows = '';
    if (data['offre']) {
		var paperText = document.getElementById('paperText');
		var paperOptions = document.getElementById('paperOptions');
		var preview = document.getElementById('myPaperAdPreview');
		var infosTel = document.getElementById('previewInfosTel');

		// affichage des éléments presse
    	if (data['offre']['PFC_inclu_presse'] == 1) {
    		removeClass(paperText, 'hidden');
    		removeClass(paperOptions, 'hidden');
    		removeClass(preview, 'hidden');
    		removeClass(infosTel, 'hidden');
    		
        // cache les éléments presse
    	} else {
    		addClass(paperText, 'hidden');
    		addClass(paperOptions, 'hidden');
    		addClass(preview, 'hidden');
    		addClass(infosTel, 'hidden');
    	}
    	
    	
    	
        allRows += getAdPriceRow(data['offre']['PUFO_libelle'] + ' / ' + data['offre']['PFD_label'], 
                                 '', 
                                 1, 
                                 data['offre']['PFC_tarif']);
    }
    if (data['options']) {
        for (var i in data['options']) {
            allRows += getAdPriceRow(data['options'][i]['FOOP_libelle'], 
                                     '', 
                                     1, 
                                     data['options'][i]['FOOP_tarif']);
        }
    }
    if (data['extra'] && data['extra']['tarif']) {
    	if (!data['extra']['tarif']) {
    		data['extra']['tarif'] = 0;
    	}
    	if (!data['extra']['lignes']) {
    		data['extra']['lignes'] = 0;
    	}
    	if (!data['extra']['total']) {
    		data['extra']['total'] = 0;
    	}
        allRows += getAdPriceRow('Caractères suppl.', 
                                 (data['extra']['tarif']), 
                                 '&nbsp;', //data['extra']['lignes'], 
                                 data['extra']['total']);
    }
    
    var sTable = tableTemplate.innerHTML;
   
    sTable = sTable.replace(/\[total\]/g, data['total']);
    sTable = sTable.replace(/<tr>(\s*)<td>(\s*)rows(\s*)<\/td>(\s*)<\/tr>/i, allRows);
    oAdPriceTable.innerHTML = sTable;
    
} // end of "updateAdPrice()"



function getAdPriceRow(sLabel, sPrice, sQuantity, sTotalPrice)
{
    var sTmp = document.getElementById('tableRowTemplate');
    if (!sTmp) {
        alert('Template pour les lignes non trouvé');
        return '';
    }
    sTmp = sTmp.innerHTML;
    sTmp = sTmp.replace(/\[label\]/i, sLabel);
    sTmp = sTmp.replace(/\[price\]/i, sPrice);
    sTmp = sTmp.replace(/\[quantity\]/i, sQuantity);
    sTmp = sTmp.replace(/\[totalPrice\]/i, sTotalPrice);
	return sTmp;
}



function getOptions()
{
    var oOptions = document.getElementById('paperOptions');
    if (!oOptions) {
        return false;
    }
    
    var checked = [];
    oOptions = oOptions.getElementsByTagName('input');
    var j = 0;
    for (var i=0; i < oOptions.length; i++) {
    	//checked[j] = 0;
        if (oOptions[i].checked) {
            checked[j++] = oOptions[i].value;
        }
    }
    
    return checked;
}



function registerLimitObserver(sTarget, sObserved, limitChar, limitNewLine, limitCharPerLine)
{
    var oTarget   = document.getElementById(sTarget);
    var oObserved = document.getElementById(sObserved);
    if (!oTarget || !oObserved) {
        return false;
    }
    
    var charCount = oObserved.value;
    charCount = charCount.replace("\r\n", ' ');
    charCount = charCount.length;
    var tmp = limitChar - charCount;
    
    if (tmp > 0) {
        oTarget.innerHTML = tmp + ' caractères restants';
        if (limitNewLine > 0 && limitCharPerLine > 0) {
            oTarget.innerHTML += ' (et ' + limitNewLine + ' lignes d\'extra)';
        }
        
    // Si on a dépassé la limite principale, soit il reste des lignes en extra,
    // soit on a trop de caractères
    } else {
        if (limitNewLine > 0 && limitCharPerLine > 0) {
            tmp = tmp + (limitNewLine * limitCharPerLine);
            
            if (tmp > 0) {
                var lineLeft = Math.floor(tmp / limitCharPerLine);
                var text = 'limite principale atteinte ';
                //text += ', ' + (limitNewLine - lineLeft) + ' ligne suppl. ';
                text += '(' + lineLeft + ' lignes restantes)';
                oTarget.innerHTML = text;
                
            } else {
                oTarget.innerHTML = Math.abs(tmp) + ' caractères en trop (' + limitNewLine + ' lignes suppl. utilisées)';
            }
            
            
        } else {
            oTarget.innerHTML = Math.abs(tmp) + ' caractères en trop';
        }
    }
    
}






function updateFieldState(sId, bShow, bIsParent)
{
    var oTarget = document.getElementById(sId);
    if (!oTarget || !oTarget.parentNode) {
        return false;
    }
    if (bIsParent) {
        if (!oTarget.parentNode) {
            return false;
        }
        oTarget = oTarget.parentNode;
    }    
    if (bShow) {
        removeClass(oTarget, 'hidden');
    } else {
        addClass(oTarget, 'hidden');
    }
}




function registerEvent(sId, event, fn)
{
    var oTarget = document.getElementById(sId);
    if (!oTarget) {
        return false;
    }
    addListenner(oTarget, event, fn, true);
}


var ajaxTimer = {};
function registerAjaxEvent(sId, event, sPhpRoutine, fn, fnInit, wait)
{
    var oTarget = document.getElementById(sId);
    if (!oTarget) {
        return false;
    }
    var fnAction = function() { 
       oData = {};
        if (fnInit) {
            oData = fnInit();
        }
        if (oTarget.id && oTarget.options) {
            oData[oTarget.id] = oTarget.options[oTarget.selectedIndex].value;
        }
        oData['xhrAction'] = sPhpRoutine;
        
        // activation de la fonction indiquant le chargement des données
        //fn({'data': {0: {'label': 'chargement en cours...', 'id': 0}}});
        XHR_post(document.location.href, oData, fn);
    };
    
    if (wait) {
    	var waitForTimer = function() {
    		if (ajaxTimer[sPhpRoutine]) {
    			clearTimeout(ajaxTimer[sPhpRoutine]);
    		}
    		ajaxTimer[sPhpRoutine] = setTimeout(function() { fnAction(); return true; }, 300);
    	} // end of "waitForTimer()"
    	addListenner(oTarget, event, waitForTimer, true);
    	
    } else {
    	addListenner(oTarget, event, fnAction, true);
    }
    
    
}




/**
 * waitToUpdatePrice
 */
/*var adUpdatePriceTimer = null;
 function waitToUpdatePrice(e) {
    if (adUpdatePriceTimer) {
        clearTimeout(adUpdatePriceTimer);
    }
    adUpdatePriceTimer = setTimeout(function() { updateAdPrice(oField, e); return true; }, 300);
 } // end of "waitToSearch()"
*/



function initBeforeCall()
{
    return {'annonceId': 1};
} //  end of "initBeforeCall()"





function createFields(sZone, oInfos)
{
    var sField, sId, sName, i, j, valueId, valueLabel;
    var sColumn1 = '', sColumn2 = '', sOther = '';
    
    var iLimit = 0;
    for (i in oInfos['equipment']) {
        iLimit++;
    }
    iLimit = iLimit/2;
    //alert('iLimit=' + iLimit);
    
    for (i in oInfos['equipment']) {
        equipId    = oInfos['equipment'][i]['BIEQ_id'];
        equipLabel = oInfos['equipment'][i]['BIEQ_designation'];
        equipDesc  = oInfos['equipment'][i]['BIEQ_description'];
        equipType  = oInfos['equipment'][i]['BIEQ_type'];
        
        sField = '';
        sName = 'equipmentField[' + equipId + '][' + equipType + ']';
        sId   = 'equipmentField-' + equipId;
        var sClass = equipType;
        if (equipType == 'select' && !oInfos['values'][equipId]) {
        	sClass = 'text';
        }
        sField += '<div class="' + sClass + '">';
        
        sField += '<label for="' + sId + '">' + equipLabel + '</label>';
        if (equipType == 'select' && oInfos['values'][equipId]) {
            if (oInfos['values'][equipId]) {
                sField += '<select id="' + sId + '" name="' + sName + '">';
                sField += '<option value="0">...</option>';
                for (j in oInfos['values'][equipId]) {
                    valueId    = oInfos['values'][equipId][j]['BEV_id'];
                    valueLabel = oInfos['values'][equipId][j]['BEV_valeur'];
                    sField += '<option value="' + valueId + '">' + valueLabel + '</option>';
                }
                sField += '</select>';
            }
            
        } else if (equipType == 'textarea') {
            sField += '<textarea id="' + sId + '" name="' + sName + '"></textarea>';
            
        } else if (equipType == 'checkbox') {
        	sField += '<input type="hidden" id="' + sId + '-default" name="' + sName + '" value="0" />';
            sField += '<input type="checkbox" id="' + sId + '" name="' + sName + '" value="1" />';
            
        } else {
            sField += '<input type="text" id="' + sId + '" name="' + sName + '" value="" />';
        }
        
        if (equipDesc.length > 2) {
            sField += '<p>' + equipDesc + '</p>';
        }          
        sField += '</div>';
        
        if (equipDesc.length > 2) {
            sOther += sField;
        } else {
            if (i >= iLimit) {
                sColumn2 += sField;
            } else {
                sColumn1 += sField;
            }
        }
    } // end for
    
    var oZone = document.getElementById(sZone);
    var sHtml = ''
    if (sColumn1) {
        sHtml += '<div class="formColumn">';
        sHtml += sColumn1;
        sHtml += '</div>';
    }
    if (sColumn2) {
        sHtml += '<div class="formColumn withLeftMargin">';
        sHtml += sColumn2;
        sHtml += '</div>';
    }
    if (sOther) {
        sHtml += sOther;
    }
    oZone.innerHTML = sHtml;
    
} //  end of "createFields()"




function toggleDeck()
{
    var deck = document.getElementById('categoryDeck');
    if (!deck) {
        return false;
    }
    if (deck.className == 'compact') {
        removeClass(deck, 'compact');
    } else {
        addClass(deck, 'compact');
    }
    return false;
}





function restoreNoEdit() {
	if (this.value == '') {
		this.value = this.oldValue;
	}
}



function clearOnEdit() {
	if (this.value == this.oldValue) {
            this.value = '';
	}
}

