/**
 * Project: Javascriptian 
 * 
 * Source file:  jsian-version-2.0.1.js
 * 
 * Description: Responsible for all the utility task related to javascript
 * 
 * Author : Sahil Azim
 * 
 * Creation Date: Dec-01-2008 
 * 
 * Modified Date:
 * 
 * Version: 1.0
 * 
 * Revisions: 0
 * 
 */
var JSClass = {
   newClass:function(){
   	   function func(){
   	      if(this.init){
               this.init.apply(this, arguments);
          }
       }
       func.prototype.constructor = func;
       return func;
   }
};

var AjaxConstant = {
    SINGLE_REQUEST:true,//configurable, if you want to create and send number of ajax request at a time.
    REQUIRED_CACHING:false,//by default caching is off. means it will call fresh call every time.
    BUSY:false,
    ALL_PARAMETER:"all_parameter",
    FREE:true,
    ASYNCHRONOUS:true,
    REQUEST_STATUS:true,
    isRequestFree:function(){
        return this.SINGLE_REQUEST?this.REQUEST_STATUS:this.FREE;
    }
};

var BrowserUtil = {
    firefox:(navigator.userAgent.indexOf('Firefox')>-1),
	ie:(navigator.userAgent.indexOf('MSIE')>-1),
    safari:(navigator.userAgent.indexOf('Safari')>-1)
};

var FormConstant = {
    Text:"text",
    Password:"password",
    Hidden:"hidden",
    File:"file",
    DropDown:"select-one",
    TextArea:"textarea",
    ListBox:"select-multiple",
    CheckBox:"checkbox",
    Radio:"radio",
    GET:"GET",
    POST:"POST",
    SELECTED:"selected",
    ALL_PARAMETER:"all_parameter",
    NAMELESS_FORM:"nameless_form"// this form name is for those component which is not bloked with any form tags    
};

var PageElements = {
    FORM_COMPONENTS:null,
    FORM_MAPPED_COMPONENTS:null,
    FORM_COMPONENT_MAP:null,
    HTML_COMPONENTS:null,
    reload:function(){
      PageElements.FORM_COMPONENTS = null;
      PageElements.FORM_MAPPED_COMPONENTS = null;
      PageElements.HTML_COMPONENTS = null;
      PageElements.FORM_COMPONENT_MAP = null;
      PageElements.readFormComponent();
      //alert(PageElements.FORM_COMPONENTS);
    },
    readFormComponent:function(){
    	//alert("calling 0.1");
        var textObj = new Array();
        var passwordObj= new Array();
        var hiddenObj= new Array();
        var fileObj = new Array();
        var dropDownObj= new Array();
        var textAreaObj= new Array();
        var listBoxObj = new Array();
        var checkBoxObj=new Array();
        var radioObj = new Array();
        
        var map = new ObjectMap();
        if(PageElements.FORM_COMPONENTS===null || PageElements.FORM_COMPONENTS.length===0){
            PageElements.FORM_COMPONENTS = new Array();
            //alert("calling 0.2");
            if(document.getElementsByTagName("input")){
                var input = document.getElementsByTagName("input");
                //alert(input.length);
                for(var i=0;i<input.length;i=i+1){
                    PageElements.FORM_COMPONENTS[PageElements.FORM_COMPONENTS.length] = input[i];
                    this.updateFormBasedMap(input[i]);
                    if(input[i].type==FormConstant.Text){
                         textObj[textObj.length]=input[i];
                    }else if(input[i].type==FormConstant.Hidden){
                         hiddenObj[hiddenObj.length]=input[i];
                    }else if(input[i].type==FormConstant.Password){
                         passwordObj[passwordObj.length]=input[i];
                    }else if(input[i].type==FormConstant.File){
                         fileObj[fileObj.length]=input[i];
                    }else if(input[i].type==FormConstant.CheckBox){
                         checkBoxObj[checkBoxObj.length]=input[i];
                    }else if(input[i].type==FormConstant.Radio){
                         radioObj[radioObj.length]=input[i];
                    }
                }
                map.put(FormConstant.Text,textObj);
                map.put(FormConstant.Hidden,hiddenObj);
                map.put(FormConstant.Password,passwordObj);
                map.put(FormConstant.File,fileObj);
                map.put(FormConstant.CheckBox,checkBoxObj);
                map.put(FormConstant.Radio,radioObj);
            }
            if(document.getElementsByTagName("select")){
                var select = document.getElementsByTagName("select");
                for(var i=0;i<select.length;i=i+1){
                    PageElements.FORM_COMPONENTS[PageElements.FORM_COMPONENTS.length] = select[i];
                    this.updateFormBasedMap(select[i]);
                    if(select[i].type==FormConstant.DropDown){
                         dropDownObj[dropDownObj.length]=select[i];
                    }else{
                         listBoxObj[listBoxObj.length]=select[i];
                    }
                }
                map.put(FormConstant.DropDown,dropDownObj);
                map.put(FormConstant.ListBox,listBoxObj);
            }
            if(document.getElementsByTagName("textarea")){
                var textarea = document.getElementsByTagName("textarea");
                for(var i=0;i<textarea.length;i=i+1){
                    PageElements.FORM_COMPONENTS[PageElements.FORM_COMPONENTS.length] = textarea[i];
                    this.updateFormBasedMap(textarea[i]);
                }
                map.put(FormConstant.TextArea,textarea);
            }
        }
        PageElements.FORM_MAPPED_COMPONENTS = map;
    },
    updateFormBasedMap:function(component){
        if(PageElements.FORM_COMPONENT_MAP == null)PageElements.FORM_COMPONENT_MAP = new ObjectMap();
        var formName = FormConstant.NAMELESS_FORM;
        if(component.form && component.form.name && component.form.name != ""){
             formName = component.form.name;  
        }
        var formComponentArray = PageElements.FORM_COMPONENT_MAP.get(formName);
        if(formComponentArray==null){
	        formComponentArray=new Array();
	        PageElements.FORM_COMPONENT_MAP.put(formName,formComponentArray);
        }
        //alert("formName "+formName+ " :: component"+component.name + " :: Value "+component.value);
        formComponentArray[formComponentArray.length] = component; 
    }
}

