/**
* 
* Name:		 	setFormFields
* Description: 	setFormFields will autopopulate form fields if it is initialised for the page
* 				will use default values for the parameters if nothing passed
* 				first does a match on input name and then id if no name exists for an input
* Parameters:		ignorefields, ignoretypes
* 				ignorefields - list of names of fields to not autofill e.g. 'address3,first_name'
* 				ignoretypes - list of input types to not autofill e.g. 'hidden,button'
* @author:		CARET
* @version:		1.0
* date:			15 Jan 2010
* example: 	$(document).setFormFields(
* 				{
* 				ignorefields:'as-person',
* 				ignoretypes:'hidden,button,submit'
* 				}
* 			);
* 
* 
* requires: 	jQuery.query - Query String Modification and Creation for jQuery
* 			Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* 			Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* 			Date: 2009/8/13
* 			@author Blair Mitchelmore
* 			@version 2.1.7
* 			
* Used on:	Darwin Project - http://www.darwinproject.ac.uk/advanced-search
* 
**/
jQuery.fn.setFormFields = function (opts){
/* uses jQuery.query plugin 
should be expanded to work with select-multi */
	var ignorefields = opts.ignorefields || "";//comma deliminated list
	var ignoretypes = opts.ignoretypes || "";//comma deliminated list
	var ignoretyp =ignoretypes.split(',');
	var ignorefld =ignorefields.split(',');
	var testtypes = new Array();
	var testfields = new Array();
	if(ignoretyp){
		for(var x in ignoretyp){
			testtypes[ignoretyp[x]] = 1;
		}
	}
	if(ignorefld){
		for(var x in ignorefld){
			testfields[ignorefld[x]] = 1;
		}
	}

 $(':input').each(function(i) {
 	if(!testtypes[$(this).attr('type')]){
 		var name = $(this).attr('name')?$(this).attr('name'): $(this).attr('id');
	 	if(!testfields[name]){
 			if($.query.get(name) !== true && $.query.get(name) ){
 				$(this).attr('value',$.query.get(name));
 			}	
 		}
 	}
 });

}


/**
* 
* Name:		 	setToggler
* Description: 	takes a section of content and hides it and shows more/less option text if you need it
* 				this is a very similar to setFolder but setFolder toggles all children under a parent element
* 				setToggler only toggles the specific element 
* Parameters:	moretext, lesstext, wrapperdiv, linkclass, isbutton
* 				will use default values for the parameters if nothing passed
* @author:		CARET
* @version:		1.0
* date:			15 Jan 2010
* example: 		$('.as-hide').setToggler(
* 					{
* 					moretext: 'Show me more',
* 					lesstext: 'Show me less',
* 					wrapperdiv:"as-hidebox",
* 					linkclass:"as-hidelink"
* 					}
* 				);
* 
* 
* requires: 	
* 			
* Used on:	Darwin Project - http://www.darwinproject.ac.uk/advanced-search
* 
**/

jQuery.fn.setToggler = function (opts){

		var more_text = opts.moretext || "more options...";
		var less_text = opts.lesstext || "hide options...";
		var isbutton = opts.isbutton || "false";
		var placelink = opts.placelink || "";
		var hideme_div = this;
		var wrapperdiv = opts.wrapperdiv || "as-hidebox";
		var linkclass = opts.linkclass || "as-hidelink";

 			$(hideme_div).each(function(i) {
                var content=$(this);
                
                if(isbutton != 'false'){
                	button = document.createElement('input');
                	button.setAttribute("type", "button");
                	button.setAttribute("value", more_text);
                	button.setAttribute("name", "moreinfo");
                	morelink = $(button);
                	morelink.addClass(linkclass);
                }
                else{
                    content.wrap($(document.createElement('div')).addClass(wrapperdiv));
                	morelink = $(document.createElement('a')).addClass(linkclass);
                    morelink.html(more_text);
                }
                
                
                morelink.click(function(i) {
                	
                	if(content.css('display') == "block"){
                		if(isbutton != 'false'){
                    		$(this).val(more_text);                 			
                		}
                		else{
                    		$(this).html(more_text);                			
                		}
                		content.css('display','none');
                	}
                	else{          
                		if(isbutton != 'false'){
                    		$(this).val(less_text);                 			
                		}
                		else{
                    		$(this).html(less_text);
                    	}      
               	 		content.css('display','block');
               	 	}
                });
                
                content.css('display','none');
                
                if(placelink){
                	if(isbutton != 'false'){
                        content.parent().find(placelink).prepend(morelink);
                	}
                	else{
                        content.parent('div').parent().find(placelink).prepend(morelink);
                	}
                }
                else{
                    content.parent('div').prepend(morelink);                	
                }
               
            });

};  

/**
* 
* Name:		 	setFolder
* Description: 	Query function to set specific items to toggle
* 				this is a very similar to setToggler but setToggler toggles only toggles the specific element
* 				and this toggles all children under a parent element
* Parameters:	moreimg, lessimg, showimg, childmarker, contentmarker, contentclass
* 				will use default values for the parameters if nothing passed
* @author:		CARET
* @version:		1.0
* date:			15 Jan 2010
* example: 		$('.folding').setFolder({
* 					moreimg:'/some/img.gif',
* 					lessimg:'/some/other/img.gif',
* 					showimg:true
* 				});
* 
* 
* requires: 	
* 			
* Used on:	Darwin Project - http://www.darwinproject.ac.uk/what-is-in-the-online-database
* 
**/


jQuery.fn.setFolder = function (opts) {
	var self = this;
	var moreimg = opts.moreimg || '/images/stories/expanderbuttonplus.gif';
	var lessimg = opts.lessimg || '/images/stories/expanderbuttonminus.gif';
	var showimg = opts.showimg || false;
	var childmarker = opts.child || 'dt';
	var contentmarker = opts.content || 'dd';
	var contentclass = opts.contentclass || 'foldee';
	
	
	jQuery(self).each(function(i) {
		var content=$(this);
		content.children(childmarker).each(function(i){
			if(showimg == true){
				$(this).prepend($(document.createElement('img')).addClass('setFolderToggle').attr('src',moreimg));
			}
			$(this).click(function(){
				if(showimg == true){
					if($(this).next(contentmarker).css('display') == "block"){
						$(this).children('img.setFolderToggle').attr('src',moreimg);
					}
					else{
						$(this).children('img.setFolderToggle').attr('src',lessimg);
					}
				}
				$(this).next(contentmarker).toggle();
			});
			$(this).next(contentmarker).toggle();
			if(contentclass){
				$(this).next(contentmarker).addClass(contentclass);
			}
		});
	
	});

}




/**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/8/13
 *
 * @author Blair Mitchelmore
 * @version 2.1.7
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");
            
            if (!key) return;
            
            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = val;
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function(url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function(str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object




/* use jQuery instead of $ as something in the audio files in interviews does bad things otherwise */
jQuery(document).ready(function(){
	jQuery('.folding').setFolder(
			{
				showimg:true
			}
	);
});