// JScript File
function getServices(userId){
	Ajax.getUser(userId);	
}

//Browser Compatability functions
	function getPageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;} 
	function getPageHeight() {h= window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?       document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null;return h-20;} 
	function getEvent(e){if(e){return e;}else{return event;}}
	function getEventTarget(evt){return (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);}
	function getXMLHttpRequest(){if(widow.XMLHttpRequest){return XMLHttpRequest;}else{return new ActiveXObject('Msxml2.XMLHTTP');}}
	function addEvent(elm,eventName,handler){if (elm.addEventListener){elm.addEventListener(eventName,handler,false);}else{elm.attachEvent("on" + eventName,handler);}}

 
//DOM Helper functions
	function floatInCenter(elm){
	    x =  new Number((getPageHeight()-elm.clientHeight) / 2).toFixed(0);
	    y =  new Number((getPageWidth()-elm.clientWidth) / 2).toFixed(0);
	    elm.style.top = x.toString()+"px";
	    elm.style.left = y.toString()+"px";
	}

	function _get(id){return document.getElementById(id);} 
	
	function newDOMObject(TypeName,JSON){
	    var Retval = document.createElement(TypeName);
	    if(JSON){
	        cloneProperties(parseJSON(JSON),Retval);
	    }    
	    return Retval;
	}
	function newBR(){
	    return document.createElement("br");
	}
	function appendBR(container){
	    container.appendChild(newBR());
	}
	
	function setSize(elm,width,height){
	    elm.style.height=height;
	    elm.style.width=width;
	}
	function setDisplay(elm,Value){
	    elm.style.display=Value;
	}
	function toggleDisplay(elm){
		elm.style.display = (elm.style.display == "")?"none":"";
		return (elm.style.display == "")?true:false;
	}

	function appendDOMObject(container,TypeName,JSON){
	    	var Retval = newDOMObject(TypeName,JSON);
		container.appendChild(Retval);
	    	return Retval;
	}
	
	var cleanedEMailString;
	
	function validateEmail(str){
		regEx_eMail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		return regEx_eMail.test(str);
	}

	function cleanEmailString(str){
		newResult = function(isValid, eMail,status){
			r = new Object();
			r.isValid = isValid;
			r.eMail = eMail;
			r.status = status;
			return r;
		}  
		regEx_delimiters = /[; ,]/g;
		cleanEmailString.RetVal = new Array();
		str = new String(str);
		str = str.replace(regEx_delimiters,";");
		addresses = str.split(";");
		for(idx=0;idx< addresses.length;idx++){
			addr = addresses[idx];
			if(addr != ""){
				
				if(validateEmail(addr)){
					cleanEmailString.RetVal.push(newResult(true,addr,"Status:OK " + addr + " (mail sent)"));
				}
				else{
					cleanEmailString.RetVal.push(newResult(false,addr,"Status:FAIL " + addr + " (invalid e-mail format)"));
				}
			}
		}
		return cleanEmailString.RetVal;
	}

	function appendTable(container,className){
	    tbl = newDOMObject("table","{'cellSpacing':'0','cellPadding':'0','border':'0','className':'" + className + "'}")
	    container.appendChild(tbl);
	    return tbl;
	}        
	function appendTableRow(table,className){
	    row = table.insertRow(table.rows.length);
	    if(className.length > 0){
	        row.className = className;
	    }
	    return row;
	}        
	function appendRowCell(row,className,innerHTML,colSpan){
		innerHTML = (!innerHTML)?"":innerHTML;
		colSpan = (!colSpan)?1:colSpan;
		cell = newDOMObject("td","{'innerHTML':'" + innerHTML + "','className':'" + className + "','colSpan':'" + colSpan + "'}");
		row.appendChild(cell);
		return cell;
	}        


	function appendInputRow(table,lable,ctrl){
		retval = appendTableRow(table,"InputRow");
		appendRowCell(retval,"LabelCell",lable,1);
		cell = appendRowCell(retval,"InputCell","",1);
		if(ctrl!=null){
			cell.appendChild(ctrl);
		}
		return retval;
	}        


	function parseJSON(JSON){
	    	try{
			var Obj = eval('(' + JSON + ')');
	    		return Obj;
		}	
		catch (e){
			alert(e);
		}
	}
	function cloneProperties(FromObj,ToObj){
	    for(Name in FromObj){
	        eval("ToObj." + Name + " = FromObj." + Name + ";")
	    }        
	}
	

	function newInput(type,name){
	    return newDOMObject("input","{'type':'" + type + "','id':'" + name + "','name':'" + name + "'}");
	}


	function newButtonRow(container){
	    Buttons = newDOMObject("table","{'cellSpacing':'10','cellPadding':'2','border':'0'}")
	    container.appendChild(Buttons);
	    BtnRow = appendTableRow(Buttons,"ButtonRow")
	    spacer = appendRowCell(BtnRow,"ButtonRowSpacer","&nbsp;",1)
	    BtnRow.appendChild(spacer);
	    return BtnRow;
	}
	function onButtonClick(e){
	    btn = getEventTarget(getEvent(e));
	    btn.Action.call(btn.Context,btn.Obj)
	}

	function getContext(e){
		evt = getEvent(e);
		return getEventTarget(evt).Context;
	}
	
	function appendButton(Obj,BtnRow,Caption,Context,ClickHandler){
		btn = appendRowCell(BtnRow,"actionbutton",Caption,1)
		btn.Obj = Obj;
		btn.Context = Context;
		btn.Action = ClickHandler;
		addEvent(btn,"click",onButtonClick);
		return btn;
	}
	
	function clearChildControls(ctrl){
	    while(ctrl.firstChild){ctrl.removeChild(ctrl.firstChild);}
	}


