function displaySkillBlock()
{
    if ( this.wrapper.style.display == "none" ) { return null; }

    var val = this.value;
    this.skills_list.options.length = 0;
    
    var val = " "+val.toLowerCase();
	
    if ( sk[0].length == 3 )
	{
	    for ( var i = 0; i < sk.length; i++ )
		{
		    sk[i][3] = sk[i][1].toLowerCase();
		    sk[i][1] = sk[i][1].slice(1);
		}
	}
    
    if ( val != ' ' ) 
	{
	    for(var i=0; i < sk.length; i++)
		{
		    if (sk[i][3].indexOf(val) != -1)
			{
			    if ( ! current_skills[sk[i][0]] )
				{
				    this.skills_list.options[this.skills_list.options.length] = new Option ( sk[i][1], sk[i][0] ); 
				}
			}
		}	 	    
	    this.list_label.innerHTML = "";

	    if (this.core_skill().value != "") {
		    document.getElementById('textSpecificSkills').style.display = "none";
		    this.list_label2.innerHTML = this.core_skill().text;
		    document.getElementById('backToCoreSkill').style.display = "block";
	    }


	} 
    else 
	{
	    var core = this.core_skill().value;
	    for(var i=0; i < sk.length; i++)
		{	    
		    for (var j=0; j < sk[i][2].length; ++j)
			{
			    if ( ( sk[i][2][j] == core ) )
				{
				    if ( ! current_skills[sk[i][0]] )
					{
					    this.skills_list.options[this.skills_list.options.length] = new Option ( sk[i][1], sk[i][0] );
					}
				}
			}
		}
	    if (this.core_skill().value != "") {
		    this.list_label.innerHTML = "for " + this.core_skill().text;
	    } else {
		    this.list_label.innerHTML = "";
	    }

	    document.getElementById('textSpecificSkills').style.display = "block";
	    document.getElementById('backToCoreSkill').style.display = "none";

	}

}

function validSkill()
{
    if(document.getElementById('specific_skills').selectedIndex == -1)
    {
       return false;
    }
    return true;    
}

function addSkills( list )
{
    var max = 0;
    var tbody = this.output;
    if ( tbody.firstChild.nodeName == 'TBODY' )
    {
       tbody = tbody.firstChild;
    }

    var bye = tbody.firstChild;
    
    if ( bye.className == 'noResults' )
    {
       bye.style.display = 'none';
    }

    for ( var x = 0; x < tbody.childNodes.length; x++ )
    {
       var tr = tbody.childNodes[x];
       if ( tr.nodeName != 'TR' || ! tr.id ) { continue }
       var rank = tr.id;
       if ( rank.match( /\d+$/ ) )
       {
          rank = rank.match( /(\d+)$/ )[1];
          rank = rank * 1;
          if ( max < rank ) { max = rank }
       }
    }    
    max++;

    if ( list == null )
	{
	    for ( var x = 0; x < this.skills_list.options.length; x++ )
		{
		    if ( this.skills_list.options[x].selected )
			{
			    add_row( this, tbody, max, this.skills_list.options[x].value, this.skills_list.options[x].text );
			    max++;
			}	    
		}
	}
    else
	{
	    for(var i=0; i < sk.length; i++)
                {
                    if ( list[sk[i][0]] )
                        {
                            if ( ! current_skills[sk[i][0]] )
                                {
				    add_row( this, tbody, max, sk[i][0], sk[i][1] ); 
				    max++;
                                }
                        }
                }	    
	}

    this.doSkills();

    stripeTable( tbody );

    set_matching_candidates_number(document.searchForm);

}

