/*
 * jQuery custom scripts for Lead Zeppelin
 * http://www.leadzep.com/
 *
 * Copyright (c) 2010 cre8, Inc
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2010-07-21 (Wed, 21 July 2010)
 * Revision: 29
 */





/* Custom functions
------------------------------------------------- */
jQuery.fn.selectRange = function(start, end) {
	return this.each(function() {
		if(this.setSelectionRange) {
			this.focus();
			this.setSelectionRange(start, end);
		}
		else if(this.createTextRange) {
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd("character", end);
			range.moveStart("character", start);
			range.select();
		}
	});
};


jQuery.fn.selectText = function() {
	if(document.selection) {
		document.selection.empty();
		var range = document.body.createTextRange();
		range.moveToElementText(this);
		range.select();
	}
	else if(window.getSelection) {
		window.getSelection().removeAllRanges();
		var range = document.createRange();
		range.selectNode(this);
		window.getSelection().addRange(range);
	}
};


jQuery.fn.addFieldGroup = function(group) {
	var i = $("div."+group+"_prototype").length;
	var node = $("div."+group+"_prototype")[0].innerHTML;
	this.parent().append('<div class="field_group '+group+'_group">'+node+'</div>');
	this.parent().append('<a class="add_'+group+'" href="#" title="Add another">Add another</a>');
	this.remove();
	$("a.add_"+group).click(function() {$(this).addFieldGroup(group); return false;});
};


jQuery.fn.dueDates = function() {
	this.datepicker({
		buttonImage:     "/assets/img/ui/icons/calendar.png",
		buttonImageOnly: true,
		constrainInput:  true,
		changeMonth:     true,
		changeYear:      true,
		dateFormat:      "mm/dd/yy",
		minDate:         "+0d",
		maxDate:         null,
		showOn:          "both"
	});
};


jQuery.fn.reStripeTable = function() {
	this.find("tr.activated").remove();
	this.find("tr.complete").remove();
	this.find("tr:odd").removeClass("odd even").addClass("odd");
	this.find("tr:even").removeClass("odd even").addClass("even");
};


jQuery.fn.completeTask = function(index) {
	var el = this;
	var id = this.val();
	
	el.parent().parent().addClass("complete");
	
	$.ajax({
		url: "/tasks/complete/"+id,
		success: function() {
			if(index) {
				var rows = $("#tasks tbody tr").length-1;
				
				if(rows > 0) {
					el.parent().parent().fadeOut("slow");
					setTimeout("$('#tasks').reStripeTable();", 500);
				}
				else {
					$("#tasks").fadeOut("slow");
					$("form.options").after("<p>You don&#8217;t have any tasks right now.</p>");
				}
			}
			else {
				var tableID = el.parent().parent().parent().parent().attr("id");
				var rows = $("#"+tableID+" tbody tr").not(".complete").length;
				
				if(rows > 0) {
					el.parent().parent().fadeOut("slow");
				}
				else {
					$("#"+tableID).parent().fadeOut("slow");
				}
			}
		}
	});
};


jQuery.fn.activateTask = function() {
	var el = this;
	var id = this.val();
	
	el.parent().parent().addClass("activated");
	
	$.ajax({
		url: "/tasks/activate/"+id,
		success: function() {
			var rows = $("#tasks tbody tr").length-1;
			
			if(rows > 0) {
				el.parent().parent().fadeOut("slow");
				setTimeout("$('#tasks').reStripeTable();", 500);
			}
			else {
				$("#tasks").prev().fadeOut("slow");
				$("#tasks").fadeOut("slow");
				$("form.options").after("<p>Looks like you haven&#8217;t completed any tasks.</p>");
			}
		}
	});
};


jQuery.fn.deleteTask = function() {
	var id = this.attr("id").substring(7);
	var table = this.parent().parent().parent().parent().parent().parent();
	
	$("#delete_"+id).parent().parent().parent().parent().addClass("complete");
	$("#delete_"+id).parent().parent().parent().parent().addClass("deleted");
	
	$.ajax({
		url: "/tasks/delete/"+id,
		success: function() {
			$("#delete_"+id).parent().parent().parent().parent().fadeOut("slow");
			
			var rows = table.find("tbody tr").length-1;
			
			if(rows > 0) {
				setTimeout("$('#tasks').reStripeTable();", 500);
			}
			else {
				table.fadeOut("slow");
				
				if($("body").hasClass("tasks")) {
					$(".main h1").after("<p>You don&#8217;t have any tasks right now.</p>");
				}
				else {
					table.parent().fadeOut("slow");
				}
			}
		}
	});
};


jQuery.fn.set_options = function() {
	var reg     = new RegExp('[<>]','g');
	var options = $("#options").val().replace(reg, "").split("\n");
		
	switch(this.val()) {
		case "1":
			var node = '<input type="text" size="30" name="custom_field" id="custom_field" />';
			$("#field_preview").html(node);
		break;
		case "4":
			var node = "";
			
			for(var i = 0; i < options.length; i++) {
				if(options[i].length > 0) {
					node += '<input type="checkbox" name="checkbox_'+i+'" id="checkbox_'+i+'" /><label for="checkbox_'+i+'">'+options[i]+'</label> '
				}
			}
			
			$("#field_preview").html(node);
		break;
		case "5":
			var node = "";
			
			for(var i = 0; i < options.length; i++) {
				if(options[i].length > 0) {
					node += '<input type="radio" name="custom_radio" id="radio_'+i+'" /><label for="radio_'+i+'">'+options[i]+'</label> '
				}
			}
			
			$("#field_preview").html(node);
		break;
		case "6":
			$("#custom_field option").remove();
			
			$("#field_preview").html('<select name="custom_field" id="custom_field"></select>');
			
			for(var i = 0; i < options.length; i++) {
				if(options[i].length > 0) {
					$("#custom_field").append('<option value="'+options[i]+'">'+options[i]+'</option>');
				}
			}
		break;
	}
};