var ObjectMap = JSClass.newClass();

ObjectMap.prototype = {
    elementKey:null,
    elementValue:null,
    init:function(){
      this.elementKey = new Array();
      this.elementValue = new Array();
    },
    getKeys:function(){
        return this.elementKey;
    },
    get:function(key){
        var obj=null;
        if(key){
            for(var i=0;i<this.elementKey.length;i=i+1){
                if(this.elementKey[i]==key){
                    obj=this.elementValue[i];
                    break;
                }
            }
        }
        return obj;
    },
    getValue:function(index){
        if(index>-1 && index<this.elementValue.length){
            return this.elementValue[index];
        }else{
            return null;
        }
    },
    getKey:function(index){
        if(index>-1 && index<this.elementKey.length){
            return this.elementKey[index];
        }else{
            return null;
        }
    },
    getIndex:function(key){
        var obj=-1;
        if(key){
            for(var i=0;i<this.elementKey.length;i=i+1){
                if(this.elementKey[i]==key){
                    obj=i;
                    break;
                }
            }
        }
        return obj;
    },
    put:function(key,value){
        var index = this.getIndex(key);
        if(index==-1){
            this.elementKey[this.elementKey.length]=key;
            this.elementValue[this.elementValue.length]=value;
        }else{
            this.elementValue[index]=value;
        }
    },
    remove:function(key){
        if(key){
            var tempKey=new Array();
            var tempValue = new Array();
            for(var i=0;i<this.elementKey.length;i=i+1){
                if(this.elementKey[i]!=key){
                     tempKey[tempKey.length]=this.elementKey[i];
                     tempValue[tempValue.length]=this.elementValue[i];
                }
            }
            this.elementKey=tempKey;
            this.elementValue=tempValue;
        }
    },
    length:function(){
        return this.elementKey.length;
    }
}

/*
*   Responsible to return the HTML Object by ID, ClassName, TagName, or any particular Attribute
*/
var ObjectBy ={
    Id:function(){
        var obj;
        if(this.arguments){
            if(this.arguments.length>1){
                obj = new ObjectMap();
                for(var i=0;i<this.arguments.length;i=i+1){
                    obj.put(this.arguments[i],document.getElementById(this.arguments[i]));
                }
            }else{
                obj = document.getElementById(this.arguments[0]);
            }
        }
        return obj;
    },
    className:function(tagName,className){
        var obj;
        if(tagName && className){
            var tempObj;
            var tempArr;
            var elem = document.getElementsByTagName(tagName);
            if(elem && elem.length>0){
                obj = new Array();
                for(var i=0;i<elem.length;i++){
                    if(elem[i].className == className){
                        obj[obj.length]=elem[i];
                    }
                }
            }
        }
        return obj;
    },
    name:function(name){
        return document.getElementsByName(name);
    },
    tagName:function(name){
        return document.getElementsByTagName(name);            
    },
    attribute:function(tagName,attributeName){
         var obj;
        if(tagName && attributeName){
            var tempObj;
            var tempArr;
            var elem = document.getElementsByTagName(tagName);
            if(elem && elem.length>0){
                obj = new Array();
                for(var i=0;i<elem.length;i++){
                    if(eval("elem[i]."+attributeName)){
                        obj[obj.length]=elem[i];
                    }
                }
            }
        }
        return obj;       
    }
}

var FormObjectBy = {
    Id:function(){
        return ObjectBy.Id.apply(this,arguments);
    },
    className:function(tagName,className){
        return ObjectBy.className(tagName,className);
    },
    name:function(name,formname){
        var obj = null;
        var elements = PageElements.FORM_COMPONENTS;
        if(formname)elements = PageElements.FORM_COMPONENT_MAP.get(formname);
        if(elements){
            for(var i=0;i<elements.length;i=i+1){
                if(elements[i].name==name){

                    //ensure to return only one object.
                    //for group of object use group method.
                    obj=elements[i];
                }
            }
        }
        return obj;
    },
    tagName:function(name){
       return ObjectBy.tagName(name);
    },
    type:function(type){
       return PageElements.FORM_MAPPED_COMPONENTS.get(type);
    },
    group:function(name,formname){
        var obj = null;
        var elements = PageElements.FORM_COMPONENTS;
        if(formname)elements = PageElements.FORM_COMPONENT_MAP.get(formname)
        if(elements){
            obj=new Array();
            for(var i=0;i<elements.length;i=i+1){
                if(elements[i].name==name){
                    obj[obj.length]=elements[i];
                }
            }
        }
        return obj;
    }
}

var ErrorUtil = {
	errorCode:[404,500],
	errorMessage:["File Not Found","Server Error"],
	messagePrefix:"Javascriptian <br>",//You can change it according to your application
	message:function(code){
		for(var i=0;i<this.errorCode.length;i=i+1){
			if(code===this.errorCode[i]){
				return this.messagePrefix+this.errorMessage[i];
			}
		}
	}
};

