var widgetRegister = new Array();
var iframeObj;

function getNewAjaxFormHttpRequest(){
    try{
        a = new XMLHttpRequest();
    }
    catch(e){
    }
    if(window.ActiveXObject) {
        try {
            a = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
        try {
            a = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
        throw new Error("Could not find an XMLHttpRequest alternative.")
    }
}
}
return a;
}

function WidgetObject( anchor ){
    this.getAttributeValue = getAttributeValue;
    this.anchor = anchor;
    //alert(this.anchor.attributes.length);
    for ( a=0; a < this.anchor.attributes.length; a++ ){
        try{
            attribute = this.anchor.attributes[a];
            if(attribute==undefined )
                continue;
            eval ( "this."+attribute.name+"=\""+attribute.value+"\"");
        }
        catch(e){
        }
    }
    this.hiddenField = this.display;
    this.ajaxRequest = this.concept;
    if ( this.childlist == "yes" ){
        this.ajaxRequest = "childlist";
    }
    this.setConcept = setConcept;
    this.view = this.getAttributeValue("view");
    this.view = this.getAttributeValue(this.concept, this.view);
    this.prepareDiv = prepareDiv;
    this.setLinks = setLinks;
    this.hideFormDiv = hideFormDiv;
    this.hideViewDiv = hideViewDiv;
    this.widgetId = this.timestamp+"_"+this.dataname;
    widgetRegister[this.widgetId] = this;
    this.getFormDiv = getFormDiv;
    this.getViewDiv = getViewDiv;
    this.getId = getId;
    this.getForm = getForm;
    this.executeAjaxCall = ajaxWidgetCall;
}

function setConcept( concept ){
    this.concept = concept;
    this.view = this.getAttributeValue("view");
    this.view = this.getAttributeValue(this.concept, this.view);    
}

function getForm(){
    this.actualForm = document.getElementById("vmForm_"+this.lastCallTimeStamp);
    return this.actualForm;
}

function getFormDiv(){
    try{
        this.formDiv = document.getElementById( this.timestamp+"_subFormDiv");
        return this.formDiv;
    }catch( e ){
    return undefined;
}
}

function getViewDiv(){
    try{
        this.viewDiv = document.getElementById( this.timestamp+"_"+this.dataname+"_view_div");
        return this.viewDiv;
    }catch( e ){
    return undefined;
}
}

function getId(){
    this.id = undefined;
    if ( document.getElementById( this.timestamp+"_"+this.dataname) ){
        this.id = document.getElementById( this.timestamp+"_"+this.dataname).value;
    }else{
    if ( this.getForm() && this.getForm().id ){
        this.id = this.getForm().id.value;
    }
}
return this.id;
}

function hideFormDiv(){
    this.getFormDiv().innerHTML = "";
    this.getFormDiv().style["border"] = "";
    this.getFormDiv().style["display"] = "none";
    this.getFormDiv().onclick = "";
    this.setLinks();
}

function hideViewDiv(){
    this.getViewDiv().innerHTML = "";
    this.getViewDiv().style["border"] = "";
    this.getViewDiv().style["display"] = "none";
    this.setLinks();
}

function prepareDiv(){
    try{
        if ( "view" != this.concept ){
            formDiv = this.getFormDiv();
            formDiv.innerHTML="Sending request...";
            formDiv.style["position"]="absolute";
            formDiv.style["border"] = "1px solid black";
            formDiv.style["background"] = "#ffffff";        
            formDiv.style["display"] = "block";
            position = getPosition( this.anchor );
            div = this.getViewDiv();
            var positionY=position.y+div.offsetHeight;
            formDiv.style.top = positionY+"px";
            formDiv.style.left = div.offsetLeft+"px";
        }else{
        div = this.getViewDiv();
        div.innerHTML ="Sending request...";
    }
}catch(e){

}
}

function getAttributeValue( attributeName, defaultValue ){
    if ( this.anchor.attributes[ attributeName ] ){
        return this.anchor.attributes[ attributeName ].value;
    }else{
    return defaultValue;
}
}

