    // Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


// Marks all the items as selected for the submit button.  
function selectList(sourceList) {
    sourceList = window.document.forms[0].parentList;
    for(var i = 0; i < sourceList.options.length; i++) {
        if (sourceList.options[i] != null)
        sourceList.options[i].selected = true;
    }
    return true;
}

// Deletes the selected items of supplied list.
function deleteSelectedItemsFromList(sourceList) {
    var maxCnt = sourceList.options.length;
    for(var i = maxCnt - 1; i >= 0; i--) {
        if ((sourceList.options[i] != null) && 
            (sourceList.options[i].selected == true)) {
            sourceList.options[i] = null;
        }
    }
    $(sourceList).focus();
}
function deleteOption(theSel, theIndex)
{ 
  var selLength = theSel.length;
  if(selLength>0)
  {
    theSel.options[theIndex] = null;
  }
}


function copyAvailableToSelected(fromList,toList,selectWhenFinished) {
    for ( i=0; i<fromList.length ; i++){
        if (fromList.options[i].selected == true ) {
            toList.options[toList.length]= new Option(fromList.options[i].text,
               fromList.options[i].value,null,true );
        }
    }
    if( selectWhenFinished ){
      selectAllOptions(selectWhenFinished);
    }
    $(toList).focus();
}
function moveAvailableToSelected(fromList,toList,selectWhenFinished) {
    for ( i=0; i<toList.length; i++)
    {
        if(toList.options[i].value == "")
            toList.options[i] = null;
    }
    for ( i=0; i<fromList.length ; i++){
        if (fromList.options[i].selected == true ) {
          found = false
          for ( j=0; j<toList.length ; j++){
            if (fromList.options[i] == toList.options[j]){
              found = true
            }
          }
          if ( !found ) {
            toList.options[toList.length]= new Option(fromList.options[i].text, fromList.options[i].value,null,true );
          }
        }
    }
    deleteSelectedItemsFromList(fromList);
    if( selectWhenFinished ){
      selectAllOptions(selectWhenFinished);
    }
}
function selectAllOptions(list) {
    for (var i=0; i<list.length ; i++){
        list.options[i].selected = true;
    }
    return true;
}

function selectAllMultipleByClass(classname)
{
  $$(classname).each(selectAllOptions)
}
// shows the survey page when the user clicks on the corresponding tab.
//
// assumes the div id is of the form: survey_page_##
// assumes the class for the tab is current or not_current
// requires prototype.js
	function setSurveyTabCurrent(name,total_pages,tab_id) {
      var tabs = $(tab_id);
      total_pages.times(function(page_num){
        var page = $('survey_page_' + (page_num+1));
        Element.hide(page);
        var tab = $(tab_id + '_' + (page_num+1));	
        });
      var current_page = $('survey_page_'+name);
      Element.show(current_page);
      var current_tab = $(tab_id + '_' + (name));
        current_tab.className = 'selected';
  }

// see app/helpers/welcome_helper.rb for calling from rails/ruby
function link_to_google_map(latitude,longitude,info_html,div,zoom,controls) {
  if (GBrowserIsCompatible()) { 
    GUnload();
    var point = new GLatLng(latitude, longitude); 
    var map = new GMap2(document.getElementById(div)); 
    map.setCenter(point, zoom); 
    if(info_html != ''){
      map.openInfoWindowHtml(point,info_html);
    }
    if( controls ) {
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
    }
  }
}

function slide_show(){
  setTimeout(new Effect.MoveBy('imageBoxInside',0,-300,{duration: 0.3,  transition: Effect.Transitions.slowstop}),50)
}
//    start_slideshow(1, 4, 2000);
    
function start_slideshow_mv(start_frame, end_frame, delay) {
  setTimeout(switch_slides_mv(start_frame,start_frame,end_frame, delay), delay);
}
                            
function switch_slides_mv(frame, start_frame, end_frame, delay) {
  return (function() {
    //Effect.Fade('slideshow' + frame);
    if (frame >= end_frame) { 
      new Effect.MoveBy('imageBoxInside',0,(300*end_frame),{duration: 0,  transition: Effect.Transitions.slowstop})
      frame = start_frame; 
    } else { 
      new Effect.MoveBy('imageBoxInside',0,-300,{duration: 4,  transition: Effect.Transitions.slowstop})
      frame = frame + 1; 
    }
    //setTimeout("Effect.Appear('slideshow" + frame + "');", 850);
    setTimeout(switch_slides_mv(frame, start_frame, end_frame, delay), delay + 850);
  })
}