function setFields() {
	var fields = "", labels = "";
	
	$("#my_fields option").each(function(){
		fields += $(this).val()  + ",";
		labels += $(this).html() + ",";
	});
	
	$("#fields").val(fields.slice(0, -1));
	$("#labels").val(labels.slice(0, -1));
}


function addFormField() {
	$("#fields_available option:selected").each(function() {
		var node  = $(this);
		var notes = 0;
		$("#my_fields option").each(function() {
			if($(this).attr("value")=="other[notes][]") {notes++;}
		});
		if(notes >= 10) {
			jAlert("A maximum of 10 note fields are available per form.", "Limit Reached");
		}
		else {
			if(node.attr("value")=="other[notes][]") {
				jPrompt("Edit Field Name:", "Notes", "Form Creator", function(r) {
					if(r) {
						r = r.replace(/,/g,''); // strip commas
						node.html(r);
						$("#my_fields").append(node);
						$("#fields_other").append('<option value="other[notes][]">Notes</option>');
						setFields();
					}
				});
			}
			else if(node.attr("value")=="file") {
				jPrompt("Edit Field Name:", "File Upload", "Form Creator", function(r) {
					if(r) {
						r = r.replace(/,/g,''); // strip commas
						node.html(r);
						$("#my_fields").append(node);
						setFields();
					}
				});
			}
			else {
				$("#my_fields").append(node);
			}
		}
	});
	setFields();
}


function removeFormField() {
	$("#my_fields option:selected").each(function() {
		if($(this).attr("value")=="notes" || $(this).attr("value")=="other[notes][]") {$(this).remove();}
		else if($(this).attr("value")=="file") {$("#fields_other").append($(this));}
		else if($(this).attr("value").indexOf("custom")==0) {$("#fields_custom").append($(this));}
		else {$("#fields_basic").append($(this));}
	});
	setFields();
}


function moveField(dir) {
	switch(dir) {
		case "up":   $("#my_fields option:selected").each(function(){$(this).insertBefore($(this).prev());}); break;
		case "down": $("#my_fields option:selected").each(function(){$(this).insertAfter($(this).next());});  break;
	}
	setFields();
}


