// rails.js it is in here to reduce requests to the server
jQuery(function ($) {
    var csrf_token = $('meta[name=csrf-token]').attr('content'),
        csrf_param = $('meta[name=csrf-param]').attr('content');

    $.fn.extend({
        /**
         * Triggers a custom event on an element and returns the event result
         * this is used to get around not being able to ensure callbacks are placed
         * at the end of the chain.
         *
         * TODO: deprecate with jQuery 1.4.2 release, in favor of subscribing to our
         *       own events and placing ourselves at the end of the chain.
         */
        triggerAndReturn: function (name, data) {
            var event = new $.Event(name);
            this.trigger(event, data);

            return event.result !== false;
        },

        /**
         * Handles execution of remote calls firing overridable events along the way
         */
        callRemote: function () {
            var el      = this,
                method  = el.attr('method') || el.attr('data-method') || 'GET',
                url     = el.attr('action') || el.attr('href'),
                dataType  = el.attr('data-type')  || 'script';

            if (url === undefined) {
              throw "No URL specified for remote call (action or href must be present).";
            } else {
                if (el.triggerAndReturn('ajax:before')) {
                    var data = el.is('form') ? el.serializeArray() : [];
                    $.ajax({
                        url: url,
                        data: data,
                        dataType: dataType,
                        type: method.toUpperCase(),
                        beforeSend: function (xhr) {
                            el.trigger('ajax:loading', xhr);
                        },
                        success: function (data, status, xhr) {
                            el.trigger('ajax:success', [data, status, xhr]);
                        },
                        complete: function (xhr) {
                            el.trigger('ajax:complete', xhr);
                        },
                        error: function (xhr, status, error) {
                            el.trigger('ajax:failure', [xhr, status, error]);
                        }
                    });
                }

                el.trigger('ajax:after');
            }
        }
    });

    /**
     *  confirmation handler
     */
    $('a[data-confirm],input[data-confirm]').live('click', function () {
        var el = $(this);
        if (el.triggerAndReturn('confirm')) {
            if (!confirm(el.attr('data-confirm'))) {
                return false;
            }
        }
    });


    /**
     * remote handlers
     */
    $('form[data-remote]').live('submit', function (e) {
        $(this).callRemote();
        e.preventDefault();
    });

    $('a[data-remote],input[data-remote]').live('click', function (e) {
        $(this).callRemote();
        e.preventDefault();
    });

    $('a[data-method]:not([data-remote])').live('click', function (e){
        var link = $(this),
            href = link.attr('href'),
            method = link.attr('data-method'),
            form = $('<form method="post" action="'+href+'"></form>'),
            metadata_input = '<input name="_method" value="'+method+'" type="hidden" />';

        if (csrf_param != null && csrf_token != null) {
          metadata_input += '<input name="'+csrf_param+'" value="'+csrf_token+'" type="hidden" />';
        }

        form.hide()
            .append(metadata_input)
            .appendTo('body');

        e.preventDefault();
        form.submit();
    });

    /**
     * disable-with handlers
     */
    var disable_with_input_selector           = 'input[data-disable-with]';
    var disable_with_form_remote_selector     = 'form[data-remote]:has('       + disable_with_input_selector + ')';
    var disable_with_form_not_remote_selector = 'form:not([data-remote]):has(' + disable_with_input_selector + ')';

    var disable_with_input_function = function () {
        $(this).find(disable_with_input_selector).each(function () {
            var input = $(this);
            input.data('enable-with', input.val())
                .attr('value', input.attr('data-disable-with'))
                .attr('disabled', 'disabled');
        });
    };

    $(disable_with_form_remote_selector).live('ajax:before', disable_with_input_function);
    $(disable_with_form_not_remote_selector).live('submit', disable_with_input_function);

    $(disable_with_form_remote_selector).live('ajax:complete', function () {
        $(this).find(disable_with_input_selector).each(function () {
            var input = $(this);
            input.removeAttr('disabled')
                 .val(input.data('enable-with'));
        });
    });

});

// end rails.js 

// For discussion and comments, see: http://remysharp.com/2009/01/07/html5-enabling-script/
(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(',');for(var i=0;i<e.length;i++){document.createElement(e[i])}})()

