﻿//------------------------------------------------------------------------------------------------------------------
// Globals
//------------------------------------------------------------------------------------------------------------------

var PE_ObjProp;
var PE_CalendarId;
var PE_PropertiesCol;
var PE_doPush;
var PE_widthWnd = 260, PE_heightWnd = 50;
var nt = 0;

//------------------------------------------------------------------------------------------------------------------
// Base functions
//------------------------------------------------------------------------------------------------------------------

function radCalendar_EditDateProps(e, day, month, year, calendarId) {
    var d = new Date(year, month, day);
    var pX = getMouseX(e);
    var pY = getMouseY(e);
    PE_CalendarId = calendarId;
    var dayProps = document.getElementById(calendarId + "_DateProperties_").value;
    PE_doPush = true;
    if (dayProps != "") {
        PE_PropertiesCol = eval('(' + dayProps + ')');
        for (i = 0; i < PE_PropertiesCol.length; i++) {
            if (PE_PropertiesCol[i].dat == DateToString(day, month, year)) {
                PE_doPush = false;
                radPropertyEditor(PE_PropertiesCol[i], pX, pY, "addItemToJson", "returnToInitSelect"); 
                break;
            }
        }
    }
    if (PE_doPush) {
        var objToAdd = eval('(' + document.getElementById(calendarId + "_DatePropertiesInit_").value + ')');
        objToAdd.dat = DateToString(day, month, year);
        radPropertyEditor(objToAdd, pX, pY, "addItemToJson", "unselectDateInCal");
    }
}