function prepForm() {
	var form   = "<dl>";
	var note   = 1;
	var fields = $("#fields").val().split(",");
	var labels = $("#labels").val().split(",");
	
	$.each(fields, function(index, value) {
		switch(value) {
			case "address":
				form += '<dt><label for="lz-address-1">'+labels[index]+'</label></dt><dd><textarea rows="4" cols="30" name="lead[addresses][street][]" id="lz-address-1" style="color: #999;" onfocus="if(this.innerHTML=='+"'Street'"+') {this.innerHTML=\'\'; this.style.color='+"'#000'"+';}">Street</textarea><br /><input type="text" size="20" name="lead[addresses][city][]" value="City" style="color: #999;" onfocus="if(this.value==this.defaultValue) {this.value=\'\'; this.style.color='+"'#000'"+';}" /> <input type="text" size="4" name="lead[addresses][state][]" value="State" style="color: #999;" onfocus="if(this.value==this.defaultValue) {this.value=\'\'; this.style.color='+"'#000'"+'; this.maxLength = 2;}" /> <input type="text" size="10" name="lead[addresses][zip][]" value="ZIP" maxlength="10" style="color: #999;" onfocus="if(this.value==this.defaultValue) {this.value=\'\'; this.style.color='+"'#000'"+';}" /><br /><select class="country" name="lead[addresses][country][]"><option value="1">Afghanistan</option><option value="2">&#197;land Islands</option><option value="3">Albania</option><option value="4">Algeria</option><option value="5">American Samoa</option><option value="6">Andorra</option><option value="7">Angola</option><option value="8">Anguilla</option><option value="9">Antarctica</option><option value="10">Antigua and Barbuda</option><option value="11">Argentina</option><option value="12">Armenia</option><option value="13">Aruba</option><option value="14">Australia</option><option value="15">Austria</option><option value="16">Azerbaijan</option><option value="17">Bahamas</option><option value="18">Bahrain</option><option value="19">Bangladesh</option><option value="20">Barbados</option><option value="21">Belarus</option><option value="22">Belgium</option><option value="23">Belize</option><option value="24">Benin</option><option value="25">Bermuda</option><option value="26">Bhutan</option><option value="27">Bolivia</option><option value="28">Bosnia and Herzegovina</option><option value="29">Botswana</option><option value="30">Bouvet Island</option><option value="31">Brazil</option><option value="32">British Indian Ocean Territory</option><option value="33">Brunei Darussalam</option><option value="34">Bulgaria</option><option value="35">Burkina Faso</option><option value="36">Burundi</option><option value="37">Cambodia</option><option value="38">Cameroon</option><option value="39">Canada</option><option value="40">Cape Verde</option><option value="41">Cayman Islands</option><option value="42">Central African Republic</option><option value="43">Chad</option><option value="44">Chile</option><option value="45">China</option><option value="46">Christmas Island</option><option value="47">Cocos (Keeling) Islands</option><option value="48">Colombia</option><option value="49">Comoros</option><option value="50">Congo</option><option value="51">Congo, The Democratic Republic of the</option><option value="52">Cook Islands</option><option value="53">Costa Rica</option><option value="54">C&#244;te d\'Ivoire</option><option value="55">Croatia</option><option value="56">Cuba</option><option value="57">Cyprus</option><option value="58">Czech Republic</option><option value="59">Denmark</option><option value="60">Djibouti</option><option value="61">Dominica</option><option value="62">Dominican Republic</option><option value="63">Ecuador</option><option value="64">Egypt</option><option value="65">El Salvador</option><option value="66">Equatorial Guinea</option><option value="67">Eritrea</option><option value="68">Estonia</option><option value="69">Ethiopia</option><option value="70">Falkland Islands (Malvinas)</option><option value="71">Faroe Islands</option><option value="72">Fiji</option><option value="73">Finland</option><option value="74">France</option><option value="75">French Guiana</option><option value="76">French Polynesia</option><option value="77">French Southern Territories</option><option value="78">Gabon</option><option value="79">Gambia</option><option value="80">Georgia</option><option value="81">Germany</option><option value="82">Ghana</option><option value="83">Gibraltar</option><option value="84">Greece</option><option value="85">Greenland</option><option value="86">Grenada</option><option value="87">Guadeloupe</option><option value="88">Guam</option><option value="89">Guatemala</option><option value="90">Guernsey</option><option value="91">Guinea</option><option value="92">Guinea-Bissau</option><option value="93">Guyana</option><option value="94">Haiti</option><option value="95">Heard Island and McDonald Islands</option><option value="96">Holy See (Vatican City State)</option><option value="97">Honduras</option><option value="98">Hong Kong</option><option value="99">Hungary</option><option value="100">Iceland</option><option value="101">India</option><option value="102">Indonesia</option><option value="103">Iran, Islamic Republic of</option><option value="104">Iraq</option><option value="105">Ireland</option><option value="106">Isle of Man</option><option value="107">Israel</option><option value="108">Italy</option><option value="109">Jamaica</option><option value="110">Japan</option><option value="111">Jersey</option><option value="112">Jordan</option><option value="113">Kazakhstan</option><option value="114">Kenya</option><option value="115">Kiribati</option><option value="116">Korea, Democratic People\'s Republic of</option><option value="117">Korea, Republic of</option><option value="118">Kuwait</option><option value="119">Kyrgyzstan</option><option value="120">Lao People\'s Democratic Republic</option><option value="121">Latvia</option><option value="122">Lebanon</option><option value="123">Lesotho</option><option value="124">Liberia</option><option value="125">Libyan Arab Jamahiriya</option><option value="126">Liechtenstein</option><option value="127">Lithuania</option><option value="128">Luxembourg</option><option value="129">Macao</option><option value="130">Macedonia, Republic of</option><option value="131">Madagascar</option><option value="132">Malawi</option><option value="133">Malaysia</option><option value="134">Maldives</option><option value="135">Mali</option><option value="136">Malta</option><option value="137">Marshall Islands</option><option value="138">Martinique</option><option value="139">Mauritania</option><option value="140">Mauritius</option><option value="141">Mayotte</option><option value="142">Mexico</option><option value="143">Micronesia, Federated States of</option><option value="144">Moldova</option><option value="145">Monaco</option><option value="146">Mongolia</option><option value="147">Montenegro</option><option value="148">Montserrat</option><option value="149">Morocco</option><option value="150">Mozambique</option><option value="151">Myanmar</option><option value="152">Namibia</option><option value="153">Nauru</option><option value="154">Nepal</option><option value="155">Netherlands</option><option value="156">Netherlands Antilles</option><option value="157">New Caledonia</option><option value="158">New Zealand</option><option value="159">Nicaragua</option><option value="160">Niger</option><option value="161">Nigeria</option><option value="162">Niue</option><option value="163">Norfolk Island</option><option value="164">Northern Mariana Islands</option><option value="165">Norway</option><option value="166">Oman</option><option value="167">Pakistan</option><option value="168">Palau</option><option value="169">Palestinian Territory, Occupied</option><option value="170">Panama</option><option value="171">Papua New Guinea</option><option value="172">Paraguay</option><option value="173">Peru</option><option value="174">Philippines</option><option value="175">Pitcairn</option><option value="176">Poland</option><option value="177">Portugal</option><option value="178">Puerto Rico</option><option value="179">Qatar</option><option value="180">Reunion</option><option value="181">Romania</option><option value="182">Russian Federation</option><option value="183">Rwanda</option><option value="184">Saint Barth&#233;lemy</option><option value="185">Saint Helena</option><option value="186">Saint Kitts and Nevis</option><option value="187">Saint Lucia</option><option value="188">Saint Martin (French part)</option><option value="189">Saint Pierre and Miquelon</option><option value="190">Saint Vincent and the Grenadines</option><option value="191">Samoa</option><option value="192">San Marino</option><option value="193">Sao Tome and Principe</option><option value="194">Saudi Arabia</option><option value="195">Senegal</option><option value="196">Serbia</option><option value="197">Seychelles</option><option value="198">Sierra Leone</option><option value="199">Singapore</option><option value="200">Slovakia</option><option value="201">Slovenia</option><option value="202">Solomon Islands</option><option value="203">Somalia</option><option value="204">South Africa</option><option value="205">South Georgia and the South Sandwich Islands</option><option value="206">Spain</option><option value="207">Sri Lanka</option><option value="208">Sudan</option><option value="209">Suriname</option><option value="210">Svalbard and Jan Mayen</option><option value="211">Swaziland</option><option value="212">Sweden</option><option value="213">Switzerland</option><option value="214">Syrian Arab Republic</option><option value="215">Taiwan</option><option value="216">Tajikistan</option><option value="217">Tanzania, United Republic of</option><option value="218">Thailand</option><option value="219">Timor-Leste</option><option value="220">Togo</option><option value="221">Tokelau</option><option value="222">Tonga</option><option value="223">Trinidad and Tobago</option><option value="224">Tunisia</option><option value="225">Turkey</option><option value="226">Turkmenistan</option><option value="227">Turks and Caicos Islands</option><option value="228">Tuvalu</option><option value="229">Uganda</option><option value="230">Ukraine</option><option value="231">United Arab Emirates</option><option value="232">United Kingdom</option><option value="233" selected="selected">United States</option><option value="234">United States Minor Outlying Islands</option><option value="235">Uruguay</option><option value="236">Uzbekistan</option><option value="237">Vanuatu</option><option value="238">Venezuela</option><option value="239">Viet Nam</option><option value="240">Virgin Islands, British</option><option value="241">Virgin Islands, U.S.</option><option value="242">Wallis and Futuna</option><option value="243">Western Sahara</option><option value="244">Yemen</option><option value="245">Zambia</option><option value="246">Zimbabwe</option></select> <input type="hidden" name="lead[addresses][type][]" value="1" /></dd>';
			break;
			
			case "email":
				form += '<dt><label for="lz-email-1">'+labels[index]+'</label></dt><dd><input class="email" type="text" size="40" name="lead[emails][address][]" id="lz-email-1" /> <input type="hidden" name="lead[emails][type][]" value="1" /></dd>';
			break;
			
			case "file":
				form += '<dt><label for="lz-file-1">'+labels[index]+'</label></dt><dd><input class="file" type="file" name="lead[files][file][]" id="lz-file-1" /></dd>';
			break;
			
			case "notes":
				form += '<dt><label for="lz-notes-'+note+'">'+labels[index]+'</label></dt><dd><textarea rows="5" cols="40" name="lead[notes][note][]" id="lz-notes-'+note+'"></textarea> <input type="hidden" name="lead[notes][label][]" value="'+labels[index]+'" /></dd>';
				note++;
			break;
			
			case "other[notes][]":
				form += '<dt><label for="lz-notes-'+note+'">'+labels[index]+'</label></dt><dd><textarea rows="5" cols="40" name="lead[notes][note][]" id="lz-notes-'+note+'"></textarea> <input type="hidden" name="lead[notes][label][]" value="'+labels[index]+'" /></dd>';
				note++;
			break;
			
			case "phone":
				form += '<dt><label for="lz-phone-1">'+labels[index]+'</label></dt><dd><input type="text" name="lead[numbers][number][]" id="lz-phone-1" /> <input type="hidden" name="lead[numbers][type][]" value="1" /></dd>';
			break;
			
			case "website":
				form += '<dt><label for="lz-website-1">'+labels[index]+'</label></dt><dd><input type="text" size="40" name="lead[websites][url][]" id="lz-website-1" /> <input type="hidden" name="lead[websites][type][]" value="1" /></dd>';
			break;
			
			default:
				if(value.indexOf("custom")==0) {
					var field   = (value.substring(7, value.indexOf("]["))).split(";");
					var options = (value.substring(value.indexOf("][")+2, (value.length-1))).split(";");
					
					switch((field[0]/1)) {
						case 1:
							form += '<dt><label for="lz-custom-'+field[1]+'">'+labels[index]+'</label></dt><dd><input type="text" name="lead[custom]['+field[1]+'][]" id="lz-custom-'+field[1]+'" /></dd>';
						break;
						
						case 4:
							form += '<dt>'+labels[index]+'</dt>';
							form += '<dd>';
							$.each(options, function(i, val) {
								form += '<input type="checkbox" name="lead[custom]['+field[1]+'][]" id="lz-custom-'+field[1]+'-'+(i+1)+'" value="'+val+'" />';
								form += '<label for="lz-custom-'+field[1]+'-'+(i+1)+'">'+val+'</label> ';
							});
							form += '</dd>';
						break;
						
						case 5:
							form += '<dt>'+labels[index]+'</dt>';
							form += '<dd>';
							$.each(options, function(i, val) {
								form += '<input type="radio" name="lead[custom]['+field[1]+'][]" id="lz-custom-'+field[1]+'-'+(i+1)+'" value="'+val+'" />';
								form += '<label for="lz-custom-'+field[1]+'-'+(i+1)+'">'+val+'</label> ';
							});
							form += '</dd>';
						break;
						
						case 6:
							form += '<dt><label for="lz-custom-'+field[1]+'">'+labels[index]+'</label></dt>';
							form += '<dd>';
							form += '<select name="lead[custom]['+field[1]+'][]" id="lz-custom-'+field[1]+'">';
							$.each(options, function(i, val) {
								form += '<option value="'+val+'">'+val+'</option>';
							});
							form += '</select>';
							form += '</dd>';
						break;
						
					}
				}
				else {
					var size = (value=="firstname" || value=="lastname") ? ' size="40"' : "";
					form += '<dt><label for="lz-'+value+'">'+labels[index]+'</label></dt><dd><input type="text"'+size+' name="lead['+value+']" id="lz-'+value+'" /></dd>';
				}
		}
	});
	
	form += "</dl>";
	return form;
}


