﻿

// Tools
function $(id) {
    return document.getElementById(id);
}

var __attachedEvents = new Array();

function $AttachEvent(elem, event, func) {
    var ob = { elemid: elem.id, eventName: event };
    __attachedEvents.push(ob);
    
    if (elem == null) { return; }
    if (event == null || event == '') { return; }
    if (func == null) { return; }

    if (elem.addEventListener) {
        elem.addEventListener(event.replace('on', ''), func, false);
    }
    else if (elem.attachEvent) { 
        elem.attachEvent(event, func);
    }
    else {
        elem.event = func;
    }
}

function $IsEventAttached(elem, event) {
    for (var i = 0; i < __attachedEvents.length; i++) {
        if (__attachedEvents[i].elemid == elem.id && __attachedEvents[i].eventName == event) {
            return true;
        }
    }
    return false;
}

function $AttachLink(id, lnk) {
    $(id).setAttribute('href', lnk);
}

function $GetEventKey(event) {
    return (window.event) ? event.keyCode : event.which;
}

function $GetQueryParameter(ParameterName) {
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?"));
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (
                aQueryString[iParam].indexOf(ParameterName + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

function IsAnEmailAddress(str) {
    //var verif = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
    var verif = /^([a-zA-Z0-9_\+\-\.]{1,})@([a-zA-Z0-9_\+\-\.]{1,})\.([a-zA-Z0-9_\+\-\.]{1,})$/i;
    if (verif.exec(str) != null) {
        return true;
    }
    return false;
}

function $ImportScript(src) {
    var src = __CONF__URL_MEDIA + "JScripts/" + src + ".js?" + new Date().toDateString().replace(' ', '-').replace(' ', '-').replace(' ', '-');
    document.write("<script type='text/javascript' src='"+src+"'></script>");
}

function $ImportScriptAjaxCB(response, Params) {
    window.eval(response);
    if(Params && Params[0]){
        Params[0](Params[1]);
    }
}

function $ImportScriptAjax(src,callback,params) {
    if (src.substring(0, 4).toLowerCase() != "http") {
        src = __CONF__URL_MEDIA + "JScripts/" + src + ".js";
    }
    var co = "?";
    if (src.indexOf('?', 0) > 0) {
        co = '&';
    }
    src += co + new Date().toDateString().replace(' ', '-').replace(' ', '-').replace(' ', '-');
    AjaxHttpGet(src, $ImportScriptAjaxCB, [callback,params]);

}

function $ImportScriptInHead(src, callback) {
    if (src.substring(0, 4).toLowerCase() != "http") {
        src = __CONF__URL_MEDIA + "JScripts/" + src + ".js";
    }
    src += "?" + new Date().toDateString().replace(' ', '-').replace(' ', '-').replace(' ', '-');
    var script = document.createElement("script");
    script.src = src;
    script.type = "text/javascript";
    // Firefox
    script.onload = callback;
    // IE
    script.onreadystatechange = function() {
        if (/loaded|complete/.test(this.readyState)) {
            callback();
        }
    };
    document.getElementsByTagName("head")[0].appendChild(script);
}

function GetElementByClassNamePath(myElem, ClassNamePath) {
    if (myElem == null) return myElem;
    if (ClassNamePath.length == 0) return myElem;
    if (myElem.className == ClassNamePath) return myElem;
    if (myElem.hasChildNodes()) {
        var ClassNames = ClassNamePath.split('::');
        for (var i = 0; i < myElem.childNodes.length; i++) {
            if (myElem.childNodes[i].className == ClassNames[0])
                return GetElementByClassNamePath(myElem.childNodes[i], ClassNamePath.substr(ClassNames[0].length, ClassNamePath.length - ClassNames[0].length).replace(/^::/gi, ''));
        }
    }
    return myElem;
}

function ShowAjaxLoading() {
    $('AjaxLoadingBlk').style.display = '';
}

function HideAjaxLoading() {
    $('AjaxLoadingBlk').style.display = 'none';
}

function ChangeDivOpacity(dvID, Opacity) {
    var object = $(dvID).style;
    object.opacity = (Opacity / 100);
    object.MozOpacity = (Opacity / 100);
    object.KhtmlOpacity = (Opacity / 100);
    object.filter = "alpha(opacity=" + Opacity + ")";
}

function HTMLEncode(str) {
    if (str == null) return null;
    msgEncoded = '';
    allLines = str.split('\n');
    for (var i = 0; i < allLines.length; i++) {
        if (i > 0) msgEncoded += '<br />';
        div = document.createElement('div');
        text = document.createTextNode(allLines[i]);
        div.appendChild(text);
        msgEncoded += div.innerHTML;
    }
    return msgEncoded;
}

function HTMLDecode(str) {
    var RegEx1 = /&amp;/gi;
    var RegEx2 = /&gt;/gi;
    var RegEx3 = /&lt;/gi;
    return str.replace(RegEx1, "&").replace(RegEx2, ">").replace(RegEx3, "<");
}

function GetCurentPageName() {
    var uri = new Object();
    uri.dir = location.href.substring(0, location.href.lastIndexOf('\/'));
    uri.page = location.href.substring(uri.dir.length + 1, location.href.length + 1);
    pos = uri.page.indexOf('?'); if (pos > -1) { uri.page = uri.page.substring(0, pos); }
    pos = uri.page.indexOf('#'); if (pos > -1) { uri.page = uri.page.substring(0, pos); }
    uri.ext = ''; pos = uri.page.indexOf('.'); if (pos > -1) { uri.ext = uri.page.substring(pos + 1); uri.page = uri.page.substr(0, pos); }
    uri.file = uri.page;
    if (uri.page == '' || uri.page=='default')
        return "Default";
    return uri.page
}
// Handling some .Net JS exceptions
function EndRequestHandler(sender, args) {
    if (args.get_error() != undefined) {
        var errorMessage;
        if (args.get_response().get_statusCode() == '200') {
            errorMessage = args.get_error().message;
        }
        else {
            errorMessage = 'An unspecified error occurred. ';
        }
        args.set_errorHandled(true);
        if (JSDebugMode) {
            alert(errorMessage);
        }
    }
}

function AttachSysErrorHandling() {
    try {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    } catch (ex) {
        
    }
}

function AttachWindowOnLoadCall(method) {
    if (window.onload) {
        var oldOnLoad = window.onload;
        var onloadfunction = function() {
            oldOnLoad();
            method();
        };
    } else {
        var onloadfunction = method;
    }
    window.onload = onloadfunction;
}

function AttachWindowOnUnloadCall(method) {
    if (window.onunload) {
        var oldOnUnload = window.onunload;
        var onunloadfunction = function() {
            oldOnUnload();
            method();
        };
    } else {
        var onunloadfunction = method;
    }
    window.onunload = onunloadfunction;
}

AttachWindowOnLoadCall(AttachSysErrorHandling);


// WaterMark
var __WaterMarkTexts = new Array();

function IsWaterMarkEntrySet(id) {
    if ($(id).value == __WaterMarkTexts[id])
        return false;
    return true;
}

function InitWaterMark(id) {
    __WaterMarkTexts[id] = $(id).value;
    var ClassSuffix = 'WaterMarked';
    if ($(id).className.length > 0)
        ClassSuffix = ' ' + ClassSuffix;
    if (!$(id).className.match('WaterMarked'))
        $(id).className += ClassSuffix;
    $(id).onfocus = function() {
        if ($(this.id).value == __WaterMarkTexts[this.id]) {
            $(this.id).value = "";
            $(this.id).className = $(this.id).className.replace(' WaterMarked', '').replace('WaterMarked', '');
        }
    };
    $(id).onblur = function() {
        if ($(this.id).value == "" || $(this.id).value == __WaterMarkTexts[this.id]) {
            var ClassSuffix = "";
            if ($(this.id).className.length > 0) {
                ClassSuffix += ' ';
            }
            ClassSuffix += 'WaterMarked';
            $(this.id).className += ClassSuffix;
            $(this.id).value = __WaterMarkTexts[this.id];
        }
    };
}

// AnnimScroll
function AnnimScrollBlockRight(ScrollToPosition, BlockId, Step, Speed, GoFast) {
    if ($(BlockId).scrollLeft < ScrollToPosition) {
        $(BlockId).scrollLeft = $(BlockId).scrollLeft + (GoFast ? Step * 4 : Step);
        setTimeout('AnnimScrollBlockRight(' + ScrollToPosition + ', \'' + BlockId + '\', ' + Step + ', ' + GoFast + ')', Speed);
    }
    else {
        document.getElementById(BlockId).scrollLeft = ScrollToPosition;
    }
}

function AnnimScrollBlockLeft(ScrollToPosition, BlockId, Step, Speed, GoFast) {
    if ($(BlockId).scrollLeft > ScrollToPosition) {
        $(BlockId).scrollLeft = $(BlockId).scrollLeft - (GoFast ? Step * 4 : Step);
        setTimeout('AnnimScrollBlockLeft(' + ScrollToPosition + ', \'' + BlockId + '\', ' + Step + ', ' + GoFast + ')', Speed);
    }
    else {
        $(BlockId).scrollLeft = ScrollToPosition;
    }
}

function ReduceDiv(divId, fromHeight) {
    var newheight = fromHeight / 2 - 1;
    if (newheight > 10) {
        $(divId).style.height = newheight + 'px';
        setTimeout('ReduceDiv("' + divId + '", ' + newheight + ')', 40);
    }
    else {
        $(divId).style.height = '0px';
    }
}

function RaiseDiv(divId, fromHeight, toHeight) {
    var newheight = fromHeight + (((toHeight - fromHeight) / 2) + 1);
    if (newheight + 10 < toHeight) {
        $(divId).style.height = newheight + 'px';
        setTimeout('RaiseDiv("' + divId + '", ' + newheight + ', ' + toHeight + ')', 40);
    }
    else {
        $(divId).style.height = toHeight + 'px';
    }
}
// Ajax HTTP Request
function getXhr() { if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); else if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest, veuillez le mettre à jour"); xhr = false; } }

function GetFullUrl(Url) {
    if (Url.toString().indexOf("?", 0) > 1) {
        Url += '&' + new Date().getTime();
    }
    else {
        Url += '?' + new Date().getTime();
    }
    return Url;
}

function AjaxCall(Type, Url, PostData, CallBack, Params) {
    this._Type = Type;
    this._Url = Url;
    this._PostData = PostData;
    this._CallBack = CallBack;
    this._Params = Params;

    this.ExecuteNow = function() {
        getXhr();
        var tmpCallBack = this._CallBack;
        var tmpParams = this._Params;
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    MyTrace('Call : AjaxHttpPost, Response : ' + xhr.responseText);
                    __AjaxSemaphore = true;
                    setTimeout('AjaxHttpManagerCall()', 0);
                    try {
                        if (tmpCallBack != null) {
                            tmpCallBack(xhr.responseText, tmpParams);
                        }
                    }
                    catch (ex) {
                        if (JSDebugMode) {
                            alert('Error in CallBack : ' + ex);
                        }
                    }
                }
                else {
                    if (JSDebugMode) {
                        alert('XHR status Error : ' + xhr.statusText);
                    }
                }
            }
        };
        if (Type == 'POST') {
            xhr.open("POST", GetFullUrl(this._Url), true);
            xhr.setRequestHeader('Content-Type', 'text/xml');
            xhr.send(this._PostData + '\nAjaxSecureGuid=' + __AjaxSecureGuid);
        }
        else {
            xhr.open("GET", GetFullUrl(this._Url), true);
            xhr.setRequestHeader('Content-Type', 'text/xml');
            xhr.send(null);
        }
    }
}