//SOME serviceObj Controls

	function appendSelectOption(container,caption,name,aServiceObj,valueFieldName,defaultValue){

		optionList =  appendDOMObject(container,"div","{'className':'SelectOptionCtrl'}");
		tbl = appendTable(optionList,"");
		Row_1 =  appendTableRow(tbl,"");

		Cell_1 = appendRowCell(Row_1,"",caption,1);
		Cell_2 = appendRowCell(Row_1,"","",1);
		optionListInput =  appendDOMObject(Cell_2,"input","{'type':'text','name':'" + name + "','id':'" + name + "','className':'OptionCtrl','value':'" + defaultValue + "'}");
		optionListInput.setAttribute("autocomplete","off");
		appendDOMObject(Cell_2,"br",null);
		optionListInput.Options = aServiceObj;


		optionListInput.listContainer = appendDOMObject(Cell_2,"div","{'className':'listContainer'}");
		optionListInput.listContainer.style.position = "absolute";
		optionListInput.listContainer.style.zIndex = 5000;
		optionListInput.valueFieldName = valueFieldName
		optionListInput.focus();
		optionListInput.select();
		optionListInput.optionSelect = function(val){
			this.value = val;
			this.focus();
			this.keyUpDisable = false;
			this.onOptionSelect();
		}
		optionListInput.onOptionSelect = function(){
		}
		optionList.keydown = function(e){
			evt = getEvent(e);
			target = getEventTarget(e);
			listContainer = target.listContainer;
			options = target.Options.Items;
			selectedIndex = target.selectedIndex;
			switch(evt.keyCode){
				case 38: //up arrow
					if(selectedIndex>-1){
						btn = target.Buttons[target.selectedIndex];
						btn.style.backgroundColor = "#ffffff";
							target.selectedIndex--
						if(target.selectedIndex != -1){ 
							btn = target.Buttons[target.selectedIndex]
							btn.style.backgroundColor = "#cccccc";
							target.value = btn.innerHTML;
						}
					}
					this.keyUpDisable = true;
					break;
				case 40: //down arrow
					if(selectedIndex<target.Count-1){
						if(target.selectedIndex != -1){ 
							btn = target.Buttons[target.selectedIndex];
							btn.style.backgroundColor = "#ffffff";
						}
						target.selectedIndex++
						btn = target.Buttons[target.selectedIndex]
						btn.style.backgroundColor = "#cccccc";
						target.value = btn.innerHTML;
					}
					this.keyUpDisable = true;
					break;
			}
			
		}

		optionList.keyup = function(e){
			if(this.keyUpDisable){
				this.keyUpDisable = false;
			}
			else{
				evt = getEvent(e);
				target = getEventTarget(e);
				listContainer = target.listContainer;
				options = target.Options.Items;
				selectedIndex = target.selectedIndex;
				targetValue = target.value.toLowerCase();
				clearChildControls(listContainer);
				target.Buttons = Array();
				target.Count = 0;
				target.selectedIndex = -1;
				if(targetValue.length > 0){
					target.onShow();
					var ListCtrl =  appendTable(listContainer,"ListCtrl");
					for(idx in options){
						option = getPropValByName(options[idx],target.valueFieldName);
						if(option){
							lowerOption = option.toLowerCase();
							if(lowerOption.indexOf(targetValue)==0){
								target.Count++;
								r = appendTableRow(ListCtrl,"");
								target.Buttons.push(appendButton(option,r,option,target,target.optionSelect));
							}
						}
					}
				}
			}
		}
		addEvent(optionListInput,"keydown",optionList.keydown);
		addEvent(optionListInput,"keyup",optionList.keyup);
		optionListInput.keyUpDisable = false;
		optionListInput.hideList = function(){
			clearChildControls(this.listContainer);
		}
		optionListInput.onShow = function(){
		}
		return optionListInput;
	}

	function appendTabs(container){
		tab =  appendDOMObject(container,"div","{'className':'TabCtrl'}");
		tab.btnRow = newButtonRow(tab);
		tab.Panels = Array();
		tab.Buttons = Array();
		tab.TabIndex = 0;
		tab.addTab = function(caption){
			pnl = appendDOMObject(this,"div","{'className':'TabPanel'}");
			tbtn = appendButton(this.TabIndex,this.btnRow,caption,this,this.setIndex);
			this.Panels.push(pnl);
			this.Buttons.push(tbtn);
			this.TabIndex++;
			return pnl;
		}
		tab.setIndex = function(idx){
			this.TabIndex = idx;
			for (i in this.Buttons){
				selected = i==idx;
				btn = this.Buttons[i];
				pnl = this.Panels[i];
				if(selected){
					pnl.style.display = "";	
					btn.className = "selected_tab"
				}
				else{
					pnl.style.display = "none";	
					btn.className = "tab"
				}
			}
		}
		return tab;	
	}
	

	function getSelect(obj,name,valueFieldName,textFieldName){
	    var select = newDOMObject("select","{'id':'" + name + "','name':'" + name + "'}");
	    for(var i=0;i<obj.Count;i++){
	        elm = obj.Items[i];
		Value = getPropValByName(elm,valueFieldName);
		Text = getPropValByName(elm,textFieldName);
	        o = newDOMObject("option","{'value':'" + Value + "','innerHTML':'" + Text + "'}");
	        select.appendChild(o);    
	    }        
	    return select;
	}
	function getPropValByName(obj,PropertyName){
		val = eval("obj." + PropertyName + ";");
		return val;
	}
	function foreach(obj,callFunction){
	    for(idx in obj){
	        callFunction(obj[Idx]);    
	    }
	}
