window.addEvent('domready', function() {
  
  current_url = window.location.toString();
	current_url = current_url.replace("http://", "");
	current_url = current_url + "/"
	current_url = current_url.replace("//", "/");
	
	// remember me alert about security
	
	if ($("remember_me")){
  	$("remember_me").addEvent("click", function(el){
  	  if ($("remember_me").get("checked")){
  	    alert("WARNING \n\nYou will be logged in automatically every time you visit the site from this computer.\n Only use this feature if your computer is not used by others.\n");
  	  }
  	});
  }
	
  if ($('calendar_data')){calendar()}
  
  // autocomplete organisation ======================================================

  if ($("organisation_search")){
    
    //on change event listener
    $("organisation_name").addEvent("keyup", function(e){
    
      resultDiv = $('organisation_results');
      textBox = $("organisation_name");
      keywords = textBox.value;
    
      if (keywords != "" && e.key != "down" && e.key != "up" && e.key != "enter"){
          $('loading_image').setStyle('width', '16px');
        	var myHTMLRequest = new Request.HTML({
        	  url:'/registration/organisations',
        	  onSuccess: function(html) {
        	    resultDiv.set('text', '');
        	    resultDiv.adopt(html);
        	    resultDiv.setStyle('display','block');
        	    $('loading_image').setStyle('width', '0');
        	    
            $$('#organisation_results a').each(function(element){
        	      element.addEvent('click', function(el){
          	      el.stop();
          	      organisation_name = element.get('text');
          	      textBox.set('value', organisation_name);
          	      resultDiv.setStyle('display','none');
        	      });
        	    });
      	    }
        	  }).get({'keywords': keywords}); 
      
        //display results in div
        myHTMLRequest.send();
       }
       else if (e.key == "down" || e.key == "up" )
       {
         // kill submit of form
         $('organisation_search_form').addEvent('submit', function(el){
           el.stop();
         });
         
         // loop through each result finding the highlighted one. 
         // If there isn't one make the first one highlighted.
         highlighted_id = 0;
         c = 0;
         
         $$('#organisation_results ul li a').each(function(link_el){
           c += 1;
           if (link_el.hasClass("highlighted")){
             //get the id of the highlighted class and remove the highlight 
             highlighted_id = c
             link_el.removeClass("highlighted");
           }
         });
        
          
         // add one to the highlight number to move it to the next id
         if (e.key == "down" && highlighted_id < c)
         {
           highlighted_id = highlighted_id + 1;
           
         }
         else if (e.key == "up" && highlighted_id > 1)
         {
           highlighted_id = highlighted_id - 1;
         }
         
         divname = "result_" + highlighted_id.toString();
         $(divname).getElement('a').addClass('highlighted');
       }
       else if (e.key == "enter"){
         
         // get highlighted text
         $('organisation_name').set('value',$(divname).getElement('a').get('text'));
         resultDiv.setStyle('display','none');
         
         // set submit of form to working again
         $('organisation_search_form').addEvent('submit', function(el){
           $('organisation_search_form').submit();
         });
       }
       else
       {
         // hide the div if there ae no keywords
         resultDiv.setStyle('display','none');
       }
    })
  } 
  
  
  //custom nav expander
  
  $$('li.parent').each(function(element){
   
    hiddenArea = element.getElement('ul');
  	
  	if (hiddenArea){
    	var mySlide = new Fx.Slide(hiddenArea);
    	mySlide.hide()
    	element.addEvent('mouseenter', function(e){
  		  mySlide.slideIn();
  	  });
  	  element.addEvent('mouseleave', function(e){
  		  mySlide.slideOut();
  	  });
    }
  });
  
  $$('.header .search .text').each(function(element){
    element.addEvent('click', function(e){
      element.set('value','');
		  element.addClass('blank');
	  });
  });
  
  // remove text from login boxes when they are clicked on ==================
  if ($$(".email_address")){
    $$(".email_address").each(function(element){
      element.addEvent('focus', function(){
        element.set('value','');
      })
    })
  }
  if ($("password")){
    $("password").addEvent('focus', function(element){
      $("password").set('value','');
    })
  }
  
  // calendar next and previous requests ====================================
  function calendar(){
    $('calendar_previous').addEvent('click', function(element){
      element.stop();
      calendar_request($('calendar_previous').href);
    })

    $('calendar_next').addEvent('click', function(element){
      element.stop(); 
      calendar_request($('calendar_next').href);
    })
  }
  function calendar_request(myURL){
    calendar_wrapper = $('calendar_data');
    var req = new Request.HTML({url: myURL , 
  		onSuccess: function(html) {
  			calendar_wrapper.set('text', '');
  			calendar_wrapper.adopt(html);
  			calendar();
  		}
  	})
  	req.get();
  }
  
  // tags filters based on cookie values ===================================
  if ($("tags")){
		chosen_tags = Cookie.read("sitc_chosen_tags");
    if (chosen_tags){
      chosen_tags.split(',');
      // loop through chosen_tags, checking them if a value was found in the cookie
      $$("#tags input").each(function(element){
        if(chosen_tags.contains(element.get('value'))){
          element.set('checked','true');
        }
      });
   }
  

		
		//select all tags and submit when all_tags is selected and uncheck all_tags when tags unselected
		
		
		
		
		$("all_tags").addEvent('click', function(){
		  
		  // get current choices
		  current_choices = $("tags").toQueryString();
		  
		  //load cookie choices
		  saved_tags = Cookie.read("sitc_saved_tags");
		  
		  if (saved_tags)
		  {
		    // loop through setting check boxes from saved tags
		    saved_tags.split(',');
		    
		    $$("#tags input").each(function(element){
		      element.set('checked',false);
          if(saved_tags.contains(element.get('value'))){
            element.set('checked',true);
          }
        });
		  }
		  else  
		  {
		    // first time so set all tags to checked
	    	$$("#tags input.tags").each(function(element){
  				element.set('checked',true);
  			})
		  }
      
      // save current choices to cookie
	    Cookie.write('sitc_saved_tags', current_choices);
	    
	    // toggle button label
		  if ($("all_tags").value == "Select All")
		  {
		    $("all_tags").value = "My Profile"
				$$("#tags input.tags").each(function(element){
					element.set('checked','true');
				});
		  }
		  else
		  {
		    $("all_tags").value = "Select All"
		  }
		  // added because internet explorer does not send request when check boxes check by js
			 	query = $("tags").toQueryString();
        url = $("tags").getProperty("action");
			$("tags").get('send', { 
        url: url, 
        method: 'get', 
        onFailure: function(){ 
                alert('Could not retrieve data. Please try again.'); 
        }, 
        onSuccess: function(responseText, responseXML){ 
                $("tag_results").set('html', responseText); 
        }
      }).send();
		
		})
		
		//if ($('all_tags').get('checked') == true){
	  //	$$("#tags input.tags").each(function(element){
		//		element.set('checked','true');
		//		element.addEvent('click', function(){
		//			$("all_tags").set('checked', 'false');
		//		});
		//	})
		//}
    
    
    $$("#tags input").each(function(element){
      element.addEvent('click', function(el){
        
        query = $("tags").toQueryString();
        url = $("tags").getProperty("action");
      
        // create new RSS link
        if ($('rss_link'))
        {
          $('rss_link').set('href', url + ".xml?" + query);
        }
        if (query.length > 0)
        {

      	  $("tags").get('send', { 
            url: url, 
            method: 'get', 
            onFailure: function(){ 
                    alert('Could not retrieve data. Please try again.'); 
            }, 
            onSuccess: function(responseText, responseXML){ 
                    $("tag_results").set('html', responseText); 
            }
          }).send();
        }
        else
        {
          element.setProperty("checked", "true");
          alert("You must filter by at least one category.");
        }
      });
    });
  }
  
  if ($("primary_roles")){
    chosen_tags = Cookie.read("sitc_primary_roles");
    if (chosen_tags){
      chosen_tags = unescape(chosen_tags.replace(/\+/g,  " "));
      chosen_tags.split(',');
    
      // loop through chosen_tags, checking them if a value was found in the cookie
      $$("#primary_roles input").each(function(element){
        if(chosen_tags.contains(element.get('value'))){
          element.set('checked','true');
        }
      });
    }
  
    $("primary_roles").addEvent('click', function(el){
      query = $("primary_roles").toQueryString();
      url = $("primary_roles").getProperty("action");
      
      // create new RSS link
      if ($('rss_link'))
      {
        $('rss_link').set('href', url + ".xml?" + query);
      }
      
      var req = new Request.HTML({
        url: url,
        update: "primary_roles_results",
        data: query
    	})
    	req.get();
  	
    });
  }  
  
});