function radPropertyEditor(strProp,x,y,prmFonctionEnd,prmFonctionCanc) {
    var wnd = radopen(null, "propEdt");
    var wndName = wnd.get_name();
    if (document.getElementById("divPropEdit") != null) {
        document.getElementById("divPropEdit").parentNode.removeChild(document.getElementById("divPropEdit"));
    }
    var ele = document.createElement("div");
    ele.setAttribute("id", "divPropEdit");
    //ele.innerHTML = "";
    var cssClass = "";
    var ctlType = "";
    ele.style.height = "100%";
    //var strProp = "[{label:'date', nom: 'text', type: 'date',valeur:''},{label:'age', nom: 'text', type: 'int',valeur:''},{label:'vrai', nom: 'checkbox', type: 'boolean',valeur:''}]";
    PE_ObjProp = strProp; // strProp; // eval('(' + strProp + ')');
    PE_heightWnd = 50;
    var iht = "<FORM NAME=\"form1\" class='RadForm_Default'><table style='height:100%; width:100%'>";
    for (i = 0; i < PE_ObjProp.props.length; i++) {
        if (PE_ObjProp.props[i].Type == "Boolean") {
            cssClass = "";
            ctlType = "checkbox";
            var checked = "";
            if (PE_ObjProp.props[i].Value) { checked = "checked"; }
            iht = iht + "<tr class='rwWindowContent'><td style='text-align:left;margin:0px;padding:0px;font: 12px \"Segoe UI\",Arial,Verdana;'>" + PE_ObjProp.props[i].Label + "</td><td><INPUT class='" + cssClass + "' style='border: 0px;' TYPE='" + ctlType + "' NAME='" + PE_ObjProp.props[i].Type + i + "' " + checked + " ALT='" + PE_ObjProp.props[i].Label + "' onfocus='setCorrection(" + PE_ObjProp.props[i].Type + i + ")'";
            iht = iht + "></tr>";
            PE_heightWnd = PE_heightWnd + 50;
        }
        else {
            cssClass = "rwDialogInput";
            ctlType = "text";
            if (PE_ObjProp.props[i].Multiline == true) {
                iht = iht + "<tr class='rwWindowContent'><td style='text-align:left;margin:0px;padding:0px;font: 12px \"Segoe UI\",Arial,Verdana;'>" + PE_ObjProp.props[i].Label + "</td><td><textarea class='" + cssClass + "' style='resize:none;' NAME='" + PE_ObjProp.props[i].Type + i + "' VALUE='" + PE_ObjProp.props[i].Value.toLocaleString() + "' ALT='" + PE_ObjProp.props[i].Label + "' onfocus='setCorrection(" + PE_ObjProp.props[i].Type + i + ")'";
                iht = iht + ">" + PE_ObjProp.props[i].Value + "</textarea></tr>";
                PE_heightWnd = PE_heightWnd + 70;
            }
            else if (PE_ObjProp.props[i].Type == "Float" || PE_ObjProp.props[i].Type == "Double") {
                iht = iht + "<tr class='rwWindowContent'><td style='text-align:left;margin:0px;padding:0px;font: 12px \"Segoe UI\",Arial,Verdana;'>" + PE_ObjProp.props[i].Label + "</td><td><INPUT class='" + cssClass + "' TYPE='" + ctlType + "' NAME='" + PE_ObjProp.props[i].Type + i + "' VALUE='" + PE_ObjProp.props[i].Value.toLocaleString() + "' ALT='" + PE_ObjProp.props[i].Label + "' onfocus='setCorrection(" + PE_ObjProp.props[i].Type + i + ")'";
                iht = iht + "></tr>";
                PE_heightWnd = PE_heightWnd + 50;
            }
            else {
                iht = iht + "<tr class='rwWindowContent'><td style='text-align:left;margin:0px;padding:0px;font: 12px \"Segoe UI\",Arial,Verdana;'>" + PE_ObjProp.props[i].Label + "</td><td><INPUT class='" + cssClass + "' TYPE='" + ctlType + "' NAME='" + PE_ObjProp.props[i].Type + i + "' VALUE='" + PE_ObjProp.props[i].Value + "' ALT='" + PE_ObjProp.props[i].Label + "' onfocus='setCorrection(" + PE_ObjProp.props[i].Type + i + ")'";
                iht = iht + "></tr>";
                PE_heightWnd = PE_heightWnd + 50;
            }
        }

    }
    //iht = iht + "<tr><td><input class=\"rfdDecorated\" style='width:50px;' type='button' name='btnOK' value='OK' onClick=\"validateOk(this.form, '" + wndName + "');\"></td>"; //<input cssClass=\"rxPopupButton\" type='button' name='btnOK' value='OK' onClick=\"validateOk(this.form);\"></table></form>";
    //iht = iht + "</table><div class='rwDialogPopup' style='text-align:center;margin-top:10px;padding-bottom:5px;'><a onclick='validateOk(this.form, '" + wndName + "');'class='rwPopupButton' href='javascript:void(0);'><span class='rwOuterSpan'><span class='rwInnerSpan'>OK</span></span></a> </div></form>";
    //iht = iht + "<td><input class=\"rfdDecorated\" type='button' name='btnCancel' value='Cancel' onClick=\"radWindowClose('" + wndName + "');\"></td></tr></table>"
    var buttonOk = '</table><div class="rwDialogPopup" style="position:absolute;bottom:0;text-align:center;margin:0px;padding-bottom:20px;"><a onclick="nt++;validateOk(form1,\'' + wndName + '\',' + prmFonctionEnd +');" class="rwPopupButton" href="javascript:void(0);"><span class="rwOuterSpan"><span class="rwInnerSpan">OK</span></span></a>';
    var buttonCancel = '<a onclick="nt++;CancOp('+prmFonctionCanc+');radWindowClose(\'' + wndName + '\');" class="rwPopupButton" href="javascript:void(0);"><span class="rwOuterSpan"><span class="rwInnerSpan">Cancel</span></span></a> </div></form>';
    iht = iht + buttonOk;
    iht = iht + buttonCancel;
    ele.innerHTML = iht;
    wnd.set_contentElement(ele);
    wnd.isClosed(false);
    wnd.set_modal(true);
    wnd.set_behaviors(+Telerik.Web.UI.WindowBehaviors.Resize);
    wnd.set_destroyOnClose(false);
    wnd.set_visibleStatusbar(false);
    wnd.set_visibleTitlebar(false);
    wnd.set_width(PE_widthWnd);
    wnd.set_height(PE_heightWnd);
    wnd.add_resize(radPropertyEditor_onResize);
    wnd.moveTo(x, y);
    return true;
}

function radPropertyEditor_onResize(sender, eventArgs) {
    var bounds = sender.getWindowBounds();
    if (bounds.width < PE_widthWnd) {
        sender.set_width(PE_widthWnd);
    }
    if (bounds.height < PE_heightWnd) {
        sender.set_height(PE_heightWnd);
    }
}

//------------------------------------------------------------------------------------------------------------------
// Utilities
//------------------------------------------------------------------------------------------------------------------