var EventUtil = {
    addEventListener:function(target, type, callback, captures) {
        if (target.addEventListener) {
            target.addEventListener(type, callback, captures);
        } else if (target.attachEvent) {
            target.attachEvent('on'+type, callback);
        } else {
            target['on'+type] = callback;
        }
    },
    fireEvent : function(obj, type) {
        if(BrowserUtil.ie){
            obj.fireEvent("on" + type);
        }else {
            var evt = document.createEvent('MouseEvents');
            evt.initEvent(type, true, true);
            obj.dispatchEvent(evt);
        }
    },
    getSrcElement : function(evt){
        if(evt){
             if(BrowserUtil.ie){
              return evt.srcElement;
             }else{
              return evt.target;
             }
        }
    },
    getParentElement : function(evt){
        var srcElement = EventUtil.getSrcElement(evt);
        if(srcElement){
             if(BrowserUtil.ie){
                return srcElement.parentElement;
             }else{
                return srcElement.parentNode;
             }
        }
    }
};

var List = JSClass.newClass();
List.prototype = {
        list:null,
        init:function(name){
        	this.list = FormObjectBy.name(name);
            //alert("name:"+name+" :: object:"+this.list);
        },
        addOption:function(text,value){
            this.list.options[this.list.options.length] = new Option(text,value);
        },
        removeAll:function(){
            var len =this.list.options.length;
            for(var i=0;i<len;i=i+1){
                this.list.options[0]= null;
            }
        },
        remove:function(index){
            if(index<this.list.options.length)
                this.list.options[index]= null;
        },
        removeSelected:function(){
            for(var i=0;i<this.getLength();i=i+1){
                if(this.list.options[i].selected){
                    this.list.options[i]=null;
                    i=i-1;
                }
            }
        },
        getLength:function(){
            //alert(this.list);
            return this.list.options.length;            
        },
        selectIndex:function(index){
        	this.list.options[index].selected = true; 
        },
        selectByValue:function(value){
        	if(this.list){
                for(var i=0;i<this.list.options.length;i=i+1){
                    if(this.list.options[i].value==value){
                        this.list.options[i].selected = true;
                    }
                }
            }
        },
        getSelectedIndex:function(){
            if(FormConstant.DropDown==this.list.type){
                return this.list.selectedIndex;
            }else if (FormConstant.ListBox==this.list.type){
                var ind=new Array();
                if(this.list){
                    for(var i=0;i<this.list.options.length;i=i+1){
                        if(this.list.options[i].selected){
                            ind[ind.length]=i;
                        }
                    }
                }
                return ind;
            }
        },
        getSelectedValue:function(){
            var ind=new Array();
            if(this.list){
                for(var i=0;i<this.list.options.length;i=i+1){
                    if(this.list.options[i].selected){
                        ind[ind.length]=this.list.options[i].value;
                    }
                }
            }
            if(FormConstant.DropDown==this.list.type && ind.length>0){
                return ind[0];
            }else if (FormConstant.ListBox==this.list.type && ind.length>0){
                return ind;
            }else{
                return null;
            }
        },
        getSelectedText:function(){
            var ind=new Array();
            if(this.list){
                for(var i=0;i<this.list.options.length;i=i+1){
                    if(this.list.options[i].selected){
                        ind[ind.length]=this.list.options[i].text;
                    }
                }
            }
            if(FormConstant.DropDown==this.list.type && ind.length>0){
                return ind[0];
            }else if (FormConstant.ListBox==this.list.type && ind.length>0){
                return ind;
            }else{
                return null;
            }
        },
        getValues:function(){
        	var ind=new Array();
            if(this.list){
                for(var i=0;i<this.list.options.length;i=i+1){
                    ind[ind.length]=this.list.options[i].value;
                }
            }
            return ind;
        },
        getTexts:function(){
            var ind=new Array();
            if(this.list){
                for(var i=0;i<this.list.options.length;i=i+1){
                    ind[ind.length]=this.list.options[i].text;
                }
            }
            return ind;
        },
        getType:function(){
            return this.list.type;            
        }
}

var CommonUtil = {
    /**
     * Method to sort value of List in descending order.
     */
    sortAsc:function (a, b){
        var i=-1;
        try{
        if(a){
            a = CommonUtil.trim(a).toLowerCase();
            if(a.length>0 && a.substring(0,1).charCodeAt(0)==160){
                a=a.substring(1);
            }
        }
        if(b){
            b = CommonUtil.trim(b).toLowerCase();
            if(b.length>0 && b.substring(0,1).charCodeAt(0)==160){
                b=b.substring(1);
            }
        }
        try{
        i=a>b?1:a<b?-1:0;
        }catch(e){i=0;}
        }
        catch(e){}
        return i;
    },
    /**
      * This function is responsible for removing right space.
      */
     rtrim:function(value) {
        if(value){
	        if (isNaN(value)) {
	            var re = /((\s*\S+)*)\s*/;
	            return value.replace(re, "$1");
	        }else{
	        	return value;
	        }
        }
        
        return "";
    },
    /**
      * Removes leading and ending whitespaces.
      */
    trim:function (value) {
        if (value === null) {
            value = "";
        }
        return CommonUtil.ltrim(CommonUtil.rtrim(value));
    },
    /**
      * This function is responsible for removing left space.
      */
    ltrim:function(value){
	    if(value){
	        if (isNaN(value)) {
	            var re = /\s*((\S+\s*)*)/;
	            return value.replace(re, "$1");
	        }else{
	        	return value;
	        }
	     }
        return "";
    },
    getEncodedString:function(value){
        var encoded = "";
        value = CommonUtil.trim(value);
        if(value){
        	//to convert number into string.
        	value=""+value;
            while(value.indexOf("  ")>=0){
                value = value.replace(/  /g," ");
            }
            var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()";
            var HEX = "0123456789ABCDEF";
            var plaintext = value;
            for (var i = 0; i < plaintext.length; i=i+1 ) {
                var ch = plaintext.charAt(i);
                if (ch == " ") {
                    encoded += "+";
                } else if (SAFECHARS.indexOf(ch) != -1) {
                    encoded += ch;
                } else {
                    var charCode = ch.charCodeAt(0);
                    if (charCode < 255) {
                        encoded += "%";
                        encoded += HEX.charAt((charCode >> 4) & 0xF);
                        encoded += HEX.charAt(charCode & 0xF);
                    }
                }
            }
        }
        return encoded;
    },
    isValidSession:function(req){
        var isValid = true;
        var appPath = "./";
        var responseText = req.responseText;
        if (responseText.indexOf("j_security_check") > 0) {
            window.location = appPath;
            isValid = false;
            document.cookie = "jsian=expired";
        }
        return isValid;
    }
};