var __AjaxSemaphore = true;
var __AjaxCalls = new Array();

function AjaxHttpManagerCall() {
    if(__AjaxCalls.length == 0) return;
    if (__AjaxSemaphore) {
        var myCall = __AjaxCalls.pop();
        __AjaxSemaphore = false;
        myCall.ExecuteNow();
    }
}

function AjaxHttpManager(Type, Url, PostData, CallBack, Params) {
    var obj = new AjaxCall(Type, Url, PostData, CallBack, Params);
    __AjaxCalls.push(obj);
    if (__AjaxSemaphore) {
        AjaxHttpManagerCall();
    }
}

function AjaxHttpPost(Url, PostData, CallBack, Params) {
    AjaxHttpManager('POST', Url, PostData, CallBack, Params);
}

function AjaxHttpGet(Url, CallBack, Params) {
    AjaxHttpManager('GET', Url, null, CallBack, Params);
}

// MyAlert
function CloseMyAlert(callBack) {
    document.body.removeChild($('MyAlertBlk'));
    if (callBack != 'null')
        setTimeout(callBack + '()', 10);
}

function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function getScrollTop() {
    return f_filterResults(
        window.pageYOffset ? window.pageYOffset : 0,
        document.documentElement ? document.documentElement.scrollTop : 0,
        document.body ? document.body.scrollTop : 0);
}