function choosePlan(n) {
	$("table.plans .buttons td.active strong").each(function() {
		if($(this).hasClass("free")) {$(this).after('<div class="buttons"><a class="upgrade free" href="#" title="Select our free plan">Downgrade</a></div>');}
		if($(this).hasClass("basic")) {$(this).after('<div class="buttons"><a class="upgrade basic" href="#" title="Upgrade to our Basic plan &#8212; just $24/month">Upgrade</a></div>');}
		if($(this).hasClass("standard")) {$(this).after('<div class="buttons"><a class="upgrade standard" href="#" title="Upgrade to our Standard plan &#8212; just $49/month">Upgrade</a></div>');}
		if($(this).hasClass("max")) {$(this).after('<div class="buttons"><a class="upgrade max" href="#" title="Upgrade to our Max plan &#8212; just $99/month">Upgrade</a></div>');}
		$(this).remove();
		$("a.upgrade").each(function() {
			if($(this).hasClass("free")) {$(this).click(function() {choosePlan(1); return false;});}
			if($(this).hasClass("basic")) {
				if(n>2) {$(this).html("Downgrade");} else {$(this).html("Upgrade");}
				$(this).click(function() {choosePlan(2); return false;});
			}
			if($(this).hasClass("standard")) {
				if(n>3) {$(this).html("Downgrade");} else {$(this).html("Upgrade");}
				$(this).click(function() {choosePlan(3); return false;});
			}
			if($(this).hasClass("max")) {$(this).click(function() {choosePlan(4); return false;});}
		});
	});
	$("table.plans td, table.plans th").each(function() {$(this).removeClass("active");});
	$("table.plans td:nth-child("+n+"), table.plans th:nth-child("+n+")").each(function() {$(this).addClass("active");});
	$("table.plans td:nth-child("+n+") div.buttons").each(function() {
		var c;
		switch(n) {case 1: c = "free"; break; case 2: c = "basic"; break; case 3: c = "standard"; break; case 4: c = "max"; break;}
		$(this).after('<strong class="'+c+'">Selected</strong>');
		$(this).remove();
	});
	$("#plan").val(n);
}