/*
* ParameterUtil is the utility class used to build the parameter to send to the server.
*/
var Parameter = JSClass.newClass();

Parameter.prototype = {
    /*
    * When you give null argument in this method it will pick all the form component
    * from the current page and return. But it is recommended to pass the parameter name
    * list in this method it is the type of array
    */
    parameter:null,
    parameterMap:null,
    /*Private: this method is for internal use no need to call externally*/
    init:function(){
        this.parameter = "";
        this.parameterMap = new ObjectMap();
    },
    /*Private: this method is for internal use no need to call externally*/
    setAllParameter:function(selected){
        //default list box part is selected one
        var elements=PageElements.FORM_COMPONENTS;
        for(var i in elements){
            this.setParameter(elements[i].name,selected);
        }
    },
    /*Private: this method is for internal use no need to call externally*/
    getParameterString:function(name , seperator, selected,formname){
        var param = "";
        var seperatedBy = seperator?CommonUtil.getEncodedString(seperator):"&";
        var formArray = FormObjectBy.group(name,formname);
        if(formArray && formArray.length>0){
            for(var i in formArray){
               var value = "";
               var obj = formArray[i];
               if((obj.type == FormConstant.Text
                       || obj.type == FormConstant.TextArea
                       || obj.type == FormConstant.Hidden
                       || obj.type == FormConstant.DropDown
                       || obj.type == FormConstant.File
                       || obj.type == FormConstant.Password) && !obj.disabled){
                    value = obj.name +"="+ CommonUtil.getEncodedString(obj.value);
               }else if((obj.type == FormConstant.Radio || obj.type == FormConstant.CheckBox) && obj.checked && !obj.disabled){
                   if(seperator){
                       if(i==0)value += obj.name + "=";
                        value += CommonUtil.getEncodedString(obj.value);
                   }else{
                        value += obj.name + "="+CommonUtil.getEncodedString(obj.value);                       
                   }
               }else if(obj.type == FormConstant.ListBox && !obj.disabled){
                    var val = "";
                    for (var j = 0; j < obj.options.length; j=j+1) {
                        if(selected){
                            if(obj.options[j].selected){
                                if(!seperator)
                                    val += obj.name +"="+ CommonUtil.getEncodedString(obj.options[j].value)+seperatedBy;
                                else
                                    val += CommonUtil.getEncodedString(obj.options[j].value)+seperatedBy;
                            }
                        }else{
                            if(!seperator)
                                val += obj.name +"="+ CommonUtil.getEncodedString(obj.options[j].value)+seperatedBy;
                            else
                                val += CommonUtil.getEncodedString(obj.options[j].value)+seperatedBy;
                        }
                    }
                    if(seperator)val=obj.name+"="+val;
                    if(val!="")value=val.substring(0,val.lastIndexOf(seperatedBy));
               }
               if(value!="")param+=value+seperatedBy;
            }
            if(param!="" && param.length == param.lastIndexOf(seperatedBy)+seperatedBy.length){
                param = param.substring(0,param.lastIndexOf(seperatedBy));
            }
        }
        return param;
    },
    /*Public: responsible to set the parameter with the given name */    
    setParameter:function(name,selected,formname){
        var value = this.parameterMap.get(name);
        if(!value){
           value = this.getParameterString(name,null,selected,formname);
           this.parameterMap.put(name,value);
        }
    },
    /*Public: responsible to set the explicit parameter with the given name */
    setExternalParameter:function(name,value){
        this.parameterMap.put(name,value);         
    },
    /*Public: responsible to return the parameter value if required all then
    provide the selected information as true or false to render the list box information
    if some elements need to render selected and some not then use setParameter for only those
    list box and use all and selected as required it will prioritize the setParameter value.
    */
    getParameter:function(all,selected){
        if(FormConstant.ALL_PARAMETER == all){
            this.setAllParameter(selected);
        }
        if(this.parameterMap.length()>0){
           for(var i=0;i<this.parameterMap.length();i++){
               this.parameter+=this.parameterMap.getValue(i)+(i+1<this.parameterMap.length()?"&":"");
           }
        }
        return this.parameter;
    },
    getParameterByForm:function(formname,objectname,selected){
        if(formname){
            var elements=PageElements.FORM_COMPONENT_MAP.get(formname);
            //alert("elements==="+ elements); 
            if(objectname){
               for(var i in elements){
                   if(elements[i].name == objectname){
                       this.setParameter(elements[i].name,selected,formname);
                       break;
                   }
               }
            }else{
                for(var i in elements){
                	this.setParameter(elements[i].name,selected,formname);
                }
            }
            this.parameter = this.getParameter(null,selected)
        }else{
            this.parameter = this.getParameter(FormConstant.ALL_PARAMETER,selected);    
        }
        return this.parameter;
    }

}