function ajaxCall( anchor ){
    widgetObject = new WidgetObject( anchor );
    widgetObject.executeAjaxCall();
}

function childListClick( widgetId, id, concept ){
    // I think we can have: view, edit, delete or remove
    // if in search mode, view is add
    var widgetObject = widgetRegister[widgetId];
    if( widgetObject.concept == "search" ){
        widgetObject.nextAction = "displayChildList";
        url = "../handlers/addH.jsp";
        var parameters = "ajaxRequest="+widgetObject.ajaxRequest;
        parameters += "&_parentID="+widgetObject._parentid;
        parameters += "&_childID="+id;
        parameters += "&_addTo="+widgetObject.dataname;
        widgetObject.concept = "add";
        postAjaxCall( widgetObject, url, parameters );
    }else{
    widgetObject.concept = concept;
    if(concept!="view"){
        widgetObject.nextAction = "form";
        widgetObject.childId = undefined;
    }
    else{
        widgetObject.nextAction = "view";
        widgetObject.childId = id;
    }
    widgetObject.executeAjaxCall();
}
}

function getViewByName( timeStamp,target,returnTo,id){
    childListClick( target, id, "view" );
}

function ajaxWidgetCall(){
    this.prepareDiv();
    this.setLinks();
    nowTimeStamp = new Date().getTime();
    this.lastCallTimeStamp = nowTimeStamp;
    concept = this.concept;
    var parameters = "ajaxRequest="+this.ajaxRequest;
    parameters += "&timeStamp="+this.lastCallTimeStamp;
    parameters += "&returnTo="+this.dataname;
    if ( this.display ){
        parameters += "&hiddenField="+this.display;
    }
    if ( this.getId() && !( this.childlist == "yes" ) ){
        parameters += "&id="+this.getId();
    }
    if ( this.target ){
        parameters += "&_target="+this.target;
    }
    if(this.hideheaders){
        parameters += "&_hideHeaders=true";
    }
    if ( concept == "view" ){
        widgetObject.nextAction = "view";
    }else{
    widgetObject.nextAction = "form";
}
if ( this.childlist == "yes" ){
    parameters += "&_parentID="+this._parentid;
    if ( this.concept == "create" ){
        parameters += "&_addTo="+this.dataname;
    }
    parameters += "&_target="+this.widgetId;
    if ( this.childId ){
        parameters += "&_childID="+this.childId;
    }
    if ( this.concept == "view" ){
        parameters += "&id="+this.childId;
    }
    if ( this.concept == "select" ){
        widgetObject.nextAction = "view";
    }
}

url = "../"+this.view+"/"+concept+".jsp";    
postAjaxCall( this, url, parameters );

}

function postAjaxCall( widgetObject, url, parameters ){
    widgetObject.ajaxFormHttpRequest = getNewAjaxFormHttpRequest();
    widgetObject.ajaxFormHttpRequest.onreadystatechange = onReadyState;
    widgetObject.ajaxFormHttpRequest.open("POST",url, true);
    widgetObject.ajaxFormHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    widgetObject.ajaxFormHttpRequest.setRequestHeader("Content-length", parameters.length);
    widgetObject.ajaxFormHttpRequest.send(parameters);
}