function add_row( par, tbody, max, value, text )
{
    var row = document.createElement( 'TR' );
    if ( tbody.firstChild ) {
	tbody.insertBefore(row, tbody.firstChild);
    } else {
        tbody.appendChild( row );
    }
    row.id = par.addType+max;
    var inputs = new Array;
    inputs[0] = document.createElement( 'INPUT' );
    inputs[0].type = 'hidden';
    inputs[0].name = par.addType;
    inputs[0].value = max;

    var cell = document.createElement('TD');
    row.appendChild( cell );

    span = document.createElement( 'SPAN' );
    span.className = 'skillName';
    span.appendChild( document.createTextNode(  text  ) );
    cell.appendChild( span );
    cell.appendChild( document.createElement('BR') );

    var input =  document.createElement( 'INPUT' );
    input.type = 'hidden';
    input.name = 'skill_name_id_'+max;
    input.value = value;
    input.id =  input.name;
    inputs[inputs.length] = input;
    current_skills[ value ] = 1;

    input =  document.createElement( 'INPUT' );
    input.type = 'hidden';
    input.name = 'skill_name_'+max;
    input.value = text;
    input.id =  input.name;
    inputs[inputs.length] = input;

    span = document.createElement( 'SPAN' );
    span.className = 'skillLabel';
    span.appendChild( document.createTextNode('Min skill level') );
    cell.appendChild( span );

    span = document.createElement( 'SPAN' );
    span.className = 'skillSelect';
    var level = document.createElement( 'SELECT' );
    level.options[level.options.length] = new Option( "Beginner", "1", true, true);
    level.options[level.options.length] = new Option( "Intermediate", "2" );
    level.options[level.options.length] = new Option( "Expert", "3" );
    level.name = 'skill_level_id_'+max;
    level.id = level.name;
    span.appendChild( level );
    cell.appendChild( span );
    addEvent( level, 'change', function() { set_matching_candidates_number(document.searchForm) } );

    span = document.createElement( 'SPAN' );
    span.className = 'expLabel';
    span.appendChild( document.createTextNode('Min experience') );
    cell.appendChild( span );

    span = document.createElement( 'SPAN' );
    span.className = 'skillSelect';
    var level = document.createElement( 'SELECT' );
    level.options[level.options.length] = new Option( "Not important", "1", true, true); // was less than 1 yr
    level.options[level.options.length] = new Option( "1 year", "2" );
    level.options[level.options.length] = new Option( "2 years", "3" );
    level.options[level.options.length] = new Option( "3 years", "4" );
    level.options[level.options.length] = new Option( "4 years", "5" );
    level.options[level.options.length] = new Option( "5 years", "6" );
    level.options[level.options.length] = new Option( "6 years", "7" );
    level.options[level.options.length] = new Option( "7 years", "8" );
    level.options[level.options.length] = new Option( "8 years", "9" );
    level.options[level.options.length] = new Option( "9 years", "10" );
    level.options[level.options.length] = new Option( "10-15 years", "11" );
    level.options[level.options.length] = new Option( "16-20 years", "12" );
    level.options[level.options.length] = new Option( "21 years +", "13" );
    level.name = 'exp_level_id_'+max;
    level.id = level.name;
    span.appendChild( level );
    cell.appendChild( span );
    addEvent( level, 'change', function() { set_matching_candidates_number(document.searchForm) } );

    cell.appendChild( document.createElement('BR') );

    span = document.createElement( 'SPAN' );
    span.className = 'skillLabel';
    span.appendChild( document.createTextNode('Importance') );
    cell.appendChild( span );

    span = document.createElement( 'SPAN' );
    span.className = 'skillSelect';
    var level = document.createElement( 'SELECT' );
    level.options[level.options.length] = new Option( "Required", "1", true, true);
    level.options[level.options.length] = new Option( "Highly desirable", "2" );
    level.options[level.options.length] = new Option( "Preferable", "3" );
    level.options[level.options.length] = new Option( "Advantageous", "4" );
    level.name = 'importance_level_'+max;
    level.id = level.name;
    span.appendChild( level );
    cell.appendChild( span );

    addEvent( level, 'change', function() { set_matching_candidates_number(document.searchForm) } );
    
    var anc = document.createElement( 'A' );
    anc.className = 'remDetails';
    anc.href = '';
    anc.appendChild( document.createTextNode('remove') );
    anc.removeRow = removeRow;
    addEvent( anc, 'click', anc.removeRow );
    
    cell.appendChild( anc );

    for ( var i = 0; i < inputs.length; i++ )
    {
        cell.appendChild( inputs[i] );
    }

}

