function newLocation(newUrl) {
	window.location=newUrl;
}

function popup(location) {
	window.open(location,'btPopup','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=400');
}

// password strength...thanks logmein.com!
function RatePassword(pwd,maxwidth) {
	var strength  = GetPasswordStrength(pwd);
	var strengthPercent = ConvertToPercent(strength);
	$("strengthdisplay").innerHTML = GetPasswordStrengthText(strengthPercent);
	var widthGood = 0;
	var widthBad = maxwidth;
	if (strengthPercent >= 80) {
		// anything above 80% is displayed as 100% good
		widthGood = maxwidth;
		widthBad = 0;
	} else if (strengthPercent >=0 && strengthPercent < 100) {
		// between zero and 100 display the ratio
		widthGood = (maxwidth * strengthPercent) / 100;
		widthBad = maxwidth - widthGood;
	}
	$('bardisplayGood').style.width = widthGood + 'px';
	$('bardisplayBad').style.width = widthBad + 'px';
}

function GetPasswordStrength(pwd) {
	// zero-length passwords cannot be rated
	if (pwd.length == 0) {
		  return -1;
	}
	// passwords that are too short are zero-strong
	if (pwd.length < 6) {
		  return 0;
	}
	var charsSpecial = "";
	var charsLowercase = "";
	var charsUppercase = "";
	var charsNumeric = "";
	var rating = 0;
	var bonus = 0;
	var i;

	// characters that follow each other in the alphabet are bad
	var charcode = pwd.charCodeAt(0);
	for (i=1; i<pwd.length; i++) {
		  var diff = pwd.charCodeAt(i) - charcode;
		  charcode = pwd.charCodeAt(i);
		  if (diff == 1 || diff == -1) {
				pwd = pwd.substring(0, i) + pwd.substring(i-1, i) + pwd.substring(i+1, pwd.length);
		  }
	}

	// put password characters into the right buckets
	for (i=0; i<pwd.length; i++) {
		  if (pwd.charCodeAt(i) >= 'a'.charCodeAt(0) && pwd.charCodeAt(i) <='z'.charCodeAt(0)) {
				charsLowercase += pwd.substring(i, i+1);
		  } else if (pwd.charCodeAt(i) >= 'A'.charCodeAt(0) && pwd.charCodeAt(i) <='Z'.charCodeAt(0)) {
				charsUppercase += pwd.substring(i, i+1);
		  } else if (pwd.charCodeAt(i) >= '0'.charCodeAt(0) && pwd.charCodeAt(i) <='9'.charCodeAt(0)) {
				charsNumeric += pwd.substring(i, i+1);
		  } else {
				charsSpecial += pwd.substring(i, i+1);
		  }
	}

	rating = GetDistribution(charsLowercase);
	rating += GetDistribution(charsUppercase);
	rating += GetDistribution(charsNumeric);
	rating += GetDistribution(charsSpecial);

	if (charsLowercase.length > 0) bonus++;
	if (charsUppercase.length > 0) bonus++;
	if (charsNumeric.length > 0) bonus++;
	if (charsSpecial.length > 0) bonus++;

	rating = rating * (1 + ((bonus-1) / 4));
	return rating;
}

function ConvertToPercent(strength) {
	return 6*strength;
}

function GetDistribution(str) {
	var distribution = 0;
	var uniques = "";
	var i;
	for (i=0; i < str.length; i++) {
		if (uniques.indexOf(str.substring(i, i+1)) == -1) {
			uniques += str.substring(i, i+1);
		}
	}
	return uniques.length + ((str.length - uniques.length) / 5);
}

function GetPasswordStrengthText(strength) {
	if (strength == 0) {
		return "Too Short";
	} else if (strength > 0 && strength < 20) {
		return "Very Weak";
	} else if (strength >= 20 && strength < 40) {
		return "Fair";
	} else if (strength >= 40 && strength < 60) {
		return "Good";
	} else if (strength >= 60 && strength < 80) {
		return "Strong";
	} else if (strength >= 80) {
		return "Very Strong";
	} else {
		return "None";
	}
}

function enableCancel() {
  return true;
}

function updating_week(teetimeId) {
  msg = '<span style="color:red">Updating...</span>';
  $('#droppable_tee_time_' + teetimeId + '_names').html(msg);
  $('#draggable_teams').html(msg);
  return true;
}

function submit_round_form(bool) {
  if (bool == null) {
    onsub = true
  } else {
    onsub = bool
  }
  submit_form_working('round_form_buttons','round_form_working','roundform',onsub);
}
function submit_course_form() {
  submit_form_working('course_form_buttons','course_form_working','courseform',false);
}
function submit_outing_form() {
  submit_form_working('outing_form_buttons','outing_form_working','outingform',false);
}

function submit_form_working(buttons, working, formname, onsub) {
  $("#"+buttons).hide();
  $("#"+working).show();
  if (onsub == true) {
    $(formname).onsubmit();
  } else {
    $("#"+formname).submit();
  }
}