/*****************************START An Alphabet Object *************************/
	var Alphabet = {};
	Alphabet.Letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
	Alphabet.appendDirectory = function(container,aServiceObj,aServiceObjProperty){

		Alphabet.btn = appendDOMObject(container,"div","{'className':'alpha_dir_image'}");
		Alphabet.btn.title = aServiceObj.infoTitle;
		addEvent(Alphabet.btn,"click",Alphabet.onImageClick);

		Alphabet.dir = appendDOMObject(container,"div","{'className':'AlphaListCtrl'}");
		Alphabet.dir.style.position = "absolute";
		Alphabet.dir.style.display = "none";
		Alphabet.dir.onShow = function(){
		}
		Alphabet.dir.hide = function(){
			Alphabet.dir.style.display = "none";
		}
		btn = appendDOMObject(Alphabet.dir,"span","{'innerHTML':'X','className':'closeButton'}");
		appendDOMObject(Alphabet.dir,"span","{'innerHTML':'" + aServiceObj.infoTitle + "'}");
		addEvent(btn,"click",Alphabet.onImageClick);
		appendDOMObject(Alphabet.dir,"br",null);
		appendDOMObject(Alphabet.dir,"br",null);

		Alphabet.list = appendDOMObject(Alphabet.dir,"div","{'className':'AlphaList'}");
		Alphabet.dir.list =  appendTable(Alphabet.list,"AlphaListTable");
		for(idx_alpha=0;idx_alpha<Alphabet.Letters.length;idx_alpha++){
			alpha = Alphabet.Letters[idx_alpha];
			row = appendTableRow(Alphabet.dir.list,"");
			cell = appendRowCell(row,"",alpha,1);
			cell = appendRowCell(row,"","&nbsp;",1);
			for(idx_SrvObj in aServiceObj.Items){
				srvObj = aServiceObj.Items[idx_SrvObj];
				prop = getPropValByName(srvObj,aServiceObjProperty);
				if (prop) {
					if(prop.indexOf(alpha)==0){
						row = appendTableRow(Alphabet.dir.list,"");
						cell = appendRowCell(row,"AlphaListLink","&nbsp;",1);
						cell = appendRowCell(row,"AlphaListLink",prop,1);
						if(aServiceObj.alphaListClickHandler){
							addEvent(cell,"click",aServiceObj.alphaListClickHandler);
							cell.afterClick = Alphabet.onImageClick;
						}
					}
				}
			}
		}
		return Alphabet.dir;
	}
	Alphabet.onImageClick = function(e){
		toggleDisplay(Alphabet.dir);
		if(Alphabet.dir.style.display==''){
			Alphabet.dir.onShow();		
		}
	}