function removeRow(e)
{
    var row   = this.parentNode.parentNode;
    var tbody = row.parentNode;
    var table = tbody.parentNode;

    if ( tbody.nodeName == 'TABLE' ) 
	{
	    table = tbody;
	}

    if ( row.id.match( /^skills(\d+)/ ) )
    {
       var rowId = row.id.match( /^skills(\d+)/ )[1];
       var skillId = document.getElementById( 'skill_name_id_'+rowId ).value;
       current_skills[skillId] = 0;
       table.searcher.doSkills();
    }

    tbody.removeChild( row );

    if ( tbody.childNodes.length == 1 && S1.hasClass( tbody.firstChild,  'noResults' )  )
    {
       tbody.firstChild.style.display = '';
    }

    stripeTable( tbody );

    set_matching_candidates_number(document.searchForm);
    
    if (!e) var e = window.event;
    if ( !e ) { return }
    if ( e.preventDefault ) { e.preventDefault() }
    else { e.returnValue = false }  
    return false;
}

function stripeTable( tbody )
{
   for ( var x = 0 ; x < tbody.childNodes.length; x++ )
   {
      if ( ! S1.hasClass( tbody.childNodes[x], 'noResults' ) )
      {
          if ( x % 2 ) { S1.swapClass( tbody.childNodes[x], 'even', 'odd' ) }
	  else { S1.swapClass( tbody.childNodes[x], 'odd', 'even' ) }
      }
   }
}



function searchSetup()
{

    // set up specific skill related components
    var skills            = document.getElementById('search_text');
    skills.skills_list     = document.getElementById('specific_skills');
    skills.specific_skill = function() { return this.skills_list.options[this.skills_list.selectedIndex] };
    skills.text_search    = document.getElementById('search_submit');
    skills.add_skill      = document.getElementById('skillsAdd');
    skills.output         = document.getElementById('skillsTable');
    skills.core_skill     = function() { return document.searchForm.core_skill.options[document.searchForm.core_skill.selectedIndex]; }
    skills.min_exp        = function() { return document.searchForm.min_experience.options[document.searchForm.min_experience.selectedIndex]; }
    skills.skill_level    = function() { return document.searchForm.min_skill_level.options[document.searchForm.min_skill_level.selectedIndex]; }
    skills.output         = document.getElementById('skillsTable'); 
    skills.output.searcher = skills;
    skills.wrapper         =  document.getElementById('skillsBox');
    skills.list_label = document.getElementById('forCoreSkill');
    skills.list_label2 = document.getElementById('forCoreSkill2');
   
    skills.addType  = 'skills';

    // these are method calls
    skills.doSkills = displaySkillBlock;
    skills.add      = addSkills;
    skills.check    = validSkill;

    addEvent(skills, 'keyup', function () { skills.doSkills() } );
    addEvent(skills, 'focus', function () { skills.doSkills() } );
    addEvent(skills.add_skill, 'click', function () { if ( skills.check() ) { skills.add() } } );
    addEvent(document.getElementById('core_skill'), 'change', function() { skills.doSkills() });

    skills.current_skills = new Object;

    read_page_cookie();
    
    if ( document.getElementById( 'seid' ) )
	{
	    addEvent( document.getElementById('searchForm'), 'submit', storeCheck );
	}
    addEvent( document.getElementById('searchForm'), 'submit', set_page_cookie );

    var a_list = document.getElementsByTagName('A');
    for ( var i = 0; i < a_list.length; i++ )
	{
	    if ( S1.hasClass( a_list[i], 'remDetails' ) )
		{
		    a_list[i].removeRow = removeRow;
		    addEvent( a_list[i], 'click', a_list[i].removeRow );
		}
	}
}	

function storeCheck()
{
    if ( document.getElementById( 'seid' ) )
	{
	    var inputs = input_store_string(true);
	    inputs = inputs.concat(select_store_string(true));
	    inputs = inputs.concat(skills_store_string(true));
	    var storeTest = inputs.join('&');
	    
	    if ( storeTest != storeValue ) 
		{
		    var update = confirm( 'You have changed this search do you wish to update it?\nSelect cancel to do the search without updating it.' );
		    if ( update )
			{
			    // do some funky stuff...
			    storeTest += '&ss=1';
			    var qs = [ 's=' + escape( storeTest ), 'seid='+document.getElementById('seid').value, 'submit=1' ].join('&');
			    var url = '/cvdb/store-search.cgi?'+qs;
			    S1.runRequestText( url, function(){return true} );
			}
		    else
			{
			    // Remove the hidden seid input.
			    document.getElementById('seid').parentNode.removeChild(document.getElementById('seid'));
			}
		}
	}
}

