// AT WINDOW LOAD ------------------------------

	window.onload =(function() {
	  $('textarea.AutoGrow').autogrow();
	  $('.AutoGrow textarea').autogrow();
	}); // END Window Load
	

// AT PAGE LOAD ------------------------------

	$(function () {


	    // hack to add class to ActionBar
	    $('#ActionBarButtons .InnerDiv').addClass('ClearFix');

	    // fix scroll bar in Firefox	
	    if ($.browser.mozilla) { $('body').css('overflow-y', 'scroll') };

	    // PREVENT EDIT PAGES TO USE ENTER KEY TO SUBMIT THE FORM
	    $('body.EditObject #Col2 input, body.EditObject #Col2 select, body.EditObject #Col3 input, body.EditObject #Col3 select').bind('keydown', function (e) {
	        var $key = e.keyCode || e.which;
	        if ($key == 13) { return false }
	    });

	    // CUSTOM DROPDOWN <SELECT> REPLACEMENTS
	    $('.MakeCustomDropdown select').each(function () { $(this).VSDropdown() });
	    $('.CustomDropdown').VSDropdown();
		$('.VSCustomDropdown').show();

	    // TABLE ENHANCEMENTS
	    $('table.list tr').each(function () {
	        $(this).find('td:first').addClass('First');
	        $(this).find('td:last').addClass('Last');
	    });


	    // APPY MASKED INPUT TO PHONE INPUTS 319-721-7236
	    //	 $("#date").mask("99/99/9999");
	    //	 $("#phone").mask("(999) 999-9999");
	    //	 $("#tin").mask("99-9999999");
	    //	 $("#ssn").mask("999-99-9999");
	    $(".PhoneMasked input, input.PhoneMasked").mask("999-999-9999");
	    $(".ZipMasked input, input.ZipMasked").mask("99999");
				
	    /* 
	    The Following Masks are allowed:
	    * a - Represents an alpha character (A-Z,a-z)
	    * 9 - Represents a numeric character (0-9)
	    * * - Represents an alphanumeric character (A-Z,a-z,0-9)
	
	    Optionally, if you are not satisfied with the underscore ('_') character as a placeholder, you may pass an optional argument to the maskedinput method.
	    $("#product").mask("99/99/9999",{placeholder:" "});

	    You can now supply your own mask definitions.
	    $.mask.definitions['~']='[+-]';
	    $("#eyescript").mask("~9.99 ~9.99 999");
	    */

	    // FORCE NUMBERS ONLY
	    $('input.ForceNumbers').live('keydown', function (e) {
	        var key = e.charCode || e.keyCode || 0;
	        // allow backspace, tab, delete, decimals, arrows, numbers and keypad numbers ONLY
	        return (
			key == 8 ||
			key == 9 ||
			key == 46 ||
			key == 190 ||
			key == 110 ||
			(key >= 37 && key <= 40) ||
			(key >= 48 && key <= 57) ||
			(key >= 96 && key <= 105));
	    });

	    // SIMPLE/ADVANCED SEARCH SLIDETOGGLE ---------------------------------------------------------------------------------
	    $('.AdminSearch .ToggleSearch').live('click', function () {
	        $(this).toggleClass('More');
	        $(this).closest('.AdminSearch').find('.SearchForm').slideToggle();
	    });

	    // MODULESEARCH DROPDOWN -----------------------------------------------------
	    $('.AdminSearch .ToggleSearch').hover(function () { $(this).addClass('Hovered') }, function () { $(this).removeClass('Hovered') });

	    // USER PROFILE DROPDOWN -----------------------------------------------------
	    $('#UserInfo .UsernameLink, #UserInfo .UserOptionTrigger').bind('click', function () {
	        var $c = $('#UserInfo'),
			$l = $c.find('.UsernameLink'),
			$dd = $c.find('.UserOptionLinks');
	        $dd.show();
	        $l.blur().addClass('selected');
	        $c.bind('mouseleave', function () {
	            $dd.hide();
	            $l.removeClass('selected');
	        });
	    });

	    // ADMIN GLOBAL SEARCH DROPDOWN -----------------------------------------------------

		$('#AdminSearchField').val( $('#AdminSearchOptions a.Active').text() );
	    $('#AdminSearch').hover(
		function () {
		    if ($(this).is(':animated')) { $(this).stop() }
		    var $h = $('#AdminSearchOptions').outerHeight() + 26;
		    $(this)
				.addClass('Hovered')
				.animate({ height: $h }, 100, function () { });
		    $('#AdminSearchOptions').fadeIn(100);
		},
		function () {
		    if ($(this).is(':animated')) { $(this).stop() }
		    $(this).animate({ height: 25 }, 100, function () { $('#AdminSearchOptions').hide(); $(this).removeClass('Hovered') })
		}
	);
	    $('#AdminSearchType').val($('#AdminSearchField').val());
	    $('#AdminSearchField')
		.live('click', function () { $(this).select() })
		.live('blur', function () { if ($.trim($(this).val()) == '') { $(this).val($('#AdminSearchType').val()) } })
        .keypress(function (e) {
            if (e.which == 13) {
                e.preventDefault();
                $(this).blur();
                $('#AdminSearchButton').focus().click();
            }
        });
	    $('#AdminSearchOptions a').live('click', function () {
	        var $t = $(this),
			$txt = $t.html(),
			$m = $t.data('admin-module-id'),
			$i = $('#AdminSearchField'),
			reg = new RegExp('^search for.*');
	        $('#AdminSearchType').val($txt);
	        if (reg.test($i.val().toLowerCase())) { $('#AdminSearchField').val($txt).select() }
	        else { $('#AdminSearchField').select() }
	        $('#AdminModuleID').val($m);
	        $t.addClass('Active').siblings().removeClass('Active');
	    });

	    // ACTIONBAR ------------------------------------------------------------------------------

		// resize action bar if window sized smaller than viewable area
			var	bar = $('#ActionBarButtons .InnerDiv'),
				subLinks = bar.find('.LeftSide>ul>li:not(:first)'),
				wdths = bar.find('.LeftSide').getOuterWidth() + bar.find('.RightSide').getOuterWidth();
			// copy actionbar links to a new li in the actionbar - it'll show when the screen is tiny and popup the links	
				bar.find('.LeftSide>ul').append('<li class="LinkPopup"><a href="javascript:;"><span>Options</span></a><ul></ul></li>');
				bar.find('.LinkPopup').find('ul').append(subLinks.clone());
				subLinks.addClass('ActionButtons');
						
			$('#ActionBarButtons ul li ul').each(function () {
				$(this).css('margin-top', -( $(this).outerHeight() + $(this).closest('li').outerHeight() - 2));
			});
			
			ActionBarResize();  // on page load, check actionbar size
			
			$(window).resize(function() { // on window resize, check actionbar size
				ActionBarResize();
			});
		
		function ActionBarResize(){
			var w = $(window).width(),
				bar = $('#ActionBarButtons .InnerDiv');	
			if (w < 1000){
				bar.addClass('AutoWidth');
				// if left and right links in actionbar are too big to fit together, hide left and show option popup
				if ( wdths > w ){ bar.addClass('ShrinkButtons') } 
				else{ bar.removeClass('ShrinkButtons') }
			}
			else{ bar.removeClass('AutoWidth ShrinkButtons') }
		}
	
	    $('#ActionBarButtons ul li, #ActionBarButtons ul li #AcceptedDate').hover(function () { $(this).addClass('Hover') }, function () { $(this).removeClass('Hover') });

		// CONTROL THE DATE SETTINGS BOX POPUP
	    $('#ActionBarButtons .DateSettings, #ActionBarPopups a.CloseBox').live('click', function () {
	        var $box = $('.PopupBox'),
				$c = $box.find('.ActionBarContentArea'),
				$h = $c.outerHeight() + 10;
	        if (parseInt($box.css('margin-top')) < 0) { $box.animate({ marginTop: 0 }) }
	        else { $box.animate({ marginTop: -$h }) }
	    });
	    $('.ActionBarContentArea input, .ActionBarContentArea select').live('change', function () {
	        var $box = $(this).closest('.PopupBox'),
			$c = $box.find('.ActionBarContentArea'),
			$h = $c.outerHeight() + 10;
	        $box.animate({ marginTop: -$h });
	    });

	    // RESIZE THE PREVIEW IMAGE IF IT's BIGGER THAN 500 PIXELS WIDE	
	    if ($('.PreviewImage').length) {
	        var $img = $('.PreviewImage'),
			$w = $img.width(),
			$h = $img.height(),
			$nh = $w / 500;

	        if ($w > 500) {
	            $img.width(500).height($h / $nh)
	            $img.after('<div>This image preview has been resized to fit in this page.  Actual file was not resized.</div>');
	        }
	    }

		$('.InlineLabels .MagicLabelWidth').each(function(){
			var maxW = 0,
				maxOuter = 0,
				$t = $(this),
				$labels = $t.find('label').filter(function(){ return $(this).closest('fieldset.CheckRadio').size()==0 }).add( $t.find('.CheckRadio legend') );
				
			$labels.each(function(){
				var $l = $(this).css('width','auto'),
					w = $l.width();
				maxW = w > maxW ? w : maxW;
			});
			
			$labels.width(maxW);
			$t.find('.Indent').css('marginLeft',$labels.outerWidth());
			$t.find('.RadioButtonListContainer, .CheckBoxListContainer').css('marginLeft',$labels.outerWidth());
		});
	
		$('.RadioInputField').bind('click blur focus',function(){ $(this).siblings('input').attr('checked',true); });

	});