/*****************************END An Alphabet Object *************************/



//AJAX command Queue Objects

	function Command(Obj,Method,Params){
	    this.object = Obj;
	    this.method = Method;    
	    this.params = Params;
	    this.execute = function(){
	        this.method.call(this.object,this.params);
	        return false;
	    }    
	}
	function ProcessQueue(){
	    this.items = new Array();
	    this.suspended = false;
	    
	    this.add = function(Command){
	        this.items.push(Command);
	        Process.call(this);
	    }
	    this.next = function(){
	        return (this.items.length>0)?this.items.shift():null;
	    }
	    function Process(){
	        if(!this.suspended){
	            this.currentCommand=this.next();
	            if(this.currentCommand){
	                this.suspended = this.currentCommand.execute();
	            }    
	        }
	    }
	    this.Continue= function(){
	        this.suspended = false;
	        Process.call(this);
	    }
	    this.executeCallback = function(Response){
		if(this.currentCommand!=null){
		        this.currentCommand.executeCallback(Response);
		}
	        this.Continue.call(this);
	    }       
	}

	Ajax = {};
	Ajax.onLoad = new EventObj();
	Ajax.Queue = new ProcessQueue();
	Ajax.addAsync=function(obj,Method,URL,CallbackMethod){
	    Ajax.Queue.add(new asyncRequest(obj,Method,URL,CallbackMethod));
	}
	Ajax.addSync=function(obj,Method,params){
	    Ajax.Queue.add(new Command(obj,Method,params));
	}
	Ajax.addCommand=function(Command){
	    Ajax.Queue.add(Command);
	}
	Ajax.makeRequest = function(Method,URL)
	{
	    this.request = new XMLHttpRequest();
	    this.request.onreadystatechange = Ajax.onResponse;
	    this.request.open(Method,URL,true);
	    this.request.send(URL);
	}
	Ajax.onResponse = function()
	{
	    if(Ajax.request.readyState==4){
	        if(Ajax.request.status==200)
	        {
	            Ajax.Queue.executeCallback(Ajax.getResponse());
	        }
	        else{
	            alert("ERROR: Ajax request status = " + Ajax.request.status);
	        }    
	    }
	}
	
	Ajax.getResponse = function()
	{	
		if(this.request.responseXML){
			if(this.request.responseXML.documentElement){
			        return this.request.responseXML.documentElement.childNodes[0].nodeValue;
			}
			else{
			        return this.request.responseText;
			}
		}else{
		        return this.request.responseText;
		}
	}
	
	Ajax.getKeyWords = function(onLoadHandler)
	{	
		if(Ajax._keyWords==null){
			Ajax._keyWords = new serviceObj("getKeyWords","");
			Ajax._keyWords.infoTitle = "Glossary of Keywords";
			Ajax._keyWords.onLoad.addHandler(onLoadHandler);
			Ajax._keyWords.alphaListClickHandler = function(e){
				evt = getEvent(e);
				trg = getEventTarget(evt);
				x = _get("search_searchword");
				x.value = trg.innerHTML;
				x.focus();
				trg.afterClick();
				//requested by linda
				if (document.searchForm) {
					_get('loadingGIF').style.display = '';
					document.searchForm.submit();
				}
			}
		}
		return Ajax._keyWords;
	}



	function Pair(Name,Value){
	    this.name = Name;
	    this.value = Value;
	}
	
	function asyncRequest(Obj,Method,URL,CallbackMethod){
	    this.object = Obj;
	    this.method = Method;    
	    this.url = URL;    
	    if(CallbackMethod){
	        this.callbackMethod = CallbackMethod;    
	    }
	    else{
	        this.callbackMethod = null;    
	    }
	    this.execute = function(){
	        Ajax.makeRequest(this.method,this.url);
	        return this.callbackMethod != null;
	    }
	    this.executeCallback = function(Response){
	        if(this.callbackMethod){
	            this.callbackMethod.call(this.object, Response);
	        }    
	    }       
	}
	
	
	
	function EventObj(){
		this.Handlers = new Array();
	}
	EventObj.prototype.addHandler = function(handler){
		this.Handlers.push(handler);
	}
	EventObj.prototype.RaiseEvents = function(args){
		for(var i=0,j=this.Handlers.length;i<j;i++){
		    e = this.Handlers[i];
		    e(args);
		}    
	}
	