function resetForm() {
  var sf = document.getElementById('searchForm');

  stopCheck = true;

  if ( confirm("Clear all search options?") ) {
    // Clear any skills
    var list = document.getElementsByTagName( 'A' );
    var l = [];
    for ( var i = 0; i < list.length; i++ )
    {
       if ( S1.hasClass( list[i], 'remDetails' ) )
       {
          l[l.length] = list[i];
       }
    }
    for ( var i = 0; i < l.length; i++ )
    {
       l[i].removeRow();
    }
    
    var to_clear = [ 'cvmatch_selects','cvmatch_skills','cvmatch_checks','cvmatch_texts','cvmatch_tab' ];

    for ( var i = 0; i < to_clear.length; i++ )
    {
       delete_cookie( to_clear[i] );
    }

    var to_ignore = { 'termscheck':1 };
    
    list = document.getElementsByTagName( 'SELECT' );

    for ( var i = 0; i < list.length; i++ )
	{
	    if ( list[i].name && to_ignore[list[i].name] == null ) { list[i].selectedIndex = 0 }
	}

    list = document.getElementsByTagName( 'INPUT' );
    for ( var i = 0; i < list.length; i++ )
        {
            if ( list[i].name && to_ignore[list[i].name] == null ) 
		{ 
		    if ( list[i].type == 'checkbox' || list[i].type == 'radio' )
			{
			    list[i].checked = false;
			}
		    else if ( list[i].type == 'text' )
			{
			    list[i].value = '';
			}
		}
        }

    document.getElementById('search_text').doSkills();

    if ( document.getElementById('seid') )
	{
	    document.getElementById('SSname').innerHTML = '';
	    document.getElementById('seid').parentNode.removeChild(document.getElementById('seid'));
	}
    stopCheck = false;
    set_matching_candidates_number(sf);
  }
}

function select_store_string(for_query)
{
    // Get all the select box indexs
    list = document.getElementsByTagName( 'SELECT' );
    result = [];
    for ( var i = 0; i < list.length; i++ )
	{
	    if ( list[i].name && list[i].name != 'specific_skills' ) { 
		if ( for_query ) { result[i] = list[i].name + '=' + list[i].options[list[i].selectedIndex].value }
		else { result[i] = list[i].name + ':' + list[i].selectedIndex }
	    }
	}
    
    if ( for_query )
	{
	    return result;
	}
    else
	{
	    return result.join(',');
	}   
}

function input_store_string(for_query)
{

    // Inputs. Split into checkboxes and others
    var list = document.getElementsByTagName( 'INPUT' );
    var checks = {};
    var text = [];
    for ( var i = 0; i < list.length; i++ )
        {
            if ( list[i].name ) 
		{ 
		    if ( list[i].type == 'checkbox' || list[i].type == 'radio' )
			{
			    if ( for_query )
				{
				    if ( list[i].type == 'checkbox' )
					{
					    var val = list[i].checked == true?list[i].value:'';
					    text[text.length] = list[i].name + '=' + val;
					}
				    else
					{
					    if  ( list[i].checked == true ) { text[text.length] = list[i].name + '=' + list[i].value; }
					}
				}
			    else
				{
				    if ( ! checks[list[i].name] ) { checks[list[i].name] = [] }
				    if ( list[i].checked == true ) { checks[list[i].name][checks[list[i].name].length] = list[i].value }
				}
			}
		    else if ( list[i].type == 'text' && list[i].name != 'search_text' )
			{
			    if ( for_query ) { text[text.length] = list[i].name + '=' + list[i].value;}
			    else { text[text.length] = list[i].name + ':' + list[i].value; }
			}
		}
        }

    var ret = '';

    if ( for_query )
	{
	    ret = text;
	}
    else 
	{
	    var result = [];
	    for ( var i in checks )
		{
		    result[result.length]=i+':'+checks[i].join('xox');
		}
	    
	    ret = [ result.join('oxo'), text.join('xox') ];
	}

    return ret;
}