function start_slideshow(start_frame, end_frame, delay) {
  setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay);
}
                            
function switch_slides(frame, start_frame, end_frame, delay) {
  return (function() {
    Effect.Fade('slideshow' + frame);
    if (frame == end_frame) { frame = start_frame; } else { frame = frame + 1; }
    setTimeout("Effect.Appear('slideshow" + frame + "');", 850);
    setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay + 850);
  })
}
    // observing the window.onload event and doing stuff!
Event.observe(window, 'load', function() {
        var e = $A(document.getElementsByTagName('*')).find(function(e) {
        return (e.tagName.toUpperCase() == 'INPUT' && (e.type == 'text' || e.type == 'password'))
              || e.tagName.toUpperCase() == 'TEXTAREA' || e.tagName.toUpperCase() == 'SELECT';
        });
        if (e) e.focus();
        //Nifty("div.rounded_info_box","big transparent");
        //Nifty("div.rounded_survey_box","big transparent tl bl");
        //Nifty("div.SectionTextQ","big transparent tl bl");
});
 // inserting form fields on the fly
var counter = 0;

function moreFields() {
	counter++;
	var newFields = $('readroot').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	for (var i=0;i<newField.length;i++) {
		var theName = newField[i].name
		if (theName)
			newField[i].name = theName + counter;
	}
	var insertHere = $('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}
// window.onload = moreFields;
// check/uncheck all form checkboxes
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
  for (i = 0; i < field.length; i++) {
  field[i].checked = true;}
  checkflag = "true";
  return "Uncheck all"; }
else {
  for (i = 0; i < field.length; i++) {
  field[i].checked = false; }
  checkflag = "false";
  return "Check all"; }
}
Event.observe(window, 'load', function() {
    if($('noticeExplanation') && $('noticeMessage').innerHTML != "")
    Effect.Fade('noticeExplanation', {delay: 5.0, duration: 3.0});
});

// Enforces that atleast 1 radio input is selected
//
// used in app/views/reports/templates.html.haml
function ensure_radio_selected() {
  var group_checked = false; 
  $$("input[type='radio'][name='template_list']").each(function (obj) { 
    if(obj.checked) {group_checked = true; }
  }); 
  if(!group_checked) {
    alert("Please select a template first."); 
  } 
  return group_checked;
}

function select_csv_template(obj, selection_name)
{
 template_name = obj.options[obj.selectedIndex].value
 Form.getInputs('export_csv_fields','checkbox', selection_name).each(function (obj) {
   obj.checked = false;
   if( template_name == "all" || (csv_templates[template_name] && csv_templates[template_name][obj.value]) ) {
      obj.checked = true;  
    }
 })
}

var csv_templates = {}

function add_csv_template(key, value)
{
  csv_templates[key] = value
}

function init_csv_templates(json_object)
{
  csv_templates = json_object
}

function moveUpSelectedItemsFromList(sourceList) {
    var maxCnt = sourceList.options.length;
    for(var i = maxCnt - 1; i >= 0; i--) {
        if ((sourceList.options[i] != null) && 
            (sourceList.options[i].selected == true)) {
            sourceList.options[i] = null;
        }
    }
}

// Found the up/down code at:
//
// WWW: http://www.mattkruse.com/
// Author: Matt Kruse <matt@mattkruse.com>
//

function moveOptionUp(obj){
  if(!hasOptions(obj)){return;}
  for(i=0;i<obj.options.length;i++){
    if(obj.options[i].selected){
      if(i != 0 && !obj.options[i-1].selected){
        swapOptions(obj,i,i-1);
        obj.options[i-1].selected = true;
      }
    }
  }
}

function moveOptionDown(obj){
  if(!hasOptions(obj)){return;}
  for(i=obj.options.length-1; i >= 0; i--){
    if(obj.options[i].selected){
      if(i !=(obj.options.length-1) && ! obj.options[i+1].selected){
        swapOptions(obj,i ,i+1);
        obj.options[i+1].selected = true;
      }
    }
  }
}

