/*
    The Xtreme Validation Framework.

    XVALIDATION-NOTIFIERS: Extended Notifiers

    $Id: pyco.xvalidation-notifiers.js,v 1.2 2007/01/16 07:10:57 thanh.an Exp $
*/
//-----------------------------------------------------------------------------------------------
// @requirements: common-dom
var myScrollGenError;
if (!window.PYCO_COMMON_DOM) {
    alert("Reference Error:\n" +
            "Pyco Common DOM is required.\n" +
            "(Please make sure that you have pyco.common-dom.js in your include path.)");
}
// Reference definition
if (window.PYCO_XVALIDATION_NOTIFIERS) {
    window.PYCO_XVALIDATION_NOTIFIERS.count ++;
    alert("Reference Error:\n" +
            "Duplicated references of Pyco XValidation Notifiers found. Ref. count = " + (window.PYCO_XVALIDATION_NOTIFIERS.count));
} else {
    window.PYCO_XVALIDATION_NOTIFIERS = new Object();
    window.PYCO_XVALIDATION_NOTIFIERS.count = 1;
}
//-----------------------------------------------------------------------------------------------
// @class: BalloonNotifier
function BalloonNotifier() {
};
// @static fields:
BalloonNotifier.ALERT_POST_TRIES = ["BT:LL", "BT:CC", "BT:RR", "TT:LR", "MM:LR", "BB:LR", "TB:LL", "TB:CC", "TB:RR", "TT:RL", "MM:RL", "BB:RL"];

// @static init:
var div;
BalloonNotifier.handleWindowOnload = function (systemEvent) {
    if (BalloonNotifier.alertBox) {
        return;
    }
    div = document.createElement("div");
    div.setAttribute("id","alertBox");
    div.setAttribute("class","WrapPopUp");
    var ie=document.all;
    if (ie) {
        div.attributes("id").value = "alertBox";
        div.attributes("class").value = "WrapPopUp";
    }
    var initTopPos="74px";
    /*if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
        initTopPos = "47px";
    }*/
    div.innerHTML = 
                    "       <div class=\"WrapInside\">\n"+
                    "            <div class=\"Fermer\">\n"+
                    "                   <a onclick=\"BalloonNotifier.closeAlert(); return false;\" title=\"Fermer\" href=\"#\">Fermer</a>"+
                    "             </div>\n"+
                    "             <div class=\"WrapContent\" >\n"+
                    "                   <div id=\"upGenError\" class=\"UpButton\"> "+
                    "                       <img src=" + upImage + " width=\"7\" height=\"20\"> "+
                    "                   </div> "+
                    "                   <div id=\"downGenError\" class=\"DownButton\"> "+
                    "                       <img src=" + downImage + " width=\"7\" height=\"20\"> "+
                    "                   </div> "+
                    "                   <div id=\"trackGenError\" class=\"TrackLine\"> "+
                    "                       <img src=" + trackImage + " width=\"7\" height=\"161\"> "+
                    "                   </div> "+
                    "                   <div id=\"dragGenError\" class=\"DragPointer\" style=\"top:" + initTopPos + "\"> "+
                    "                       <img src=" + dragImage + " width=\"7\" height=\"53\"> "+
                    "                   </div>" +
                    "                   <h2 id=\"alertBoxTitle\">Error title goes here</h2>\n" +
                    "                   <div id=\"contentMaskGenError\" class=\"ContentMask\">" +
                    "                       <div id=\"graphicsb0GenError\" class=\"InsideContent\">" +
                    "                           <dl id=\"alertBoxBody\"></dl>\n"+
                    "                       </div" +
                    "                   </div>"+
                    "             </div>\n"+
                    "       </div>"
    Dom.getId("mainContent").appendChild(div);
    BalloonNotifier.alertBox = Dom.get("alertBox");
    BalloonNotifier.title = Dom.get("alertBoxTitle");
    BalloonNotifier.body = Dom.get("alertBoxBody");
    BalloonNotifier.firstError=Dom.get("alertBox");

};
Dom.registerEvent(window, "load", BalloonNotifier.handleWindowOnload);

