/* Popular phrases - PRESTWICKHOUSE - 20:36:42, Fri Jan 27, 2012 */
var asPhrases=new Array ('levels of understanding','frankenstein','to kill a mockingbird','the great gatsby','romeo and juliet','hamlet','macbeth','animal farm','the odyssey','latin and greek roots','hunger games','answers vocabulary power plus','night','vocabulary power plus','of mice and men','articles','things fall apart','speak','great expectations','othello','into the wild','1984','short stories','monster','the crucible','the color purple','lord of the flies','pride and prejudice','side by side','the giver','julius caesar','the pearl','heart of darkness','wuthering heights','a raisin in the sun','rhetorical devices','brave new world','blooms taxonomy literature guide','to kill a mockingbird downloadable','vocabulary for the college bound','the outsiders','house on mango street','antigone','grammar','fahrenheit 451','canterbury tales','beowulf','a separate peace','poisonwood bible','twelfth night','their eyes were watching god','oedipus','in cold blood','tale of two cities','kite runner','treasure island','adventures of huckleberry finn','dr jekyll and mr hyde','anthem','metamorphosis','siddhartha','growing your vocabulary learning from latin and greek roots','downloadable teaching units','jane eyre','poetry','maus','downloadable ap teaching units','ethan frome','and then there were none','life of pi','inherit the wind','frankenstein test','multiple critical perspectives','the color of water','tears of a tiger','the scarlet letter','night by elie wiesel','huckleberry finn','the alchemist','the jungle','the count of monte cristo','crime and punishment','hatchet','book 4 answer key','taming of the shrew','vocabulary from latin and greek roots','all quiet on the western front','narrative of the life of frederick douglass','invisible man','a midsummer night\'s dream','a lesson before dying','the things they carried','romeo and juliet downloadable','gulliver\'s travels','growing your vocabulary','the hobbit','death of a salesman','catcher in the rye','posters','ap','black boy','to kill a mockingbird teaching unit','hound of the baskervilles','call of the wild','dracula','slaughterhouse five','dawn','out of the dust','vocabulary power plus for the new sat','twelve angry men','our town','grapes of wrath','rhetoric','oedipus rex','sherlock holmes','the bluest eye','vocabulary from latin and greek','alice \'s adventures','hamlet ap','vocabulary power plus answer keys','the importance of being earnest','much ado about nothing','that was then this is now','non-fiction','pre-ap','the awakening','the stranger','powerpoint for the classroom','the great gatsby downloadable','nonfiction','white fang','medea','king lear','farewell to manzanar','answer key vocabulary','vocabulary power plus for the new act','streetcar named desire','grammardog','vocabulary for the college bound answer key','watsons go to birmingham','touching spirit bear','rosencrantz and guildenstern are dead','huck finn','house of the scorpion','graphic novels','midsummer nights dream','tuck everlasting','of mice and men ap','the handmaid\'s tale','transcendentalism','sat','jubilee','my brother sam is dead','daisy miller','pre-ap readings and exercises','the tempest','sat prep','the awakening test','all quiet on the western front ap','latin and greek roots book iv','rhetoric logic argumentation','a prayer for owen meany','levels of understanding macbeth','native son','the bean trees','fahrenheit 451 downloadable','practice makes perfect','the kite runner teaching unit','poe','12 angry men','the lion the witch and the wardrobe','ap language','dorian gray','pygmalion','old man and the sea','freak the mighty','prefixes','1984 study guide','vocabulary power plus for the act','reading and analyzing non-fiction slant spin and bias','little women','turn of the screw','lord of the flies downloadable','book 2 answer key','a christmas carol','frederick douglass novel test','to kill a mockingbird activity pack','i know why the caged bird sings','grammar for writing','harry potter and the sorcerer\'s stone','great expectations ap teaching unit','adventures of tom sawyer','teacher\'s pet','mystery','catcher in the rye teaching units','among the hidden','a doll\'s house','dubliners','fallen angels','gatsby','mythology','joy luck club','the adventures of huck finn','the giver teaching unit','merchant of venice','inferno','a farewell to arms','edith hamilton mythology','introduction to literary theory','picture of dorian gray','the hiding place','reading and analyzing non-fiction','the pigman','frankenstein ap teaching unit','a midsummer\'s night dream','curious incident','the grapes of wrath test','tom sawyer','grammar dog','holes','beloved','romeo and juliet graphic novel','hamlet test','killer angels','the book thief','across five aprils','a raisin in the sun activity pack','ap to kill a mockingbird','ap the things they carried','cry the beloved','alice','levels of understanding the catcher in the rye','all quiet','a thousand splendid suns','number the stars','bridge to terabithia','darkness before dawn','tom sawyer teaching unit','ap language and composition','pre ap','african american literature','grammardog guide downloadable pdf','ralph ellison','the glass menagerie','diary of anne frank','dr faustus','levels of understanding romeo and juliet','prince and the pauper','anne frank','around the world in eighty days','devils arithmetic','great gatsby test','technology','all my sons','night activity pack','tuesdays with morrie','frederick douglass','macbeth downloadable','cry the beloved country','jane eyre paperback','i am the cheese','witch of blackbird pond','rhetorical devices a handbook and activities for student writers','narrative of the life','grendel','anthology','steps to good grammar','connecticut yankee','techniques of propaganda','6 traits','flowers for algernon','3 simple truths','class sets','the mayor of casterbridge','hound of the baskervilles response journal','roll of thunder','dictionaries','red pony','dante\'s inferno','non fiction','jekyll and hyde','there are no children here','my side of the mountain','fever 1793','roll of thunder hear my cry','hiroshima','emma','fahrenheit 451 teaching unit','huckleberry finn elesson','mastery','reading assessments','the help','ap frankenstein','silas marner','midsummer','legend of sleepy hollow','the time machine','african american','lord of the flies response journals','main street','speak laurie halse anderson','scarlet letter dvd','frankenstein paperback','the secret life of bees paperback','answer key','enders game','logic','adventure','journalism','sounder','o pioneers','macbeth response journal','a doll house','angelas ashes','vocabulary power plus act','teacher\'s edition power plus','ap huckleberry finn','brave new world teaching unit','practice makes perfect level 11','romeo and juliet teaching unit','the catcher in the rye paperback','julius caesar teaching unit','iliad','tupac shakur','latin and greek presentation','wuthering heights paperback','common sense','ap english language','roll of thunder downloadables','5 steps','northanger abbey','wuthering','greek literature','complete teacher\'s kit','over sea under stone','digital daily warmups','leaves of grass','benjamin franklin','vocabulary for the college bound c','power plus act','gifted hands','roots','fences','writing','the giver downloadable','rime of the ancient mariner','readings and exercises','use bloom s taxonomy to help students independently evaluate literature','classic american short stories','ap from a to z','sir gawain and the green knight','a tale of two cities ap','the crucible ap teaching unit','fahrenheit','chaucer','poisonwood','killing mr griffin','the republic','the learning tree','speech','peter pan','when i was puerto rican','classic ghost stories','pilgrims progress','things fall apart activity','i robot','great expectations vocabulary','east of the sun','old man and the sea ap teaching unit','the boy in the striped pajamas','walk two moons','creative writing','go ask alice','philosophy','reading and writing','don quixote','the lottery','my antonia','the devil\'s arithmetic','johnny tremain','the outsiders activity pack','the three musketeers','litplan teacher pack raisin in the sun','daily writing fundamentals','crucible ap','rhetorical devices powerpoint','slam','the crucible activity pack','catch-22','reading smarter','american born chinese','harlem renaissance','dandelion wine','coriolanus','frankenstein elesson','levels of understanding reproducible','writing descriptive paragraphs','elements of style posters','the five people you meet in heaven','study guides','mary shelley\'s frankenstein','war of the worlds','ap macbeth','writing an a research paper','julius caesar side by side','selected federalist papers','the good earth','the hound of baskerville teaching unit','romeo and juliet audio','romeo and juliet side by side','one day in the life of ivan denisovich','middle school','frankenstein mary shelley','simile','pearl downloadable','outsiders response journal','ordinary people','pygmalion ap teaching unit','camus','great american poems','book 3 answer key','the sorcerer\'s stone','to kill a mockingbird multiple','the contender','touchstone classics','reading and analyzing non fiction','macbeth side by side','light in the forest','things fall apart ap teaching unit','kafka','the chocolate war','les miserables','ap oedipus rex','close reading','sherman alexie','their eyes were','blooms','literature','oliver twist','secret life of bees','all the pretty horses','improving sentences','satire','one flew over the cuckoos nest','waiting for godot','madame bovary','lord of the flies audio','propaganda and persuasion','slant spin and bias','analysis argument synthesis','vocabulary power plus presentations','5 steps to a 5','huck finn litplan','soldier\'s heart','to kill a mockingbird audio','10 days','inferno teaching unit','ceremony','freedom writer\'s diary','mice and men movie','skills','glass menagerie ap','douglass','hamlet multiple critical perspectives','reading stories for comprehension success','grammar proficiency test','jacob have i loved','voice','activity packs','latin and greek roots book 3','the once and future king','pride','that was then','mastery of grammar','the princess bride','romeo and juliet study guide','research paper','logical fallacies','a modest proposal','hunger games teaching guide','literary terms poster','antigone touchstone','language of politicians poster','ap english','practice makes perfect level 10','and then there','thomas paine','amistad','as you like it','the secret life of bees teaching unit','daily warm ups','alice in wonderland','no easy answers','animal farm cd','rumble fish','esperanza rising','150 great short stories reproducible activities','wuthering heights activities','grammar wars','the rose that grew from concrete','state assessment','power plus book g','power plus book h','short story unit','dicey\'s song','from the mixed up files of mrs basil e frankweiler','vocabulary power plus for the new sat book two','literary elements posters','cyrano de','response journal mockingbird','lost generation','to kill a mockingbird vocabulary','latin and greek roots book iii','joy luck club ap','prestwick house ap language and composition','scarlet letter activity pack','spoon river anthology','romeo','huckleberry','thesaurus','tuesdays with','propaganda','dante inferno','1984 audio','gilgamesh','maps from literature','catcher ap','huck finn activity','short story anthology','animal farm poster','dickens','individual learning packets teaching units','fahrenheit 451 test','maximum impact','of mice and men downloadable','of mice and men teaching unit','othello teaching unit','american short stories','the alchemist teaching unit','the cay','novel test','parrot in the oven','2001','darkness','beowulf multiple critical perspectives','grammar exercises','tale of two cities paperback','odyssey mandelbaum','let them laff there way to bedder proofreading skills','101 great american poems','rosencrantz and guildenstern','frankenstein downloadable teaching unit','life of pi ap','antigone film','the scarlet letter ap teaching unit','vocabulary power','incidents in the life of a slave girl','vonnegut','expository writing','ap teaching units pride and prejudice','where the red fern grows','catcher in the rye activity pack','robert cormier','dr.faustus','teacher\'s kits','their eyes were watching','the stranger activity pack','reading for information','the fountainhead','oedipus teaching','analogies','ap dolls house','the hobbit response journal','persuasion','ap the picture of dorian gray','shiloh','rhetoric logic argumentation teacher edition','night ap','propaganda and persuasion techniques','wizard of oz','henry v','ebooks','scarlet letter downloadable','hip hop poetry and the classics','writing posters','hamlet folger','pre ap readings','unit 10','college bound','the awakening downloadable','vocabulary from latin and greek roots book iv','the prince','reading and analyzing nonfiction','macbeth audio','james patterson','growing your vocabulary learning from latin and greek roots book a','state reading assessments','abridged','1984 downloadables','scorpion walter dean myers','pre ap readings and exercises','kate chopin','measure for measure','koran','friday night lights','adventures in fantasy','uncle toms cabin','grammar dog frankenstein','walt whitman','one day in the life','billy budd','study guide othello','durango street','the namesake','book g','multiple critical','heart of darkness test','adventures in wonderland','mla handbook','death be not proud','the giver activity pack','multiple','stranger in a strange land','activity pack brave new world','the pearl ap','le morte','huckleberry finn adapted','night teach','tom sawyer activity pack','litplan the scarlet letter','a tale of two cities downloadable','stargirl','of mice and men headlines poster','the egypt game','yellow wallpaper','frankenstein download','lead ins to literature','portrait of the artist','ap unit for huck finn','parts of speech','power points','fathers and sons','discovering genre poetry','to kill a mockingbird cd','antony and cleopatra','the great gatsby dvd','daily','of mice and men activity pack','root words','headlines posters odyssey','grammar for writing teacher','book ii','fellowship of the ring','english grammar and mechanics','symbolism','practical english','english teacher\'s book of instant word games','phunny stuff','tess of the d\'urbervilles','a time to kill','from the mixed up files','bleachers','cold blood','things they carried activity pack','rhetorical poster','maximum ride','hamlet downloadable ap teaching units','pearl activity','cuckoo','beloved activity pack','ap practice tests','dante club','julius caesar elesson','dracula downloadable teaching unit','elessons','when the emperor was divine','the count of monte cristo abridged','woodsong','medea litplan','reading the newspaper','macbeth multiple perspectives','levels of understanding to kill a mockingbird','frankenstein teacher edition','hoops','no promises in the wind','true confessions','shakespeare poster','parts of speech poster','the outsiders poster','discovering voice','gre','the memory keepers daughter','antigone headlines','angela','pronouns','the bronze bow','animal farm dvd','non-fiction text structure','ernest gaines','whiteboard','the jungle book','devil in the white city','song of roland','machiavelli','romeo and juliet video','their eyes were watching god dvd','building better writing skills','making inferences','six great sherlock','fahrenheit 451 puzzle pack','the education of little tree','vocabulary cartoons','writing skills','a thousand','bridge to terabithia elesson','o\'brien','tim o\'brien','holocaust','indian in the cupboard','odysseus','hacker','oliver','cat on a hot tin roof','the elephant man','best of o henry','the chocolate war paperback','contemporary','ap unit death of a salesman','power plus for the act','journey to the center of the earth','sentence writing','grammardog great expectations','farewell to manzanar teaching unit','captains courageous','writing downloadable','children of the river','writing essays','a man for all seasons','the mysterious stranger','grammar and usage','o henry','ap the bluest eye','the lion the witch','the puzzle pack things fall apart','inferring meaning','downloadable great expectations','julius caesar poster','the cage','a retrieved reformation','adventures of huck','thornton wilder','the giver test','the pearl puzzle pack','a tree grows in brooklyn','the effect of gamma rays on man in the moon marigolds','tess','the tempest downloadable','the story of my life','ap language downloadables','teacher scarlet letter','the glass menagerie book','the bean trees teaching unit','t.s eliot','audio and teaching unit night','all\'s well that ends well','to kill a mockingbird lesson','the souls of black folk','to kill a mockingbird complete','the adventures of sherlock holmes','ap study guides','ap writing','a christmas carol vocabulary','ap teaching units sample','a christmas carol response journal','the lord of the flies levels of understanding','all quiet on the','the shakespeare stealer','the cricket in times square','the mighty','as i lay dying study guide','things fall apart multiple','aladdin','teacup full of roses','activity ender\'s game','an occurence at owl creek bridge','apa','the lion the witch and wardrobe','tuck everlasting study guide','asher lev','the slave dancer','they poured fire on us from the sky','teaching grammar','the land','the grapes of wrath journals','the outsiders elessons','the iliad activity pack','to kill a mockingbird teacher','transparencies','angry men','art of the personal essay','artemis fowl','reading and analyzing non-fiction teacher \'s edition','the chrysanthemums','tao','america street','the view from saturday','teaching writing in the inclusive classroom','things fall apart elesson','vocabulary power plus for the new sat book two teacher \'s edition','the pinballs','touching spirit bear puzzle pack','tunes for bears to dance to','timeline posters','tao te ching','teacher\'s edition vocabulary','tarzan','timed reading','asia','as i lay','the hollow men','ap teaching unit pi','trojan women','the story of the amistad','the subjection of women','almost a woman','the last battle','around the world in','twelfth','applied communication','abridged jane eyre','arithmetic puzzle','a jury of her peers','the diamond as big as the ritz','the two towers','the outsiders audio','trino\'s choice','tempest dvd','the great brain','ap a to z');
/* $Revision: 6883 $
 *
 */