function addItemToJson() {
    var test = document.getElementById(PE_CalendarId + "_DateProperties_").value;
    if (PE_doPush) {
        PE_PropertiesCol.push(PE_ObjProp);
    } //ajouter le nouveau item à la collection des propriétés
    var json_data = JSON.stringify(PE_PropertiesCol); //créer la chain JSon
    document.getElementById(PE_CalendarId + "_DateProperties_").value = json_data;
    var dte = new Date(PE_ObjProp.dat);
    selectDateInCal(PE_CalendarId, PE_ObjProp.dat)
    //selectAllDatInCal(PE_CalendarId);
    /* selectDate = document.getElementById(PE_CalendarId).value;
    selectDate = selectDate.slice(0, -1);
    selectDate = selectDate + ",[" + dte.getDate() + "," + (dte.getMonth() + 1) + "," + dte.getFullYear() + "]]";
    var selectDate = "[";
    for (i = 0; i < PE_PropertiesCol.length; i++) {
    selectDate = selectDate + "[" + PE_PropertiesCol[i].dat + "]"
    if (i != PE_PropertiesCol.length - 1) { selectDate = selectDate + "," }
    }
    selectDate = selectDate + "]";
    document.getElementById("DMD_CCF_CalendarEdit_SD").value = "[[2010,6,4],[2010,6,7]]";
    */
    var tsts = document.getElementById(PE_CalendarId + "_DateProperties_").value;
}
function CancOp(fctCancOp) {
    fctCancOp();
}
//***** selection, unselection date fonction*************
function selectAllDatInCal(idCalendar) {
    ClearAll(idCalendar);
    for (i = 0; i < PE_PropertiesCol.length; i++) {
        selectDateInCal(idCalendar, PE_PropertiesCol[i].dat);
    }
}
function selectDateInCal(idCalendar, myDate) {
    var calendar = $find(idCalendar);
    var dte = new Date(myDate);
    strDay = [dte.getFullYear(), dte.getMonth() + 1, dte.getDate()];
    calendar.selectDate(strDay, true);
}
function ClearAll(idCalendar) {
    var calendar = $find(idCalendar);
    calendar.unselectDates(calendar.get_selectedDates());
}

function returnToInitSelect() {
    if (PE_doPush) { unselectDateInCal; }
    else{selectDateInCal(PE_CalendarId, PE_ObjProp.dat);}
}
function unselectDateInCal(idCalendar,myDate) {
    var calendar = $find(PE_CalendarId);
    var dte = new Date(PE_ObjProp.dat);
    strDay = [dte.getFullYear(), dte.getMonth() + 1, dte.getDate()];
    calendar.unselectDate(strDay, true);
}
//************************ End selection unselection***************
function trim(sString) {
    while (sString.substring(0, 1) == ' ' || sString.substring(0, 1) == '\t' || sString.substring(0, 1) == '\r' || sString.substring(0, 1) == '\n') {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length - 1, sString.length) == ' ' || sString.substring(sString.length - 1, sString.length) == '\t' || sString.substring(sString.length - 1, sString.length) == '\r' || sString.substring(sString.length - 1, sString.length) == '\n') {
        sString = sString.substring(0, sString.length - 1);
    }
    return sString;
}

function DateToString(day, month, year) {
    return LeftPad(month, 2) + '/' + LeftPad(day, 2) + '/' + year.toString()
}

function LeftPad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function getMouseX(e) {
    var posx = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
    }
    else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
    }
    return posx;
}
function getMouseY(e) {
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY) {
        posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
    }
    return posy;
}


function setCorrection(nmC) {
    nmC.style.backgroundColor = '';
}

//------------------------------------------------------------------------------------------------------------------
// Validation
//------------------------------------------------------------------------------------------------------------------

function validateOk(Myfrm, wndName,fctEndOp) {
    //if (nt > 1) { var frm = Myfrm[0]; } else { var frm = Myfrm; }//obtenir le bon objet form
    var frm = Myfrm;
    var tstVal = true; //teste valider ou non
    for (i = 0; i < frm.length; i++) {//parcourir les éléments de la form
        if (frm[i].name.indexOf("Int") != -1) {
            if (verifint(frm[i].value) == -1 || (PE_ObjProp.props[i].MaxValue != null && PE_ObjProp.props[i].MinValue != null
            && (frm[i].value < PE_ObjProp.props[i].MinValue || frm[i].value > PE_ObjProp.props[i].MaxValue))) {
                frm[i].style.backgroundColor = '#FF1201'; 
                tstVal = false;
            }
            else { PE_ObjProp.props[i].Value = verifint(frm[i].value); } //affecter la valeur saisie au objet propriété
        }
        else if (frm[i].name.indexOf("Date") != -1) {
            if (!verifdate(frm[i].value)) { frm[i].style.backgroundColor = '#FF1201'; tstVal = false; }
            else { PE_ObjProp.props[i].Value = frm[i].value; }
        }
        else if (frm[i].name.indexOf("Float") != -1 || frm[i].name.indexOf("Double") != -1) {
            if (verifint(frm[i].value) == -1 || (PE_ObjProp.props[i].MaxValue != null && PE_ObjProp.props[i].MinValue != null
            && (frm[i].value < PE_ObjProp.props[i].MinValue || frm[i].value > PE_ObjProp.props[i].MaxValue))) {
                frm[i].style.backgroundColor = '#FF1201';
                tstVal = false;
            }
            else { PE_ObjProp.props[i].Value = verifFloat(frm[i].value); }
        }
        else if ((frm[i].name.indexOf("Boolean") != -1)) {
            PE_ObjProp.props[i].Value = frm[i].checked;
        }
        else if ((frm[i].name.indexOf("String") != -1)) {
            //if (frm[i].value == "") { frm[i].style.backgroundColor = '#FF1201'; tstVal = false; }
            if (false) {}
            else { PE_ObjProp.props[i].Value = trim(frm[i].value); }
        }
    }

    if (tstVal) { fctEndOp(); radWindowClose(wndName); }
}

