// -------------------------------------------------------------------
// Madgex Limited
// Copyright (c) 2007 Madgex Limited. All Rights Reserved.
// MultiSelect chaining & upgrading
// James Wragg
// 3rd August 2007
// -------------------------------------------------------------------
// requires = common.js


	function dynSelect( JobMatrix ){

		this.Name = "dynSelect";
		this.Version = 0.1;
		this.JobMatrix = JobMatrix;
		this.config = {
			"ParentID"				: "liJobSectorID", // id of parent select list (sectors)
			"ParentLabel"			: "Sector", // Label used on the child select
			"ChildID"				: "liJobFunctionID", // id of the child select list (job functions)
			"ChildTarget"			: "jobFunction", // id of the target div for the child select to appear
			"ChildLabel"			: "Job Function", // Label used on the child select
			"SectorsULID"			: "SectorsUL", // if of the Unordered List that is upgraded to Parent select list
			"CombinedHierarchicalID": "liJobSectorHLID", // id of the long hierarcical select list of all sectors/jobs 
			"PassedParentValuesID"	: "dynSelect-SetParentSelected", // id of the hidden value that specifies pre-selected Sectors
			"PassedChildValuesID"	: "dynSelect-SetChildSelected", // id of the hidden value that specifies pre-selected Jobs
			"ActiveFormClass"		: "dynSelect-Active", // Class 
			"debug"					: false
		};
		
		// Figure out what browser is being used
		var b = navigator.userAgent.toLowerCase();
		this.browser = {
			version: (b.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
			safari: /webkit/.test(b),
			opera: /opera/.test(b),
			msie: /msie/.test(b) && !/opera/.test(b),
			mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
		};

		// Returns an array of the selected values from select#id
		this.GetSelected = function( elemid ){
			var results = new Array();

			if ((select = document.getElementById(elemid)) && (select.nodeName.toLowerCase() == "select")){
				for ( var x = 0; x < select.options.length; x++ ){
					if ( select.options[x].selected ){
						results.push(select.options[x].value);
					}
				}		
				return results;
			}else{
				return false;
			}
		}
		
		// Sets the selected values to select#id
		this.SetSelected = function( elemid, idColl ){
			if (typeof(idColl) == "string") idColl = idColl.trim().split(",");

			if ((elem = document.getElementById(elemid)) && (elem.nodeName.toLowerCase() == "select")){
				
				// reset all parent selections
				for ( var x = 0; x < elem.options.length; x++ ){
					elem.options[x].selected = false;
				}

				// set options
				for ( var x = 0; x < elem.options.length; x++ ){
					for ( var y = 0; y < idColl.length; y++ ){
						if ( elem.options[x].value == idColl[y] ){
							elem.options[x].selected = true;
						}
					}
				}
				return true;
			}else{
				return false;
			}
		}
		
		this.PopulateSelect = function( elemId, options ){
			
			if ( elem = document.getElementById(elemId) ){
			
				// reset select
				elem.options.length = 0;
				
				for (var x = 0; x < options.length; x++){

					var opt = document.createElement('OPTION');
					opt.value = options[x].ID;
					opt.text = options[x].Title;
					
					if (this.browser.safari){
						elem.add(opt, x);
					}else{
						elem.options.add(opt, x);
					}

				}			
				
			}
		}

		this.GetULSelected = function( elemId ){
			if (!elemId)
				var elemId = this.config.SectorsULID;

			if (upgradeSectors = document.getElementById(elemId)){
				// get the ul contents 
				var SelectedSectors = new Array();
				
				for ( var x = 0; x < upgradeSectors.childNodes.length; x++){
					if (upgradeSectors.childNodes[x].nodeName.toLowerCase() == "li"){
						SelectedSectors.push(upgradeSectors.childNodes[x].id);
					}
				}
			
				return SelectedSectors;
			} else {
				return false;
			}
			

		}
		
		
		this.GetHierSelected = function( elem ){
			if (!elem)
				var elem = this.config.CombinedHierarchicalID;
				
			var results = new Object();
			results.Parents = [];
			results.JobFuncs = [];
			
			if ( target = document.getElementById(elem) ){
				
				for ( var x = 0; x < target.options.length; x++){
					if ( target.options[x].selected ){
						var value = target.options[x].value.split(".");
						
						if ( value.length == 2 ){
							if (results.Parents.indexOf(value[0]) == "-1")
								results.Parents.push(value[0]);
							
							if (results.JobFuncs.indexOf(value[1]) == "-1")
								results.JobFuncs.push(value[1]);
						}
					
					}				
				}
			
				return results;
			} else {
				return false;
			}
		}

		
		this.ParentChange = function(ev){
			
			if(!(t=ev.target||ev.srcElement)){
				var t = ev;
			}
			var obj = t.DynReference;
			
			// get current selection
			var SelectedIndustries = obj.GetSelected(obj.config.ParentID);
			var SelectedJobs = obj.GetSelected(obj.config.ChildID);
			var Jobs = obj.JobMatrix.GetSectorJobs(SelectedIndustries);

			// populate the child multiselect
			obj.PopulateSelect(obj.config.ChildID, Jobs);
			obj.SetSelected(obj.config.ChildID, SelectedJobs);
		}
		
		
		this.CreateChildSelect = function(needFieldSet){
					
			if (target = document.getElementById(this.config.ChildTarget)){
							
				target.innerHTML = this.CreateSelectDOMChunk(this.config.ChildLabel, this.config.ChildID, needFieldSet);								
				this.PopulateSelect(this.config.ChildID, this.JobMatrix.GetSectorJobs(this.GetSelected(this.config.ParentID)));
											
				return true;

			}else{		
				return false;
				
			}
		}	

		
		this.UpgradeHierSelect = function(){
			// targetDiv is the ID of the div that will contain the selector
			var targetID = this.config.CombinedHierarchicalID;

			if (target = document.getElementById(targetID)){
			
				var opts = this.GetHierSelected();
				target.style.display = 'none';
					
				var id = this.config.ParentID;
				/*
				var s;

				s = "  <select class='dropDown' name='" + id + "' id='" + id + "' size='6' multiple='multiple'>\n";
				s += "  </select>\n";
				*/
				
				// target.parentNode.innerHTML = s;
				target.parentNode.parentNode.innerHTML = this.CreateSelectDOMChunk(this.config.ParentLabel, id);
				this.PopulateSelect(this.config.ParentID, this.JobMatrix.IndustrySectors);
				this.SetSelected(this.config.ParentID, opts.Parents);
				
				this.CreateChildSelect();
				this.SetSelected(this.config.ChildID, opts.JobFuncs);
				
				return true;

			}else{		
				return false;
				
			}
		}	
		
		
		this.CreateSelectDOMChunk = function(label, id, needFieldSet){
			var s = "";
			
			if(!needFieldSet && typeof(needFieldSet) == "undefined" )
			    //s += "<fieldset class=\"multiselect\">\n";			
			    
			s += "<p>\n";			
			s += "  <label for='" + id + "'>" + label;
			if ( document.getElementsByTagName("body")[0].id == "applyPage" || (document.getElementsByTagName("body")[0].id == "MyProfile" && this.config.ParentID == "Current_Sector"))
			{
			    s +=  "<span class=\"mandatory\">*</span>";
			}
			s += "</label>\n";
			s += "  <select class='dropDown' name='" + id + "' id='" + id + "' size='6' multiple='multiple'>\n";
			s += "  </select>\n";
			s += "</p>\n";

			if(!needFieldSet && typeof(needFieldSet) == "undefined" )
			    //s += "</fieldset>\n";
			
			return s;
		}
		
		
		this.UpgradeSectorUL = function(){
			
			if (target = document.getElementById(this.config.SectorsULID)){
			
				// get the ul options
				var opts = this.GetULSelected();

				target.parentNode.innerHTML = this.CreateSelectDOMChunk(this.config.ParentLabel, this.config.ParentID, true);		
				
				this.PopulateSelect(this.config.ParentID, this.JobMatrix.IndustrySectors);
				this.SetSelected(this.config.ParentID, opts);
				this.PopulateSelect(this.config.ChildID, this.JobMatrix.GetSectorJobs(this.GetSelected(this.config.ParentID)));


				return true;

			}else{		
				return false;
				
			}

		}

		
		this.Activate = function(){
			var parent = document.getElementById(this.config.ParentID);
			var child  = document.getElementById(this.config.ChildID);
	        parent.DynReference = this;
			
			// if passed values set them
			// parent
			if( opts = document.getElementById(this.config.PassedParentValuesID) ){
				if (opts.value != ""){
				    this.SetSelected(parent.id, opts.value);
				    this.ParentChange(parent);
			    }
			}

			// child
			if( opts = document.getElementById(this.config.PassedChildValuesID) ){
				if (opts.value != ""){
    				this.SetSelected(child.id, opts.value);
			    }
			}
			
			// add the ActiveFormClass to the form to allow for CSS changes
			var formNode = parent;
			while (formNode.nodeName.toLowerCase() != "body" && formNode.nodeName.toLowerCase() != "form"){
				formNode = formNode.parentNode;
			}
			CSSClass.add(formNode, this.config.ActiveFormClass);
				
			// add listener event on the parent select to watch for a change
			YAHOO.util.Event.addListener(parent, 'change', this.ParentChange);
		}
		
	}



// data object for the parent child relationship
	var JobMatrix = {
		IndustrySectors: [],
		JobFunctions: [],

		LoadSector: function( title, id ){
			if (title && id){
				var IndSector = {};
				IndSector.Title = title;
				IndSector.ID = id;
				
				this.IndustrySectors.push(IndSector);
			}
		},

		LoadJobFunc: function( title, id, parents ){
			if (title && id && parents){
				var Job = {};
				Job.Title = title;
				Job.ID = id;
				Job.Parents = parents;
				
				this.JobFunctions.push(Job);
			}
		},
		
		GetSectorJobs: function( SectColl ){

			
			// if passed values from the hidden input
			if (typeof(SectColl) == "string"){
				SectColl = SectColl.trim().split(",");
			}
			
			// horrible nested looping to find the Job Functions for the chosen sectors	
			var results = [];

			for (var x = 0; x < this.JobFunctions.length; x++){ // step through each job function
				for ( var y = 0; y < this.JobFunctions[x].Parents.length; y++ ){ // step through each job functions parents
					for ( var z = 0; z < SectColl.length; z++ ){ // step through the selected industries
						
						if ( SectColl[z] == this.JobFunctions[x].Parents[y] ){ // found a job function with the selected ind as a parent
							if ( results.indexOf(this.JobFunctions[x]) == "-1" ) // check if the results array already has it
								results.push(this.JobFunctions[x]); // add it to the results.
						}
						
					}
				}
			}
			
			return results;

		}
	};






	function InitDynSearch(){

		 
		if ( document.getElementsByTagName("body")[0].id == "MyProfile" ){
            // My Profile page
    		// for the My Profile page there is a second hierarcical list that needs upgrading.
		
        		var s1 = new dynSelect( JobMatrix );
		        s1.config.ParentID = "Current_Sector";
		        s1.config.ParentLabel = "Current Job Sector";
		        s1.config.ChildID = "Current_Job_Function";
		        s1.config.ChildTarget = "jobFunction";
		        s1.config.ChildLabel = "Current Job Function";
		        s1.config.CombinedHierarchicalID = "liJobSectorHLID";
		        s1.config.PassedParentValuesID = "dynSelect-SetParentSelected";
		        s1.config.PassedChildValuesID = "dynSelect-SetChildSelected";
		        
		        if(s1.UpgradeHierSelect())
		        {
		            s1.Activate();			
		        }


		        var s2 = new dynSelect( JobMatrix );		
		        s2.config.ParentID = "Preferred_Sector";
		        s2.config.ParentLabel = "Preferred Job Sector";
		        s2.config.ChildID = "Preferred_job_Function";
		        s2.config.ChildTarget = "Pref-jobFunction";
		        s2.config.ChildLabel = "Preferred Job Function";
		        s2.config.CombinedHierarchicalID = "Pref-liJobSectorHLID";
		        s2.config.PassedParentValuesID = "Pref-dynSelect-SetParentSelected";
		        s2.config.PassedChildValuesID = "Pref-dynSelect-SetChildSelected";

		        if(s2.UpgradeHierSelect())
		        {
		            s2.Activate();
		        }

        }else if ( document.getElementsByTagName("body")[0].id == "applyPage" ){
	
        		var s1 = new dynSelect( JobMatrix );
		        s1.config.ParentID = "Current_Sector";
		        s1.config.ParentLabel = "Current Job Sector";
		        s1.config.ChildID = "Current_Job_Function";
		        s1.config.ChildTarget = "jobFunction";
		        s1.config.ChildLabel = "Current Job Function";
		        s1.config.CombinedHierarchicalID = "liJobSectorHLID";
		        s1.config.PassedParentValuesID = "dynSelect-SetParentSelected";
		        s1.config.PassedChildValuesID = "dynSelect-SetChildSelected";
		        
		        if(s1.UpgradeHierSelect())
		        {
		            s1.Activate();					
		        }
        }  
        else if ( document.getElementsByTagName("body")[0].id == "JobAlert" ){
            // Email Alerts - simgle hierarcical list
    		var s1 = new dynSelect( JobMatrix );
	        s1.UpgradeHierSelect();
	        s1.Activate();			

        } else if ( document.getElementsByTagName("body")[0].id == "JobSearch" ){
            // Advanced Search - Should be one big hier list to upgrade
    		var s1 = new dynSelect( JobMatrix );
	        s1.UpgradeHierSelect();
	        s1.Activate();			
            
        } else if ( document.getElementsByTagName("body")[0].id == "RefineSearch" ){
	
        		var s1 = new dynSelect( JobMatrix );
		        s1.config.ParentID = "liJobSectorID";
		        s1.config.ParentLabel = "Sector";
		        s1.config.ChildID = "liJobFunctionID";
		        s1.config.ChildTarget = "jobFunction";
		        s1.config.ChildLabel = "Job Function";
		        s1.config.CombinedHierarchicalID = "liJobSectorHLID";
		        s1.config.PassedParentValuesID = "dynSelect-SetParentSelected";
		        s1.config.PassedChildValuesID = "dynSelect-SetChildSelected";
		        
		        s1.UpgradeHierSelect();
		        s1.Activate();	
		        				            
         }else if ( document.getElementsByTagName("body")[0].id == "home" ){
	
        		var s1 = new dynSelect( JobMatrix );
		        s1.config.ParentID = "liJobSectorID";
		        s1.config.ParentLabel = "Sector";
		        s1.config.ChildID = "liJobFunctionID";
		        s1.config.ChildTarget = "jobFunction";
		        s1.config.ChildLabel = "Job Function";
		        s1.config.CombinedHierarchicalID = "liJobSectorHLID";
		        s1.config.PassedParentValuesID = "dynSelect-SetParentSelected";
		        s1.config.PassedChildValuesID = "dynSelect-SetChildSelected";
		        
		        s1.UpgradeHierSelect();
		        s1.Activate();					
        } 
        
        
         /*else if ( document.getElementsByTagName("body")[0].id == "RefineSearch" ){
            // Refine Search - Should be one big hier list to upgrade
    		var s1 = new dynSelect( JobMatrix );
            if ( countRealNodes(document.getElementById(s1.config.SectorsULID)) > 1 ){
    	        s1.CreateChildSelect(false);
    	        s1.UpgradeSectorUL();
	            s1.Activate();
	       }        
         else if ( document.getElementsByTagName("body")[0].id == "home" ){
            // Home page - add in job functions
    		var s1 = new dynSelect( JobMatrix );
		    s1.CreateChildSelect();
		    s1.Activate();			
            
        }*/

		
	};


// fire the event off when the DOM is ready
	YAHOO.util.Event.onDOMReady(InitDynSearch);
	