BalloonNotifier.closeAlert = function () {
    myScrollGenError.dragObj.hideVis();
    myScrollGenError.trackObj.hideVis();
    myScrollGenError.downObj.hideVis();
    myScrollGenError.upObj.hideVis();
    var contentObject = document.getElementById("graphicsb0GenError");
    var dragObject = document.getElementById("dragGenError");
    contentObject.style.top = 0+"px";
    dragObject.style.top = 74+"px";
    
    if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
        dragObject.style.top = 47+"px";
    }
    //BalloonNotifier.firstError.focus();
    //BalloonNotifier.firstError.select();
    BalloonNotifier.alertBox.style.display = "none";
    hideLightBox();
    //Enable scrollbar
    showPopUpIndicator = "false";

};
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function ReplaceAll(value){

    var strText = new String(value);
    var strReplaceAll = strText;
    var intIndexOfMatch = strReplaceAll.indexOf( "&nbsp;" );
     // Loop over the string value replacing out each matching
     // substring.
     while (intIndexOfMatch != -1){
     // Relace out the current instance.
     strReplaceAll = strReplaceAll.replace( "&nbsp;", " " );
      
     // Get the index of any next matching substring.
     intIndexOfMatch = strReplaceAll.indexOf( "&nbsp;" );
     }
     return strReplaceAll.trim();
    }