function setLinks(){
    try{
        id = this.id;
        formType = this.type;
        search = document.getElementById(this.dataname+"_search_anchor");
        view = document.getElementById(this.dataname+"_view_anchor");
        create = document.getElementById(this.dataname+"_create_anchor");
        modify = document.getElementById(this.dataname+"_modify_anchor");
        
        if ( !formType && !id ){
            // this means no selected object or open form
            //just show search and create
            setElementDisplay(search,"inline");
            setElementDisplay(create,"inline");
            setElementDisplay(modify,"none");
            setElementDisplay(view,"none");
            return;
        }
        
        if ( !formType && id ){
            // this means a selected object but no open form
            //just show search and view ( and maybe clear )
            setElementDisplay(search,"inline");
            setElementDisplay(create,"none");
            setElementDisplay(modify,"inline");
            setElementDisplay(view,"inline");
            return;
        }
        
        //now we have a form type
        if ( "CREATE" == formType ){
            setElementDisplay(search,"inline");
            setElementDisplay(create,"none");
            setElementDisplay(modify,"none");
            setElementDisplay(view,"none");
            return;
        }
        
        //now we have a form type
        if ( "MODIFY" == formType ){
            setElementDisplay(search,"none");
            setElementDisplay(create,"none");
            setElementDisplay(modify,"none");
            setElementDisplay(view,"none");
            return;
        }
        
        //now we have a form type
        if ( "SEARCH" == formType ){
            setElementDisplay(search,"none");
            setElementDisplay(create,"inline");
            setElementDisplay(modify,"none");
            setElementDisplay(view,"none");
            return;
        }
        setElementDisplay( search, "inline");
        setElementDisplay(create,"inline");
        setElementDisplay(modify,"inline");
        setElementDisplay(view,"inline");
    }catch(e){
    
}    
}

function setElementDisplayByID( id, style ){
    element = document.getElementById( id );
    if ( element ){
        element.style.display = style;
    }
}

function setElementDisplay( element, style ){
    if ( element ){
        element.style.display = style;
    }
}

