String.prototype.ltrim = function(charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return this.replace(re, '');
}

String.prototype.rtrim = function(charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('[' + charlist + ']+$', 'g');
    return this.replace(re, '');
}

String.prototype.trim = function(charlist) {
    return this.ltrim(charlist).rtrim(charlist);
}

var Sys = (function() {
	var elFocus = '';
	var inpTxt = [];
	var prevents = {};
	var elDlgShadow = null;
	var elDlgWindow = null;
	var positionDlg = function() {
		elDlgWindow.css({'top': ((elDlgShadow.height() / 2) - (elDlgWindow.height() / 2)) + 'px',
			'left': ((elDlgShadow.width() / 2) - (elDlgWindow.width() / 2)) + 'px'});
	};
	return {
		openMenu: function(id,btn) {
			var sub = $('#sub' + id);
			if (!sub.length)
				return;
			var show = (sub.css('display') == 'none');
			$('.categories .button').filter('.active').removeClass('active');
			$('.categories .sub:visible').hide();
			if (show) {
				$(btn).parent().addClass('active');
				sub.css('display', 'block');
			} else {
				$(btn).parent().removeClass('active');
				sub.css('display', 'none');
			}
		},
		
		setFocus: function(el) {
			elFocus = el;
		},
		
		focusInput: function() {
			var frie = $('.frie:visible');
			var el;
			if (frie.length > 0)
				el = frie.first();
			else if (elFocus.length)
				el = $(elFocus).filter(':visible:enabled').first();
			else
				el = $('input,select,textarea').filter(':visible:enabled').first();
			el.focus();
		},
		
		inputEnable: function(id, txt) {
			var inp = $('#' + id);
			if (inp.length > 0) {
				inpTxt[id] = txt;
				if ((!inp.val().length || inp.val() == txt) && !inp.is(':focus')) {
					inp.val(txt);
					inp.addClass('inactive');
				}
				inp.focus(function() {Sys.inputActive(id);});
				inp.blur(function() {Sys.inputInactive(id);});
			}
		},

		inputActive: function(id) {
			var inp = $('#' + id);
			if (inp.val() == inpTxt[id]) {
				if (!inp.is('select'))
					inp.val('');
				inp.select();
			}
			inp.removeClass('inactive');
		},

		inputInactive: function(id) {
			var inp = $('#' + id);
			if (inp.is('select') && inp.val() == inpTxt[id]) {
				inp.addClass('inactive');
			} if (inp.val() == '') {
				inp.val(inpTxt[id])
				inp.addClass('inactive');
			}
		},

		inputClear: function() {
			var inp;
			for (var i in inpTxt) {
				inp =  $('#' + i);
				if (inp.val() == inpTxt[i])
					inp.val('');
			}
		},
		
		submit: function(form, preventDbl) {
			form = form || 'form';
			if (preventDbl) {
				if (prevents[form])
					return;
				prevents[form] = true;
			}
			Sys.inputClear();
			document.forms[form].submit();
		},
				
		buildUrl: function(u) {
			if (typeof(u) == 'object') {
				var s = u[0];
				if (typeof(u[1]) == 'object') {
					var k;
					var sp = '?';
					for (k in u[1]) {
						s += sp + encodeURIComponent(k) + '=' + encodeURIComponent(u[1][k]);
						sp = '&';
					}
				}
				if (typeof(u[2]) != 'undefined')
					s += '#' + u[2];
				return s;
			}
			return u;
		},
		
		dlgOpen: function(url, width, height) {
			if (elDlgShadow === null) {
				elDlgShadow = $('#dlgShadow');
				elDlgWindow = $('#dlgWindow');
				elDlgShadow.css('opacity', 0.3).click(function() {
					Sys.dlgClose();
				});
				$(window).resize(positionDlg);
			}
			elDlgWindow.html('').css({width: width + 'px', height: height + 'px'});
			$('<iframe></iframe>').attr({frameborder: 0, src: url}).appendTo(elDlgWindow);
			positionDlg();
			elDlgShadow.fadeIn('fast');
			elDlgWindow.fadeIn('fast');
		},
		
		dlgClose: function() {
			var win = window.parent || window;
			$(win.document).find('#dlgWindow').hide();
			$(win.document).find('#dlgShadow').hide();
			$(win.document).find('#dlgWindow').html('');
		},
		
		selectAll: function(name, checked) {
			if (checked)
				$('input[name="'+name+'"]').attr('checked', true);
			else
				$('input[name="'+name+'"]').attr('checked', false);
		},
		
		init: function() {
			$('.addr_zip_code1').keyup(function(e) {
				if ($(this).val().length == 2 && e.which == 109) {
					$(this).next('.addr_zip_code2').first().focus();
				}
			});
			$('.addr_zip_code2').keyup(function(e) {
				if ($(this).val().length == 0 && e.which == 8) {
					$(this).prev('.addr_zip_code1').first().focus();
				}
			});
			Sys.focusInput();
		}
	};
})();