function hasOptions(obj){
  if(obj!=null && obj.options!=null){ return true; }
  return false;
}

function swapOptions(obj,i,j){
  var o = obj.options;
  var i_selected = o[i].selected;
  var j_selected = o[j].selected;
  var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
  var temp2 = new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
  
  o[i] = temp2;
  o[j] = temp;
  o[i].selected = j_selected;
  o[j].selected = i_selected;
}

function sortSelect(obj){
  var o = new Array();
  if(!hasOptions(obj)){
    return;
  }
  for(var i=0;i<obj.options.length ;i++){
    o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
  }
  if(o.length==0){return;}
  
  o = o.sort( function(a,b){
      if((a.text+"") <(b.text+"")){return -1;}
      if((a.text+"") >(b.text+"")){return 1;}
      return 0;
      });
  for(var i=0;i<o.length;i++){
    obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected , o[i].selected);
  }
}


// used in report filters viewing tab
function   check_all_select(selector, msg_flash) { set_checked_all(selector, true,  msg_flash); }
function uncheck_all_select(selector, msg_flash) { set_checked_all(selector, false, msg_flash); }

function set_checked_all(selector, value, msg_flash)
{
  var match = $$(selector);
  match.each(function(e) {e.checked = value;});
  
  var mark_text = value ? "Selected " : "Unselected "
  $(msg_flash).innerHTML = mark_text + match.size() + " styles.";
  $(msg_flash).show();
  Effect.Fade(msg_flash, {delay: 3});
}


/* grouping 3 stage multiselect */
/* arguments (via object literal): 
   options:   a list of option elements who's values contain a JSON array
   gutter_id: a hidden select name with the complete list of available ungrouped options.
   target_id: destination select name which the values matched in gutter_id's options via the JSON array will be placed into.

   ex: passed in options each has a value like [1,2,3] and [1,4,5], code will search gutter_id's option values for 1,2,3,4,5 and
       place them in the target_id's options.

/* This started out as a hide/show logic but changed to a hidden multiselect with cloneNode because IE6/7 cant hide options! */
function multiselect_show_only(incoming_args)
{
  /* defaults */
  args = { select_all:true }

  /* merge incoming with default, override default */
  for (var argName in incoming_args) {
    args[argName] = incoming_args[argName];
  }

  /* deselect all, hide all */
  $A($(args.target_id).options).each(function(option)
  {
    $(args.target_id).removeChild(option);
  });

  /* Iterate groupers, Iterate their groupees and show/select them */
  /* v2 could shorten to 1 loop, by making the css selector dynamic and search w/o the 'value' tag for 'all' */
  var selected_groupers = $A(args.options).select(function(e){return e.selected})
  var processed_groupees = {};
  selected_groupers.each(function(grouper)
  {
    var groupees = eval(grouper.value);
    if(groupees == "all")
    {
      $A($(args.gutter_id).options).each(function(option)
      {
        if(processed_groupees[option.value] == undefined)
        {
          var cloned_option = $(args.target_id).appendChild(option.cloneNode(true));
          if(args.select_all == true) {
            cloned_option.selected = true;
          }
          processed_groupees[option.value] = true;
        }
      });      
    }
    else
    {
      groupees.each(function(groupee)
      {
        var css_selector = "#"+args.gutter_id+" option[value="+groupee+"]"
        var option = $$(css_selector)[0]
        if(option != undefined)
        {
          /* dont add them if already added */
          if(processed_groupees[option.value] == undefined)
          {
            var cloned_option = $(args.target_id).appendChild(option.cloneNode(true));
            if(args.select_all == true) {
              cloned_option.selected = true;
            }
            processed_groupees[option.value] = true;
          }
        }
      });
    }
  });
};


// application template
document.observe("dom:loaded", function() {
  $('nav_search_box').hide();
  $('nav_search').removeClassName('clicked');
  $('nav_search').observe( 'click', reveal_search_box );
});

function reveal_search_box(){
  $('nav_search_box').toggle();
  $('nav_search').toggleClassName('clicked');
}