function deleteNote(id) {
	$.ajax({
		url:     "/notes/delete/"+id,
		success: function() {$("#note_"+id).slideUp();}
	});
}


function editNote(id, notes) {
	$.ajax({
		type: "POST",
		data: "notes_"+id+"="+notes,
		url: "/notes/edit/"+id,
		success: function() {
			notes = notes.replace(/\n/g,"<br />");
			$("#note_copy_"+id+" p:first-child").html(notes);
			$("#note_copy_"+id).slideDown(250);
			$("#edit_note_"+id).slideUp(250);
			$("#edit_note_"+id).find("button img").attr("src", "/assets/img/ui/icons/disk_black.png");
		}
	});
}


function tweets() {
	$("div.twtr-tweet:odd").css("background-color","#ffffff");
}


function checkSignup() {
	$("#signup").validate({
		rules: {
			firstname:        "required",
			lastname:         "required",
			email:            {required: true, email: true},
			username:         {required: true, username: true, minlength: 4},
			password:         {required: true, minlength: 5},
			confirm_password: {required: true, minlength: 5, equalTo: "#password"}
		},
		messages: {
			firstname: "Please provide your first name",
			lastname:  "Please provide your last name",
			email:     "Please enter a valid email address",
			username: {
				required:  "Please choose a username with at least 4 characters.",
				username:  "Your username can only contain letters, numbers, or dashes.",
				minlength: "Please choose a username with at least 4 characters."
			},
			password: {
				required:  "Please choose a password",
				minlength: "Your password must be at least 5 characters long"
			},
			confirm_password: {
				required:  "Please confirm your password",
				minlength: "Your password must be at least 5 characters long",
				equalTo:   "Please enter the same password as above"
			}
		}
	});
}


function checkProfile(add) {
	if(add) {
		$("#add").validate({
			rules: {
				firstname:        "required",
				lastname:         "required",
				email:            {required: true, email: true},
				username:         {required: true, minlength: 4},
				password:         {required: true, minlength: 5},
				confirm_password: {required: true, minlength: 5, equalTo: "#password"}
			},
			messages: {
				firstname: "Please provide the user&#8217;s first name",
				lastname:  "Please provide the user&#8217;s last name",
				email:     "Please enter a valid email address",
				username:  "Please choose a username with at least 4 characters.",
				password: {
					required:  "Please choose a password",
					minlength: "Passwords must be at least 5 characters long"
				},
				confirm_password: {
					required:  "Please confirm your password",
					minlength: "Passwords must be at least 5 characters long",
					equalTo:   "Please enter the same password as above"
				}
			}
		});
	}
	else {
		$("#edit").validate({
			rules: {
				firstname: "required",
				lastname:  "required",
				email:     {required: true, email: true},
				username:  {required: true, username: true, minlength: 4}
			},
			messages: {
				firstname: "Please enter both your first and last name",
				lastname:  "Please enter both your first and last name",
				email:     "Please enter a valid email address",
				username: {
					required:  "Please choose a username with at least 4 characters.",
					username:  "Your username can only contain letters, numbers, or dashes.",
					minlength: "Please choose a username with at least 4 characters."
				}
			}
		});
	}
}