// FUNCTIONS -------------------------------------------------------------------------------------------

// --- AUTOGROWING TEXTAREAS ---

/* LICENSED UNDER THE LESSER GNU PUBLIC LICENSE */
/* http://code.google.com/p/gaequery/ */
(function($) {
	$.fn.autogrow = function(options) {
		this.filter('textarea').each(function() {
			var $this       = $(this),
				minHeight   = $this.height(),
				lineHeight  = $this.css('lineHeight');
			var shadow = $('<div></div>').css({
					position:   'absolute',
					top:        -10000,
					left:       -10000,
					width:      $(this).width(),
					fontSize:   $this.css('fontSize'),
					lineHeight: $this.css('lineHeight'),
					resize:     'none'
				}).appendTo(document.body);
			var update = function() {
				var val = this.value.replace(/</g, '&lt;')
									.replace(/>/g, '&gt;')
									.replace(/&/g, '&amp;')
									.replace(/\n/g, '<br/>');
				shadow.html(val);
				$(this).css('height', Math.max(shadow.height() + 20, minHeight));
			}
			$(this).change(update).keyup(update).keydown(update);
			update.apply(this);
		});
		return this;
	}
})(jQuery);



// --- CROP URL --- crop url down from [~/home/abc/lmn/qrs/xyz] to [~/home/abc/.../xyz] depending on the parent element size
$.fn.fitUrl = function(){
	var $t = $(this),
		$s = $t.siblings(),
		$w = $t.width(),
		$pw = $t.parent().width(),
		$url = $t.html(),
		$c = 0,
		$sw = 0;
	$s.each(function(){
		$sw += $(this).width();
	 });
	if ( $w+$sw > $pw ){
		do  {
			var $sp = ($url.indexOf('/.../')>0) ? findStrPos($url,'/',1) :  $url.indexOf('/',1),
				$np = $url.indexOf('/',$sp+1),
				$repl = $url.slice( $sp , $np ),
				$dots = ( $c == 0 ) ? $dots = '/...' : $dots = '';
			$url = $url.replace($repl,$dots)
			$t.html( $url );
			$w = $t.width();
		// to help prevent infinite loop in case of an error
			$c += 1;
			if ( $c > 50 ) { return false; }
		} while ( $w+$sw > $pw )
	}
};