function skills_store_string(for_query)
{
    // Skills ( required values already stored in selects)
    var list = document.getElementsByTagName( 'INPUT' );
    var result = [];
    for ( var i = 0; i < list.length; i++ )
	{
	    if ( list[i].name == 'skills' )
		{
		    var number = list[i].value;
		    var skill = document.getElementById('skill_name_id_'+number).value;
		    var name = document.getElementById('skill_name_'+number).value;
		    if ( for_query ) 
			{ 
			    result[result.length] = 'skill_name_id_'+number+'='+skill; 
			    result[result.length] = 'skill_name_'+number+'='+name; 
			    result[result.length] = 'skills='+number; 
			}
		    else { result[result.length] = skill; }
		}
	}

    if ( for_query ) { return result; }
    else { return result.join(':'); }
}

function set_page_cookie()
{
    document.cookie = 'cvmatch_selects='+escape(select_store_string(false));

    var inputs = input_store_string(false);

    document.cookie = 'cvmatch_checks='+escape(inputs[0]);
    document.cookie = 'cvmatch_texts='+escape(inputs[1]);


    document.cookie = 'cvmatch_skills='+escape(skills_store_string(false));
    //document.cookie = 'cvmatch_tab='+current_tab;
    
}


function read_page_cookie()
{
    stopCheck = true;
    // Skills stuff here.
    var ck = get_cookie_value('cvmatch_skills');
    if ( ck != '' )
	{
	    var skillsController  = document.getElementById('search_text');	    

	    var skills = unescape(ck).split(':');
	    var list = {};
	    for ( var i = 0; i < skills.length; i++ )
		{
		    list[skills[i]] = 1;
		}
	    skillsController.add(list);
	
	}

    ck = get_cookie_value('cvmatch_checks');
    if ( ck != '' )
	{
	    var checks = unescape(ck).split('oxo');
	    for ( var i = 0; i < checks.length; i++ )
		{
		    var options = checks[i].split(':');
		    var list = document.getElementsByName(options[0]);
		    if ( list.length > 0 )
			{
			    var checked_on = options[1].split('xox');
			    var hash = {};
			    
			    for ( var j = 0; j < checked_on.length; j++ ) { hash[checked_on[j]] = 1 }		    
			    
			    for ( var j = 0; j < list.length; j++ )
				{
				    list[j].checked = (hash[list[j].value] != null?true:false);
				}
			}
		}
	}

//    checkQuals();

    ck = get_cookie_value('cvmatch_selects');
    if ( ck != '' )
	{
	    var selects = unescape(ck).split(',');
	    for ( var i = 0; i < selects.length; i++ )
		{
		    var vals = selects[i].split(':');

		    if ( document.getElementsByName(vals[0])[0] && 
			 document.getElementsByName(vals[0])[0].nodeName == 'SELECT' )
			{
			    document.getElementsByName(vals[0])[0].selectedIndex = vals[1];
			}
		}
	}

    document.getElementById('search_text').doSkills();


    ck = get_cookie_value('cvmatch_texts');
    if ( ck != '' )
	{
	    var texts = unescape(ck).split('xox');
	    for ( var i = 0; i < texts.length; i++ )
		{
		    var vals = texts[i].split(':');
		    if ( document.getElementsByName(vals[0]).length > 0 )
			{

			    document.getElementsByName(vals[0])[0].value = vals[1];

			}
		}
	}

    /*    ck = get_cookie_value('cvmatch_tab');
	  if ( ck != '' )
	  {
	  showSection(ck);
	  }*/

    stopCheck = false;
    set_matching_candidates_number(document.searchForm);    

    if ( document.getElementById('seid') )
	{
	    var inputs = input_store_string(true);
	    inputs = inputs.concat(select_store_string(true));
	    inputs = inputs.concat(skills_store_string(true));
	    storeValue = inputs.join('&');
	}
}

function delete_cookie( name )
{
    var d = new Date(0);
    document.cookie = name+'=;expires='+d.toGMTString();
}

function get_cookie_value( name )
{
    var result = '';
    var start = document.cookie.indexOf( name+'=' );
    if ( start != -1 )
	{
	    start = start + name.length +1;
	    var end = document.cookie.indexOf( ';', start ) == -1?document.cookie.length:document.cookie.indexOf( ';', start );
	    result = document.cookie.substring(start,end);
	}
    return result;
}


addLoader(searchSetup);
