function limitChars(textid, limit, infodiv) {
 	var text = $('#'+textid).val(); 
	//newlines are counted as 2 characters in the ruby activerecord validations
	var textlength = text.length + countNewline(text);

 	if(textlength > limit) {
		$('#' + infodiv).html('You cannot write more than '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}
	else {
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}

function countNewline(text) {
	var newLines = 0
	for (i=0; i<=text.length-1; i++) {
    	if (text.charAt(i) == '\n') {
			newLines++
		}
  	}
	return newLines
}

function feedback() {
  var msg = $('#feedbackmessage').val();
  if (msg) {
    $('#feedbackstatus').html('Sending...');
    $('#feedbackbutton').attr('disabled', 'disabled').addClass('disabled').removeClass('default').blur();
    $.ajax({type: "POST", url: "/send-feedback", data: {message:msg, email: $('#feedbackemail').val()},
            error: function(x,ts,et) {
              $('#feedbackstatus').html("Whoops! We're experiencing some technical hiccups. If you're not too frustrated by this, please e-mail us at customerservice@limos.com instead.");
            },
            success: function(d,t) {
              $('#feedbackstatus').html('Thanks for taking the time to write!');
            }
    });
  }
}

// http://www.netlobo.com/url_query_string_javascript.html
function gup(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return results[1];
}

function jAlert(message,title,callback) {
  $("<div>"+message+"</div>").alert(title,callback);	
}

jQuery.fn.extend({
  // TODO: Also make an extension for 'confirm'
  alert: function(title,callback,width,height) {
	text = this.html();
	t = ( title ? title : 'Alert');
	w = ( width ? width : 500 );
	h = ( height ? height : 200 );

	// can add some more cool styling to this block later
	ablock = "<div>"+text+"</div>"
    $(ablock).dialog({
	  title:t,
	  bgiframe:true,
	  modal:true, 
	  buttons: {Ok: function() {
	    $(this).dialog('close');
	    if( jQuery.isFunction(callback) ) {
		 callback.call();
	    }
	  }}, 
	  dialogClass: 'alert', 
	  width:w, 
	  height:h
	});
  }
});



function addErrMsg( to_field, err_id ) {
	$(to_field).addClass('error-field');
	$(to_field).removeClass('text-input-help');
	if( !$('#'+err_id).length ){ $('<div id="'+err_id+'" class="error-msg">'+$('#required_field_text').text()+'</div>').insertBefore(to_field); }
}
function rmErrMsg( to_field, err_id ) {
	$('#'+err_id).remove();
	$(to_field).removeClass('error-field');
}

// Goes through all the text_default input boxes and clears their default text, if it exists.
function clear_all_text_default_fields(){
	$(".text_default").each(function(){
		if($(this).val() == $(this).attr('refid')){ $(this).val(''); $(this).removeClass('text-input-help'); }
	});
}


/* kind of a hack since there isn't a way to independly style jquery-ui dialog buttons */
/* needs to be called after each dialog('open') */
function ui_close_addclass() {
	$("div.ui-dialog-buttonpane button:contains('Cancel')").addClass("gryCancel");
}





jQuery.fn.extend({
	ftoggle: function(){
		// toggle the visibility of an element using a quick fade instead of plain show/hide
		if( $(this).is(':visible') )
		   $(this).fadeOut('fast');
		else
		   $(this).fadeIn('fast');
	},
  gradient: function( gcolor, gsteps){
	  // creates a series of absolute DIVs with absolute positioning under the current content of the given element.
	  
	  // don't bother in IE6
	  if($.browser.msie && $.browser.version=="6.0") return false;
		
	  var pDiv = $(this);
    var jDiv = null;
    var intStep = 0;
    var gopacity = 1;
    var tz = 0;
    var tpos = '';

    // Up the z-index of all the current children so they won't get covered by the gradient
    var pz = pDiv.css('z-index');
    pz = ( pz > 1 ? pz : 1 );
    pDiv.css({'z-index': pz, 'position':'relative'});
    pDiv.children().each( function() {
	     tz = $(this).css('z-index');
	     tz = ( tz > pz ? tz : pz );
	     tpos = $(this).css('position');
	     tpos = ( tpos == 'absolute' ? tpos : 'relative')
	     $(this).css({'z-index': tz+1, 'position': tpos});
    });
 
    // Create the gradient elements.
    for (  intStep = 0 ; intStep < gsteps ; intStep++ ){ 
			jDiv = $( "<div class='jgrad'></div>" );

			//Set the properties on the fade level.
			gopacity -= 1/gsteps;
			gopacity = ( gopacity < 0 ? 0 : gopacity );
			jDiv.css (
			  {
			    'backgroundColor': gcolor,
			    'top': intStep+"px",
			    'left': "0px",
			    'position': "absolute",
			    'z-index': pz
			  })
			  .width( '100%' )
			  .height( '1px' )
			;
			// Add the fade level to the containing parent.
			jDiv.appendTo(this); 
			jDiv.fadeTo( 0, gopacity );
    }
  }
});
