// from: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
jQuery.fn.hint = function () {
  return this.each(function (){
    var t = jQuery(this); // get jQuery version of 'this'
	var elem = t.length ? t[0] : t;
    var title = t.attr('title'); // get it once since it won't change
    if (title) { // only apply logic if the element has the attribute
      // on blur, set value to title attr if text is blank
      t.blur(function (){
        if (elem.value == '') {
          elem.value = title;
          t.addClass('blur');
        }
      });
      // on focus, set value to blank if current value matches title attr
      t.focus(function (){
        if (elem.value == title) {
          elem.value = '';
          t.removeClass('blur');
        }
      });
      // now change all inputs to title
      t.blur();
    }
    // remove any values that match the title when the form is submitted
    t.parents('form:first()').submit(function(){
	if (elem.value == title) {
		elem.value;
		t.removeClass('blur');
	}
	});

  });
};

// from: http://www.kaktus.cc/weblog/view/1192629359.html
jQuery.fn.convert_selects = function()
{
    $(this).find('select').each(function()
    {
        var date = new Date();
        
        // Create a list wrapper
        var wrapper = document.createElement('div');
        wrapper.id = this.name + '_wrapper_' + date.getTime();
        $(wrapper).addClass('select wrapper ' + this.name);
        this.parentNode.insertBefore(wrapper, this);
        
        // Store the information for sending the form
        $('<input type="hidden" />')
            .attr('name', this.name)
            .attr('value', this.value)
            .appendTo(wrapper);
        
        // Title to display the selected item
        $('<div></div>')
            .addClass('title')
            .attr('id', this.name + '_title')
            .click(function()
            {
                if ($(this.parentNode).find('ul.selection').css('display') == 'block')
                {
                    $(this.parentNode).find('ul.selection').hide();
                }
                else
                {
                    $(this.parentNode).find('ul.selection').show();
                }
            })
            .appendTo(wrapper);
        
        // Extra wrapper that can be styled
        $('<span></span>')
            .addClass('title')
            .html($(this).find('option:selected(0)').html())
            .appendTo($('#' + wrapper.id + ' div.title'));
        
        // List for wrapping the emulated selection list
        $('<ul></ul>')
            .addClass('selection')
            .css(
            {
                display: 'none',
                position: 'absolute',
                listStyle: 'none',
                zIndex: '1000',
                margin: '0 -1px',
                padding: '1px'
            })
            .appendTo(wrapper);
        
        // Loop through each option in the original select
        $(this).find('option').each(function(i)
        {
            // Create a new list element for each option
            $('<li></li>')
                .html(this.innerHTML)
                .attr('title', this.value)
                .css(
                {
                    display: 'block',
                    padding: '1px 3px'
                })
                .mouseover(function()
                {
                    $(this).addClass('hover');
                })
                .mouseout(function()
                {
                    $(this).removeClass('hover');
                })
                .click(function()
                {
                    // When the list item has been clicked, update the hidden input field
                    $(this.parentNode.parentNode).find("input[@type='hidden']").attr('value', $(this).attr('title'));
                    
                    // Remove select classnames from the selection list
                    $(this.parentNode).find('li').removeClass('selected');
                    
                    // Add the 'selected' class to currently selected list item
                    $(this).addClass('selected');
                    
                    // Change the visible title
                    $(this.parentNode.parentNode).find('div.title span').html(this.innerHTML);
                    $(this.parentNode).hide();
                })
                .appendTo('#' + wrapper.id + ' ul.selection');
            
            // Set the selected class to the selected list item
            if (this.value == this.parentNode.value)
            {
                $(wrapper).find('li.' + this.value).addClass('selected');
            }
        });
        
        // Remove the original select list
        this.parentNode.removeChild(this);
    });
}