//teste si la date est valide
function verifdate(datesaisie) {
    if (isNaN(Date.parse(datesaisie))) { return false; }
    else { return true; }
    /* var dateaverif = datesaisie; //.value;
    //var rfocu=champdat;
    // rangement de la date dans des variables
    if (dateaverif != "" && navigator.browserLanguage == "fr") {
    if (!verifdateFr(dateaverif)) {
    //alert("Attention soit la date n'est pas correcte, soit elle n'est pas au format JJ/MM/AAAA");
    //DonnerFocus(rfocu);
    return false;
    }
    }
    return true;*/
}

function verifdateFr(d) {
    var dateaverifier = d;
    var firstSlach = dateaverifier.indexOf("/", 0);
    var secondSlach = dateaverifier.indexOf("/", 3);
    // rangement de la date dans des variables
    var jStr = dateaverifier.substring(0, firstSlach);
    var mStr = dateaverifier.substring(firstSlach + 1, secondSlach);
    var aStr = dateaverifier.substring(secondSlach + 1, (dateaverifier.length));

    if (jStr != "" && jStr.length < 3) {
        var j = parseInt(jStr, 10);
    }
    else {
        return false;
    }
    if (mStr != "" && mStr.length < 3) {
        var m = parseInt(mStr, 10);
    }
    else {
        return false;
    }

    if (aStr != "" && aStr.length == 4) {
        var a = parseInt(aStr, 10);
    }

    else {
        return false;
    }
    if ((isNaN(m)) || (m < 1) || (m > 12)) {
        return false;
    }
    //test si il s'agit d'une année bissextile pour accepter le 29/02
    if (((a % 4) == 0 && (a % 100) != 0) || (a % 400) == 0) {
        if ((isNaN(j)) || ((m != 2) && ((j < 1) || (j > 31))) || ((m == 2) && ((j < 1) || (j > 29))) || (m <= 7 && m % 2 == 0 && j > 30) || (m > 7 && m % 2 == 1 && j > 30)) {
            return false;
        }
    }
    else {
        if ((isNaN(j)) || ((m != 2) && ((j < 1) || (j > 31))) || ((m == 2) && ((j < 1) || (j > 28))) || (m <= 7 && m % 2 == 0 && j > 30) || (m > 7 && m % 2 == 1 && j > 30)) {
            return false;
        }
    }
    return true;
}

function verifint(num) {
    num = trim(num);
    if (num != "") {
        var nm = parseInt(num, 10);
        if (isNaN(nm) || nm != num) {
            return -1;
        }
        else {
            if (num.toString().indexOf(",") != -1 || num.toString().indexOf(".") != -1) {
                return -1;
            }
            return nm;
        }
    }
    else {
        return "";
    }
}

function verifFloat(num) {
    var DecimalSeparator =  Number("1.7").toLocaleString().substr(1, 1);
    if (num != "") {
        var myFloat = num;
        //si le séparateur est ,
        if (DecimalSeparator == ",") {
            while (myFloat.indexOf(".") != -1) {
                myFloat = myFloat.replace(".", "");
            }
            myFloat = myFloat.replace(",", ".");
        }
        //si le séparateur est .
        else {
            myFloat = num;
            while (myFloat.indexOf(",")!=-1) {
                myFloat=myFloat.replace(",", "");
            }
        }
        if (!isNaN(parseFloat(myFloat))) {
            return parseFloat(myFloat);
        }
        else {
            return -1;
        }
    }
    else {
        return 0;
    }

}