function getPosition(el) {
    var r = { x: el.offsetLeft, y: el.offsetTop };
    if (el.offsetParent) {
        var tmp = getPosition(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y+6;
    }
    return r;
}

function onReadyState(){
    for ( a in widgetRegister ){
        widgetObject = widgetRegister[a];
        ajaxFormHttpRequest = widgetObject.ajaxFormHttpRequest;
        if (ajaxFormHttpRequest!=null && ajaxFormHttpRequest.readyState == 4) {
            try{
                if ( "formSumitResult" == widgetObject.nextAction ){
                    xml = ajaxFormHttpRequest.responseXML;
                    response = xml.documentElement;
                    status = response.getElementsByTagName('status')[0].childNodes[0].nodeValue;
                    if ( status == "ERROR" ){
                        message = response.getElementsByTagName('message')[0].childNodes[0].nodeValue;
                        alert( message );
                    }else{
                    if ( widgetObject.childlist == "yes" ){
                        widgetObject.setConcept("select");
                        widgetObject.executeAjaxCall();
                        return;
                    }else{
                    hiddenValue = response.getElementsByTagName('hiddenvalue')[0].childNodes[0].nodeValue;
                    id = response.getElementsByTagName('id')[0].childNodes[0].nodeValue;
                    populate(widgetObject.dataname, id, hiddenValue);
                    widgetObject.hideFormDiv();                  
                }
            }
        }else if ( "displayChildList" == widgetObject.nextAction ){
        if ( ajaxFormHttpRequest.responseText != "" ){
            alert( ajaxFormHttpRequest.responseText );                       
        }else{
        widgetObject.setConcept("select");
        widgetObject.executeAjaxCall();
        widgetObject.executeAjaxCall();
        return;                        
    }
}else if ( "view" == widgetObject.nextAction ){
viewDiv = widgetObject.getViewDiv();
viewDiv.style.display = "block";
viewDiv.innerHTML = "<div onclick=\"hideAjaxViewDiv( '"+widgetObject.widgetId+"' )\" class='ajaxInlinePopup'>Close X</div>";
if(widgetObject.expandview && widgetObject.childId){
    viewDiv.innerHTML+="<div onclick=\"childListClick( '"+widgetObject.widgetId+"','"+widgetObject.id+"','modify' )\" class='ajaxInlinePopup'>Edit</div>";
    viewDiv.innerHTML += "<div onclick=\"window.location='../"+widgetObject.expandview+"/view.jsp?id="+widgetObject.childId+"'\" class='ajaxInlinePopup'>Expand</div>";
}
viewDiv.innerHTML += ajaxFormHttpRequest.responseText;
try{
    widgetObject.hideFormDiv();
}
catch( exception ){
    alert( " hide form div " + exception );
}
}else{
// assume this is a form request and the last form in order is the new form
formDiv = widgetObject.getFormDiv();
formDiv.innerHTML = "<div onclick=\"hideAjaxFormDiv('"+widgetObject.widgetId+"');\" class='ajaxInlinePopup'><b>X</b>Close</div>";
formDiv.innerHTML += ajaxFormHttpRequest.responseText;
}
widgetObject.ajaxFormHttpRequest=null;            
}catch( e ){
viewDiv = widgetObject.getViewDiv();
viewDiv.style.display = "block";
viewDiv.innerHTML = "<div onclick=\"hideAjaxViewDiv( '"+widgetObject.widgetId+"' )\" class='ajaxInlinePopup'>Close X</div>";
viewDiv.innerHTML += e + "<br><br>"+ ajaxFormHttpRequest.responseText;
try{
    widgetObject.hideFormDiv();
}
catch( exception ){
    alert( " hide form div " + exception );
}
}
widgetObject.setLinks();
}
}
}

function ajaxFormSubmit(ajaxForm){
    var formIdToMatch = ajaxForm.attributes['id'].value;
    var widgetObject;
    for ( o in widgetRegister ){
        widgetObject = widgetRegister[o];
        try{
            if ( widgetObject.getForm() && formIdToMatch == widgetObject.getForm().attributes['id'].value ){
                break;
            }else{
            //alert( "Form, id:"+formIdToMatch +" ts "+ widgetObject.timestamp + " lcts " + widgetObject.lastCallTimeStamp );
        }
    }catch( e ){
    
}
}
try{
    if(ajaxForm.attributeName){
        ajaxForm.target="hiddenAjaxFrame";
        iframeObj=new iFrameElement(widgetObject);
        ajaxForm._targetURL.value="../handlers/iframeConfirmH.jsp";
        if(ajaxForm.returnTo){
            ajaxForm.returnTo.disabled=true;
        }
        ajaxForm.submit();
        return;
    }else {
    var parameters = "";
    for ( i = 0 ; i < ajaxForm.elements.length; i++ ){
        el = ajaxForm.elements[i];
        if ( el.value && el.name && el.type && !el.disabled ){
            parameters += "&"+el.name + "=" + el.value;
        }
    }
    parameters = "ajaxRequest="+widgetObject.ajaxRequest+parameters;
    url = "../handlers/formSubmitH.jsp";
    if(widgetObject.concept=="worksheet"){
        url = "../handlers/multiModifyH.jsp";
    }
    
    if ( ajaxForm.action.indexOf("searchH.jsp") != -1 ){
        url = ajaxForm.action;
        widgetObject.nextAction = "searchResult";
        parameters += "&_target="+widgetObject.widgetId;
    }else{
    widgetObject.nextAction = "formSumitResult";
}
widgetObject.hideFormDiv();
widgetObject.prepareDiv();
postAjaxCall(widgetObject, url, parameters)
}
}
catch( exception ){
    alert( "On submit " + exception );
}
}

function hideAjaxFormDiv( widgetId ){
    var widgetObject = widgetRegister[widgetId];
    widgetObject.hideFormDiv();
}

function hideAjaxViewDiv( widgetId ){
    var widgetObject = widgetRegister[widgetId];
    if ( widgetObject.concept == "view" && "yes" == widgetObject.childList ){
        widgetObject.concept = "select";
        widgetObject.executeAjaxCall();
    }else{
    widgetObject.hideViewDiv();        
}
}

function iFrameElement(widgetObject){
    this.widgetObject=widgetObject;
}

function iFrameH(){
    iframeObj.widgetObject.setConcept("select");
    iframeObj.widgetObject.nextAction = "view";
    iframeObj.widgetObject.executeAjaxCall();
}