if(typeof(_sli_init )!='object'){var _sli_init=new Array();}
if(typeof(sli_init )!='function'){function sli_init(){ for(var x=0;x<_sli_init.length;x++) _sli_init[x]();}}
if(typeof(asPhrases)!='object'){ var asPhrases = new Array(); }
if(typeof(__SLI_customisations)!='object'){var __SLI_customisations = new Object();}
if(typeof(__SLI_ClientDefaults)!='object'){ var __SLI_ClientDefaults=[]; }
if(typeof(__SLI_validSearchBoxes)!='object'){ var __SLI_validSearchBoxes = new Array(); }
if(typeof(__SLI_asug_used_flag)!='object'){ var __SLI_asug_used_flag = false; }
if(typeof(__SLI_width)!='object'){ var __SLI_width = 0; }
if(typeof(sli_targeturl)!='object'){ var sli_targeturl = ""; }


    __AutoComplete = new Object(); //namespace...
    __AutoComplete_mouseMoved=false;

    // Basic UA detection
    isIE = document.all ? true : false;
    isGecko = navigator.userAgent.toLowerCase().indexOf('gecko') != -1;
    isOpera = navigator.userAgent.toLowerCase().indexOf('opera') != -1;

    /* defaults and options */

    var __SLI_ApplicationName = 'AutoSuggest';
        __SLI_customisations[ 'AutoSuggest' ] =
                {
                    'ShowBrandingFooter' : true
                    ,
                    'TextBoxIDPrefix' : 'sli_search_'
                    ,
                    'BrandingFooterImagePath' : 'http://assets.resultspage.com/autosuggest/sli_systems-powered_150_15.gif'
                    ,
                    'BrandingFooterTitleTooltip' : 'AutoSuggest Powered by SLI Systems'
                    ,
                    'DropListMinWidth' : 150
                    ,
                    'MaxListItems' : 10
                    ,
                    'Alignment' : true
                    ,
                    'TextBoxIDCustom' : []
                    ,
                    'ValidSearchBoxes' : false 
                    ,
                    'IE6SelectBox' : false 
                    ,
                    'IE6SelectBoxPadding' : 0
                    ,
                    'TargetURL' : ''
                    ,
                    'IframeAlignment' : false
                    ,
                    'AlignmentBorderBug' : false
                    ,
                    'IE6OnFocus' : false
                };
    /* 0 = keyname, 1 = value */
    for( defaultValuePair in __SLI_ClientDefaults )
    {
        __SLI_customisations[__SLI_ApplicationName][__SLI_ClientDefaults[defaultValuePair][0]]=__SLI_ClientDefaults[defaultValuePair][1];
    }

    /* pre-fetch branding footer image if being used...
     */
    if( __SLI_customisations[ __SLI_ApplicationName ][ 'ShowBrandingFooter' ] )
    {
        
        if(location.protocol == "https:")
        {
            __SLI_customisations[ __SLI_ApplicationName ][ 'BrandingFooterImagePath' ] = __SLI_customisations[ __SLI_ApplicationName ][ 'BrandingFooterImagePath' ].replace(/http:/i, 'https:');
        }
    
        var __AutoCompleteBranding = new Image();
        __AutoCompleteBranding.src=__SLI_customisations[ __SLI_ApplicationName ][ 'BrandingFooterImagePath' ];
    }


    function AutoComplete_init()
    {
        if(!isOpera)
        {
            var oldonresize=function(){};
            if(typeof(window.onresize)=='function')
                oldonresize = window.onresize;//play nicely with other people's toys
            window.onresize= function(){ oldonresize(); AutoComplete_HideAll(); AutoComplete_Create( asPhrases ); }

            AutoComplete_Create( asPhrases );
            
            var els = document.getElementsByTagName('input');
            if(els)
            {
               for ( i = 0; i < els.length; i++ )
               {
                  if(els[i].name == "asug")
                  {
                     els[i].disabled = true;
                  }
               }
            }
        }
    }




    /**
    * Attachs the autocomplete object to a form element. Sets
    * onkeypress event on the form element.
    *
    * @param string formElement Name of form element to attach to
    * @param array  data        Array of strings of which to use as the autocomplete data
    */
    //function AutoComplete_Create (id, data)
    /*
     * iterate over 'sli_search_*' assumes one or more search boxes numbered from 1...
    */
    function AutoComplete_Create( data )
    {
        var idx=1, e, id, searchBoxPrefix=__SLI_customisations[ __SLI_ApplicationName ][ 'TextBoxIDPrefix' ];
        while( e = document.getElementById(searchBoxPrefix+idx) )
        {
            AutoComplete_AttachHandlers(e, data);
            if( __SLI_customisations[ __SLI_ApplicationName ][ 'ValidSearchBoxes' ] )
            {
                __SLI_validSearchBoxes.push(searchBoxPrefix+idx);
            }
            idx++;
        }
        
        
        //this array comes from the customised list
        var otherTextBoxIdList = __SLI_customisations[ __SLI_ApplicationName ][ 'TextBoxIDCustom' ];
        if( otherTextBoxIdList)
        {
            for(idx=0;idx<otherTextBoxIdList.length;idx++)
            {
                e = document.getElementById(otherTextBoxIdList[idx]);
                if(e)
				{
					if( __SLI_customisations[ __SLI_ApplicationName ][ 'ValidSearchBoxes' ] )
                	{
	                    __SLI_validSearchBoxes.push( otherTextBoxIdList[idx] );
                	}
					AutoComplete_AttachHandlers(e, data);
				}
            }
        }
        
    } 

    function AutoComplete_AttachHandlers(e, data){
        var iframe,id;
        id=e.id;


        __AutoComplete[id] = {'data':data,
                              'isVisible':false,
                              'element':document.getElementById(id),
                              'dropdown':null,
                              'highlighted':null};

        __AutoComplete[id]['element'].setAttribute('autocomplete', 'off');
        __AutoComplete[id]['element'].onkeydown = function(e) {if (!e) e = window.event; return AutoComplete_KeyDown(this.getAttribute('id'), e);}
        __AutoComplete[id]['element'].onkeyup = function(e) {if (!e) e = window.event; return AutoComplete_KeyUp(this.getAttribute('id'), e);}
        // The function call on the next line was changed by Andrew Grieve April 2008
        __AutoComplete[id]['element'].onkeypress = function(e) {if (!e) e = window.event; return AutoComplete_KeyPress(this.getAttribute('id'), e);}
        __AutoComplete[id]['element'].onclick = function(e)
        {
            if( __SLI_customisations[ __SLI_ApplicationName ][ 'IE6OnFocus' ] )
            {
                __AutoComplete[id]['element'].focus();
            }
            if (!e) e = window.event; e.cancelBubble = true; e.returnValue = false;
        }



        // Hides the dropdowns when document clicked
        var docClick = function()
        {
            if( __SLI_customisations[ __SLI_ApplicationName ][ 'ValidSearchBoxes' ] )
            {
               for(var i=0; i < __SLI_validSearchBoxes.length; i++)
               {
                   if(document.getElementById(__SLI_validSearchBoxes[i]))
                   {
                       AutoComplete_HideDropdown(__SLI_validSearchBoxes[i]);
                   }
               }
            }
            else
            {
                for (id in __AutoComplete)
                {
                   AutoComplete_HideDropdown(id);
                }
            }
        }

        if (document.addEventListener) {
            document.addEventListener('click', docClick, false);
        } else if (document.attachEvent) {
            document.attachEvent('onclick', docClick, false);
        }


        // Max number of items shown at once
        if (arguments[2] != null) {
            __AutoComplete[id]['maxitems'] = arguments[2];
            __AutoComplete[id]['firstItemShowing'] = 0;
            __AutoComplete[id]['lastItemShowing'] = arguments[2] - 1;
        }

        AutoComplete_CreateDropdown(id);

        // Prevent select dropdowns showing thru
        if (isIE) {
            iframe = document.createElement('iframe');
            __AutoComplete[id]['iframe'] = iframe;
                iframe.id = id +'_iframe';
                iframe.style.position = 'absolute';
                iframe.style.top = '0';
                iframe.style.left = '0';
                iframe.style.width = '0px';
                iframe.style.height = '0px';
                iframe.style.zIndex = '98';
                iframe.style.visibility = 'hidden';
                
                if(location.protocol == "https:")
                {
                   iframe.src = 'https://assets.resultspage.com/autosuggest/blank.html';
                }
                
                if( __SLI_customisations[ __SLI_ApplicationName ][ 'IE6SelectBox' ] )
                {
                  iframe.style.width = __SLI_width  + __SLI_customisations[ __SLI_ApplicationName ][ 'IE6SelectBoxPadding'];
                }

            if( __SLI_customisations[ __SLI_ApplicationName ][ 'IframeAlignment' ] )
            {
                document.body.insertBefore( iframe );
            }
            else
            {
                __AutoComplete[id]['element'].parentNode.insertBefore( iframe, __AutoComplete[id]['element'] );
            }
        }
    }

    /**
    * Creates the dropdown layer
    *
    * @param string id The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_CreateDropdown(id)
    {
        var theSearchbox = __AutoComplete[id]['element'];
        var theDropDown;
        var left_top = AutoComplete_getPos( theSearchbox );
        var left  = left_top[0];
        var top   = left_top[1] + theSearchbox.offsetHeight;
        var width = theSearchbox.offsetWidth;

        if ( width < __SLI_customisations[ __SLI_ApplicationName ][ 'DropListMinWidth' ] )
        {
            width = __SLI_customisations[ __SLI_ApplicationName ][ 'DropListMinWidth' ];
        }

        theDropDown = document.createElement('div');
        theDropDown.className = 'autocomplete'; // Don't use setAttribute()


        if(__SLI_customisations[ __SLI_ApplicationName ][ 'Alignment' ] == true && document.body)
        {
            theDropDown.style.position = 'absolute';
            document.body.insertBefore(theDropDown, document.body.nextSibling);
            
            // Position it
            theDropDown.style.visibility = 'hidden';
            theDropDown.style.left       = left + 'px';
            theDropDown.style.top        = top + 'px';
            theDropDown.style.width      = width + 'px';
            theDropDown.style.zIndex     = '99999';
        }
        else if(__SLI_customisations[ __SLI_ApplicationName ][ 'Alignment' ] == "offsetrelative" && document.body)
        {
          theSearchbox.parentNode.insertBefore(theDropDown, theSearchbox);
          // Position it
          if(sli_getStyle(theSearchbox.offsetParent, 'position') != "absolute")
          {
            theSearchbox.offsetParent.style.position = 'relative';
          }
          theDropDown.style.position = 'absolute';
          theDropDown.style.left = (theSearchbox.offsetLeft) + 'px';
          theDropDown.style.top = (theSearchbox.offsetTop + theSearchbox.offsetHeight) + 'px';
          if ( theSearchbox.clientWidth < __SLI_customisations[ __SLI_ApplicationName ][ 'DropListMinWidth' ] )
          {
            theDropDown.style.width = __SLI_customisations[ __SLI_ApplicationName ][ 'DropListMinWidth' ];
          }
          else
          {
            theDropDown.style.width = (theSearchbox.clientWidth) + 'px';
          }
          theDropDown.style.visibility = 'hidden';
          theDropDown.style.zIndex     = '99999999';
        }
        else
        {
            theSearchbox.parentNode.insertBefore(theDropDown, theSearchbox);
            // Position it
            theDropDown.style.visibility = 'hidden';
            theDropDown.style.left       = left + 'px';
            theDropDown.style.top        = top + 'px';
            theDropDown.style.width      = width + 'px';
            theDropDown.style.zIndex     = '99999';
        }
        

        __AutoComplete[id]['dropdown'] = theDropDown;
        __SLI_width = width;
    }

    function /* array [ left, top ] */ AutoComplete_getPos( obj )
    {
        var curleft = curtop = 0;
        var sli_flag = 0;

        if (obj.offsetParent)
        {
           do
           {
              if ( __SLI_customisations[ __SLI_ApplicationName ][ 'AlignmentBorderBug' ] )
              {         
                
                if(sli_flag == 1)
                {
                    var clientTop = (obj.offsetHeight - obj.clientHeight) / 2;
                    curtop += clientTop;

                    var clientLeft = (obj.offsetWidth - obj.clientWidth) / 2;
                    curleft += clientLeft;
                }
                sli_flag = 1;
              }
           
              curleft += obj.offsetLeft;
              curtop += obj.offsetTop;
           }
           while (obj = obj.offsetParent);
        }
        return [curleft,curtop];
    }

    /**
    * Shows the dropdown layer
    *
    * @param string id The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_ShowDropdown(id)
    {

        AutoComplete_HideAll();



        var value = __AutoComplete[id]['element'].value;
        var toDisplay = new Array();
        var newDiv    = null;
        var text      = null;
        var numItems  = __AutoComplete[id]['dropdown'].childNodes.length;

        __AutoComplete_mouseMoved=false;
        // SLI Code Modification - Start - Andrew Grieve April 08
        // Trim the textbox so that if is starts with a space then the feature will still work
        //value = value.replace(/^\s+|\s+$/g,"");
        value = value.replace(/^\s+/g,"");

        if(value.length == "")
        {
            // If Textbox length is nothing (after the trim) then don't show dropdown.
            return;
        }
        // SLI Code Modification - End

        // Remove all child nodes from dropdown
        while (__AutoComplete[id]['dropdown'].childNodes.length > 0) {
            __AutoComplete[id]['dropdown'].removeChild(__AutoComplete[id]['dropdown'].childNodes[0]);
        }


        var count=0;
        // Go thru data searching for matches
        for (i=0; i<__AutoComplete[id]['data'].length; ++i)
        {
            // SLI Code Modification - Start - Andrew Grieve April 08 - Added lower casing
            if (__AutoComplete[id]['data'][i].substr(0, value.length).toLowerCase() == value.toLowerCase())
            {
                // SLI Code Modification - End
                toDisplay[toDisplay.length] = __AutoComplete[id]['data'][i];
                count++;
                /* how many to display? */
                if(count == __SLI_customisations['AutoSuggest']['MaxListItems'] ) /* Code inserted to keep list to a maximum of 10 values (was 20 or 30) */
                {
                    break;
                }
            }
        }

        // No matches?
        if (toDisplay.length == 0) {
            AutoComplete_HideDropdown(id);
            return;
        }



        // Add data to the dropdown layer
        for (i=0; i<toDisplay.length; ++i) {
            newDiv = document.createElement('div');
            newDiv.className = 'autocomplete_item'; // Don't use setAttribute()
            newDiv.setAttribute('id', 'autocomplete_item_' + i);
            newDiv.setAttribute('index', i);
            newDiv.style.zIndex = '99999';

             // Scrollbars are on display ?
            if (toDisplay.length > __AutoComplete[id]['maxitems'] && navigator.userAgent.indexOf('MSIE') == -1) {
                newDiv.style.width = __AutoComplete[id]['element'].offsetWidth - 22 + 'px';
            }

            newDiv.onmouseover =
        function()
        {
            if( __AutoComplete_mouseMoved )
                AutoComplete_HighlightItem(__AutoComplete[id]['element'].getAttribute('id'), this.getAttribute('index'));
        };

            newDiv.onclick     =    function()
                                    {
                                    	  __SLI_asug_used_flag = true;
                                                                           
                                        AutoComplete_SetValue(__AutoComplete[id]['element'].getAttribute('id'));
                                        AutoComplete_HideDropdown(__AutoComplete[id]['element'].getAttribute('id'));
                                        AutoComplete_submitForm(id);
                                    }



            text   = document.createTextNode(toDisplay[i]);
            newDiv.appendChild(text);
            newDiv.title='Search for ' + toDisplay[i];

            /* ellipsis for IE only */
            if( isIE )
            {
                newDiv.style.textOverflow = 'ellipsis';
                newDiv.style.width = '100%';
                newDiv.style.whiteSpace = 'nowrap';
                newDiv.style.overflow = 'hidden';

            }
            __AutoComplete[id]['dropdown'].appendChild(newDiv);
        }
        /*
         * append DIV containing footer branding...
         */
        if(__SLI_customisations['AutoSuggest']['ShowBrandingFooter'])
        {
            i = toDisplay.length;
            newDiv = document.createElement('div');
            newDiv.className = 'autocomplete_footer'; // Don't use setAttribute()
            newDiv.setAttribute('id', 'autocomplete_item_' + i);
            newDiv.setAttribute('index', i);
            newDiv.style.zIndex = '99999';
            newDiv.innerHTML = '<a href="http://www.sli-systems.com/powered-by.php" title="' +
                                __SLI_customisations[ __SLI_ApplicationName ][ 'BrandingFooterTitleTooltip' ] +
                                '"><img class="autocomplete_footer_branding" src="'+__AutoCompleteBranding.src+'" /></a>';

            __AutoComplete[id]['dropdown'].appendChild(newDiv);
        }


        // Too many items?
        if (toDisplay.length > __AutoComplete[id]['maxitems']) {
            __AutoComplete[id]['dropdown'].style.height = (__AutoComplete[id]['maxitems'] * 15) + 2 + 'px';

        } else {
            __AutoComplete[id]['dropdown'].style.height = '';
        }


        /**
        * Set left/top in case of document movement/scroll/window resize etc
        */
        if(__SLI_customisations[ __SLI_ApplicationName ][ 'Alignment' ] == "true" || __SLI_customisations[ __SLI_ApplicationName ][ 'Alignment' ] == "false")
        {
            var left_top = AutoComplete_getPos( __AutoComplete[id]['element'] );
            __AutoComplete[id]['dropdown'].style.left = left_top[0];
            __AutoComplete[id]['dropdown'].style.top  = left_top[1] + __AutoComplete[id]['element'].offsetHeight;
        }


        // Show the iframe for IE
        if (isIE) {
            
            if(!__SLI_customisations[ __SLI_ApplicationName ][ 'Alignment' ] == true)
            {
               __AutoComplete[id]['iframe'].style.width  = __AutoComplete[id]['dropdown'].offsetWidth;
            }
            
            
            __AutoComplete[id]['iframe'].style.top    = __AutoComplete[id]['dropdown'].style.top;
            __AutoComplete[id]['iframe'].style.left   = __AutoComplete[id]['dropdown'].style.left;
            __AutoComplete[id]['iframe'].style.height = __AutoComplete[id]['dropdown'].offsetHeight;

            __AutoComplete[id]['iframe'].style.visibility = 'visible';
        }

    e =  __AutoComplete[id]['dropdown'];

    e.onmousemove =
        function()
        {
            if(!__AutoComplete_mouseMoved){__AutoComplete_mouseMoved=true;}
            this.onmousemove = null;
        }

        // Show dropdown
        if (!__AutoComplete[id]['isVisible']) {
            __AutoComplete[id]['dropdown'].style.visibility = 'visible';
            __AutoComplete[id]['isVisible'] = true;
        }


        // If now showing less items than before, reset the highlighted value
        if (__AutoComplete[id]['dropdown'].childNodes.length != numItems) {
            __AutoComplete[id]['highlighted'] = null;
        }
    }



    /**
    * Hides the dropdown layer
    *
    * @param string id The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_HideDropdown(id)
    {
        if (__AutoComplete[id]['iframe'])
        {
            __AutoComplete[id]['iframe'].style.visibility = 'hidden';
        }
        
        if (__AutoComplete[id]['dropdown'])
        {
            __AutoComplete[id]['dropdown'].style.visibility = 'hidden';
        }

        __AutoComplete[id]['highlighted'] = null;
        __AutoComplete[id]['isVisible']   = false;
    }


    /**
    * Hides all dropdowns
    */
    function AutoComplete_HideAll()
    {
         if( __SLI_customisations[ __SLI_ApplicationName ][ 'ValidSearchBoxes' ] )
         {
               for(var i=0; i < __SLI_validSearchBoxes.length; i++)
               {
                   if(document.getElementById(__SLI_validSearchBoxes[i]))
                   {
                       AutoComplete_HideDropdown(__SLI_validSearchBoxes[i]);
                   }
               }
         }
         else
         {
                for (id in __AutoComplete)
                {
                   AutoComplete_HideDropdown(id);
                }
         }
    }


    /**
    * Highlights a specific item
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    * @param int    index The index of the element in the dropdown to highlight
    */
    function AutoComplete_HighlightItem(id, index) // mouseover, index is the list element index, zero-based
    {
        if (__AutoComplete[id]['dropdown'].childNodes[index]) {
            for (var i=0; i<__AutoComplete[id]['dropdown'].childNodes.length; ++i) {
                if (__AutoComplete[id]['dropdown'].childNodes[i].className == 'autocomplete_item_highlighted') {
                    __AutoComplete[id]['dropdown'].childNodes[i].className = 'autocomplete_item';
                }
            }

            __AutoComplete[id]['dropdown'].childNodes[index].className = 'autocomplete_item_highlighted';
            __AutoComplete[id]['highlighted'] = index;

            //also see below...
            //__AutoComplete[id]['element'].value = __AutoComplete[id]['dropdown'].childNodes[index].innerHTML;
            //AutoComplete_SetValue(id);
        }
    }


    /**
    * Highlights the menu item with the given index
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    * @param int    index The index of the element in the dropdown to highlight
    */
    function AutoComplete_Highlight(id, index) // keyboard up/down - index is the direction of travel, 1==down,-1=up
    {
        var childNodes = __AutoComplete[id]['dropdown'].childNodes;
        if(childNodes.length)
        {
	        var lastItem = ( ( childNodes[ childNodes.length - 1 ].className != 'autocomplete_footer' ) ? childNodes.length - 1 : childNodes.length - 2 );

            // Out of bounds checking
            //if (index == 1 && __AutoComplete[id]['highlighted'] == __AutoComplete[id]['dropdown'].childNodes.length - 1) {
            if (index == 1 && __AutoComplete[id]['highlighted'] == lastItem ) {
                childNodes[__AutoComplete[id]['highlighted']].className = 'autocomplete_item';
                __AutoComplete[id]['highlighted'] = null;

            } else if (index == -1 && __AutoComplete[id]['highlighted'] == 0) {
                childNodes[0].className = 'autocomplete_item';
                __AutoComplete[id]['highlighted'] = lastItem;
                index = 0;//hack!
            }

            // Nothing highlighted at the moment
            if (__AutoComplete[id]['highlighted'] == null) {

                childNodes[0].className = 'autocomplete_item_highlighted';
                __AutoComplete[id]['highlighted'] = 0;
                newIndex = 0;
                
            } else {

                if (childNodes[__AutoComplete[id]['highlighted']]) {
                
                    childNodes[__AutoComplete[id]['highlighted']].className = 'autocomplete_item';
                }

                var newIndex = parseInt( __AutoComplete[id]['highlighted'] ) + parseInt(index);

                if (childNodes[newIndex]) {

                    childNodes[newIndex].className = 'autocomplete_item_highlighted';

                    __AutoComplete[id]['highlighted'] = newIndex;
                }
            }

            //populate textbox with currently highlighted term...
            //__AutoComplete[id]['element'].value = __AutoComplete[id]['dropdown'].childNodes[newIndex].innerHTML;
            AutoComplete_SetValue(id);
        }
    }


    /**
    * Sets the input to a given value
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_SetValue(id)
    {
        __AutoComplete[id]['element'].value = __AutoComplete[id]['dropdown'].childNodes[__AutoComplete[id]['highlighted']].innerHTML.replace(/&amp;/, "&");
    }


    /**
    * Checks if the dropdown needs scrolling
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_ScrollCheck(id)
    {
        // Scroll down, or wrapping around from scroll up
        if (__AutoComplete[id]['highlighted'] > __AutoComplete[id]['lastItemShowing']) {
            __AutoComplete[id]['firstItemShowing'] = __AutoComplete[id]['highlighted'] - (__AutoComplete[id]['maxitems'] - 1);
            __AutoComplete[id]['lastItemShowing']  = __AutoComplete[id]['highlighted'];
        }

        // Scroll up, or wrapping around from scroll down
        if (__AutoComplete[id]['highlighted'] < __AutoComplete[id]['firstItemShowing']) {
            __AutoComplete[id]['firstItemShowing'] = __AutoComplete[id]['highlighted'];
            __AutoComplete[id]['lastItemShowing']  = __AutoComplete[id]['highlighted'] + (__AutoComplete[id]['maxitems'] - 1);
        }

        __AutoComplete[id]['dropdown'].scrollTop = __AutoComplete[id]['firstItemShowing'] * 15;
    }


    /**
    * Function which handles the keypress event
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_KeyDown(id, e)
    {
        var result = true;

       var event;
       event = e;
       if(!event) event = window.event;

        var keyCode = event.keyCode;

        switch (keyCode) {

            // Return/Enter
            case 13:
                if (__AutoComplete[id]['highlighted'] != null) {
                    AutoComplete_SetValue(id);
                    AutoComplete_HideDropdown(id);
					
                    __SLI_asug_used_flag = true;
					
                    if( e = __AutoComplete[id]['element'].form['asug'] )
                    {
                        
                        e.disabled=false;
                        e.value = __AutoComplete[id]['asug'];
                    }

                }

                result = AutoComplete_submitForm(id);

                break;

            // Escape
            case 27:
                AutoComplete_HideDropdown(id);
                event.returnValue = false;
                event.cancelBubble = true;
                break;

            // Up arrow
            case 38:
                if (!__AutoComplete[id]['isVisible']) {
                    AutoComplete_ShowDropdown(id);
                }

                AutoComplete_Highlight(id, -1);
                AutoComplete_ScrollCheck(id, -1);
                
                if( e = __AutoComplete[id]['element'].form['asug'] )
                {
                   e.disabled=false;
                   e.value = __AutoComplete[id]['asug'];
                }

                                
                result = false;
                break;

            // Tab
            case 9:
                if (__AutoComplete[id]['isVisible']) {
                    AutoComplete_HideDropdown(id);
                }
                return;

            // Down arrow
            case 40:

                if (!__AutoComplete[id]['isVisible']) {
                    AutoComplete_ShowDropdown(id);
                }

                AutoComplete_Highlight(id, 1);
                //AutoComplete_ScrollCheck(id, 1);

                if( e = __AutoComplete[id]['element'].form['asug'] )
                {
                   e.disabled=false;
                   e.value = __AutoComplete[id]['asug'];
                }

                result = false;
                break;
        }
        return result;
    }


    /**
    * Function which handles the keyup event
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_KeyUp(id, e)
    {
       var event;
       event = e;
       if(!event) event = window.event;

        var keyCode = event.keyCode;

        switch (keyCode) {
            case 13:
                event.returnValue = false;
                event.cancelBubble = true;
                
                break;

            case 27:
                AutoComplete_HideDropdown(id);
                event.returnValue = false;
                event.cancelBubble = true;
                break;

            case 38:
            case 40:
                return false;
                break;

            default:
                AutoComplete_ShowDropdown(id);
                
                __AutoComplete[id]['asug']=__AutoComplete[id]['element'].value;

                if( e = __AutoComplete[id]['element'].form['asug'] )
                {
                   e.disabled=true;
                   e.value = "";
                }  
                
                break;
        }
    }

    /**
    * Function which handles the keypress event
    * This function added April 2008 by Andrew Grieve
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    */

    // SLI Code Modification - Start - Andrew Grieve April 08
    function AutoComplete_KeyPress(id, e)
    {
        var event = e;
        if(!event) event = window.event;
        var keyCode = event.keyCode;

        if (keyCode == 13 && isGecko || isOpera)
        {
            return false;
        }
        
        if( __SLI_customisations[ __SLI_ApplicationName ][ 'TargetURL' ] )
        {
            if (keyCode == 13 && isIE)
            {
                return false;
            }
        }
        
    }
    // SLI Code Modification - End

    /**
    * Returns whether the dropdown is visible
    *
    * @param string id    The form elements id. Used to identify the correct dropdown.
    */
    function AutoComplete_isVisible(id)
    {
        return __AutoComplete[id]['dropdown'].style.visibility == 'visible';
    }

    function AutoComplete_submitForm(id)
    {
      var e, f, result=true;
      if( f = __AutoComplete[id]['element'].form )
      {
        if( __AutoComplete[id]['element'].value != '' )
        {
          if(__SLI_asug_used_flag == true)
          {
            if( e = f['asug'])
            {
              e.value = __AutoComplete[id]['asug'];
              e.disabled=false;
            }
          }

          if( __SLI_customisations[ __SLI_ApplicationName ][ 'TargetURL' ] )
          {
            asugvar = "";
            if(__SLI_asug_used_flag == true)
            {
              asugvar = '&asug=' + escape(__AutoComplete[id]['asug']);
            }

            sliRegex = /resultsdemo\.com/;
            if(sliRegExArray = sliRegex.exec(document.domain))
            {
              sliRegex = /^http:\/\/(.*)\//;
              sliTargetDomain = sliRegex.exec(__SLI_customisations[__SLI_ApplicationName ][ 'TargetURL' ]);
              __SLI_customisations[__SLI_ApplicationName ][ 'TargetURL' ] = __SLI_customisations[__SLI_ApplicationName ][ 'TargetURL' ].replace(sliTargetDomain[1], document.domain);
            }

            document.location.href = __SLI_customisations[__SLI_ApplicationName ][ 'TargetURL' ] + escape(__AutoComplete[id]['element'].value) + asugvar;
          }
          else
          {
            if(f.onsubmit)
            {
              if(f.onsubmit() !== false)
              {
                f.submit();
              }
            }
            else
            {
              f.submit();
            }
          }

          AutoComplete_HideAll();
        }
        else
          result = false;
      }
      return result;
    }
    
    // get the style that will be applied by the browser, including stylesheets
    function sli_getStyle(el,styleProp)
    {
      if (el.currentStyle)
        var y = el.currentStyle[styleProp];
      else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
      return y;
    }

    // register with onLoad(er...
    _sli_init.push( AutoComplete_init );
    
    function sli_addEvent(obj, evType, fn) {
    	if (obj.addEventListener) {
    		obj.addEventListener(evType, fn, false);
    		return true;
    	} else if (obj.attachEvent) {
    		var r = obj.attachEvent("on" + evType, fn);
    		return r;
    	} else {
    		return false;
    	}
    }
    
    function sli_load()
    {
    	sli_addEvent(window, 'load', sli_init);
    }