function checkCC() {
	var date      = new Date();
	var thisYear  = date.getFullYear();
	var thisMonth = date.getMonth() + 1;
	
	$("#credit-card").submit(function() {
		if($("#x_address").val()=="Street") {
			$("#x_address").removeClass("preview");
			$("#x_address").val("");
		}
		if($("#x_city").val()=="City") {
			$("#x_city").removeClass("preview");
			$("#x_city").val("");
		}
		if($("#x_state").val()=="State") {
			$("#x_state").removeClass("preview");
			$("#x_state").val("");
		}
		if($("#x_zip").val()=="ZIP") {
			$("#x_zip").removeClass("preview");
			$("#x_zip").val("");
		}
	});
	
	$("#credit-card").validate({
		rules: {
			x_card_type: "required",
			x_card_num:  {required: true, number: true, minlength: 16, maxlength: 16},
			x_card_code: {required: true, number: true, minlength: 3, maxlength: 4},
			x_address:   {required: true},
			x_city:      {required: true},
			x_state:     {required: true, minlength: 2, maxlength: 2},
			x_zip:       {required: true,number: true, minlength: 5, maxlength: 5}
		},
		messages: {
			x_card_type: "Select your card type.",
			x_card_num: {
				required:  "Your Card Number is required.",
				number:    "Only numbers may be entered.",
				minlength: "Your Card Number must be at least 16 digits.",
				maxlength: "Your Card Number must be at most 16 digits."
			},
			x_card_code: {
				required:  "Your card's security code is required",
				number:    "Only numbers may be entered.",
				minlength: "Your security code must be at least 3 digits.",
				maxlength: "Your security code must be at most 4 digits."
			},
			x_address: "Please provide your billing address.",
			x_city:    "Please provide your billing city.",
			x_state: {
				required:  "Your billing state is required.",
				maxlength: "Your billing state must be at least 2 characters.",
				maxlength: "Your billing state must be at most 2 characters."
			},
			x_zip: {
				required:  "Billing ZIP Code is required.",
				number:    "Your ZIP Code can only contain numbers.",
				maxlength: "Your ZIP code must be at least 5 digits.",
				maxlength: "Your ZIP code must be at most 5 digits."
			}
		},
		errorPlacement: function(error, element) {
			if(element.attr("name") == "x_city" || element.attr("name") == "x_state" || element.attr("name") == "x_zip") {error.insertAfter("#x_zip");}
			else {error.insertAfter(element);}
		},
		submitHandler: function(form) {
			var month = $("#exp_month").val();
			var year = $("#exp_year").val();
			
			if(year==thisYear) {
				if(month!=10 && month!=11 && month!=12) {
					month = month.substring(1)/1;
				}
				if(month<thisMonth) {
					jAlert("You&#8217;re living in the past. Please enter a date in the future so we can process your card.", "Expiration Date Error", function(r) {
						$("#exp_month").focus();
					});
					return false;
				}
				else if(month==thisMonth) {
					jAlert("Your card is expiring this month. Please provide a different credit card.", "Expiration Date Error", function(r) {
						$("#exp_month").focus();
					});
					return false;
				}
				else {
					form.submit();
				}
			}
			else {
				form.submit();
			}
		}
	});
}


function checkEmail(id) {
	$(id).validate({
		rules: {
			name:    "required",
			subject: "required",
			fromEmail: {
				required: true,
				email:    true
			},
			replyToEmail: {
				required: true,
				email:    true
			},
			body: "required"
		},
		messages: {
			name:         "Please enter a name for your email",
			subject:      "Please enter a subject for your email",
			fromEmail:    "Please enter a valid email address",
			replyToEmail: "Please enter a valid email address"
		}
	});
}


function checkForm(id) {
	$(id).validate({
		rules: {
			name: "required",
			my_fields: {
				required: function(element) {
					return $("#my_fields option").length == 0;
				}
			}
		},
		messages: {
			name:      "Please enter a name for your form.",
			my_fields: "You must select at least one field for your form."
		},
		errorPlacement: function(error, element) {
			if (element.attr("name") == "my_fields") {error.insertAfter("#formFields");}
			else {error.insertAfter(element);}
		}
	});
}


function selectEvents() {
	$("select.network").live("change", function() {
		switch($(this).val()) {
			case "1": $(this).prev().attr("class", "fb text"); $(this).prev().val("http://www.facebook.com/"); $(this).prev().selectRange(24,24); break;
			case "2": $(this).prev().attr("class", "li text"); $(this).prev().val("http://www.linkedin.com/"); $(this).prev().selectRange(24,24); break;
			case "3": $(this).prev().attr("class", "tw text"); $(this).prev().val("http://twitter.com/"); $(this).prev().selectRange(19,19); break;
		}
	});
	
	$('select[name="lead[assign_to]"], select[name="assignedTo"]').live("change", function() {
		switch($(this).val()) {
			case "" : $(this).next().slideUp(250); break;
			default : $(this).next().slideDown(250); $(this).find("option:selected").each(function() {$(this).parent().next().find("span").html($(this).html());});
		}
	});
}
/* -------------------------------------------------
                             end custom functions */