function getWindowSize() {
    var db = (!document.documentElement.clientWidth) ? document.body : document.documentElement;
    var windowWidth = (window.innerWidth) ? window.innerWidth : db.clientWidth;
    var windowHeight = (window.innerHeight) ? window.innerHeight : db.clientHeight;
    return { 'width': windowWidth, 'height': windowHeight };
}

function getPageSize() {
    var windowSize = getWindowSize();
    var xScroll = document.body.scrollWidth;
    var yScroll = (window.innerHeight && window.scrollMaxY) ? window.innerHeight + window.scrollMaxY : document.body.scrollHeight;
    var pageWidth = (xScroll < windowSize.width) ? windowSize.width : xScroll;
    var pageHeight = (yScroll < windowSize.height) ? windowSize.height : yScroll;
    return { 'width': pageWidth, 'height': pageHeight };
}

function MyAlertPosition() {
    try {
        var windowSize = getWindowSize();
        var pageSize = getPageSize();
        $('MyAlertBlk').style.top = (getScrollTop() + 100) + 'px';
        $('MyAlertBlk').style.left = Math.round((getPageSize().width - 25) / 2 - ($('MyAlertBlk').style.width.toString().replace('px', '') / 2)) + 'px';
        setTimeout('MyAlertPosition()', 10);
    }
    catch (e) { }
}
function MyAlert(title, body, callBack) {
    dvAlertContainer = document.createElement("DIV");
    document.body.appendChild(dvAlertContainer);
    dvAlertContainer.id = 'MyAlertBlk';
    dvAlertContainer.className = 'MyAlertBlk';
    dvAlertContainer.style.width = '320px';

    dvMyAlert = document.createElement("DIV");
    dvMyAlert.id = 'MyAlertPopup';
    dvMyAlert.className = 'WzPopupV2';
    dvMyAlert.style.width = '320px';

    dvTitle = document.createElement("DIV");
    dvTitle.id = "ContentTitle";
    dvTitle.innerHTML = title;

    dvBody = document.createElement("DIV");
    dvBody.id = "ContentBody";
    dvBody.innerHTML = '<div id="WarningMessage"></div>' + body;

    dvFooter = document.createElement("DIV");
    dvFooter.id = "ContentFooter";
    dvFooter.innerHTML = "<input type=\"submit\" id=\"CloseButt\" value=\"Fermer\" onclick=\"javascript:CloseMyAlert(\'" + callBack + "\');return false;\" />";

    dvMyAlert.appendChild(dvTitle);
    dvMyAlert.appendChild(dvBody);
    dvMyAlert.appendChild(dvFooter);

    dvAlertContainer.appendChild(dvMyAlert);
    SuroundWithPopup('MyAlertPopup');

    MyAlertPosition();
    CurentEnterCallBack = null;
    $('CloseButt').focus();

    document.body.appendChild(dvAlertContainer);
}