/*----------------------------------------------------------------------
kehk.js -- Copyright KEHK Inc. 2009

The KEHK library holds high level information about the browser 
environment, loads the skin for the site, and has utility classes used 
by the skin.

Created by Robert Beaupre July 14, 2008
Updated by Robert Beaupre July 14, 2008
----------------------------------------------------------------------*/


if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var KEHK = {};

KEHK.DOM = function () {
	
  return {
    add_stylesheet: function ( path, media ) {
      var stylesheet = document.createElement("link");
      stylesheet.setAttribute("rel", "stylesheet");
      stylesheet.setAttribute("type", "text/css");
      stylesheet.setAttribute("media", media);
      stylesheet.setAttribute("href", path);
	
      if ( typeof stylesheet!=="undefined" ) {
	    document.getElementsByTagName("head")[0].appendChild(stylesheet);
      }
    },
  
    add_javascript: function ( path ) {
      var js = document.createElement("script");
	  js.setAttribute("type", "text/javascript");
	  js.setAttribute("src", path);
	
      if ( typeof js !=="undefined" ){
	    document.getElementsByTagName("head")[0].appendChild(js);
      }
    },
  
    get_element: function ( id ) {
      return document.getElementById(id);
    },
    
	change_class_of_element: function ( element, class_name ) {
	  element.className = class_name;	
	},

	give_id_to_element: function ( element, id ) {
	    element.id = id;
	},
	get_elements_by_class_name: function ( class_name, n ) {
	  if(!n) n = document.getElementsByTagName("body")[0];
	    var a = [];
		var re = new RegExp('\\b' + class_name + '\\b');
		var els = n.getElementsByTagName("*");
		for(var i=0,j=els.length; i<j; i++) {
		  if(re.test(els[i].className)) {
			a.push(els[i]);
		  }
		}
		return a;
	},
	insert_after: function ( referenceNode, newNode )
	{
	    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
	},
	get_inner_element_of_tag_name: function ( el, tag_name ) {
	  if ( el ) {
	    for ( var j = 0; j < el.childNodes.length; j++ ) {
	      if ( el.childNodes[j].tagName === tag_name) {
	        return el.childNodes[j];
		  }
		}
	  }	
	}
  };
}();


KEHK.DOM.Manipulators = function () {
	
  return {
	exchange_element_text_for_image: function ( element_id, src, on_mouse_over, on_mouse_down ) {
	  var mo = "";
	  var md = "";
	  if ( on_mouse_over ) {
		mo = " onmouseover='this.src=\"" + on_mouse_over + "\"' onmouseout='this.src=\"" + src + "\"'";
	  } 
	
	  if ( on_mouse_down ) {
		md = " onmousedown='this.src=\"" + on_mouse_down + "\"' ";
		if ( on_mouse_over ) {
		  md += "onmouseup='this.src=\"" + on_mouse_over + "\"'";
		}
	  }
	
      if ( KEHK.DOM.get_element(element_id) ){
		var alt = KEHK.DOM.get_element(element_id).innerHTML;
		KEHK.DOM.get_element(element_id).innerHTML = "<img src='" + src + "' alt=' " + alt + " ' " + mo + md + " />";
	  }
	}
  };
}();

KEHK.Platform = function () {
  var browsers = ["konqueror", "chrome", "safari", "omniweb", "opera", "webtv", "icab", "msie", "firefox"];
  var oss = ["linux", "x11", "mac", "win"];
  var i;
  
  //public methods will expose these variables
  var _browser = "";
  var _version = "";
  var _os = "";
		
  return {
    detect: function () {
	  var ua = window.navigator.userAgent.toLowerCase();

	  for ( i=0; i<browsers.length; i++ ) {
		if ( _browser === "" ) {
		  if ( ua.indexOf(browsers[i]) + 1 ) {
		    _browser = browsers[i];
		  }
		} 
	  }

	  if ( _browser === "" ) {
		_browser = "unknown";
	  }

	  if ( _browser === "konqueror" ) {
		_os = "linux";
	  }

	  for ( i=0; i<oss.length; i++ ) {
		if ( _os === "" ) {
		  if ( ua.indexOf(oss[i]) + 1 ) {
			_os = oss[i];
		  }
		} 
	  }

	  if ( _os === "" ) {
	    _os = "unknown";
	  }

	  if ( _version === "" ) {
	    if ( ua.indexOf("version") + 1 ) {
		  _version = ua.charAt(ua.indexOf("version") + 1 + "version".length);
	    } else {
		  _version = ua.charAt(ua.indexOf(_browser) + 1 + _browser.length);
	    }
	  }
    },
    
    browser: function () {
	  return _browser;
    },
	
	browser_version: function () {
	  return _version;
	},
	
	os: function () {
	  return _os;	
	}
  };
}();