(function($) {
    $.fn.autogrow = function(options) {
        this.filter('textarea').each(function() {
            var $this       = $(this),
                minHeight   = $this.height();
            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(this).width() - parseInt($this.css('paddingLeft')) - parseInt($this.css('paddingRight')),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);
            var update = function() {
                var times = function(string, number) {
                    for (var i = 0, r = ''; i < number; i ++) r += string;
                    return r;
                };
                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n$/, '<br/>&nbsp;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/ {2,}/g, function(space) {return times('&nbsp;', space.length - 1) + ' '});
                
                shadow.html(val);
				var newHeight = shadow.height() + 20;
				if (options['maxHeight'] && newHeight > options['maxHeight'])
					newHeight = options['maxHeight'];
                $(this).css('height', Math.max(newHeight, minHeight));
            
            }
            $(this).change(update).keyup(update).keydown(update);
            update.apply(this);
        });
        return this;
    }
})(jQuery);

jQuery.expr[':'].focus = function(elem) {
	return elem === document.activeElement && (elem.type || elem.href);
};

$(function() {
	Sys.init();
});


// Wiki
var Wiki = (function() {
	var clientPC = navigator.userAgent.toLowerCase();
	var ver = parseInt(navigator.appVersion); 
	var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));

	bbcode = new Array();
	bbtags = new Array('<b>','</b>','<u>','</u>','<i>', '</i>', '<s>','</s>', '<sup>', '<sup/>');

	return {
		setStyle: function(txtarea_id, style) {
			var txtarea = document.getElementById(txtarea_id);
			txtarea.focus();
			donotinsert = false;
			oSelection = false;
			bblast = 0;

			if ((ver >= 4) && is_ie) {
				oSelection = document.selection.createRange().text; 
				if (oSelection) {
					document.selection.createRange().text = bbtags[style] + oSelection + bbtags[style + 1];
					txtarea.focus();
					oSelection = '';
					return;
				}
			} else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
				this.mozWrap(txtarea, bbtags[style], bbtags[style + 1]);
				return;
			}
			this.storeCaret(txtarea);
		},

		mozWrap: function(txtarea, open, close) {
			var selLength = txtarea.textLength;
			var selStart = txtarea.selectionStart;
			var selEnd = txtarea.selectionEnd;
			if (selEnd == 1 || selEnd == 2)
				selEnd = selLength;

			var s1 = (txtarea.value).substring(0,selStart);
			var s2 = (txtarea.value).substring(selStart, selEnd)
			var s3 = (txtarea.value).substring(selEnd, selLength);
			txtarea.value = s1 + open + s2 + close + s3;
			return;
		},

		storeCaret: function(textEl) {
			if (textEl.createTextRange) 
				textEl.caretPos = document.selection.createRange().duplicate();
		}
	};
})();