//MyConfirm
function CloseMyConfirm(callBack) {
    document.body.removeChild($('MyConfirmBlk'));
    if (callBack != 'null')
        eval(callBack + '();');
}

function MyConfirmPosition() {
    try {
        var windowSize = getWindowSize();
        var pageSize = getPageSize();
        $('MyConfirmBlk').style.top = (getScrollTop() + 100) + 'px';
        $('MyConfirmBlk').style.left = Math.round((getPageSize().width - 25) / 2 - ($('MyConfirmBlk').style.width.toString().replace('px', '') / 2)) + 'px';
        setTimeout('MyConfirmPosition()', 10);
    }
    catch (e) { }
}

function MyConfirm(title, body, callBackOk,callBackCancel) {
    dvConfirmContainer = document.createElement("DIV");
    document.body.appendChild(dvConfirmContainer);
    dvConfirmContainer.id = 'MyConfirmBlk';
    dvConfirmContainer.className = 'MyAlertBlk';
    dvConfirmContainer.style.width = '320px';

    dvMyConfirm = document.createElement("DIV");
    dvMyConfirm.id = 'MyConfirmPopup';
    dvMyConfirm.className = 'WzPopupV2';
    dvMyConfirm.style.width = '320px';

    dvTitle = document.createElement("DIV");
    dvTitle.id = "ContentTitle";
    dvTitle.innerHTML = title;

    dvBody = document.createElement("DIV");
    dvBody.id = "ContentBody";
    dvBody.innerHTML = '<div id="WarningMessage"></div>' + body;

    dvFooter = document.createElement("DIV");
    dvFooter.id = "ContentFooter";
    dvFooter.innerHTML = "<input type=\"submit\" id=\"ConfirmButt\" value=\"Confirmer\" onclick=\"javascript:CloseMyConfirm(\'" + callBackOk + "\');return false;\" style='margin-right:105px;' />"
    + "<input type=\"submit\" id=\"CancelButt\" value=\"Annuler\" onclick=\"javascript:CloseMyConfirm(\'" + callBackCancel + "\');return false;\" />";

    dvMyConfirm.appendChild(dvTitle);
    dvMyConfirm.appendChild(dvBody);
    dvMyConfirm.appendChild(dvFooter);

    dvConfirmContainer.appendChild(dvMyConfirm);
    SuroundWithPopup('MyConfirmPopup');

    MyConfirmPosition();
    CurentEnterCallBack = null;
    $('ConfirmButt').focus();

    document.body.appendChild(dvConfirmContainer);
}

//END MyConfirm

function ShowHelpMsg(img) {
    $('WarningMesgBlk').innerHTML = img.getAttribute('alt');
    $('WarningMesgBlk').style.display = '';
}
function HideHelpMsg(img) {
    $('WarningMesgBlk').style.display = 'none';
}

// getAnchorPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
    // This function will return an Object with x and y properties
    var useWindow = false;
    var coordinates = new Object();
    var x = 0, y = 0;
    // Browser capability sniffing
    var use_gebi = false, use_css = false, use_layers = false;
    if (document.getElementById) { use_gebi = true; }
    else if (document.all) { use_css = true; }
    else if (document.layers) { use_layers = true; }
    // Logic to find position
    if (use_gebi && document.all) {
        x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
        y = AnchorPosition_getPageOffsetTop(document.all[anchorname]);
    }
    else if (use_gebi) {
        var o = document.getElementById(anchorname);
        x = AnchorPosition_getPageOffsetLeft(o);
        y = AnchorPosition_getPageOffsetTop(o);
    }
    else if (use_css) {
        x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
        y = AnchorPosition_getPageOffsetTop(document.all[anchorname]);
    }
    else if (use_layers) {
        var found = 0;
        for (var i = 0; i < document.anchors.length; i++) {
            if (document.anchors[i].name == anchorname) { found = 1; break; }
        }
        if (found == 0) {
            coordinates.x = 0; coordinates.y = 0; return coordinates;
        }
        x = document.anchors[i].x;
        y = document.anchors[i].y;
    }
    else {
        coordinates.x = 0; coordinates.y = 0; return coordinates;
    }
    coordinates.x = x;
    coordinates.y = y;
    return coordinates;
}

var __movingActualPosition = 0;
function JumpToAnchorTop(GoToPosition) {
    var actualPosition = getScrollTop();
    if (__movingActualPosition == actualPosition) {
        window.scroll(0, GoToPosition);
        return;
    }
    __movingActualPosition = actualPosition;
    var step = (actualPosition < GoToPosition) ? GoToPosition - actualPosition : actualPosition - GoToPosition;
    step = step / 2;
    actualPosition = (actualPosition < GoToPosition + 1) ? actualPosition - step : actualPosition + step;
    if (step > 10) {
        window.scroll(0, actualPosition);
        setTimeout('JumpToAnchorTop(\'' + GoToPosition + '\')', 66);
    }
    else {
        window.scroll(0, GoToPosition);
    }
}

function JumpToAnchorBottom(GoToPosition) {
    var actualPosition = getScrollTop();
    actualPosition = actualPosition + ((GoToPosition - actualPosition) / 2) + 1;
    if (__movingActualPosition == actualPosition) {
        window.scroll(0, GoToPosition);
        return;
    }
    __movingActualPosition = actualPosition;
    if (actualPosition < GoToPosition - 1) {
        window.scroll(0, actualPosition);
        setTimeout('JumpToAnchorBottom(\'' + GoToPosition + '\')', 66);
    }
    else {
        window.scroll(0, GoToPosition);
    }
}

function JumpToAnchor(anchorName) {
    var ActualPosition = getScrollTop();
    var GoToPosition = getAnchorPosition(anchorName).y;
    if (ActualPosition > GoToPosition) {
        JumpToAnchorTop(GoToPosition);
    }
    else if (ActualPosition < GoToPosition) {
        JumpToAnchorBottom(GoToPosition);
    }
}

// getAnchorWindowPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname) {
    var coordinates = getAnchorPosition(anchorname);
    var x = 0;
    var y = 0;
    if (document.getElementById) {
        if (isNaN(window.screenX)) {
            x = coordinates.x - document.body.scrollLeft + window.screenLeft;
            y = coordinates.y - document.body.scrollTop + window.screenTop;
        }
        else {
            x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset;
            y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset;
        }
    }
    else if (document.all) {
        x = coordinates.x - document.body.scrollLeft + window.screenLeft;
        y = coordinates.y - document.body.scrollTop + window.screenTop;
    }
    else if (document.layers) {
        x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset;
        y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset;
    }
    coordinates.x = x;
    coordinates.y = y;
    return coordinates;
}

// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft(el) {
    var ol = el.offsetLeft;
    while ((el = el.offsetParent) != null) { ol += el.offsetLeft; }
    return ol;
}
function AnchorPosition_getWindowOffsetLeft(el) {
    return AnchorPosition_getPageOffsetLeft(el) - document.body.scrollLeft;
}
function AnchorPosition_getPageOffsetTop(el) {
    var ot = el.offsetTop;
    while ((el = el.offsetParent) != null) { ot += el.offsetTop; }
    return ot;
}
function AnchorPosition_getWindowOffsetTop(el) {
    return AnchorPosition_getPageOffsetTop(el) - document.body.scrollTop;
}

//Form validation tools

function fillValidationField(validFieldName, type, text) {
    if (type == "validImg") {
        var validImg = document.createElement("IMG");
        validImg.setAttribute("src", "http://cms.womzone.com/00_WomzoneV2.0/StyleCSS/imgs/General/ValidationIcon.gif");
        validImg.setAttribute("style", "margin-top:-5px;");
        $(validFieldName).innerHTML = "";
        $(validFieldName).appendChild(validImg);
    } else if (type == "errorImg") {
        var errorImg1 = document.createElement("IMG");
        errorImg1.setAttribute("src", "http://cms.womzone.com/00_WomzoneV2.0/StyleCSS/imgs/General/ErrorIcon.gif");
        errorImg1.setAttribute("style", "margin-top:-5px;");
        $(validFieldName).innerHTML = "";
        $(validFieldName).appendChild(errorImg1);
    } else if (type == "text") {
        $(validFieldName).innerHTML = text;
    }
}