var AjaxRequest = JSClass.newClass();
AjaxRequest.prototype = {
     req:null,
     init:function(){
        var request = null;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            request = new XMLHttpRequest();
            if (request.overrideMimeType) {
                request.overrideMimeType("text/xml");
            }
        } else {
            if (window.ActiveXObject) { // IE
                try {
                    request = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                    try {
                        request = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {
                    }
                }
            }
        }
        this.req = request;
     },

     sendRequest:function(requestInfo){
         if(AjaxConstant.isRequestFree()){
            AjaxConstant.REQUEST_STATUS = AjaxConstant.BUSY;
            requestInfo.onProcess();
            var request = this.req;
            request.onreadystatechange = function(){
                this.states = request.readyState;
                if (this.states == 0 || this.states == 1 || this.states == 2 || this.states == 3){
                	document.body.style.cursor = "wait";
                    requestInfo.onProcess();
                }
                if (this.states == 4) {
                    AjaxConstant.REQUEST_STATUS=AjaxConstant.FREE;
                    if (request.status == 200) {
                    	CommonUtil.isValidSession(request);
                        requestInfo.ResponseText=request.responseText;
                        requestInfo.ResponseXML=request.responseXML;
                        requestInfo.onComplete();
                        PageElements.reload();
                        document.body.style.cursor = "default";
                    } else {
                        requestInfo.onError(request.status);
                    }
                }
            };
            //alert("Method:"+requestInfo.Method+":: URL:"+requestInfo.URL+":"+requestInfo.Parameter+":: asynchronous"+requestInfo.Asynchronous);
            request.open(requestInfo.Method, requestInfo.URL, requestInfo.Asynchronous);
            if (requestInfo.Method == FormConstant.POST) {
                request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                request.setRequestHeader("Content-length", requestInfo.Parameter.length);
                request.setRequestHeader("Connection", "close");
            }
            request.send(requestInfo.Parameter);
         }else{
             requestInfo.onBusy();
         }
     }
}


var RequestInfo = JSClass.newClass();

RequestInfo.prototype = {
      init:function(method,url,param,appObj){
          this.Parameter = param?param:""; // if you pass null here it will pick all the form component and send it. but it is not recommended.
          if(!AjaxConstant.REQUIRED_CACHING){
          	if(this.Parameter!="")this.Parameter+="&";
          	this.Parameter+="jstime="+DateUtil.getCurrentTimeInMS();
          }
          this.ApplicationObject = appObj;//set the application object for your action after request complete.
          this.URL = url;
          this.Method = method?method:FormConstant.POST;//default method is POST
          if(this.Method == FormConstant.GET){
            this.URL = this.URL + "?" + this.Parameter;
          }
      },
      ApplicationObject:null,
      Method:FormConstant.POST,//default method is POST
      Parameter:null,
      URL:null,
      Asynchronous:AjaxConstant.ASYNCHRONOUS,
      ResponseText:null,
      ResponseXML:null,
      onProcess:function(){
          if(this.ApplicationObject.onProcess)
           this.ApplicationObject.onProcess();
      },
      onComplete:function(){
          this.ApplicationObject.xml = this.ResponseXML;
          this.ApplicationObject.text = this.ResponseText;
          this.ApplicationObject.onComplete();
      },
      onError:function(code){
        if(this.ApplicationObject.onError)
           this.ApplicationObject.onError(code);
      },
      onBusy:function(){
          if(this.ApplicationObject.onBusy)
           this.ApplicationObject.onBusy();
      }
}

var JSAjax = {
      sendRequest:function(method,url,parameter,appObj){
        var req = new AjaxRequest();
        if(AjaxConstant.ALL_PARAMETER == parameter){
        	parameter = new Parameter().getParameter(AjaxConstant.ALL_PARAMETER)
        }
        req.sendRequest(new RequestInfo(method,url,parameter,appObj));
      }
}

var  ListElement = JSClass.newClass();

ListElement.prototype = {
    /**
     * Constructor to intialize form and its element.
     */

    text : null,
    value : null,
    element :null,
    name :null,
    sortByValue : false,

    init:function(name){
        this.text = new Array();
        this.value = new Array();
        this.element = new List(name);
        this.name = name;
        this.sortByValue = false;
        this.addFromList();
    },

    /**
     * Method to add
     */
    add : function(){
        // we expect name of list that is going to add the selected option into the current one
        var listLength = arguments.length;
        if(listLength > 0){
            for(var index = 0; index<listLength; index=index+1){
                var tempListObj = new ListElement(arguments[index]);
                //alert(arguments[index]+"step 212 "+eval("this.form."+arguments[index]));
                //retrieve the list of text and values from the given list name in the argument

                var tempText = tempListObj.getSelectedText();
                var tempValue = tempListObj.getSelectedValue();
                //alert(arguments[index]+"::"+tempText + "::" + tempValue);
                tempListObj.removeSelection();
                //loop upto the selected value;
                for(var j=0;j<tempValue.length;j=j+1){
                    if(!this.isExist(tempValue[j])){
                        this.text[this.text.length] = tempText[j];
                        this.value[this.value.length] = tempValue[j];
                    }
                }
                this.refresh();
                this.empty();
                for(var i=0;i<this.text.length;i=i+1){
                    this.addToList(this.text[i],this.value[i]);
                }
            }
        }
    },
    /**
     * Method to add value and text to List.
     */
    addToList : function(text, val){
        if(!this.isExist(val)){
            this.element.addOption(text,val);
        }
    },
    /**
     * Method to sort List by value.
     */
    sortValue : function(){
        this.sortByValue = true;
        this.addFromList();
    },
    /**
     * Method to remove value and text to List.
     */
    removeSelected : function(){
        this.element.removeSelected()
        this.addFromList();
    },
    /**
     * Method to refresh List Element.
     */
    refresh : function(){

        var tempList = new Array();
        for(var i=0;i<this.text.length;i=i+1){
            if(this.sortByValue){
                tempList[tempList.length]=this.value[i]+" ****"+this.text[i];
            }else{
                tempList[tempList.length]=this.text[i]+" ****"+this.value[i];
            }
        }
        //alert("tempList before "+tempList);
        tempList.sort(CommonUtil.sortAsc);
        //alert("tempList after "+tempList);
        //refresh the Array();
        this.text = new Array();
        this.value = new Array();
        for(var i=0;i<tempList.length;i=i+1){
            var temp = tempList[i].split(" ****");
            if(temp[1]!==null){
                if(this.sortByValue){
                    this.text[this.text.length]=temp[1];
                    this.value[this.value.length]=temp[0];
                }else{
                    this.text[this.text.length]=temp[0];
                    this.value[this.value.length]=temp[1];
                }
            }
        }
    },
    /**
     * Method to empty List.
     */
    empty : function(){
        this.element.removeAll();
    },
    /**
     * Method to add value and text from List.
     */
    addFromList : function(){
        var length = this.getLength();
        this.text = this.element.getTexts();
        this.value = this.element.getValues();
    },
    /**
     * Method to sort value in List.
     */
    sortMe : function(sortByValue){
        if(sortByValue)this.sortByValue = sortByValue
        this.refresh();
        this.empty();
        for(var i=0;i<this.text.length;i=i+1){
            this.addToList(this.text[i],this.value[i]);
        }
    },
    /**
     * Method to get length of List.
     */
    getLength : function(){
        return this.element.getLength();
    },
    /**
     * Method to get selected value from List.
     */
    getSelectedValue : function(){
       if(!this.element.getSelectedValue())return new Array(); 
       return FormConstant.DropDown == this.element.list.type? new Array(this.element.getSelectedValue()):this.element.getSelectedValue();
    },
    /**
     * Method to get selected text from List.
     */
    getSelectedText : function(){
        if(!this.element.getSelectedText())return new Array();
        return FormConstant.DropDown == this.element.list.type? new Array(this.element.getSelectedText()):this.element.getSelectedText();
    },
    /**
     * Method to remove selection from List box.
     */
    removeSelection : function(){
        var length = this.getLength();
        for(var i=0;i<length;i=i+1){
            if(this.element.list.options[i].selected){
                this.element.list.options[i].selected = false;
            }
        }
    },

    /**
     * Method to check values exist or not in List.
     */
    isExist : function(values){
        var exist = false;
        var length = this.getLength();
        for(var i=0;i<length;i=i+1){
            if(this.value[i] == values){
                exist = true;
                break;
            }
        }
        return exist;
    }
}