/********************************/
/*        perlObject            */
/********************************/

	function perlObject(){
	}

    	perlObject.prototype.Bind = function(obj){
		cloneProperties(obj,this)
	} 	
/********************************/
/*        perlObjectCollection  */
/********************************/
	function perlObjectCollection()
	{
	}
	perlObjectCollection.prototype.Bind = function(JSON){
		if(JSON.indexOf("{'Error':")==0){
		    
		    this.onError(JSON);
		}
		else{
		    obj = parseJSON(JSON);
		    this.hashItems(obj);
		    if(this.Count > 0){
		        this.CurrentItem = this.Items[0];
		    }
		}
		this.onLoad.RaiseEvents(this);  
	}
	perlObjectCollection.prototype.hashItems = function(items){
		this.Count = 0;
		while(items[this.Count])
		{
			this.Items[this.Count] = new this.ItemType(items[this.Count])
			this.Count++;
		}
	}
/********************************/
/*        Item              */
/********************************/

    Item.prototype = new perlObject();
    Item.prototype.constructor = Item;
    
    function Item(obj){
	this.afterSave = new EventObj();
        this.Bind(obj);
    }

/********************************/
/*        Item              */
/********************************/



/********************************/
/*        serviceItem          	*/
/********************************/

	function serviceItem(serviceMethod,getParams){
		this.getParams = getParams;
		this.onLoad = new EventObj();
		this.serviceMethod = serviceMethod;
		this.getData();
	}
	serviceItem.prototype.getData = function(){
		//Ajax.addAsync(this,"GET","http://www.rccp.org.za/services/jason_data.php?method=" + this.serviceMethod + this.getParams,this.onLoadHandler);
		Ajax.addAsync(this,"GET","/services/jason_data.php?method=" + this.serviceMethod + this.getParams,this.onLoadHandler);
	}
	serviceItem.prototype.onLoadHandler = function(JSON){
		cloneProperties(parseJSON(JSON),this);
		this.onLoad.RaiseEvents(this);
	}

/********************************/
/*        serviceItem          	*/
/********************************/





/********************************/
/*        serviceObj          	*/
/********************************/
	serviceObj.prototype = new perlObjectCollection();
	serviceObj.prototype.constructor = serviceObj;
	
	function serviceObj(serviceMethod,getParams){
		this.Count = 0;
		this.Items = new Array();
		this.getParams = getParams;
		this.CurrentItem;
		this.ItemType = Item
		this.onCurrentItemChange = new EventObj();
		this.onLoad = new EventObj();
		this.serviceMethod = serviceMethod;
		this.getData();
	}
	serviceObj.prototype.getData = function(){
		//Ajax.addAsync(this,"GET","http://www.rccp.org.za/services/jason_data.php?method=" + this.serviceMethod + this.getParams,this.Bind);
		Ajax.addAsync(this,"GET","/services/jason_data.php?method=" + this.serviceMethod + this.getParams,this.Bind);
	}


	function appendCloseButton(container,onClickHandler){
		appendCloseButton.retVal = appendDOMObject(container,"span","{'innerHTML':'X','className':'closeButton'}");
		addEvent(appendCloseButton.retVal,'click',onClickHandler);
		return appendCloseButton.retVal;
	}

	function appendText(container,className,text){
		appendText.retVal = appendDOMObject(container,"span","{'innerHTML':'" + text + "','className':'" + className + "'}");
		return appendText.retVal;
	}
	function appendImage(container,className,imgURL){
		appendImage.retVal = newImage(className,imgURL);
		container.appendChild(appendImage.retVal);
		return appendImage.retVal;
	}
	function newImage(className,imgURL){
		return newDOMObject("img","{'src':'" + imgURL + "','className':'" + className + "'}");
	}
	function appendImageButton(container,className,imgURL,text,onClickHandler,context){
		appendImageButton.retVal = newImageButton(className,imgURL,text,onClickHandler,context);
		container.appendChild(appendImageButton.retVal);
		return appendImageButton.retVal;
	}
	function newImageButton(className,imgURL,text,onClickHandler,context){
		newImageButton.retVal = newDOMObject("div","{'className':'" + className + "'}");
		newImageButton.retVal.Context = context;
		newImageButton.retVal.Image = appendImage(newImageButton.retVal,"ImageButton",imgURL);
		newImageButton.retVal.Image.Context = context;
		addEvent(newImageButton.retVal,'click',onClickHandler);
		if((text != null)&&(text.length>0)){
			appendBR(newImageButton.retVal);
			newImageButton.retVal.Caption = appendText(newImageButton.retVal,text,text);
			newImageButton.retVal.Caption.Context = context;
		}
		return newImageButton.retVal;
	}