KEHK.Enhancer = function () {
 
  var skin_name = "mm";
  var skin_version = "01";
  var base_path = "/kehk/";
  var skin_modifier = "_skins";

  function enhancer_path () {
	  return base_path + skin_name + skin_modifier + "/";
   }
	
  return {
    enhance: function () {
	  if ( document.write ) { //make sure we have some basic functionality		
	    //KEHK.DOM.add_stylesheet(base_path + "enhancer.css", "screen, projection");
	    KEHK.DOM.add_stylesheet(enhancer_path() + skin_name + "_" + skin_version + ".css", "screen, projection");
	    KEHK.DOM.add_stylesheet(enhancer_path() + skin_name + "_print_" + skin_version + ".css", 'print');
	    KEHK.DOM.add_javascript(enhancer_path() + skin_name + "_" + skin_version + ".js");

	    KEHK.Platform.detect();
	  
	    KEHK.Url.extract();
	  }
    },

    enhance_when_loaded: function () {
	  KEHK.Loader.set_loaded(true);
    }
  };
}();



KEHK.Url = function () {
  //public methods will expose these variables
  var _protocol = "";
  var _host = "";
  var _path = "";
  var _file_requested = "";

  return {
    extract: function () {
      var slash = '/' 
	  if (location.pathname.match(/\\/)) { 
	    slash = '\\'
      }
	  _protocol        = location.protocol;
	  _host            = location.host;
	  _path            = location.pathname;
	  _file_requested  = location.pathname.substring(location.pathname.lastIndexOf(slash) + 1, location.pathname.length);
    },
    
    protocol: function () {
	  return _protocol;
    },

    host: function () {
	  return _host;
    },

    path: function () {
	  return _path;
    },

    file_requested: function () {
	  return _file_requested;
    }
  };	
}();

KEHK.Environment = function () {
	
  return {
    window_width: function () {
	  var width = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    width = window.innerWidth;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    width = document.documentElement.clientWidth;
	  } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    width = document.body.clientWidth;
	  }
	  return width;
	},

	window_height: function () {
	  var height = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    height = window.innerHeight;
	  } else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    height = document.documentElement.clientHeight;
	  } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    height = document.body.clientHeight;
	  }
	  return height;
	}	
  };
}();

KEHK.Loader = function () {
  var loaded = false;
  return {
	add_load_event: function ( func )  {
      if ( typeof window.onload !== 'function' ) {
        window.onload = func;
      } else {
	    var oldonload = window.onload;
        window.onload = function () {
          if ( oldonload ) {
	        oldonload();
          }
          func();
        }
      }
    },
    set_loaded: function( is_loaded ) {
	  loaded = is_loaded;
    },
    is_loaded: function () {
	  return loaded;
    }
  };
}();

KEHK.MathUtils = function () {

  return {
    is_even: function (number ) {
	  return !(number % 2);
	}	
  };	
}();