// new jQuery stuff! 

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}
 
jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});
 
/*
Submit a form with Ajax
Use the class ajaxForm in your form declaration
<% form_for @comment,:html => {:class => "ajaxForm"} do |f| -%>
*/
jQuery.fn.submitWithAjax = function() {
  this.unbind('submit', false);
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  }); 
  return this;
};
jQuery.fn.submitPutWithAjax = function() {
  this.unbind('submit', false);
  this.submit(function() {
    $.put(this.action, $(this).serialize(), null, "script");
    return false;
  });
  return this;
};
 
/*
Retrieve a page with get
Use the class get in your link declaration
<%= link_to 'My link', my_path(),:class => "get" %>
*/
jQuery.fn.getWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.get($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  });
  return this;
};
 
/*
Post data via html
Use the class post in your link declaration
<%= link_to 'My link', my_new_path(),:class => "post" %>
*/
jQuery.fn.postWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.post($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  });
  return this;
};
 
/*
Update/Put data via html
Use the class put in your link declaration
<%= link_to 'My link', my_update_path(data),:class => "put",:method => :put %>
*/
jQuery.fn.putWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.put($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  });
  return this;
};
 
/*
Delete data
Use the class delete in your link declaration
<%= link_to 'My link', my_destroy_path(data),:class => "delete",:method => :delete %>
*/
jQuery.fn.deleteWithAjax = function() {
  this.removeAttr('onclick');
  this.unbind('click', false);
  this.click(function() {
    $.delete_($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  });
  return this;
};
 
/*
Ajaxify all the links on the page.
This function is called when the page is loaded. You'll probaly need to call it again when you write render new datas that need to be ajaxyfied.'
*/
function ajaxLinks(){
//    $('.ajaxForm').submitWithAjax();
//    $('a.get').getWithAjax();
//    $('a.post').postWithAjax();
//    $('a.put').putWithAjax();
//    $('a.delete').deleteWithAjax();
}
 
$(document).ready(function() {
// All non-GET requests will add the authenticity token
 $(document).ajaxSend(function(event, request, settings) {
       if (typeof(window.AUTH_TOKEN) == "undefined") return;
       // IE6 fix for http://dev.jquery.com/ticket/3155
       if (settings.type == 'GET' || settings.type == 'get') return;
 
       settings.data = settings.data || "";
       settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);
     });
 
//  ajaxLinks();
});


$(document).ready(function () {
  $(".recalc_hci_link").live("click", function() {
    $('#recalc_status').html("Working.......");
    $.getScript(this.href);
    return false;
  });

  $(".notify_outing_link").live("click", function() {
    $('#sending_email').html("Sending an email to all participants...");
    $.getScript(this.href);
    return false;
  });

});

// Not the most elegant way, but I'll never have both TRs and DIVs in the same set, so who cares?!
function alternateHighlighting(el) {
	$(el + ' tr:even').addClass('bgnormal');
	$(el + ' tr:odd').addClass('bghighlight');
	$(el + ' div:even').addClass('bgnormal');
	$(el + ' div:odd').addClass('bghighlight');
}
function setUpMouseover(el) {
	alternateHighlighting(el);
    // Apply to sub-trs
	$(el + ' tr').mouseover(function() {
	  $(this).addClass('mouseover');
	});
	$(el + ' tr:even').mouseout(function() {
	  $(this).removeClass('mouseover').addClass('bgnormal');
	});
	$(el + ' tr:odd').mouseout(function() {
	  $(this).removeClass('mouseover').addClass('bghighlight');
	});	

    // Apply to sub-divs
	$(el + ' div').mouseover(function() {
	  $(this).addClass('mouseover');
	});
	$(el + ' div:even').mouseout(function() {
	  $(this).removeClass('mouseover').addClass('bgnormal');
	});
	$(el + ' div:odd').mouseout(function() {
	  $(this).removeClass('mouseover').addClass('bghighlight');
	});	
}

function render_mini_course(html,cid) {
  $("#course_loading").hide();
  $("#course_detail").html(html);
  if ($("#course_detail").is(":hidden")) {
    $("#course_detail").slideDown("medium");
  }
  $("#round_course_id").val(cid);  
  $("#outing_course_id").val(cid);  
  $("#round_course_name").html('(newly selected)');  
  $("#outing_course_name").html('(newly selected)');  
}

function fetch_mini_course(cid) {
  $.ajax({
    type: "GET",
    cache: false,
    url: "/courses/" + cid + "/mini",
    success: function(html){
      render_mini_course(html, cid);
    }
  });   
}

jQuery.fn.show_mini_course = function() {
  this.hover(function(){
    $(this).addClass("altcursor");
  },function(){
    $(this).removeClass("altcursor");
  });
  
  this.click(function() {
    $("#course_loading").show();
    fetch_mini_course(this.id);
  });
};