/************************************************/
/*        ButtonPanel			       	*/
/************************************************/
	ButtonPanel = {};
	ButtonPanel.appendNew = function(container,panelContainer,className,imgURL,buttonText, panelTitle){
		ButtonPanel.retval = ButtonPanel.getNew(className,imgURL,buttonText, panelTitle);
		panelContainer.appendChild(ButtonPanel.retval.Panel);
		container.appendChild(ButtonPanel.retval);
		return ButtonPanel.retval;
	}
	ButtonPanel.getNew = function(className,imgURL,buttonText, panelTitle){
		ButtonPanel.retVal = newDOMObject("div","{'className':'" + className + "'}");
		ButtonPanel.retVal.Panel = Panel.appendNew(ButtonPanel.retVal,panelTitle,"Panel");
		ButtonPanel.retVal.Button = appendImageButton(ButtonPanel.retVal,"Button",imgURL,buttonText,ButtonPanel.onButtonClick,ButtonPanel.retVal.Panel);
		//ButtonPanel.retval.Panel.style.position = "absolute";
		ButtonPanel.retVal.Panel.style.display = "none";
		ButtonPanel.retVal.Panel.style.zIndex = 5000;
		ButtonPanel.retVal.appendContent = function(ctrl){
			this.Panel.appendContent(ctrl);
		}
		return ButtonPanel.retVal;
	}
	ButtonPanel.onButtonClick = function(e){
		evt = getEvent(e);
		target = getEventTarget(evt);
		if(toggleDisplay(target.Context)){
			target.Context.focus();
		}
	}
/************************************************/
/*        Panel			          	*/
/************************************************/
	Panel = {};
	Panel.appendNew = function(container,title,classname){
		Panel.getNew(title,classname);
		container.appendChild(Panel.retVal);
		return Panel.retVal;
	}
	Panel.getNew = function(title,classname){
		Panel.retVal = newDOMObject("div","{'className':'" + classname + "'}");
		Panel.retVal.onShow = new EventObj();
		Panel.retVal.Header = appendDOMObject(Panel.retVal,"div","{'className':'PanelHeader'}");
		Panel.retVal.btn = appendCloseButton(Panel.retVal.Header,Panel.onCloseButtonClick);
		Panel.retVal.Title = appendText(Panel.retVal.Header,"PanelHeaderText",title);
		Panel.retVal.btn.Panel = Panel.retVal;
		Panel.retVal.Body = appendDOMObject(Panel.retVal,"div","{'className':'PanelBody'}");
		Panel.retVal.appendContent = function(ctrl){
			this.Content = ctrl;
			this.Body.appendChild(ctrl);
		}
		Panel.retVal.focus = function(){
			this.Content.focus();
		}
		return Panel.retVal;
	}
	Panel.onCloseButtonClick = function(e){
		evt = getEvent(e);
		target = getEventTarget(evt);
		toggleDisplay(target.Panel);
	}