function findStrPos(str, char, count){
	var $c = 0,
		$pos = 0;
	if ($c < count ) {
		while( $c <= count ){
			$pos = str.indexOf(char, $pos+1)
			$c+=1;
		}
	}
	return($pos)
}

function trimStart(str, char){
	if (str.substring(0, 1) == char){ return str.substring(1) }
	return str;
}

function trimEnd(str, char){
	if (str.substring(str.length - 1) == char){ return str.substring(0, str.length - 2) }
	return str;
}

function cleanUrlFn(str){
	// replace spaces with a hyphen
	var ret = str.replace(/\s/g, '-');
	// replace any special characters with ''
	return ret.replace(/[^\w-]/g, '');
}

// ------> Function: Get the outSide Width including padding and margins...
// use $('div').getOuterWidth()
$.fn.getOuterWidth = function () {
    var $t = $(this),  pl = parseInt($t.css('padding-left')) || 0, pr = parseInt($t.css('padding-right')) || 0, mr = parseInt($t.css('margin-right')) || 0, ml = parseInt($t.css('margin-left')) || 0, br = parseInt($t.css('borderRightWidth')) || 0, bl = parseInt($t.css('borderLeftWidth')) || 0,
        w = $t.width() + pl + pr + mr + ml + br + bl;
    return w;
};