// from: http://www.reindel.com/truncate/
jQuery.fn.truncate=function(max,settings){
	settings=jQuery.extend({chars:/\s/,leave:false,trail:[false,"...",""]},settings);
	return this.each(
		function(){
			var _max = max;
			if(!settings.leave||(settings.leave&&jQuery(this).children().length==0)){
				v=jQuery.trim(jQuery(this).text());
				while(_max<v.length){
					c=v.charAt(_max);
					if(c.match(settings.chars)){
						d=v.substring(0,_max)+settings.trail[1];
						jQuery(this).html(d);
						break
					}
					_max--
				}
				if(settings.trail[0]){
					jQuery(this).html("<span>"+d+"</span>").append("<span>"+v+"</span>").find("span:eq(1)").append(settings.trail[2]).css("display","none");
					jQuery("a:eq(0)",this).click(
						function(){
							jQuery(this).parent().css("display","none").parent().find("span:eq(1)").css("display","inline");
							return false
						}
					);
					jQuery("a:eq(1)",this).click(
						function(){
							jQuery(this).parent().css("display","none").parent().find("span:eq(0)").css("display","inline");
							return false
						}
					)
				}
			}
		}
	)
};

/*
 * jQuery Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 1.2
 * Last Modified: 11/21/2007
 * 
 * Copyright 2007 Trent Richardson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
jQuery.extend({	
	ImpromptuDefaults: { prefix:'jqi', buttons:{ Ok:true }, loaded:function(){}, submit:function(){return true;}, callback:function(){}, container:'body', opacity:0.6, overlayspeed:'slow', promptspeed:'fast', show:'show'},
	SetImpromptuDefaults: function(o){ 
		jQuery.ImpromptuDefaults = jQuery.extend({},jQuery.ImpromptuDefaults,o);
	},
	prompt: function(m,o){
		o = jQuery.extend({},jQuery.ImpromptuDefaults,o);
		
		var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);	
		var b = (ie6)? jQuery(document.body):jQuery(o.container);	
		var fade = '<div class="'+ o.prefix +'fade" id="'+ o.prefix +'fade"></div>';
		if((jQuery.browser.msie && jQuery('object, applet').length > 0) || ie6)
			fade = '<iframe src="" class="'+ o.prefix +'fade" id="'+ o.prefix +'fade"></iframe>';
		var msgbox = '<div class="'+ o.prefix +'" id="'+ o.prefix +'"><div class="'+ o.prefix +'container"><div class="'+ o.prefix +'message">'+ m +'</div><div class="'+ o.prefix +'buttons" id="'+ o.prefix +'buttons">';
		jQuery.each(o.buttons,function(k,v){ msgbox += '<button name="'+ o.prefix +'button'+ k +'" id="'+ o.prefix +'button'+ k +'" value="'+ v +'">'+ k +'</button>'}) ;
		msgbox += '</div></div></div>';
		
		var jqi = b.prepend(msgbox).children('#'+ o.prefix);
		var jqif = b.prepend(fade).children('#'+ o.prefix +'fade');
		
		//ie6 calculation functions
		var getfoffset = function(){ return (document.documentElement.scrollTop || document.body.scrollTop) + 'px'; };
		var getjoffset = function(){ return (document.documentElement.scrollTop || document.body.scrollTop) + Math.round(15 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px'; };
		var ie6scroll = function(){ jqif.css({ top: getfoffset() }); jqi.css({ top: getjoffset() }); };
		
		jqif.css({ position: "absolute", height: (ie6)? "100%":b.height(), width: "100%", top: (ie6)? getfoffset():0, left: 0, right: 0, bottom: 0, zIndex: 998, display: "none", opacity: o.opacity });
		jqi.css({ position: (ie6)? "absolute" : "fixed", top: (ie6)? getjoffset():"30%", left: "50%", display: "none", zIndex: 999, marginLeft: ((((jqi.css("paddingLeft").split("px")[0]*1) + jqi.width())/2)*-1) });
			
		jQuery('#'+ o.prefix +'buttons').children('button').click(function(){ 
			var msg = jqi.children('.'+ o.prefix +'container').children('.'+ o.prefix +'message');
			var clicked = o.buttons[jQuery(this).text()];	
			if(o.submit(clicked,msg)){		
				jqi.remove(); 
				if(ie6)jQuery(window).unbind('scroll',ie6scroll);//ie6, remove the scroll event
				jqif.fadeOut(o.overlayspeed,function(){
					jqif.remove();
					o.callback(clicked,msg);
				});
			}
		});
				
		if(ie6) jQuery(window).scroll(ie6scroll);//ie6, add a scroll event to fix position:fixed
		jqif.fadeIn(o.overlayspeed);
		jqi[o.show](o.promptspeed,o.loaded);
		return jqi;
	}	
});