/************************************************/
/*        UserDocumentRatingControl          	*/
/************************************************/
	Ajax.getUserDocumentRatings = function(userId,onLoadHandler)
	{	
		getParams = "";
		Ajax.UserDocumentRatings = new serviceObj("getUserDocumentRatings",getParams);

		Ajax.UserDocumentRatings.saveRating = function(context,rating){
			userId = context.UserId;
			docId = context.document_id;
			//window.open("http://www.rccp.org.za/services/jason_data.php?method=saveUserDocumentRating&user_id=" + userId + "&document_id=" + docId + "&rating=" + rating);
			//Ajax.addAsync(this,"GET","http://www.rccp.org.za/services/jason_data.php?method=saveUserDocumentRating&user_id=" + userId + "&document_id=" + docId + "&rating=" + rating,Ajax.UserDocumentRatings.afterSave);
			Ajax.addAsync(this,"GET","/services/jason_data.php?method=saveUserDocumentRating&user_id=" + userId + "&document_id=" + docId + "&rating=" + rating,Ajax.UserDocumentRatings.afterSave);
		}
		Ajax.UserDocumentRatings.afterSave = function(JASON){
			obj = parseJSON(JASON);
			rating = Ajax.UserDocumentRatings.locate(obj.document_id);
			rating.Bind(obj)
			rating.afterSave.RaiseEvents(rating);  

		}
		Ajax.UserDocumentRatings.locate = function(documentId){
			for(idx in Ajax.UserDocumentRatings.Items){
				UserDocumentRating = Ajax.UserDocumentRatings.Items[idx];
				if(UserDocumentRating.document_id==documentId){
					return UserDocumentRating;
				}
			}
			return null;
		}
		Ajax.UserDocumentRatings.onLoadHandler = function(){
			for(idx in Ajax.UserDocumentRatings.Items){
				UserDocumentRating = Ajax.UserDocumentRatings.Items[idx];
				UserDocumentRating.UserId = Ajax.UserDocumentRatings.UserId;
				//Display Functions
				UserDocumentRating.getCaptureForm = function(){
					tbl = newDOMObject("table");
					appendInputRow(tbl,"Rate 0 Star : ",newImageButton("","/images/user0stars.JPG","",UserDocumentRating.saveRating0,this));
					appendInputRow(tbl,"Rate 1 Star : ",newImageButton("","/images/user1stars.JPG","",UserDocumentRating.saveRating1,this));
					appendInputRow(tbl,"Rate 2 Star : ",newImageButton("","/images/user2stars.JPG","",UserDocumentRating.saveRating2,this));
					appendInputRow(tbl,"Rate 3 Star : ",newImageButton("","/images/user3stars.JPG","",UserDocumentRating.saveRating3,this));
					appendInputRow(tbl,"Rate 4 Star : ",newImageButton("","/images/user4stars.JPG","",UserDocumentRating.saveRating4,this));
					appendInputRow(tbl,"Rate 5 Star : ",newImageButton("","/images/user5stars.JPG","",UserDocumentRating.saveRating5,this));
					return tbl;
				}
				UserDocumentRating.appendCtrl = function(container){
					this.ave_rating = new Number(this.ave_rating).valueOf();
					this.num_ratings = new Number(this.num_ratings).valueOf();
					switch(this.ave_rating){
						case 0:
							img = newImage("","/images/user0stars.JPG");
							break;
						case 1:
							img = newImage("","/images/user1stars.JPG");
							break;
						case 2:
							img = newImage("","/images/user2stars.JPG");
							break;
						case 3:
							img = newImage("","/images/user3stars.JPG");
							break;
						case 4:
							img = newImage("","/images/user4stars.JPG");
							break;
						case 5:
							img = newImage("","/images/user5stars.JPG");
							break;
					}
					if(this.num_ratings>0){
						blurb = this.num_ratings + " Users have Rated this Document.\nAverage Rating : " + this.ave_rating;
						img.title = blurb;
						img.alt = blurb;
						container.innerHTML = "USER RATING&nbsp;&nbsp;&nbsp;&nbsp";
						container.appendChild(img);
					}
				}

	/**********emailer bodged in *******************/
				UserDocumentRating.getEmailForm = function(){
					div = newDOMObject("div");
					tbl = appendDOMObject(div,"table");
					this.SendTo = newInput("text","send_to");
					div.SendTo = this.SendTo;
					appendEvent(this.SendTo,"keyup",this.onEMailKeyUp,this,null);
					appendInputRow(tbl,"Send To : ",this.SendTo);
					
					this.Subject = newInput("text","subject");
					appendEvent(this.SendTo,"keyup",this.onEMailKeyUp,this,null);
					appendInputRow(tbl,"Subject : ",this.Subject);
					

					this.Message = newDOMObject("textarea","{'id':'message','rows':'10'}");
					appendInputRow(tbl,"Message : ",this.Message);
					appendBR(div);
					b = newButtonRow(div);
					b = appendButton(this,b,"Send",this,this.sendMail);
					this.Status = appendText(div,"status","");
					
					
					/********overide focus ***/
					div.focus = function(){
						this.SendTo.focus();
					}
					return div;
				}
				UserDocumentRating.onEMailKeyUp = function(e){
					evt = getEvent(e);
					if(evt.keyCode== 13){
					target = getEventTarget(evt);
						target.Context.sendMail();
					}
				}
				
				UserDocumentRating.sendMail = function(){
					addresses = cleanEmailString(this.SendTo.value);
					this.Status.innerHTML = "";
					for(addrIdx=0;addrIdx<addresses.length;addrIdx++){
						r = addresses[addrIdx];	
						this.Status.innerHTML += r.status + "<br>"
						if(r.isValid){
							params = "?method=sendMail&to=" + r.eMail + "&document_id=" + this.document_id + "&from=" + Ajax.User.email + "&fromName=" + escape(Ajax.User.name) + "&subject=" + escape(this.Subject.value) + "&content=" + escape(this.Message.value); 
							//window.open("http://www.rccp.org.za/services/jason_data.php" + params);
							Ajax.addAsync(this,"GET","/services/jason_data.php" + params); 
						}
					}
				}

	/**********emailer bodged in *******************/
				//Save Functions
				UserDocumentRating.saveRating0 = function(e){
					Ajax.UserDocumentRatings.saveRating(getContext(e),0);
				}
				UserDocumentRating.saveRating1 = function(e){
					Ajax.UserDocumentRatings.saveRating(getContext(e),1);
				}
				UserDocumentRating.saveRating2 = function(e){
					Ajax.UserDocumentRatings.saveRating(getContext(e),2);
				}
				UserDocumentRating.saveRating3 = function(e){
					Ajax.UserDocumentRatings.saveRating(getContext(e),3);
				}
				UserDocumentRating.saveRating4 = function(e){
					Ajax.UserDocumentRatings.saveRating(getContext(e),4);
				}
				UserDocumentRating.saveRating5 = function(e){
					Ajax.UserDocumentRatings.saveRating(getContext(e),5);
				}
			}
		}
		Ajax.UserDocumentRatings.UserId = userId;
		Ajax.UserDocumentRatings.onLoad.addHandler(Ajax.UserDocumentRatings.onLoadHandler);
		Ajax.UserDocumentRatings.onLoad.addHandler(onLoadHandler);
		return Ajax.UserDocumentRatings;
	}
	function appendEvent(elm,eventName,handler,context,params){
		addEvent(elm,eventName,handler)
		elm.Context = context;
		elm.Params = params;
	}