//Use : type    "simple" : text field, valid = not empty, name of validation field fieldName + "Valid"
//              "email"  : text field, valid = correct email address, name of validation field fieldName + "Valid"
//              "select" : select choice, valid = not default choice (selectedIndex != 0), name of validation field fieldName + "Valid"
//              "password" : two password inputs, valid = (length >= 4) && values are equal
//                          input names : #name#1, #name#2, name of validation field : #name#2Valid
//              "checkbox*" : checkbox input, valid = checked, name of validation field (= label) fieldName + "Valid"
function ValidateField(fieldName, type) {
    if (type == "simple") {
        if ($(fieldName).value != "") {
            fillValidationField(fieldName + 'Valid', "validImg", "");
            return true;
        } else {
            fillValidationField(fieldName + 'Valid', "errorImg", "");
            return false;
        }
    } else if (type == "email") {
        if (IsAnEmailAddress($(fieldName).value)) {
            fillValidationField(fieldName + 'Valid', "validImg", "");
            return true;
        } else {
            fillValidationField(fieldName + 'Valid', "errorImg", "");
            return false;
        }
    } else if (type == "select") {
        if ($(fieldName).selectedIndex != 0) {
            fillValidationField(fieldName + 'Valid', "validImg", "");
            return true;
        } else {
            fillValidationField(fieldName + 'Valid', "errorImg", "");
            return false;
        }
    } else if (type == "checkboxCGV") {
        if (!$(fieldName).checked) {
            fillValidationField(fieldName + 'Valid', "text", "<span style='color:red;'>En cochant cette case, j'accepte les conditions g&eacute;n&eacute;rales de vente* et reconnais &ecirc;tre &acirc;g&eacute;(e) de plus de dix-huit (18) ans.</span>");
        } else {
            fillValidationField(fieldName + 'Valid', "text", "<span style='color:black;'>En cochant cette case, j'accepte les conditions g&eacute;n&eacute;rales de vente* et reconnais &ecirc;tre &acirc;g&eacute;(e) de plus de dix-huit (18) ans.</span>");
        }
    } else if (type == "checkboxPartner") {
        if (!$(fieldName).checked) {
            fillValidationField(fieldName + 'Valid', "text", "<span style='color:red;'>En cochant cette case, je reconnais m’&ecirc;tre inscrit(e) par le biais d’un site web affili&eacute; &agrave; Womzone et accepte que mes donn&eacute;es &agrave; caract&egrave;re personnel soient transmises &agrave; l’&eacute;diteur du site web affili&eacute;. Un message me sera adress&eacute; m’indiquant les modalités d’exercice de mes droits aupr&egrave;s de cet &eacute;diteur. A d&eacute;faut d’acceptation, l’inscription ne peut se poursuivre.</span>");
        } else {
            fillValidationField(fieldName + 'Valid', "text", "<span style='color:black;'>En cochant cette case, je reconnais m’&ecirc;tre inscrit(e) par le biais d’un site web affili&eacute; &agrave; Womzone et accepte que mes donn&eacute;es &agrave; caract&egrave;re personnel soient transmises &agrave; l’&eacute;diteur du site web affili&eacute;. Un message me sera adress&eacute; m’indiquant les modalités d’exercice de mes droits aupr&egrave;s de cet &eacute;diteur. A d&eacute;faut d’acceptation, l’inscription ne peut se poursuivre.</span>");
        }
    } else if (type == "password") {
        var fieldName2 = fieldName.substring(0, fieldName.length - 1);
        if ($(fieldName2 + '1').value != $(fieldName2 + '2').value || $(fieldName2 + '1').value == "") {
            fillValidationField(fieldName + 'Valid', "errorImg", "");
        } else if ($(fieldName2 + '1').value.length < 4) {
            fillValidationField(fieldName + 'Valid', "text", "<span style='color:red;'>Mot de passe trop court! Minimum 4 caractères.</span>");
        } else {
            fillValidationField(fieldName + 'Valid', "validImg", "");
        }
    }
}


// MyModalPopup
var __UsingModalPopup = false;

function MyModalAlertPosition() {
    try {
        $('MyModalPopupBlk').style.top = (getScrollTop()) + 'px';
        setTimeout('MyModalAlertPosition()', 10);
    }
    catch (e) { }
}

function ModalPopupFadeOut(id, fade) {
    if (fade >= 0) {
        ChangeDivOpacity(id, fade);
        fade -= 10;
        setTimeout('ModalPopupFadeOut(\'' + id +'\', ' + fade.toString() + ')', 50);
    }
    else {
        document.body.removeChild($(id));
    }
}