/* UI Candy
------------------------------------------------- */
$(document).ready(function(){
	
	//////////////////
	// tr:hover fix //
	//////////////////
	$("table.data tr").hover(
		function() {$(this).addClass("hover");},
		function() {$(this).removeClass("hover");}
	);
	
	///////////////////////
	// add class for IE6 //
	///////////////////////
	$('input[type="text"],input[type="password"]').addClass("text");
	$('input[type="file"]').addClass("file");
	$(":last-child").addClass("last-child");
	
	////////////////////
	// external links //
	////////////////////
	$('a[rel="external"]').attr("target","_blank");
	
	///////////////////////
	// "add group" links //
	///////////////////////
	$("a.add_email").click(function() {$(this).addFieldGroup("email");return false;});
	$("a.add_network").click(function() {$(this).addFieldGroup("network");return false;});
	$("a.add_phone").click(function() {$(this).addFieldGroup("phone");return false;});
	$("a.add_website").click(function() {$(this).addFieldGroup("website");return false;});
	$("a.add_address").click(function() {$(this).addFieldGroup("address");return false;});
	
	//////////////////
	// select boxes //
	//////////////////
	selectEvents();
	
	//////////////////////////
	// "form builder" links //
	//////////////////////////
	$("a.add_field").click(function() {addFormField(); return false;});
	$("a.remove_field").click(function() {removeFormField(); return false;});
	$("a.field_up").click(function() {moveField("up"); return false;});
	$("a.field_down").click(function() {moveField("down"); return false;});
	
	/////////////////////
	// "upgrade" links //
	/////////////////////
	$("a.upgrade").click(function() {
		if($(this).hasClass("free")) {choosePlan(1);}
		if($(this).hasClass("basic")) {choosePlan(2);}
		if($(this).hasClass("standard")) {choosePlan(3);}
		if($(this).hasClass("max")) {choosePlan(4);}
		return false;
	});
	
	$("strong.unavailable").click(function() {
		jAlert("You can not choose this because your usage currently exceeds this plan&#8217;s limits.", "Plan Unavailable");
	});
	
	/////////////////////////////////
	// company delete confirmation //
	/////////////////////////////////
	$("a.company_delete").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("Are you sure you want to delete this company?<br /><strong>This includes associated notes, tasks and attached files, and can not be undone</strong>.", "Delete Company", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	/////////////////////////////////
	// contact delete confirmation //
	/////////////////////////////////
	$("a.contact_delete").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("Are you sure you want to delete this person?<br /><strong>This includes associated notes, tasks and attached files, and can not be undone</strong>.", "Delete Person", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	//////////////////////////////
	// user delete confirmation //
	//////////////////////////////
	$("a.delete_user").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("Are you sure you want to delete this user?<br /><strong>This can not be undone</strong>.", "Delete User", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	//////////////////////////////
	// deal delete confirmation /
	///////////////////////////////
	$("a.deal_delete").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("Are you sure you want to delete this deal?<br /><strong>This includes associated notes, tasks and attached files, and can not be undone</strong>.", "Delete Deal", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	///////////////////////////////
	// email delete confirmation //
	///////////////////////////////
	$("a.delete_email").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("You are about to delete this email.<br /><strong>This can not be undone</strong>.", "Delete Email", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	//////////////////////////////
	// file delete confirmation //
	//////////////////////////////
	$("a.file_delete").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("You are about to delete this file.<br /><strong>This can not be undone</strong>.", "Delete File", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	///////////////////////////////
	// field delete confirmation //
	///////////////////////////////
	$("a.field_delete").click(function() {
		var uri = $(this).attr("href");
		$(this).attr("href", "");
		jConfirm("Deleting this custom field will also delete all associated data from your contacts and leads.<br /><strong>This can not be undone</strong>.", "Delete Field", function(r) {
			if(r) {
				window.location=uri;
			}
		});
		return false;
	});
	
	////////////////////////
	// "activity" section //
	////////////////////////
	$("div.activity").hover(
		function() {$(this).addClass("hover");},
		function() {$(this).removeClass("hover");}
	);
	
	$("a.note_delete").click(function() {
		var node = $(this);
		var load = '<img class="loading" src="/assets/img/ui/progress/loading_16x16.gif" alt="loading" width="16" height="16" />';
		jConfirm("Are you sure you want to delete this note<br />(and associated files)?<br /><strong>This can not be undone</strong>.", "Delete Note", function(r) {
			if(r) {
				$("#"+node.parent().parent().attr("id")+" div.edit").append(load);
				deleteNote(node.parent().parent().attr("id").substring(5));
				node.parent().find("a").remove();
			}
		});
		return false;
	});
	$("a.note_edit").click(function() {
		var id = $(this).parent().parent().attr("id").substring(5);
		$("#note_copy_"+id).slideUp(250);
		$("#edit_note_"+id).slideDown(250);
		$("#edit_note_"+id).submit(function() {
			$(this).find("button img").attr("src", "/assets/img/ui/progress/loading_16x16.gif");
			var notes = $("#notes_"+id).val();
			editNote(id, notes);
			return false;
		});
		return false;
	});
	
	$("table.data thead th.header").click(function() {
		var links = $(this).find("a");
		if(links.length>0) {
			if($(this).find("a").hasClass("submit_filter")) {
				var uri = $(this).find("a").attr("href");
				$("#filters").attr("action", uri);
				$("#filters").submit();
			}
			else {
				window.location = $(this).find("a").attr("href");
			}
		}
	});
	
	////////////////////////////
	// filters and pagination //
	////////////////////////////
	$("#filters input[name='filters[]']").click(function() {
		$("#filter_buttons").fadeIn(500);
		$("#filters input[name='filters[]']:checked").length==0 ? $("#filter").val("false") : $("#filter").val("true");
	});
	
	$("a.submit_filter").click(function() {
		var uri = $(this).attr("href");
		
		$("#filters").attr("action", uri);
		$("#filters").submit();
		
		return false;
	});
	
	////////////////////////
	// person search form //
	////////////////////////
	$("#q").focus(function() {if($(this).val()==this.defaultValue) {$(this).val(""); $(this).removeClass("preview");}});
	$("#q").blur(function() {if($(this).val()=="") {$(this).val("First or last name"); $(this).addClass("preview");}});
	$("#search").submit(function() {if($("#q").val()=="" || $("#q").val()=="First or last name") {alert("You must enter a search term."); $("#q").focus(); return false;} else {return true;}});
	
	//////////////////
	// date pickers //
	//////////////////
	$("input.date_due").each(function() {
		$(this).dueDates();
	});
	
	/////////////////////
	// form validation //
	/////////////////////
	if($("#add_task").length) {
		$("#add_task").validate({
			rules: {
				name: "required",
				dateDue: {required: true, date: true}
			},
			errorPlacement: function(error, element) {
				if(element.attr("name") == "dateDue") {error.insertAfter("#dateError");}
				else {error.insertAfter(element);}
			}
		});
	}
	
	///////////
	// tasks //
	///////////
	$("input.task_complete").click(function() {
		$(this).parent().parent().parent().parent().hasClass("data") ? $(this).completeTask(1) : $(this).completeTask(0);
	});
	
	$("a.task_delete").click(function() {
		$(this).deleteTask();
		return false;
	});
	
	$("input.task_activate").click(function() {
		$(this).activateTask();
	});
	
	$("#tasks a.task_edit").click(function() {
		$.browser.msie ? $("div.actions form").hide() : $("div.actions form").fadeOut(250);
		$.browser.msie ? $(this).parent().siblings("form").show() : $(this).parent().siblings("form").fadeIn(250);
		return false;
	});
	
	$("table.tasks a.task_edit").click(function() {
		$("table.tasks form").slideUp(250);
		$(this).parent().parent().siblings("form").css("display") == "none" ? $(this).parent().parent().siblings("form").slideDown(250) : $(this).parent().parent().siblings("form").slideUp(250);
		return false;
	});
	
	$("div.actions form").hover(
		function() {$.browser.msie ? $(this).find("img.close").show() : $(this).find("img.close").fadeIn(250);},
		function() {$.browser.msie ? $(this).find("img.close").hide() : $(this).find("img.close").fadeOut(250);}
	);
	
	$("div.actions form img.close").click(function() {
		$.browser.msie ? $(this).parent().parent().hide() : $(this).parent().parent().fadeOut(250);
	});
	
	$("table.tasks form img.close").click(function() {
		$(this).parent().parent().slideUp(250);
	});
	
	$("table.tasks form a.cancel").click(function() {
		$(this).parent().parent().parent().parent().parent().slideUp(250);
		return false;
	});
	
	$("div.actions form, table.tasks form").submit(function() {
		var e = false;
		$(this).find('input[type="text"]').each(function() {
			if(!e) {
				if($(this).val()=="") {
					alert("Please complete all fields");
					$(this).focus();
					e = true;
				}
			}
		});
		if(e) {
			return false;
		}
	});
	
	//////////////////
	// user toggles //
	//////////////////
	$("input#toggle_users").click(function() {
		$(this).is(":checked") ? $("input[name='users[]']").attr("checked", true) : $("input[name='users[]']").attr("checked", false);
	});
	
	$("input[name='users[]']").click(function() {
		var all = true;
		$("input[name='users[]']").each(function() {
			if(!$(this).is(":checked")) {all = false;}
		});
		
		all ? $("input#toggle_users").attr("checked", true) : $("input#toggle_users").attr("checked", false);
	});
	
	
	////////////////
	// lead index //
	////////////////
	$("input#toggle_leads").click(function() {
		if($(this).is(":checked")) {
			$("input.leads").attr("checked", true);
			$("#delete_selected").show();
			$("#save").fadeIn(500);
		}
		else {
			$("input.leads").attr("checked", false);
			$("#delete_selected").hide();
		}
	});
	
	$("input.leads").click(function() {
		var all = true;
		var any = false;
		
		$("input.leads").each(function() {
			if(!$(this).is(":checked")) { all = false; }
			else {
				$("#delete_selected").show();
				$("#save").fadeIn(500);
				any = true;
			}
		});
		
		any ? $("#delete_selected").show() : $("#delete_selected").hide();
		all ? $("input#toggle_leads").attr("checked", true) : $("input#toggle_leads").attr("checked", false);
	});
	
	$("select.status").change(function() {
		$("#save").fadeIn(500);
	});
	
	$("#delete_selected").click(function() {
		var form = $(this).parent().parent().parent().parent();
		var section = $(this).hasClass("leads") ? "leads" : "contacts";
		
		jConfirm("Are you sure you want to delete these "+section+"?<br /><strong>This includes associated notes, tasks and attached files, and can not be undone</strong>.", "Delete Confirmation", function(r) {
			if(r) {
				$("#delete").val("true");
				form.submit();
			}
		});
		
		return false;
	});
	
	
	$("#field_chooser").change(function() {
		$("#custom_preview").slideDown();
		
		var node = "";
		
		switch($(this).val()) {
			case "1":
				$(".options").slideUp();
				$("#options").rules("remove");
				$("#label_preview").html($("#label_chooser").val());
				$("#field_chooser").set_options();
			break;
			case "4":
				$(".options").slideDown();
				$("#options").rules("add", {required: true});
				$("#field_chooser").set_options();
			break;
			case "5":
				$(".options").slideDown();
				$("#options").rules("add", {required: true});
				$("#field_chooser").set_options();
			break;
			case "6":
				$(".options").slideDown();
				$("#options").rules("add", {required: true});
				$("#field_chooser").set_options();
			break;
			default: $("#custom_preview").slideUp();
		}
	});
	
	$("#label_chooser").keyup(function() {
		var reg   = new RegExp('[<>]','g');
		var label = $("#label_chooser").val().replace(reg, "");
		$("#label_preview").html(label);
	});
	
	$("#options").change(function()   { $("#field_chooser").set_options(); });
	$("#options").keydown(function()  { $("#field_chooser").set_options(); });
	$("#options").keypress(function() { $("#field_chooser").set_options(); });
	$("#options").keyup(function()    { $("#field_chooser").set_options(); });
});

$(window).load(function(){
	setTimeout("tweets();", 0);
});
/* -------------------------------------------------
                                     end UI Candy */





/* Phone Number Validator
------------------------------------------------- */
if(jQuery.validator) {
	jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
		phone_number = phone_number.replace(/\s+/g, ""); 
		return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
	}, "Please provide a valid phone number &#8212; e.g. (312) 555-5555");
	
	jQuery.validator.addMethod("username", function(value, element) {
        return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
    }, "Your username can only contain letters, numbers, or dashes.");
}
/* -------------------------------------------------
                       end Phone Number Validator */