/************************************************/
/*        USER          			*/
/************************************************/
	Ajax.getUser = function()
	{	
		if(Ajax.User==null){
			getParams = "&user_id=" + userId;
			Ajax.User = new serviceItem("getUser",getParams);
		}
		return Ajax.User;
	}
/************************************************/
/*        USER          			*/
/************************************************/


/************************************************/
/*        MAILER          			*/
/************************************************/
	function doSendMail(document_id) {
		myForm = document.getElementById('EMAILFORM_'+document_id);
		addresses = cleanEmailString(myForm.SendTo.value);
		document.getElementById('STATUS_'+document_id).innerHTML = '';
		for(i=0; i<addresses.length; i++) {
			r = addresses[i];	
			document.getElementById('STATUS_'+document_id).innerHTML += r.status + "<br>"
			if(r.isValid){
				params = "?key=&method=sendMail&to=" + r.eMail + "&document_id=" + document_id + "&from=" + Ajax.User.email + "&fromName=" + escape(Ajax.User.name) + "&subject=" + escape(myForm.Subject.value) + "&content=" + escape(myForm.Message.value); 
	//					window.open("http://www.rccp.org.za/services/jason_data.php" + params);
				Ajax.addAsync(this,"GET","/services/jason_data.php" + params,onMailSent);
			}
		}
		container = document.getElementById('EMAIL_'+document_id).style.display='none';
	}
	function onMailSent(response) {
		alert(response);
	}

/************************************************/
/*        MAILER          			*/
/************************************************/