function ModalPopupFadeIn(id, fade) {
    if (fade <= 80) {
        ChangeDivOpacity(id, fade);
        fade += 10;
        setTimeout('ModalPopupFadeIn(\'' + id + '\', ' + fade.toString() + ')', 50);
    }
}

function CloseModalPopup() {
    __UsingModalPopup = false;
    document.body.removeChild($('MyModalPopupBlkContent'));
    document.body.removeChild($('MyModalPopupBlkLoadingBlk'));
    ModalPopupFadeOut('MyModalPopupBlkBg', 80);
}

function MyModalPopupContentPosition() {
    try {
        $('MyModalPopupBlkContent').style.top = (getScrollTop() + 50) + 'px';
    }
    catch (e) { }
}

function MyModalPopupGetPostBack(Response, params) {
    $('MyModalPopupBlkLoadingBlk').style.display = 'none';
    var dv2 = document.createElement("DIV");
    dv2.setAttribute('id', 'MyModalPopupBlkContent');
    if (BrowserDetect.browser + BrowserDetect.version == 'Explorer7')
        dv2.style.width = getPageSize().width + 'px';
    if (BrowserDetect.browser + BrowserDetect.version == 'Explorer8')
        dv2.style.width = getPageSize().width + 'px';
    dv2.innerHTML = Response;
    document.body.appendChild(dv2);
    setTimeout(params[0], 1);
    MyModalPopupContentPosition();
}

function ClearModalPopup() {
    document.body.removeChild($('MyModalPopupBlkContent'));
}

function MyModalPopup(url, callback) {
    if (!__UsingModalPopup) {
        __UsingModalPopup = true;
        var dv1 = document.createElement("DIV");
        dv1.setAttribute('id', 'MyModalPopupBlkBg');
        dv1.style.height = getPageSize().height + 'px';
        dv1.style.display = 'none';
        if (BrowserDetect.browser + BrowserDetect.version == 'Explorer7')
            dv1.style.width = getPageSize().width + 'px';
        else if (BrowserDetect.browser + BrowserDetect.version == 'Explorer8')
            dv1.style.width = getPageSize().width + 'px';
        document.body.appendChild(dv1);
        ModalPopupFadeIn('MyModalPopupBlkBg', 0);
        $('MyModalPopupBlkBg').style.display = '';

        var dv2 = document.createElement("DIV");
        dv2.setAttribute('id', 'MyModalPopupBlkLoadingBlk');
        document.body.appendChild(dv2);
    }
    var LongUrl = '';
    if (url.toString().search('^LOCAL') == 0) {
        LongUrl = __CONT__URL_FRONT + url.toString().replace('LOCAL::', '');
    }
    else {
        LongUrl = __CONT__URL_FRONT + 'AjaxPages/AjaxCMS.aspx?CMS=' + url;
    }
    AjaxHttpGet(LongUrl, MyModalPopupGetPostBack, [callback]);
}

function GetChildNodeHTML(parentID, childID) {
    for (nodeIdex = 0; nodeIdex < $(parentID).childNodes.length; nodeIdex++) {
        if ($(parentID).childNodes[nodeIdex].id == childID)
            return $(parentID).childNodes[nodeIdex].innerHTML;
    }
    return '';
}

function SuroundWithPopup(idPopUp) {
    var htmlTable = '<table cellpadding="0" cellspacing="0" style="width:100%"><tr><td class="wzCTL wzBg Ste_PopupBorderImages"></td>';
    htmlTable += '<td class="wzT wzBg Ste_PopupBorderImages"></td><td class="wzCTR wzBg Ste_PopupBorderImages"></td></tr><tr><td class="wzL wzBg Ste_PopupBorderImages"></td><td><div class="wzLding Ste_PopupTrameBodyBorderColor" id="AjaxLoading" style="display:none"></div><div class="wzTtle Ste_PopupTrameBgColor Ste_MainColor">';
    htmlTable += GetChildNodeHTML(idPopUp, 'ContentTitle');
    htmlTable += '</div><div class="wzBdy Ste_PopupTrameBodyBorderColor">';
    htmlTable += GetChildNodeHTML(idPopUp, 'ContentBody');
    htmlTable += '</div><div class="wzFtr Ste_PopupTrameBgColor Ste_PopupButtonImages">';
    htmlTable += GetChildNodeHTML(idPopUp, 'ContentFooter');
    htmlTable += '</div></td><td class="wzR wzBg Ste_PopupBorderImages"></td></tr><tr><td class="wzCBL wzBg Ste_PopupBorderImages"></td><td class="wzB wzBg Ste_PopupBorderImages"></td><td class="wzCBR wzBg Ste_PopupBorderImages"></td></tr></table>';
    $(idPopUp).innerHTML = htmlTable;
    
    var w = $(idPopUp).style.width.toString().replace('px', '');
    if ($('WarningMessage') != null) {
        $('WarningMessage').className = 'WarningMessage Ste_PopupWarningMessageBorderColor Ste_PopupWarningMessageFontColor';
        $('WarningMessage').style.width = w - 124 + 'px';
        $('WarningMessage').style.display = 'none';
    }
}