KEHK.Appearance = function () {

  return {
    hide: function ( element_id ) {
	if ( KEHK.DOM.get_element ) { 
	  KEHK.DOM.get_element(element_id).style.visibility = 'hidden'; 
	}
	},

	show: function ( element_id ) { 
	  KEHK.DOM.get_element(element).style.visibility = 'visible'; 
	},
	
	no_display: function ( element_id ) { 
	  KEHK.DOM.get_element(element_id).style.display = 'none'; 
	},
	
	display: function ( element_id ) { 
	  KEHK.DOM.getelement(element_).style.display = 'inline'; 
	},
	
	fade_in: function ( element_id ) {
	  var el = KEHK.DOM.get_element(element_id);
	  if ( el ) {
	    if ( el.style.opacity !== undefined ) {
	      el.style.opacity = "0";	
	    }
	    el.style.visibility = "visible";
	    if ( el.style.opacity !== undefined ) {
	      KEHK.Fader.to(1, el, 0.05, 10);	
	    }
	  }
	},
	fade_out: function ( element_id ) {
	  var el = KEHK.DOM.get_element(element_id);
	  if ( el.style.opacity !== undefined ) {
        KEHK.Fader.to(0, el, 0.05, 10);
	  }
	  el.style.visibility = "hidden";
	}
  };	
}();

KEHK.Fader = function () {
	
  return {
	to: function ( desired_opacity, element, step, delay ) {
	  if ( desired_opacity > 1 ) {
	    desired_opacity = 1;
	  }
	  if ( desired_opacity < 0 ) {
	    desired_opacity = 0;
	  }
	  this.fade(desired_opacity, element, step, delay);
	},
	fade: function ( desired_opacity, el, step, delay ) {
	  if ( el.style.opacity < desired_opacity ) {
		el.style.opacity = parseFloat(el.style.opacity) + step;
        window.setTimeout(KEHK.Fader.fade, delay, desired_opacity, el, step, delay);
        //alert(el.style.opacity);
	  }
	  if ( el.style.opacity > desired_opacity ) {
		el.style.opacity = parseFloat(el.style.opacity) - step;
		window.setTimeout(KEHK.Fader.fade, delay, desired_opacity, el, step, delay);
	//	alert(el.style.opacity); 
	  }
	  
	  
	}
  };
}();

KEHK.Appearance.Table = function () {
  var i;

  return {
	alternate_classes_on_rows: function (table, odd_class, even_class ) {
      var t_body = table.tBodies[0];
      if ( t_body ) {
	    for ( i=0; i< t_body.rows.length; i++ ) {
	      if ( KEHK.MathUtils.is_even(i) ) {
	   	    t_body.rows[i].className = even_class;
	      } else {
		    t_body.rows[i].className = odd_class;
		  }
	    }
	  }
    }
  };
}();

KEHK.Appearance.Link = function () {
  var i;

  return {
    highlight: function (highlight_class, parent_highlight_class ) {
      links = document.getElementsByTagName("a");

      for ( i=0; i<links.length; i++ ){
        if ( links[i].pathname === this.path || "/" + links[i].pathname === this.path || (links[i].pathname === "index.html" && this.path === "/") ) {
          links[i].className = highlight_class;
        } 
      }
    }	
  };
}();

KEHK.Scroller = function () {
  return {
	scroll: function ( id_of_element ) {
	  var scroll_element = KEHK.DOM.get_element( id_of_element );
	  if ( scroll_element.childNodes.length > 0 ) {
		for ( var se=scroll_element.childNodes.length - 1; se >= 0; se-- ) {
		  if ( scroll_element.childNodes[se] && scroll_element.childNodes[se].nodeType !== 8 && scroll_element.childNodes[se].nodeType !== 3 ) {
	        scroll_element.childNodes[se].style.marginLeft = '0px';
	      } else { //firefox adds in text nodes for line breaks
		    scroll_element.removeChild(scroll_element.childNodes[se]);
	      }
	    }
	
	    window.setTimeout(function() {KEHK.Scroller.scroll_handler(scroll_element);}, 55);
	  }
	},
	scroll_handler: function ( scroll_element ) {
	  scroll_element.firstChild.style.marginLeft = (parseInt(scroll_element.firstChild.style.marginLeft) - 1) + 'px';
	  
	  if ( parseInt(scroll_element.firstChild.style.marginLeft) < -194 ) {//make this dynamic
		scroll_element.firstChild.style.marginLeft = '0px';
		scroll_element.appendChild(scroll_element.firstChild);
	  }
	  window.setTimeout(function() {KEHK.Scroller.scroll_handler(scroll_element);}, 55);
	}
	
  };
}();