var ListUtil = JSClass.newClass();

ListUtil.prototype = {
    object:null,

    init:function(){
        this.object = new Array();
    },

    addListObject :  function (){
        var length = arguments.length;
        this.object = new Array();
        if(length >0){
            for(var i=0;i<length;i=i+1){
                var listObj= new ListElement(arguments[i]);
                listObj.sortMe();
                //alert(listObj.getSelectedText());
                this.object[this.object.length] = listObj;
            }
        }
    },

    addListOption :  function (){
        var length = arguments.length;
        //expecting first argument is the name, into which another argumented list options need to add

        if(length >1){
            for(var i=0;i<this.object.length;i=i+1){
                var listElement = this.object[i];
                if(listElement.name == arguments[0]){
                    for(var j=1;j<length;j=j+1){
                        listElement.add(arguments[j]);
                    }
                    break;
                }
            }
        }
    },

    removeSelected :  function (name){
        var length = arguments.length;
        //expecting first argument is the name into another argumented list options need to add
        if(length >0){
            for(var i=0;i<this.object.length;i=i+1){
                var listElement = this.object[i];
                if(listElement.name == arguments[0]){
                    listElement.removeSelected();
                    break;
                }
            }
        }
    },

    sortByValue :  function (name){
        if(name){
            for(var i=0;i<this.object.length;i=i+1){
                var listElement = this.object[i];
                if(listElement.name == name){
                    listElement.sortValue();
                    break;
                }
            }
        }
    }
}

var ElementUtil = JSClass.newClass();

ElementUtil.prototype = {

    elements:null,

    init:function(){
        this.elements = new Array();
    },

    /**
    * Method to refresh element.
    */
    refresh : function(){
        this.elements = new Array();
    },

    /**
     * Method to show element given as parameter
     */
    showBlock : function(){
        var length = arguments.length;
        if(length>0){
            this.hideAll();
            for(var i=0;i<length;i=i+1){
                 var obj=this.findById(arguments[i]);
                 if(obj!==null){
                     obj.style.display = "block";
                 }
            }
        }
    },

    /**
     * Method to show element given as parameter.
     */
    show : function(){
        var length = arguments.length;
        if(length>0){
            this.hideAll();
            for(var i=0;i<length;i=i+1){
                 var obj=this.findById(arguments[i]);
                 if(obj!==null){
                     obj.style.display = "" ;
                 }
            }
        }
    },

    /**
     * Method to show element given as parameter
     */
    showOnly : function(){
        var length = arguments.length;
        if(length>0){
            for(var i=0;i<length;i=i+1){
                 var obj=this.findById(arguments[i]);
                 if(obj!==null){
                     obj.style.display = "" ;
                 }
            }
        }
    },

    /**
     * Method to hide All element.
     */
    hideAll : function(){
        var length = this.elements.length;
        if(length>0){
            for(var i=0;i<length;i=i+1){
                 var obj=this.elements[i];
                 if(obj!==null){
                     obj.style.display = "none" ;
                 }
            }
        }
    },

    /**
     * Method to hide element given as parameter.
     */
    hide : function(){
        var length = arguments.length;
        if(length>0){
            for(var i=0;i<length;i=i+1){
                 var obj=this.findById(arguments[i]);
                 if(obj!==null){
                     obj.style.display = "none" ;
                 }
            }
        }
    },

    /**
     * Method to set element object by id.
     */
    setObjectById : function(){
        var length = arguments.length;
        if(length>0){
            for(var i=0;i<length;i=i+1){
                var obj = document.getElementById(arguments[i]);
                if(obj!==null && this.findById(arguments[i])===null){
                    obj.style.display = "none";
                    this.elements[this.elements.length] = obj;
                }
            }
        }
    },

    /**
     * Method to find element by id.
     */
    findById : function(id){
        if(this.elements.length>0 && id!==null){
            for(var i=0;i<this.elements.length;i=i+1){
                if(this.elements[i].id==id){
                    return this.elements[i];
                }
            }
        }
        return null;
    }

}