function getLabelText(control){
    var id = control.id;
    var ie = document.all;
    var x = document.getElementsByTagName("label");
    for (var i = 0; i < x.length; i++)
    {
        if(navigator.userAgent.indexOf("Safari") > 0 && navigator.userAgent.indexOf("Mac") > 0){
            try{
                if (x[i].hasAttribute('for') && x[i].getAttribute('for') == id)
                {
                    var node = x[i].cloneNode(true);
                    if(node.childNodes.length>1){
                        node.removeChild(node.childNodes[1]);
                        }
                        
                    return ReplaceAll(node.innerHTML);
                }
            }
            catch(e){
            }
            finally{
            }
        }
        else {
            if (x[i].attributes['for'] && x[i].attributes['for'].value == id)
            {
                var node = x[i].cloneNode(true);
                if(node.childNodes.length>1){
                    node.removeChild(node.childNodes[1]);
                    }
                    return ReplaceAll(node.innerHTML);
            }
        }
    }
    return "";
};  
BalloonNotifier.prototype.notify = function (form, errors) {
    //throw new JFException("not yet implemented :-s");
    //TODO : remove 2 below line when all DONE.
    //var error = errors.getFirstError();
    //BalloonNotifier.firstError=error.field;
    var temp = errors.getAllErrors();
    var stringError = "";
    
    for (var i = 0; i < temp.length; i++)
    {
    
       stringError += "<dt>" + getLabelText(temp[i].field) + " erreur :</dt>\n";
       stringError += "<dd><span>" + temp[i].message + "</span></dd>\n";
       //temp[i].field.className = "ErrorBox";
       //rem by son.tong : 
       //do not replace other css class cause textbox can use other css class
    }
    
    //TODO : add by son.tong to integrate with client validation
    var objValidationValueMessage = document.getElementById("validationValueMessage");
    
    if (objValidationValueMessage != null)
    {
        if (objValidationValueMessage.value != "")
        {
            stringError += objValidationValueMessage.value;
        }
        //remove value when done. 
        objValidationValueMessage.value = "";
    }
    //end add by son.tong
    var alertBox = BalloonNotifier.alertBox;
    var title = BalloonNotifier.title;
    var body = BalloonNotifier.body;
    
    Dom.setInnerText(title,"Erreur(s)");
    Dom.setInnerHtml(body, stringError);
    alertBox.style.display = "block";
    myScrollGenError = new ScrollObjGenError(6,0,134,"trackGenError","upGenError","downGenError","dragGenError","contentMaskGenError","graphicsb0GenError");
    setLightBoxSize();//Setting LightBox size
    setPopUpPosition();
    showPopUpIndicator = "true";
    try
    {
        alertBox.select();
    }catch(e)
    {
    }
    
    //====== check for text box
    var allTextBox = document.getElementsByTagName("input");
    for(var count = 0; count<allTextBox.length; count++)
    {
       if (allTextBox[count].attributes['type'].value == "text" || allTextBox[count].attributes['type'].value == "password" || allTextBox[count].attributes['type'].value == "textarea")
       {
           if (allTextBox[count].style.borderColor.toString() == "")
           {
                allTextBox[count].style.borderColor = "#bdbbbb";
           }
                         
            var hasError = false;
            for(var errorCount = 0; errorCount < temp.length; errorCount++)
            {
                if(allTextBox[count].id == temp[errorCount].field.id)
                {
                  hasError = true;
                  break;
                }
            }
            if(hasError == false)
            {
                //TODO : this condition help to find out the second validation 
                // IE : "#ff0000"
                // FF : "rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0)
                // SAFARI : "rgb(255, 0, 0)"
                // We have to cheat when using the second validation with red value="#ff0001"
                var borderColorString = allTextBox[count].style.borderColor.toString();
                if (borderColorString == "#ff0000" 
                        || borderColorString == "rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0)" 
                        || borderColorString == "rgb(255, 0, 0)")
                {
                    allTextBox[count].style.borderColor = "#bdbbbb";
                }
            }
            else
            {
                allTextBox[count].style.borderColor = "#ff0000";
            }
       }
    }
    
    
    //==== check for Text Area
    var allTextAreaBox = document.getElementsByTagName("textarea");
    for(var count = 0; count<allTextAreaBox.length; count++)
    {
       if (allTextAreaBox[count].style.borderColor.toString() == "")
       {
            allTextAreaBox[count].style.borderColor = "#bdbbbb";
       }
        var hasError = false;
        for(var errorCount = 0; errorCount < temp.length; errorCount++)
        {
            if(allTextAreaBox[count].id == temp[errorCount].field.id)
            {
              hasError = true;
              break;
            }
        }
        if(hasError == false)
        {
            //TODO : this condition help to find out the second validation 
            // IE : "#ff0000"
            // FF : "rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0)
            // SAFARI : "rgb(255, 0, 0)"
            // We have to cheat when using the second validation with red value="#ff0001"
            var borderColorString = allTextAreaBox[count].style.borderColor.toString();
            if (borderColorString == "#ff0000" 
                    || borderColorString == "rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0) rgb(255, 0, 0)" 
                    || borderColorString == "rgb(255, 0, 0)")
            {
                allTextAreaBox[count].style.borderColor = "#bdbbbb";
            }
        }
        else
        {
            allTextAreaBox[count].style.borderColor = "#ff0000";
        }
   
    }
};