KEHK.Event = function () {
    
  return {  
    add_to_element: function ( element, event_type, func, use_capture ) {
	  if ( element.addEventListener ) {
		element.addEventListener(event_type, func, use_capture);
		return true;
	  } else if ( element.attachEvent ) {
		return element.attachEvent('on' + event_type, func);
	  } else {
		element['on' + event_type] = func;
	  }
	}
  };
}();


KEHK.IETransparentPNGFixer = function () {
  var applyPositioning = true;

  return {
    fix: function ( blank_transparent_gif_location ) {
      var i;

      for ( i = document.all.length - 1, obj = null; (obj = document.all[i]); i-- ) {
	    // background pngs
	    if ( obj.currentStyle.backgroundImage.match(/\.png/i) !== null ) {
	      this.background_image_fix(obj, blank_transparent_gif_location);
	    }
	    // image elements
	    if ( obj.tagName==='IMG' && obj.src.match(/\.png$/i) !== null ) {
	      this.foreground_image_fix(obj, blank_transparent_gif_location);
	    }
	    // apply position to 'active' elements
	    if ( applyPositioning && (obj.tagName==='A' || obj.tagName==='INPUT') && obj.style.position === '' ) {
		  obj.style.position = 'relative';
	    }
      }
    },

	
    background_image_fix: function ( obj, blank_transparent_gif_location ) {
      var mode = 'scale';
	  var bg	= obj.currentStyle.backgroundImage;
	  var src = bg.substring(5,bg.length-2);
	
	  if ( obj.currentStyle.backgroundRepeat === 'no-repeat' ) {
	    mode = 'crop';
	  }
	
	  obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
	  obj.style.backgroundImage = 'url('+blank_transparent_gif_location+')';
    },

    foreground_image_fix: function ( img, blank_transparent_gif_location ) {
      var src = img.src;

	  img.style.width = img.width + "px";
	  img.style.height = img.height + "px";
	  img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
	  img.src = blank_transparent_gif_location;
    }
  };	
}();

KEHK.Validators = function () {
	
  return {
    is_valid_email_address: function ( email_address ) {
	  var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	  if ( filter.test(email_address) ) { 
		return true;
	  } else {
		return false;
	  }
    }	
  }
}();


Array.prototype.swap=function (a, b) {
  var tmp=this[a];
  this[a]=this[b];
  this[b]=tmp;
}