var JSObject = {

    getObject:function(name){
        return document.getElementById(name);
    },

    showInline : function(name){
        if(JSObject.getObject(name) && JSObject.getObject(name).style){
            JSObject.getObject(name).style.display = "inline";
        }
    },

    show : function(name){
        if(JSObject.getObject(name) && JSObject.getObject(name).style){
            JSObject.getObject(name).style.display = "";
        }
    },

    hide : function(name){
        if(JSObject.getObject(name) && JSObject.getObject(name).style){
            JSObject.getObject(name).style.display = "none";
        }
    },

    innerHTML : function(name,content){
        if(JSObject.getObject(name)){JSObject.getObject(name).innerHTML = content;}
    },

    getInnerHTML : function(name){
         if(JSObject.getObject(name))
            return JSObject.getObject(name).innerHTML;
         else
            return "";
    },

    removeMe : function(name){
        if (JSObject.getObject(name).parentNode){
            JSObject.getObject(name).parentNode.removeChild(JSObject.getObject(name));
        }
    }
}

var FormValidator = {

    TEXT:"text",
    VALUE:"value",
    SELECTED_TEXT:"selected_text",
    SELECTED_VALUE:"selected_value",
    /**
    * check the given component name with the blank if it is list box then it is for atleast one selection.
    */
    isBlank:function(){
        var map = null;
        var blank = false;
        if(arguments && arguments.length>0){
            map = new ObjectMap();
            for(var i=0;i<arguments.length;i=i+1){
                var obj = FormObjectBy.name(arguments[i]);
                if(obj && (obj.value===null || obj.value.trim().length==0)){
                    map.put(arguments[i],obj);
                    blank = true;
                }else{
                    map.put(arguments[i],null);
                }
            }
        }
        if(blank){
            return map;
        }else{
            return blank;
        }
     },
    isUnChecked:function(){
        var map = null;
        var unchecked = false;
        if(arguments && arguments.length>0){
            map = new ObjectMap();
            for(var i=0;i<arguments.length;i=i+1){
                var obj = FormObjectBy.group(arguments[i]);
                if(obj && obj.length>0){
                    var ischecked = false;
                    for(var j=0;j<obj.length;j++){
                        if(!ischecked)
                            ischecked=obj[j].checked
                    }
                    if(!ischecked){
                        map.put(arguments[i],obj);
                        unchecked = true;
                    }else{
                        map.put(arguments[i],true);
                    }
                }

            }
        }
        if(unchecked){
            return map;
        }else{
            return unchecked;
        }
    },
    isUnSelected:function(){
        var map = null;
        var unselected = false;
        if(arguments && arguments.length>0){
            map = new ObjectMap();
            for(var i=0;i<arguments.length;i=i+1){
                var list = new List(arguments[i]);
                if(list.getType()==FormConstant.DropDown && list.getSelectedIndex()==0){
                    /*
                    *   Generally first element is information in dropdown so it is assumed that
                    *   first element of drop down is not to be select and should account an error.
                    */
                    map.put(arguments[i],list.list);
                    unselected = true;
                }else if(list.getType()==FormConstant.ListBox
                        && list.getSelectedIndex()
                        && list.getSelectedIndex().length==0){
                    map.put(arguments[i],list.list);
                    unselected = true;
                }else{
                    map.put(arguments[i],null);
                }
            }
        }
        if(unselected){
            return map;
        }else{
            return unselected;
        }
     },
    assert:function(objectMap,msgMap,prefix){
        var msg = "";
        if(!prefix)prefix="";
        var firstObjToFocus = null;
        if(objectMap){
            for(var i=0;i<objectMap.length();i++){
                if(objectMap.getValue(i)!=null){
                    if(!firstObjToFocus)firstObjToFocus=objectMap.getValue(i);
                    msg+=msgMap.get(prefix+objectMap.getValue(i).name)+"\n";
                }
            }
        }
        if(msg!="")alert(msg);
        if(firstObjToFocus)firstObjToFocus.focus();
     },
    /**
    * Method is responsible to check that field first and second is matching or not.
    */
    matchValue : function(first,second,msg){
        var firstObj = FormObjectBy.name(first);
        var secondObj = FormObjectBy.name(second);
        if(firstObj.value && secondObj.value && firstObj.value !=  secondObj.value){
            if(msg)alert(msg);
            return false;
        }
        return true;
    },

    /**
    * Method is responsible to check that field first and second is matching or not.
    */
    matchWithValue : function(name,value,msg){
        var firstObj = FormObjectBy.name(name);
        if(firstObj.value && firstObj.value !=  value){
            if(msg)alert(msg);
            return false;
        }
        return true;
    },

    matchList : function(first,second,matchWhat,msg){
        var firstObj = new List(first);
        var secondObj = new List(second);
        var match = true;
        var matchValue = (!matchWhat || matchWhat == FormValidator.VALUE)
        var matchText = (matchWhat == FormValidator.TEXT);
        var matchSelectedValue = (matchWhat == FormValidator.SELECTED_VALUE);
        var matchSelectedText = (matchWhat == FormValidator.SELECTED_TEXT);

        if(firstObj && secondObj){
            var fLen = firstObj.getLength();
            var sLen = secondObj.getLength();
            if(fLen==sLen){
                var firstArray = new Array();
                var secondArray = new Array();
                if(matchValue){
                    firstArray = firstObj.getValues();
                    secondArray = secondObj.getValues();
                }else if(matchText){
                    firstArray = firstObj.getTexts();
                    secondArray = secondObj.getTexts();
                }else if(matchSelectedValue){
                    firstArray = firstObj.getSelectedValue();
                    secondArray = secondObj.getSelectedValue();
                }else if(matchSelectedText){
                    firstArray = firstObj.getSelectedText();
                    secondArray = secondObj.getSelectedText();
                }

                for (var i=0;i<firstArray.length;i=i+1){
                    var found=false;
                    for (var j=0;j<secondArray.length;j=j+1){
                        if (!found && firstArray[i]==secondArray[j]){
                           found = true; 
                        }
                    }
                    if(!found){
                        match = false;
                        break;
                    }
                }
            }else{
                match = false;
            }
        }
        if(!match){
            if(msg)alert(msg);
            return false;
        }
    },
    /**
    * check the given emailName components for having valid email and display message if error
    */
    isValidEmail:function(emailName,msg){
        var emailObj = FormObjectBy.name(emailName);;
        if(emailObj){
            var email = emailObj.value;
            if(!email)email="";
            var regEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            var valid = email.match(regEx);
            if(!valid){
                if(msg)alert(msg);
                emailObj.focus();
                return false
            }
            return true;
        }else{
            return false;
        }
    },

    /**
    * this will work for both listbox and textbox. list box for minimun selection
    * and text box for min length
    */
    isLessThan:function(name,length,msg){
       var object = FormObjectBy.name(name);
       if(object && object.type == FormConstant.ListBox){
           var count = 0;
           for(var i in object.options){
               if(object.options[i].selected){
                   count=count+1;
               }
           }
           if(count<length){
               if(msg)alert(msg);
               return false;
           }
       }else{
           if(object && object.value.trim().length < length){
               if(msg)alert(msg);
               return false
           }
       }
       return true;
    },

    /**
    * this will work for both listbox and textbox. list box for maximum selection
    * and text box for min length
    */
    isGreaterThan:function(name,length,msg){
       var object = FormObjectBy.name(name);
       if(object && object.type == FormConstant.ListBox){
           var count = 0;
           for(var i in object.options){
               if(object.options[i].selected){
                   count=count+1;
               }
           }
           if(count>length){
               if(msg)alert(msg);
               return false;
           }
       }else{
           if(object && object.value.length > length){
               if(msg)alert(msg);
               return false
           }
       }
       return true;
    },

    /**
    * this will work for both listbox and textbox. list box for minimun selection
    * and text box for min length
    */
    isAlphaNumeric:function(name,msg){
        var alphaObj = FormObjectBy.name(name);
        if(alphaObj){
            var alpha = alphaObj.value;
            if(!alpha)alpha="";
            var regEx = /^([a-zA-Z0-9_-]+)$/;
            var valid = alpha.match(regEx);
            if(!valid){
                if(msg)alert(msg);
                alphaObj.focus();
                return false
            }
            return true;
        }
        return false;
    },
    
    isEqual:function(name,length,msg){
       var object = FormObjectBy.name(name);
       var equal=false;
       if(object.type == FormConstant.ListBox){
           var count = 0;
           for(var i=0;i<object.length;i=i+1){
           		if(object.options[i].selected){
                   count=count+1;
               }
           }
           equal = (count==length)
       }else{
       	   equal = (object.value.length == length)
       }
       if(!equal && msg)alert(msg);
       return equal;
    },
    
    isValidatePassword: function (pwName) {
	
	   var pwObj = FormObjectBy.name(pwName);        
       var password = pwObj.value;
        
       var Stringlen = password.length;
	   var ValidateDigits = /[^0-9]/g;
	   var ValidateSpChar = /[a-zA-Z0-9]/g;
	   var ValidateChar = /[^a-zA-Z]/g;
	
	   var digitString = password.replace(ValidateDigits , "");
	   var specialString = password.replace(ValidateSpChar, "");
	   var charString = password.replace(ValidateChar, "");
		
	   if(Stringlen < 6)
	   {
	   pwObj.focus();
	   return false;
	   }
	   if(specialString.length > 0)
	   {
	   pwObj.focus();
	   return false;
	   }
	   if(digitString.length == 0)
	   {
	   pwObj.focus();
	   return false;
	   }
	   return true;
        
		 
	} 
}

