var profileContainer;
var profileBody;
var xslDoc;
var xmlDoc;
var xmlDocCourses;
var currentPerson;

var GLOBAL_USER_ACCESS;

var MAX_Z_INDEX = 1000;
var ID_COUNTER = 1;

function raise( _elem, _id ){
    return _elem.attr( "id", _id ).css( "z-index", MAX_Z_INDEX++ )
}

var $MODAL = $(document.createElement("div"))
    .attr("class","modal")
    .css({
        position: "absolute",
        left: "25%",
        top: "25%",
        width: "50%",
        border: "solid 1px #000",
        backgroundColor: "#fff" })

var $HAZE = $(document.createElement("div"))
    .attr("id","_HAZE")
    .css({
        position: "absolute",
        width: "100%",
        height: "100%",
        left: "0px",
        top: "0px",
        opacity: "0.5",
        backgroundColor: "#fff" })
        
function raise_haze(){
    $("body").append(
        raise( $HAZE.clone(true), "" )
            //.fadeTo( "fast", 0.50 )
    )
}

function HTMLDecode(s){
    s = s.replace(/&lt;/gi, "<");
    s = s.replace(/&gt;/gi, ">");
    s = s.replace(/&amp;/gi, "&");
    return s;
}

function HTMLEncode(s){
    s = s.replace(/</gi, "&lt;");
    s = s.replace(/>/gi, "&gt;");
    s = s.replace(/&/gi, "&amp;");
    s = s.replace(/(jQuery)(.)*\"(.)*\"/gi, "");
    return s;
}

var cssButton={
        fontWeight: "normal",
        color: "#900",
        background: "#ccc",
        borderTop: "solid 1px #eee",
        borderRight: "solid 1px #aaa",
        borderBottom: "solid 1px #aaa",
        borderLeft: "solid 1px #eee",
        cursor: "pointer"
    };
    cssButton={
        fontWeight: "normal",
        textDecoration: "underline",
        color: "#900",
        padding: "5px",
        cursor: "pointer"
    };

if (!window['Node']){
    window.Node = new Object();
    Node.ELEMENT_NODE = 1;
    Node.ATTRIBUTE_NODE = 2;
    Node.TEXT_NODE = 3;
    Node.CDATA_SECTION_NODE = 4;
    Node.ENTITY_REFERENCE_NODE = 5;
    Node.ENTITY_NODE = 6;
    Node.PROCESSING_INSTRUCTION_NODE = 7;
    Node.COMMENT_NODE = 8;
    Node.DOCUMENT_NODE = 9;
    Node.DOCUMENT_TYPE_NODE = 10;
    Node.DOCUMENT_FRAGMENT_NODE = 11;
    Node.NOTATION_NODE = 12;
}

var personnel_base_url= "http://www.ed.sc.edu/personnel/"
var people_base_url= "http://www.ed.sc.edu/People/"

var loadingDiv=$(document.createElement("div"))
.append("loading...");

$.fn.serializeXML = function () {
	var out = '';
	if (typeof XMLSerializer == 'function') {
				var xs = new XMLSerializer();
				this.each(function() {
						out += xs.serializeToString(this);
				});
	} else if (this[0] && this[0].xml != 'undefined') {
				this.each(function() {
						out += this.xml;
				});
	}
	return out;
};

function getRoot(xml_){
    return xml_.substring(1,xml_.indexOf(">")).replace(/[/]/g,"").split(" ")[0];
}

function test(){alert('test');}

function closeProfile(){

		$("#"+currentPerson)
		.show();
		$("#"+profileContainer)
		.hide();
		$("#fadeFloat")
		.hide();

		xmlDoc=null;
		currentPerson=null;
		xmlDocCourses=null;

}

function getCoursesXML(person){
	if( $("person > type",xmlDoc).text()=="Faculty" ){
	    $.ajax({
	        url: personnel_base_url+"courses.asp?x="+rand(),
            data: {p: person},
            type: "GET",
            async: false,
            dataType: "xml",
            success: function(data){
				if($(data).serializeXML() != "<null/>"){
					xmlDocCourses=data;
					//document.importNode(<node to import>, <recurse children>);
					$("person",xmlDoc).append($("courses",xmlDocCourses));
                }
            },
            error: function (err){
				alert("err: "+err);
            }
	    });
	}
}

function saveXML(){
	removeNode("courses");
	$.ajax({
		type: "POST",
		contentType: "text/xml",
		url: personnel_base_url+"BuildXML.aspx?uc=update&lname="+$("person name last",xmlDoc).text()+"&fname="+$("person name first",xmlDoc).text()+"&x="+rand(),
		processData: false,
		data: $(xmlDoc).serializeXML(),
		success: function(txt) {
	        showProfile();
		}
	});
}

function removeEntry(){
	$.ajax({
		type: "POST",
		contentType: "text/xml",
		url: personnel_base_url+"BuildXML.aspx?uc=remove&lname="+$("person name last",xmlDoc).text()+"&fname="+$("person name first",xmlDoc).text()+"&x="+rand(),
		processData: false,
		data: $(xmlDoc).serializeXML(),
		success: function(txt) {
	        closeProfile();
		}
	});
}

function showProfile(){

	$(getCoursesXML(currentPerson)).ready(function(){
		$("#profileContent").html(xslt(xmlDoc,xslDoc));
		//.each(function(){
		//    if($(this).metadata().type)
		//}
		
		setupEditButton();

		//$("#"+currentPerson)
		//.after($("#"+profileContainer));

		//$("#profileCenter")
		//.append($("#"+profileContainer));
    
        if($.browser.msie){
            //$("#fadeFloat").show();
            //$(raise_haze()).ready(function(){
            $("#"+profileContainer).show();
            //});
        }else{
            $("#fadeFloat").fadeIn("fast", function(){
                $("#"+profileContainer).fadeIn( "fast" )
            })
        }
		
		//DECODE THE HTML
		$(".p_extended:not(#_contacts) .dynamicField").each(function(){
		    //var encoded=$(this).html();
		    //encoded=encoded.replace(/&lt;/g,"<");
		    //encoded=encoded.replace(/&gt;/g,">");
		    //encoded=encoded.replace(/&amp;/g,"&");
		    //$(this).html(encoded);
		    $(this).html(HTMLDecode($(this).html()));
		});
		
		//$("#"+currentPerson)
		//.hide();
	});
}

function activateSections(xml_){ //xml branch

	if($(xml_).children().text()!=""){
	
		$(xml_).children()
		    .each(
		        function(){
		        
			        root= getRoot($(this).serializeXML()); //relative root
			        n= Number($(this).attr("id"))
			        
			        if(!(n>"0")){ //if the element doesn't have an id attr or its 0 - don't descend into nodes redundantly
			        
			            if($(this).attr("grow")=="true"){
			            
	                        branch= $(this);
				            $("#_"+root+"_label")
			                    .append(
	                                $(document.createElement("span"))
	                                    .css({
	                                        fontWeight: "normal",
	                                        color: "#900",
	                                        background: "#ccc",
	                                        borderTop: "solid 1px #eee",
	                                        borderRight: "solid 1px #aaa",
	                                        borderBottom: "solid 1px #aaa",
	                                        borderLeft: "solid 1px #eee",
	                                        cursor: "pointer"
	                                    })
                                        .bind(
                                            "click",
                                            {
                                                branch: $(branch),
                                                root: root
                                            },
                                            function(e){//time waster!
                                                child=$(e.data.branch.children()[0]);

                                                //alert($(child).serializeXML());
                                                //alert($("person "+e.data.root+"",xmlDoc).children(":last").attr("id"));
                                                newNode=$(xmlDoc.createElement(getRoot($(child).serializeXML()))).attr(
				                                    "id",Number(
				                                        Number($("person "+e.data.root+"",xmlDoc).children(":last").attr("id"))+1
				                                    )
				                                );
				                                $(child).children().each(
				                                    function(){
				                                        $(newNode).append(
				                                            $(xmlDoc.createElement(getRoot($(this).serializeXML())))
				                                        );
				                                    }
				                                );
                                                $("person "+e.data.root,xmlDoc).append(
					                                newNode
                                                );
                                                $("#profileContent").html(
                                                    xslt(xmlDoc,xslDoc)
                                                ); //update profileContent
                                                
			                                    setupEditMode("#p_login"); // SETUP EDIT MODE
                                            }
                                        )
                                        .append("&nbsp;add&nbsp;")
	                            )
	                        ;
	                        
			            }
                        activateSections($(this)); // ACTIVATE SECTIONS is this recursive step ever needed?
                        
			        }
			        
		        }
		    )
		;
		
	}
}



function setupEditButton(){

    $("#p_button_close")
    .click(function(){
        closeProfile();
    });

    $("#p_button_login")
    .css({
        fontWeight: "normal",
        color: "#ddd",
        background: "#ddd",
        borderTop: "solid 1px #ddd",
        borderRight: "solid 1px #ddd",
        borderBottom: "solid 1px #ddd",
        borderLeft: "solid 1px #ddd",
        cursor: "pointer"
    })
    .bind("click",function(e){
		$("#p_login")
		.fadeOut("fast",function(){
			$(this)
			.empty()
			.append(
				$(document.createElement("input"))
				.attr("class","dynamicField")
			    .attr({
			        type: "text",
			        name: "username",
			        id: "username",
			        value: "username"
			    })
				.css({
					color: "#888",
					fontSize: "1em",
					width: "120px",
					height: "1.2em",
					verticalAlign: "middle"
				})
				.focus(function(){if(this.value=="username"){this.style.color="#000";this.value="";}})
				.blur(function(){if(this.value==""){this.style.color="#888";this.value="username";}})
			)
			.append(
				$(document.createElement("input"))
			    .attr("class","dynamicField")
			    .attr({
			        type: "password",
			        name: "password",
			        id: "password",
			        value: "password"
			    })
				.css({
					color: "#888",
					fontSize: "1em",
					width: "120px",
					height: "1.2em",
					verticalAlign: "middle"
				})
				.focus(function(){
				    if(this.value=="password"){this.style.color="#000";this.value="";}
				})
				.blur(function(){
				    if(this.value==""){this.style.color="#888";this.value="password";}
				})
			)
			.append(
			    $(document.createElement("span"))
			    .append("Login")
			    .css(cssButton)
			    .click(function(e){
				    $("#p_login")
				    .fadeOut("fast",function(){
					    usrname=el("username").value;
					    pssword=el("password").value;
					    $(this)
					    .empty()
					    .append(
						    $(document.createElement("div"))
						    .text("Logging In...")
					    );
					    $(this)
					    .fadeIn("fast",function(){
						    $.ajax({
							    type: "GET",
							    url: personnel_base_url+"login.asp?uc=login&username="+usrname+"&password="+pssword+"&usr="+currentPerson+"&x="+rand(),
							    dataType: "text",
							    success: function(response){
							        if(!isNaN(response)){
							            GLOBAL_USER_ACCESS = response
								        $("#p_login")
								        .fadeOut("fast",function(){
											$(this)
											.empty()
											.append(
												$(document.createElement("div"))
												.attr("class","p_actions")
												.append("Loading...")
											)
											.fadeIn("fast",function(){
												setupEditMode(this);
											});
								        })
								    }else{
								        $("#p_login")
								        .fadeOut("fast",function(){
								            $(this)
								            .empty()
								            .append(
								                $(document.createElement("a"))
								                .attr("href","javascript:;")
								                .attr("id","p_button_login")
								                .text("Login Failed.")
								            )
								            .fadeIn("slow",function(){
												$(this)
												.fadeOut("slow",function(){
													setupEditButton();
													$("#p_button_login").trigger("click");
												});
								            });
								        })
								    }
							    }
						    });
					    });
				    })
			    })
			);
			$("#p_login")
			.fadeIn("fast");
		});
    })
}

;;//append "remove" buttons to each group
function activateGroups()
{
	var g;
	$(".p_extended .group")
	.each(function(){
		g=$(this)
		g.append(
			$(document.createElement("div"))
			.css({
				fontWeight: "normal",
				float: "right",
				color: "#900",
				background: "#ccc",
				borderTop: "solid 1px #eee",
				borderRight: "solid 1px #aaa",
				borderBottom: "solid 1px #aaa",
				borderLeft: "solid 1px #eee",
				cursor: "pointer"
			})
			.bind(
				"click",
				{
					gXPath: g.metadata().xpath,
					gType: g.metadata().type,
					gID: g.metadata().id
				},
				function(e){
					//alert(e.data.gType);
				    xpath=e.data.gXPath;
				    /*if((e.data.gID=="0")){//&&(element with id 0 is the only element in the group)){
				        clearNode(xpath,e.data.gID);
				        alert($(".p_extended #_"+e.data.gType+"_"+Number(e.data.gID)+1));
				        $(".p_extended #_"+e.data.gType+"_"+e.data.gID).fadeOut("slow",function(){
				            $("#profileContent").html(xslt(xmlDoc,xslDoc)); //update profileContent
                            setupEditMode("#p_login");
				        });
				    }else{*/
					    removeNode(xpath,e.data.gID);
					    //if the node to be removed is the only node, then simply "empty" it since we need it as a template.
					    $(".p_extended #_"+e.data.gType+"_"+e.data.gID)
					    .fadeOut("slow",function(){
					        $(this).remove();
						    //alert($(e.data.gType,xmlDoc).serializeXML());
					    });
					/*}*/
				}
			)
			.append("&nbsp;remove&nbsp;")
		);
	})
}

function removeNode(xpath,id)
{
    /*if(id=="0"){
	    if($.browser.msie){
	        var nodeList = xmlDoc.selectNodes("person/"+xpath);
		    for(var x = 0; x < nodeList.length; x++){
			    nodeList[x].children().each(
		            function(){
		                $(this).text("");
		            }
		        )
		    }
	    }else{
	        $("person "+jQSelector(xpath),xmlDoc).children().each(
	            function(){
	                $(this).text("");
	            }
	        )
	    }
	}else{*/
	    if($.browser.msie){
		    var nodeList = xmlDoc.selectNodes("person/"+xpath);
		    for(var x = 0; x < nodeList.length; x++){
			    nodeList[x].parentNode.removeChild(nodeList[x]);
		    }
	    }else{
		    $("person "+jQSelector(xpath),xmlDoc).remove();
	    }
	/*}*/
}

function clearNode(xpath,id)
{
    $("person "+jQSelector(xpath),xmlDoc).children().each(
        function(){
            $(this).text("");
        }
    )
}

function jQSelector(xpath)
{
	xpath=xpath.replace(/\//g," ");
	xpath=xpath.replace(/@/g,"");
	return xpath;
}

function setupEditMode(sideMenu)
{
    $("#profileContent div *").show();
    $(".p_extended").show();
    
    $(".p_extended:not(#_contacts) .dynamicField").each(function(){
        $(this).html(HTMLEncode($(this).html()));
    });

    $("#p_photo").append(
		$(document.createElement("div"))
		.css({
			margin: "2px 0 0 0"
		})
		.append(
			$(document.createElement("span"))
			.css(cssButton)
			.append("&nbsp;change&nbsp;")
			.bind("click",function(){
				$(this)
				.replaceWith(
					$(document.createElement('input'))
					.attr("type","file")
					.attr("name","photo_filename")
					.attr("id","upload_photo")
					.attr("value","")
					.bind("change",function(e){
						path="person "+this.name.replace(/_/g," ");
						$(path,xmlDoc).empty();
						$(path,xmlDoc).append(
							xmlDoc.createTextNode(people_base_url+currentPerson+"/"+this.value.split("\\")[this.value.split("\\").length-1])
						);
						ajaxFileUpload(this.id);
					})
				)
			})
		)
	);

    $(activateSections(xmlDoc))
    .ready(function(){
		$(activateGroups(xmlDoc))
		.ready(function(){

			$(activateDynamicFields())
			.ready(function(){
				$(sideMenu)
				.fadeOut("fast",function(){
					$(this).empty();
					
					actions = $(document.createElement("div"))
						.attr("class","p_actions")
						
					actions.append(
						$(document.createElement("a"))
						.attr("href","javascript:;")
						.css(cssButton)
						.append("save changes")
						.click(function(e){
							$(sideMenu)
							.fadeOut("fast",function(){
								saveXML();
							})
						})
					)
					.append("&nbsp;")
						
					if ( GLOBAL_USER_ACCESS=="2" || GLOBAL_USER_ACCESS=="3" ){
						actions.append(
						    $(document.createElement("a"))
						    .attr("href","javascript:;")
						    .css(cssButton)
						    .append("delete this profile")
						    .click(function(e){
							    $(sideMenu)
							    .fadeOut("fast",function(){
								    removeEntry();
							    })
						    })
					    )
					    actions.append(
						    $( document.createElement("a") )
						    .attr("href","javascript:;")
						    .css(cssButton)
						    .append("new profile")
						    .click( function(e){
						        $.getScript( personnel_base_url + "js/personneladd.js", function(){
						            $("body").append( setupPersonnelAdd( raise( $MODAL.clone(true), "personneladd" ) ) )
							    })
						    })
					    )	
					}
					
					$(this)
					.append(actions)
					.fadeIn("fast",function(){
						//$(activateDynamicFields())
						//.ready(function(){
							//CODE SPECIFIC TO THE PERSONNEL PROFILE IMPLEMENTATION
							//begin

							if($("person courses",xmlDoc).text()){
								setupSyllabusSelect();
							}
							//end
						//});
					});
				});
			});

		});
    });
}

function setupSyllabusSelect(){
	$("#_files select.dynamicField")
	.bind(
		"change",
		function(){
			if($(this).val()=="Syllabus"){
				//alert("$(this).val()==\"Syllabus\"");
				var _this=$(this)
				//$(this)
				//.attr("")
				//$(this).parent().find(":contains('Type')").next().remove();
				//$(this).parent().find(":contains('Type')").remove();
				$(this).parent().find(":contains('Title')").next().remove();
				$(this).parent().find(":contains('Title')").remove();
				$(this).parent().find(":contains('Abstract')").next().remove();
				$(this).parent().find(":contains('Abstract')").remove();
				$(this).parent().find(":contains('Comment')").next().remove();
				$(this).parent().find(":contains('Comment')").remove();

				var s=document.createElement('select');
				$(this)
				.after(
					$(s)
					.attr("name",_this.metadata().xpath)
					.attr("class",_this.attr("class"))
					.width(_this.width())
					.change(function(){
						//$("person files file[id="+_this.metadata().num+"]"_abstract,xmlDoc).remove();
						//$("person files file[id="+_this.metadata().num+"]"_abstract,xmlDoc).remove();
						//alert(_this.metadata().num);
						$("person files file[id="+_this.metadata().num+"]",xmlDoc)
						.append(
							$(xmlDoc.createElement("course"))
							.attr("label",$(this).children("option:selected").text().split("-")[0])
							.append(xmlDoc.createTextNode(this.value))
						);
						//console.log($("person files file[id="+_this.metadata().num+"]",xmlDoc).serializeXML());
						//alert($("person files file[id="+_this.metadata().num+"]",xmlDoc).serializeXML());
					})
					.ready(function(){
						var op,_c,_t,_p,_n;
						$(s).append(
							$(document.createElement("option"))
							.attr("value","")
							.append("Select A Course")
						)
						$("person courses term",xmlDoc).each(function(i){
							_c=$(this).attr("code");
							_t=$(this).attr("value");
							$(this).children().each(
								function(){
									_p=$.trim($(this).children().eq(0).text());
									_n=$.trim($(this).children().eq(1).text());
									//op+=_t+_p+_n;
									$(s).append(
										$(document.createElement("option"))
										.attr("value",_c+_p+_n)
										.append(_t+"-"+_p+_n)
									)
								}
							);
						});
					})
				)
				.after(
					$(document.createElement("div"))
					.attr("class","p_label_sub")
					.append(
						"Course"
					)
				)
				.after(
					$(document.createElement("div"))
					.append(
						"Syllabus"
					)
				);
				$(this).css("display","none");
			}
		}
	);
}

function activateDynamicFields(){
    var i, j, d, f, v, sel, path, options, width, height, num, fileType, folder;
    var dynamicFields = $("#profileContent div .dynamicField").get();
    for (i = 0; i < dynamicFields.length; i++) { //$(dynamicField).each(function(){})
        d = dynamicFields[i]; //d = $(this)
        f = $(d).css("font-size");//<15?$(d).css("font-size"):"10pt";
        switch($(d).metadata().type) {
            case "text":
				width=($(d).width()<15)?90:$(d).width()-1;
				if (($.trim($(d).text())=="")&&($(d).metadata().label!=undefined)) {
					v=$(d).metadata().label;
					shade= "#ccc";
				}else{
					v=$.trim($(d).text());
					shade= "#000";
				}
				$(d)
				.replaceWith(
					$(document.createElement('input'))
					.attr({
						type: "text",
						name: $(d).metadata().xpath,
						value: v
					})
					.attr( "class", $(d).attr("class") )
					.width(width)
					.css({
						color: shade
					})
					.bind("focus",{label: $(d).metadata().label},
						function(e){
							if ($.trim($(this).attr("value"))==e.data.label) {
								$(this).css("color","#000");
								$(this).attr("value","");
							}
						}
					)
					.bind("blur",{label: $(d).metadata().label},
						function(e){
							if ($.trim($(this).attr("value"))=="") {
								$(this).attr("value",e.data.label);
								$(this).css("color","#ccc");
							}
						}
					)
					.keyup(function(){
						path="person "+this.name.replace(/_/g," ");
						$(path,xmlDoc).empty();
						$(path,xmlDoc).append(xmlDoc.createTextNode(this.value));
					})
				);
                break;
            case "select":
				width=($(d).width()<100)?75:$(d).width()-1;
				//width=($(d).width()<20)?90:$(d).width()+22;
                sel=document.createElement('select');
                //alert($(d).metadata().xpath);
                //alert($(d).attr("class"));
                //alert();
                $(d)
				.replaceWith(
					$(sel)
					.attr("name",$(d).metadata().xpath)
					.attr("class",$(d).attr("class"))
					.width(width)
					.change(function(){
						path="person "+this.name.replace(/_/g," ");
						$(path,xmlDoc).empty();
						$(path,xmlDoc).append(xmlDoc.createTextNode(this.value));
					})
					.each(function(){
						options=$(d).metadata().options.split(',');
						for(j=0;j<options.length;j++) {
							$(sel).append(
								$(document.createElement("option"))
								.attr("value",options[j])
								.attr("selected",function(){
									return($(d).metadata().selected==options[j])?"selected":"";
								})
								.append(options[j])
							);
						}
					})
				);
                break;
            case "textarea":
                height=($(d).height()<50)?"50px":$(d).height();
                width=($(d).width()<100)?"100px":$(d).width()-1;
                $(d)
				.replaceWith(
					$(document.createElement('textarea'))
					.attr("name",$(d).metadata().xpath)
					.attr("class",$(d).attr("class"))
					.width(width)
					.height(height)
					.keyup(function(){
						path="person "+this.name.replace(/_/g," ");
						$(path,xmlDoc).empty();
						$(path,xmlDoc).append(xmlDoc.createTextNode(this.value));//$.trim(this.innerHTML))
					})
					.append($.trim($(d).text()))
				);
                break;
			case "file":
				num=$(d).metadata().num;
				fileType=$(d).metadata().filetype;
				width=($(d).width()<100)?"100px":$(d).width()-1;
				//if(fileType=="doc"){folder="/Documents";}else{folder="";}
                $(d)
				.replaceWith(
					$(document.createElement('input'))
					.attr("type","file")
					.attr("name",$(d).metadata().xpath)
					.attr("id","upload_"+fileType+"_"+$(d).metadata().num)
					.attr("class",$(d).attr("class"))
					.attr("value",$.trim($(d).text()))
					.width(width)
					.css("font-size", f)
					.bind("change",{id: "upload_"+fileType+"_"+$(d).metadata().num},function(e){
						if(fileType=="doc"){folder="/Documents";}else{folder="";}
						path="person "+this.name.replace(/_/g," ");
						$(path,xmlDoc).empty();
						$(path,xmlDoc).append(
							xmlDoc.createTextNode(people_base_url+currentPerson+folder+"/"+this.value.split("\\")[this.value.split("\\").length-1])
						);
						ajaxFileUpload(this.id);
					})
				)
			break;
        }
    }
}



//do when xhtml DOM loads
$(document).ready(function(){

    document.body.scroll="auto";

	//profileContainer=($.query['iframe']=='1')?"iFrameProfileContainer":"profileContainer";//el(""+profileContainer);
	profileContainer="floatProfileContainer"
	profileBody=el("profileContent");
	xslDoc=null; //current stylesheet
	xmlDoc=null; //current profile

	$('div.person')
	.css({
		cursor:"pointer"
	})
	.hover(
		function(){this.style.backgroundColor="#eee";},
		function(){this.style.backgroundColor="#fff";}
	)
	.click(function(){
		if(currentPerson){
			closeProfile();
		}
		currentPerson=this.id;
		$.ajax({
			type: "GET",
			url: people_base_url+currentPerson+"/profile.xml?x="+rand(),
			dataType: "xml",
			success: function(xml_) {
				xmlDoc=getXML(xml_);
				if(xslDoc==null){
					$.ajax({
						type: "GET",
						url: personnel_base_url+"personnelProfile.xsl?x="+rand(),
						dataType: "xml",
						success: function(xsl) {
							xslDoc=xsl;
							showProfile();
						}
					});
				}else{
					showProfile();
				}
			}
		});
	});
	if($.query['p']){
		var p=($.query['p']!='')?$.query['p']:'null';
		$("#"+p)
		.trigger("click");
	}

    $(".filter_button")
    .mouseover(function(){
        this.style.backgroundColor="#ddd";
    })
    .mouseout(function(){
        this.style.backgroundColor="#ccc";
    })

});

function ajaxFileUpload(fileID){
	$("#"+fileID)
	.ajaxStart(function(){
		$("#"+fileID)
		.replaceWith(
			$(document.createElement("span"))
			.css("color","#900")
			.append("Uploading File...")
		);
	})
	//.ajaxComplete(function(){
	//	$("#"+fileID)
	//	.replaceWith(
	//		$(document.createElement("span"))
	//		.css("color","#900")
	//		.append("Updating Profile...")
	//	);
	//})
	$.ajaxFileUpload({
		url:personnel_base_url+"handleUpload.asp?of="+fileID.split("_")[1]+"&for="+currentPerson,
		secureuri:false,
		fileElementId:fileID,
		dataType: 'text',
		success: function (txt, status){
			//if(typeof(txt) != 'undefined'){
				//if(txt != ''){
					//alert($(txt).text());
				//}else{
					//alert($(txt).text());
				//}
			//}
			$("#profileContent").html(
				xslt(xmlDoc,xslDoc)
			); //update profileContent
			setupEditMode("#p_login");
		},
		error: function (txt, e){
			alert("upload error: "+e.toString());
		}
	})
	return false;
}