Array.prototype.remove = function (from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

KEHK.Tables = {};
KEHK.Tables.Sortable = function () {
  
  function create_thead(table){
    //make sure there is a thead portion to the table, if not assume the top row is the head row
	if ( table.getElementsByTagName('thead').length == 0 ) {
	  var the = document.createElement('thead');
	  the.appendChild(table.rows[0]);
	  table.insertBefore(the,table.firstChild);
	}	
  }

  function add_sort_functions_to_thead(table){
    if ( table.tHead == null ) {
      table.tHead = table.getElementsByTagName('thead')[0];
    }
    var headrow_cells = table.tHead.rows[0].cells;
    for ( var i=0; i<headrow_cells.length; i++ ) {
	  if ( headrow_cells[i].className != 'ignore_for_sort' ) {
        change_class_of_element(headrow_cells[i], 'sort_none');
        KEHK.Event.add_to_element(headrow_cells[i], 'click', function(e){KEHK.Tables.Sortable.sort_by(this);}, true);
      }
    }
  }

  function clear_previous_sort ( table ) {
    if (table.tHead == null) { 
	  table.tHead = table.getElementsByTagName('thead')[0];
	}
    var headrow_cells = table.tHead.rows[0].cells;
    for ( var i=0; i<headrow_cells.length; i++ ) {
      change_class_of_element(headrow_cells[i], 'sort_none');
    }	
  }

  function reverse_order ( table ) {
    var existing_order = [];
    var t_body = table.tBodies[0];
    for ( var i=0; i< t_body.rows.length; i++ ) {
      existing_order[i] = t_body.rows[i];
    }
    for ( var i=existing_order.length-1; i>=0; i-- ) {
      t_body.appendChild(existing_order[i]);
    }
    delete existing_order;
  }

  function find_sorted_cell_index ( table ) {
    var cell_index = 0;
    if ( table.tHead == null ) {
	  table.tHead = table.getElementsByTagName('thead')[0];
	}
    var headrow_cells = table.tHead.rows[0].cells;
    for ( var i=0; i < headrow_cells.length; i++ ) { 
      if ( headrow_cells[i].className == 'sort_up' ) {
        cell_index = i;
	  }
    }
    return cell_index;	
  }

  function get_data_type_of_column ( table, cell_index ) {
    var the_data = KEHK.Tables.Sortable.get_element_data(table.tBodies[0].rows[0].cells[cell_index]);
    the_type = 'string';
    if ( the_data != '' ) {
      if(the_data.match(/^-?[£$¤]?[\d,.]+%?$/)){
        the_type = 'number';	
      }
    }
    return the_type;
  }
		
  return {
	make_sortable: function (){
	  var tables = document.getElementsByTagName('table');
	  for ( var i=0; i < tables.length; i++ ) {
	    if ( tables[i].className.search(/\bsortable\b/) != -1 ) {
	      create_thead(tables[i]);
		  add_sort_functions_to_thead(tables[i]);
		}
	  }	
	},
	
	sort_by: function ( cell ) {
	  var table = cell.parentNode.parentNode.parentNode;
	  if ( cell.className == 'sort_up' ) {
		change_class_of_element(cell, 'sort_down');
		reverse_order(table);
	  } else if ( cell.className == 'sort_down' ) {
		change_class_of_element(cell, 'sort_up');
		reverse_order(table);
	  } else {
		clear_previous_sort(table);
		change_class_of_element(cell, 'sort_up');
		var cell_index = find_sorted_cell_index(table);
		var type = get_data_type_of_column(table, cell_index);

		if ( type == 'date' ) {
		  KEHK.Tables.Sorters.Quick.do_sort(0, table.tBodies[0].rows.length, KEHK.Comparers.date, table, cell_index);	
		} else if ( type == 'number' ) {
		  KEHK.Tables.Sorters.Quick.do_sort(0, table.tBodies[0].rows.length, KEHK.Comparers.number, table, cell_index);	
		} else { 
		  KEHK.Tables.Sorters.Quick.do_sort(0, table.tBodies[0].rows.length, KEHK.Comparers.string, table, cell_index);
		}	
	  }	
	},
	get_element_data: function ( element ) {
	  var the_data = '';
	  if ( element != null ) {
		the_data = element.innerHTML;
	    if (element.getAttribute("value_override") != null) {
		  the_data = element.getAttribute("value_override");
	    }
	  }
	  return the_data;	
	}
  };
}();

KEHK.Comparers = function () {

  return {
    string: function ( a, b ) {
	  return a < b; 
	},

	number: function ( a, b ) {
	  var aa = parseFloat(a.replace(/[^0-9.-]/g,''));
	  if ( isNaN(aa) ) {
		aa = 0;
	  } 
	  
	  var bb = parseFloat(b.replace(/[^0-9.-]/g,'')); 
	  if ( isNaN(bb) ){
		bb = 0;
	  } 
	  return aa < bb;
	},

	date: function ( a, b ) {
	  var aa = Date.parse(a);
	  var bb = Date.parse(b);

	  return aa < bb;
	}	
  };	
}();

KEHK.Tables.Sorters = {};
KEHK.Tables.Sorters.Quick = function () {
  	
  function partition(begin, end, pivot, compare_function, table, cell_index){
	var t_body = table.tBodies[0];

	var piv = KEHK.Tables.Sortable.get_element_data(t_body.rows[pivot].cells[cell_index]);
	exchange(t_body, pivot, end-1);
	var store = begin;
	var ix;
	for ( ix=begin; ix<end-1; ++ix ) {
      if ( compare_function(KEHK.Tables.Sortable.get_element_data(t_body.rows[ix].cells[cell_index]), piv) ) {
	    exchange(t_body, store, ix);
		++store;
	  }
	}
	exchange(t_body, end-1, store);

	return store;
  }

  function exchange ( t_body, a, b ) {
    if ( a == b+1 ) {
	  t_body.insertBefore(t_body.rows[a], t_body.rows[b]);
    } else if ( b == a+1 ) {
	  t_body.insertBefore(t_body.rows[b], t_body.rows[a]);
    } else {
	  var tmpNode = t_body.replaceChild(t_body.rows[a], t_body.rows[b]);
	  if ( typeof(t_body.rows[a]) != "undefined" ) {
		t_body.insertBefore(tmpNode, t_body.rows[a]);
	  } else {
		t_body.appendChild(tmpNode);
	  }
    }
  }
		
  return {
    do_sort: function (begin, end, compare_function, table, cell_index) {
	  if ( end-1 > begin ) {
	    var pivot = begin + Math.floor(Math.random()*(end-begin));

		pivot = partition(begin, end, pivot, compare_function, table, cell_index);

		do_sort(begin, pivot, compare_function, table, cell_index);
		do_sort(pivot+1, end, compare_function, table, cell_index);
	  }
    }	
  };
}();

KEHK.Tables.Sorters.Bubble = function () {

  return {
  	do_sort: function ( compare_function, table, cell_index ) {
	  var t_body = table.tBodies[0];

	  for ( var i=0; i < t_body.rows.length; i++ ) {
	    for ( var j=0; j < t_body.rows.length - i - 1; j++ ) {
	     if ( compare_function(KEHK.Tables.Sortable.get_element_data(t_body.rows[j].cells[cell_index]), KEHK.Tables.Sortable.get_element_data(t_body.rows[j + 1].cells[cell_index])) ){
	        t_body.insertBefore(t_body.rows[j + 1], t_body.rows[j]);
	  	  }
	  	}
	  }
	}
  };	
}();


KEHK.Strings = function () {
	
  return {
    replace: function ( str, to_replace, replace_with ) {
	  while ( str.indexOf(to_replace) != -1) {
	    str = str.replace(to_replace, replace_with );	
	  }
	  return str;
    }		
  };
}();


function string_to_date_from_xml ( date ) {
  var dt = new Date();

  date_time = date.split('T');
  date_portion = date_time[0].split('-');
  if ( date_time[1] ) {
    time_portion = date_time[1].split(' ')[0].split(':');
  }

  dt.setFullYear(date_portion[0], date_portion[1]-1, date_portion[2]);
  if ( date_time[1] ) {
    dt.setHours(time_portion[0]);
    dt.setMinutes(time_portion[1]);
    dt.setSeconds(0);
  } else {
	dt.setHours(0);
    dt.setMinutes(0);
    dt.setSeconds(0);
  }
  return dt;
}

function checkUncheckAll ( theElement ) {
  var theForm = theElement.form, e = 0;
  for ( e=0; e<theForm.length; e++ ){
    if ( theForm[e].type === 'checkbox' && theForm[e].name !== 'checkall' ) {
	  theForm[e].checked = theElement.checked;
	}
  }
}

function findPos ( obj ) {
  var curleft = curtop = 0;
  if ( obj.offsetParent ) {
    curleft = obj.offsetLeft
	curtop = obj.offsetTop
	while ( obj = obj.offsetParent ) {
	  curleft += obj.offsetLeft
	  curtop += obj.offsetTop
	}
  }
  return [curleft,curtop];
}

function findPosX ( obj ){
  var curleft = 0;
  if ( obj.offsetParent ) {
    while ( 1 ) {
      curleft += obj.offsetLeft;
      if ( !obj.offsetParent ) {
          break;
      }
      obj = obj.offsetParent;
    }
  } else if ( obj.x ) {
    curleft += obj.x;
  }
  return curleft;
}

function findPosY ( obj ) {
  var curtop = 0;
  if ( obj.offsetParent ) {
    while ( 1 ) {
      curtop += obj.offsetTop;
      if ( !obj.offsetParent ) {
        break;
      }
      obj = obj.offsetParent;
    }
  } else if ( obj.y ) {
    curtop += obj.y;
  }
  return curtop;
}


function change_class_of_element(element, class_name){
  element.className = class_name;	
}

function give_id_to_element(element, id){
  if(!element.id){
    element.id = id;
  }	
}

KEHK.Enhancer.enhance();
KEHK.Loader.add_load_event(KEHK.Enhancer.enhance_when_loaded);