var DateUtil = {
	getCurrentTimeInMS:function(){
		var date = new Date();
		var day = date.getDate();      // Returns the day of the month
		var mon = date.getMonth();      // Returns the month as a digit
		var year = date.getFullYear();  // Returns 4 digit year
		var hour = date.getHours();     // Returns hours
		var min = date.getMinutes();    // Returns minutes
		var sec = date.getSeconds();    // Returns seocnds
		var mil = date.getMilliseconds();  // Returns Milliseconds
		return day+""+mon+""+year+""+hour+""+min+""+sec+""+mil;
	}
}

var Import = {
    importJS:function(){
        /*First Argument: consider as path of the javascript files then name of javascript files*/
        if(arguments && arguments.length>1){
            for(var i=1;i<arguments.length;i++)
                document.write('<script type="text/javascript" src="'+arguments[0]+arguments[i]+'"></script>');
        }
    },
    importCSS:function(){
        /*First Argument: consider as path of the javascript files then name of javascript files*/
        if(arguments && arguments.length>1){
            for(var i=1;i<arguments.length;i++)
                document.write('<link rel="stylesheet" href="'+arguments[0]+arguments[i]+'" type="text/css">');
        }
    }
}

EventUtil.addEventListener(window,"load",PageElements.reload);

function setAjaxConstants(singleRequest) {
	AjaxConstant.SINGLE_REQUEST	=	singleRequest;
	}
	

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
	