// ------> Function: Get the outSide Height including padding and margins...
$.fn.getOuterHeight = function(){
    var $t = $(this), pt = parseInt($t.css('padding-top')) || 0, pb = parseInt($t.css('padding-bottom')) || 0, mt = parseInt($t.css('margin-top')) || 0, mb = parseInt($t.css('margin-bottom')) || 0, bt = parseInt($t.css('borderTopWidth')) || 0, bb = parseInt($t.css('borderBottomWidth')) || 0,
        h = $t.height() + pt + pb + mt + mb + bt + bb;
    return h;
}

/* Copyright 2011, Ben Lin (http://dreamerslab.com/)
* Licensed under the MIT License (LICENSE.txt).
*
* Version: 1.0.3
*
* Requires: jQuery 1.2.3+
*/
;(function(a){a.fn.extend({actual:function(b,k){var c,d,h,g,f,j,e,i;if(!this[b]){throw'$.actual => The jQuery method "'+b+'" you called does not exist'}h=a.extend({absolute:false,clone:false},k);d=this;if(h.clone===true){e=function(){d=d.filter(":first").clone().css({position:"absolute",top:-1000}).appendTo("body")};i=function(){d.remove()}}else{e=function(){c=d.parents().andSelf().filter(":hidden");g=h.absolute===true?{position:"absolute",visibility:"hidden",display:"block"}:{visibility:"hidden",display:"block"};f=[];c.each(function(){var m={},l;for(l in g){m[l]=this.style[l];this.style[l]=g[l]}f.push(m)})};i=function(){c.each(function(m){var n=f[m],l;for(l in g){this.style[l]=n[l]}})}}e();j=d[b]();i();return j}})})(jQuery);


$(function(){
	
$('.CleanUrl')
	.live('keypress',function(e){
		var ignore = [8,9,20,33,34,35,36,37,38,39,40,45,46] // array : backspace and arrow key codes
		var charCode = e.keyCode || e.which;
		var charStr = String.fromCharCode(charCode);
		if ( $.inArray(charCode,ignore)<0 ){
			if(/[a-zA-Z\d\-]/i.test(charStr)){ return charStr }
			else if(charCode==32){}
			else{ return false }
		}
	})
	.live('blur',function(e){ $(this).val(cleanUrlFn($(this).val())) });

$('.LowerCase').live('blur',function(e){ $(this).val( $(this).val().toLowerCase() ) });
});