function FindElemIdMatching(elem, regstr)
{
    if (elem.id != null && elem.id.match(regstr) != null) {
        return elem;
    }
    else if (elem.parentNode != null) {
        return FindElemIdMatching(elem.parentNode, regstr)
    }
    return null;
}

function FormatAnnounceInList(divID) {
    var announceElem = $(divID);

//    announceElem.style.cursor = 'pointer';
//    
//    $AttachEvent(announceElem, 'onmouseover', function(event) {
//        var event2 = event || window.event;
//        var target2 = event2.target || event2.srcElement;
//        FindElemIdMatching(target2, '^AnnounceInList_*').style.backgroundColor = '#F1F1F1';
//    });

//    $AttachEvent(announceElem, 'onmouseout', function(event) {
//        var event2 = event || window.event;
//        var target2 = event2.target || event2.srcElement;
//        FindElemIdMatching(target2, '^AnnounceInList_*').style.backgroundColor = '#FFFFFF';
//    });

//    $AttachEvent(announceElem, 'onclick', function(event) {
//        var event2 = event || window.event;
//        var target2 = event2.target || event2.srcElement;
//        document.location = GetElementByClassNamePath(FindElemIdMatching(target2, '^AnnounceInList_*'), 'AnnounceAction::MyActionList::ToDetail::MyDetailLink').href;
//    });
    
    var myTitleElem = GetElementByClassNamePath(announceElem, 'AnnounceHeader::AnnounceTitleLabel');
    var myLinkElem = GetElementByClassNamePath(announceElem, 'AnnounceAction::MyActionList::ToDetail::MyDetailLink');
    
    var NewTitle = document.createElement('SPAN');
    
    NewTitle.className = "AnnounceTitleLabel";
    var NewTitleA = document.createElement('A');
    NewTitleA.setAttribute('href', myLinkElem.href);
    NewTitleA.setAttribute('title', myTitleElem.innerHTML);
    NewTitleA.innerHTML = myTitleElem.innerHTML;

    NewTitle.appendChild(NewTitleA);
    
    GetElementByClassNamePath(announceElem, 'AnnounceHeader').removeChild(myTitleElem);
    GetElementByClassNamePath(announceElem, 'AnnounceHeader').appendChild(NewTitle);
    myLinkElem.innerHTML = "Voir le détail de l'annonce";
}

function AddUserDynamicStatus(UserGuid, ImgId) {
    var tmpSTR = '<a href="#" name="Ustatus" class="' + UserGuid + '"><img src="http://cms.womzone.com/00_WomzoneV2.0/StyleCSS/imgs/General/TPix.gif" style="border:none" class="imDisconnected" /></a>';

    $(ImgId).parentNode.innerHTML += tmpSTR;
    $(ImgId).parentNode.removeChild($(ImgId));
}

function AddDynamicLink(SpanID, Url, Alt) {
    var myA = document.createElement('a');
    myA.href = Url;
    myA.title = Alt;
    myA.className = $(SpanID).className;
    myA.innerHTML = $(SpanID).innerHTML;
    $(SpanID).innerHTML = '';
    $(SpanID).appendChild(myA);
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function GetSimpleDomainForIframe(FrontUrl) {
    var UrlArray = FrontUrl.split('.');
    return UrlArray[UrlArray.length - 2] + '.' + UrlArray[UrlArray.length - 1].replace('/', '');
}

// Debug
__DEBUG = null;
function MyTrace(str) {
    if (__DEBUG != null) {
        dv = document.createElement("DIV");
        dv.innerHTML = new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds() + " - " + str;
        $('__Console').appendChild(dv);
    }
}

function SetDebugMode(st) {
    if (st == 'On') {
        __DEBUG = true;
        c = document.createElement("DIV");
        c.setAttribute('id', '__Console');
        c.setAttribute('style', 'width:100%;height:130px;overflow:scroll;border-top:solid 4px #FF0000;background-color:#FFEEEE;margin-top:10px;');
        document.body.appendChild(c);
    }
    else if (st == 'Off' && __DEBUG != null) {
        __DEBUG = null;
        document.body.removeChild($('__Console'));
    }
}

function CynikRefresh() {
    AjaxHttpGet(__CONT__URL_FRONT + 'Extra/CleanSettings.aspx?ClearCache=1', function(response, params) {
        location.reload(true)
    }, null);
}

$ImportScript('InitApp');