// @class: InlineNotifier
function InlineNotifier() {
    this.generateErrorMessage = true;
    this.placeHolderIdPattern = "${id}Error";
    this.messageSpans = [];
}
InlineNotifier.ERROR_MESSAGE_CLASS_NAME = "ErrorMessage";
InlineNotifier.MESSAGE_CLASS_NAME = "Message";
InlineNotifier.HINT_CLASS_NAME = "Hint";
InlineNotifier.prototype.prepare = function () {
    for (var i = 0; i < this.messageSpans.length; i ++) {
        var span = this.messageSpans[i];
        Dom.addClass(span, "NotAvailable");
    }
    this.messageSpans = [];
};
InlineNotifier.prototype.getErrorMessageSpan = function (field) {
    var doc = field.ownerDocument;
    var span = null;
    if (this.generateErrorMessage) {    
        if (!field._messageSpan) {
            span = doc.createElement("span");        
            Dom.appendAfter(span, field);
            field._messageSpan = span;
        } else {
            span = field._messageSpan;
        }
    } else {
        var id = ValidationUtil.evalAgainstObject(this.placeHolderIdPattern, field);
        span = doc.getElementById(id);
    }
    if (!span._initialized) {
        var message = doc.createElement("span");
        var hint = doc.createElement("span");
        span.appendChild(message);
        span.appendChild(hint);
        
        span.className = InlineNotifier.ERROR_MESSAGE_CLASS_NAME;
        message.className = InlineNotifier.MESSAGE_CLASS_NAME;
        hint.className = InlineNotifier.HINT_CLASS_NAME;
        
        span._messageSpan = message;
        span._hintSpan = hint;
        
        span._initialized = true;
    }
    Dom.removeClass(span, "NotAvailable");
    this.messageSpans.push(span);
    return span;
    
};
InlineNotifier.prototype.notify = function (form, errors) {
    for (var i = 0; i < errors.errors.length; i++) {
        var error = errors.errors[i];
        try {
            var span = this.getErrorMessageSpan(error.field);
            Dom.setInnerText(span._messageSpan, error.message);
            
            if (!error.hint) {
                Dom.addClass(span._hintSpan, "NotAvailable");
            } else {
                Dom.removeClass(span._hintSpan, "NotAvailable");
                Dom.setInnerText(span._hintSpan, error.hint);
            }
            
        } catch (e) {
            throw e;
        }
        try {
            errors.getFirstError().field.focus();
        } catch (e) {}
    }
};
/*----*/
var dom = document.getElementById;
var iex = document.all;
var ns4 = document.layers;

function addEvent(event,method){
    this[event] = method;
    if(ns4) this.captureEvents(Event[event.substr(2,event.length).toUpperCase()]);
}
function removeEvent(event){
    this[event] = null;
    if(ns4) this.releaseEvents(Event[event.substr(2,event.length).toUpperCase()]);
}
function getElement(name,nest){
    nest = nest ? "document."+nest+"." : "";
    var el = dom ? document.getElementById(name) : iex ? document.all[name] : ns4 ? eval(nest+"document."+name) : false;
    el.css = ns4 ? el : el.style;
    el.getTop = function(){return parseInt(el.css.top) || 0};
    el.setTop = function(y){el.css.top = ns4 ? y: y+"px"};
    el.getHeight = function(){return ns4 ? el.document.height : el.offsetHeight};
    el.getClipHeight = function(){return ns4 ? el.clip.height : el.offsetHeight};
    el.hideVis = function() {
        el.css.visibility="hidden";
    };
    el.showVis = function() {
        el.css.visibility="visible";
    };
    el.addEvent = addEvent;
    el.removeEvent = removeEvent;
    return el;
}
function getYMouse(e){
    return iex ? event.clientY : e.pageY;
}

document.addEvent = addEvent;
document.removeEvent = removeEvent;

// ||||||||||||||||||||||||||||||||||||||||||||||||||
// Scroller Class

ScrollObjGenError = function(speed, dragHeight, trackHeight, trackObj, upObj, downObj, dragObj, contentMaskObj, contentObj){
    this.speed = speed;
    this.dragHeight = dragHeight;
    this.trackHeight = trackHeight;
    this.trackObj = getElement(trackObj);
    this.upObj = getElement(upObj);
    this.downObj = getElement(downObj);
    this.dragObj = getElement(dragObj);
    this.contentMaskObj = getElement(contentMaskObj);
    this.contentObj = getElement(contentObj,contentMaskObj);
    this.obj = contentObj+"Object";
    eval(this.obj+"=this");
    
    this.trackTop = this.dragObj.getTop();
    this.trackLength = this.trackHeight-this.dragHeight;
    this.trackBottom = this.trackTop+this.trackLength;
    this.contentMaskHeight = this.contentMaskObj.getClipHeight();
    this.contentHeight = this.contentObj.getHeight();
    this.contentLength = this.contentHeight-this.contentMaskHeight;
    this.scrollLength = this.trackLength/this.contentLength;
    this.scrollTimer = null;

    if(this.contentHeight < this.contentMaskHeight) {
        this.dragObj.hideVis();
        this.trackObj.hideVis();
        this.downObj.hideVis();
        this.upObj.hideVis();
    } else {
        this.dragObj.showVis();
        this.trackObj.showVis();
        this.downObj.showVis();
        this.upObj.showVis();
        var self = this;
        this.trackObj.addEvent("onmousedown", function(e){self.scrollJump(e);return false});
        this.upObj.addEvent("onmousedown", function(){self.scroll(self.speed);return false});
        this.upObj.addEvent("onmouseup", function(){self.stopScroll()});
        this.upObj.addEvent("onmouseout", function(){self.stopScroll()});
        this.downObj.addEvent("onmousedown", function(){self.scroll(-self.speed);return false});
        this.downObj.addEvent("onmouseup", function(){self.stopScroll()});
        this.downObj.addEvent("onmouseout", function(){self.stopScroll()});
        this.dragObj.addEvent("onmousedown", function(e){self.startDrag(e);return false});
        if(iex) this.dragObj.addEvent("ondragstart", function(){return false});
    }
}
ScrollObjGenError.prototype.startDrag = function(e){
    this.dragStartMouse = getYMouse(e);
    this.dragStartOffset = this.dragObj.getTop();
    var self = this;
    document.addEvent("onmousemove", function(e){self.drag(e)});
    document.addEvent("onmouseup", function(){self.stopDrag()});
}
ScrollObjGenError.prototype.stopDrag = function(){
    document.removeEvent("onmousemove");
    document.removeEvent("onmouseup");
}
ScrollObjGenError.prototype.drag = function(e){
    var currentMouse = getYMouse(e);
    var mouseDifference = currentMouse-this.dragStartMouse;
    var dragDistance = this.dragStartOffset+mouseDifference;
    var dragMovement = (dragDistance<this.trackTop) ? this.trackTop : (dragDistance>this.trackBottom) ? this.trackBottom : dragDistance;
    this.dragObj.setTop(dragMovement);
    var contentMovement = -(dragMovement-this.trackTop)*(1/this.scrollLength);
    this.contentObj.setTop(contentMovement);
}
ScrollObjGenError.prototype.scroll = function(speed){
    var contentMovement = this.contentObj.getTop()+speed;
    var dragMovement = this.trackTop-Math.round(this.contentObj.getTop()*(this.trackLength/this.contentLength));
    if(contentMovement > 0){
        contentMovement = 0;
    }else if(contentMovement < -this.contentLength){
        contentMovement = -this.contentLength;
    }
    if(dragMovement < this.trackTop){
        dragMovement = this.trackTop;
    }else if(dragMovement > this.trackBottom){
        dragMovement = this.trackBottom;
    }
    this.contentObj.setTop(contentMovement);
    this.dragObj.setTop(dragMovement);
    this.scrollTimer = window.setTimeout(this.obj+".scroll("+speed+")",25);
}
ScrollObjGenError.prototype.stopScroll = function(){
    if(this.scrollTimer){
        window.clearTimeout(this.scrollTimer);
        this.scrollTimer = null;
    }
}
ScrollObjGenError.prototype.scrollJump = function(e){
    var currentMouse = getYMouse(e);
    var dragDistance = currentMouse-(this.dragHeight/2);
    var dragMovement = (dragDistance<this.trackTop) ? this.trackTop : (dragDistance>this.trackBottom) ? this.trackBottom : dragDistance;
    this.dragObj.setTop(dragMovement);
    var contentMovement = -(dragMovement-this.trackTop)*(1/this.scrollLength);
    this.contentObj.setTop(contentMovement);
}

// ||||||||||||||||||||||||||||||||||||||||||||||||||
// Misc Functions

function fixNetscape4(){
    if(ns4origWidth != window.innerWidth || ns4origHeight != window.innerHeight){
        window.location.reload();
    }    
}
if(document.layers){
    ns4origWidth = window.innerWidth;
    ns4origHeight = window.innerHeight;
    window.onresize = fixNetscape4;
}
