var initialFade = true;

jQuery(document).ready(function() {
	$monthSelect = jQuery("select[name='calendar_nav_month']");
	$yearSelect = jQuery("select[name='calendar_nav_year']");
	
	jcForms.init();		// initialize the form handlers and validation routines
	
	jQuery("#slides ul").cycle({
		fx: 'fade',
		timeout: 7000,
		speed: 800,
		pager: "#slides_control",
		before: hideText,
		after: showText
	});
	
	jQuery("#flickr_container").cycle({
		fx: 'scrollHorz',
		timeout: 0,
		speed: 800,
		pager: "#flickr_controls .pager_panel",
		prev: "#flickr_controls .previous_panel",
		next: "#flickr_controls .next_panel"
	});
	
	jQuery("#youtube_container").cycle({
		fx: 'scrollHorz',
		timeout: 0,
		speed: 800,
		pager: "#youtube_controls .pager_panel",
		prev: "#youtube_controls .previous_panel",
		next: "#youtube_controls .next_panel"
	});
	
	jQuery(".ie").find("hr").each(function() {
		var wrapClass = "hrreplace";
		if(jQuery(this).hasClass("dotted")) wrapClass += " dotted";
		if(jQuery(this).hasClass("dark")) wrapClass += " dark";
		jQuery(this).wrap("<div class='" + wrapClass + "'></div>").hide();
	});
	
	jQuery("#flickr_container a").lightBox({ fixedNavigation:true });
	
	jQuery(window).bind("resize", resizeWindow);
	resizeWindow();
	
	/*
	jQuery("#calendar_nav_left").click(function(e) {
		ecd.jq("#EC_previousMonthLarge").click();
		updateCalendarSelect("dec");
		e.preventDefault();
	});
	
	jQuery("#calendar_nav_right").click(function(e) {
		ecd.jq("#EC_nextMonthLarge").click();
		updateCalendarSelect("inc");
		e.preventDefault();
	});
	
	$monthSelect.change(function() {
		var currMonth = $monthSelect.find("option:selected").val();
		var currYear = $yearSelect.find("option:selected").val();
	
		ecd.jq.get('http://chuckyb.jonathancarlson.com/index.php',
		{EC_action: "switchMonthLarge", EC_month: currMonth, EC_year: currYear},
		function(ecdata) {
			ecd.jq('#calendar_wrapLarge').empty().append( ecdata );
		});
	});
	
	$yearSelect.change(function() {
		var currMonth = $monthSelect.find("option:selected").val();
		var currYear = $yearSelect.find("option:selected").val();
	
		ecd.jq.get('http://chuckyb.jonathancarlson.com/index.php',
		{EC_action: "switchMonthLarge", EC_month: currMonth, EC_year: currYear},
		function(ecdata) {
			ecd.jq('#calendar_wrapLarge').empty().append( ecdata );
		});
	});
	*/
	
	jQuery("#eventStart, #eventEnd").datepicker({
		dateFormat: "mm/dd/yy"
		/*,
		showOn: "button",
		buttonImage: "http://chuckyb.jonathancarlson.com/wp-content/themes/charlesbillingsley/images/calendar.png",
		buttonImageOnly: true
		*/
	});
	
	jQuery(".reset_form").click(function() {
		jQuery(this).parents("form")
			.find("input").val("").attr("selected", "").attr("checked", "").end()
			.find("textarea").val("").end()
			.find("select").find("option:first-child").attr("selected", "selected").end().end();
	});
	
	jQuery(".continue").click(function() {
		jQuery(this).parents("form").submit();
	});
});

function updateCalendarSelect(dir) {
	var currMonth = $monthSelect.find("option:selected").val();
	var currYear = $yearSelect.find("option:selected").val();
	
	if(currMonth == 1 && dir == "dec") {
		currMonth = 12;	
		currYear--;
	} else if(currMonth == 12 && dir == "inc") {
		currMonth = 1;
		currYear++;
	} else {
		if(dir == "dec")
			currMonth--;
		else if(dir == "inc")
			currMonth++;
	}
	
	$monthSelect.find("option[value='" + currMonth + "']").attr("selected", "selected");
	$yearSelect.find("option[value='" + currYear + "']").attr("selected", "selected");
}

function resizeWindow( e ) {
	var windowWidth = jQuery(window).width();
	$wrap = jQuery("#wrap");
	
	$wrap.removeClass("hideOverflow");
	if(windowWidth < 1600) {
		if(windowWidth < 960)
			windowWidth = 960;
		$wrap.css("width", windowWidth).addClass("hideOverflow");
	} else
		$wrap.css("width", "100%");	
}

function showDescription() {
	$desc = jQuery(".slides_description");
	if($desc.html().replace(" ", "") != "")
		$desc.animate({ "bottom": "0px" }, 200);
}

function hideText() {
	$desc = jQuery(".slides_description");
	if(!initialFade) 
		$desc.animate({ "bottom": "-122px" }, 200);
}

function showText() {
	$childImg = jQuery(this).find("img");
	
	initialFade = false;
	
	$desc = jQuery(".slides_description");
	$desc.html(Url.decode($childImg.attr("alt")));
	showDescription();
}


var jcForms = {
	/* init - finds all form elements on the page who have a class of jcForms and then calls config on them */
	init: function() {
		var instance = this;
				
		jQuery("body")
			.find("input.jcForms,textarea.jcForms")
				.each(function() {
					if(jQuery(this).attr("type") != "submit") instance.config(this);
					else {
						var submitButton = "<a href='javascript:void(0);' class='jcForms button sign_me_up'>Sign me up today</a>";
						jQuery(this).after(submitButton);
						jQuery(this)
							.siblings('.button')
								.click(function() {
									var valid = true;
									var $form = jQuery(this).parents("form");
									
									$form
										.find("input.jcForms,textarea.jcForms")
											.each(function() {
												if(!instance.validate(this)) valid = false;
											});
									
									if(valid) {
										$form.submit();
									}
								});
								
						jQuery(this).hide();
					}
				});
	},
	
	/* config - configures the form handlers and validation for a form element */
	config: function(el) {
		var instance = this;
		
		if(instance.exists(el)) {
			jQuery(el)
				.focus(function() { instance.onFocus(this); })
				.blur(function() { instance.onBlur(this); })
				.change(function() { instance.onBlur(this); });
		}
	},
	
	/* onFocus - actions that occur when a form field is clicked on/tabbed to/focused on */
    onFocus: function (el) {
		if(this.exists(el)) {
			if(jQuery(el).val().toLowerCase() == jQuery(el).attr("title").toLowerCase()) jQuery(el).val("");
			if(!jQuery(el).hasClass("active")) jQuery(el).addClass("active");
		}
    },
	
	/* onBlur - actions that occur when a form field is left or tabbed away from */
	onBlur: function (el) {
		if(this.exists(el)) {
			if(jQuery(el).val() == "") {
				jQuery(el).val(jQuery(el).attr("title"));
				jQuery(el).removeClass("active");
			} else this.validate(el);
		}
	},
	
	/* validate - validates the form field based on the restrictions supplied in the class attribute */
	validate: function(el) {
		var valid = true;
		
		if(this.exists(el)) {
			if(jQuery(el).hasClass("required") && (jQuery(el).val() == "" || (jQuery(el).val() != "" && jQuery(el).val() == jQuery(el).attr("title")))) valid = false;
			if(jQuery(el).hasClass("email") && !this.checkEmail(jQuery(el).val())) valid = false;
			
			if(!valid) jQuery(el).addClass("error");
			else jQuery(el).removeClass("error");
		}
		return valid;
	},
	
	/* exists - exactly as it sounds, checks to make sure an element exists */
	exists: function(el) {
		if(jQuery(el).length) return true;
		return false;
	},
	
	/* checkEmail - validates an email address */
	checkEmail: function(email) {
		var str = email;
		var at = "@";
		var dot = ".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		
		if(str.indexOf(at) <= 0 || str.indexOf(at) == lstr || str.indexOf(dot) <= 0 || str.indexOf(dot) == lstr || str.indexOf(at,(lat+1)) != -1 || str.substring(lat-1,lat) == dot || str.substring(lat+1,lat+2) == dot || str.indexOf(dot,(lat+2)) == -1 || str.indexOf(" ") != -1) return false;
		return true;				
	}
}

var Url = {

 	// public method for URL encoding
 	encode : function (string) {
 		 return escape(this._utf8_encode(string));
 	},

 	// public method for URL decoding
	 decode : function (string) {
 	 	return this._utf8_decode(unescape(string));
 	},

 	// private method for UTF-8 encoding
 	_utf8_encode : function (string) {
  		string = string.replace(/\r\n/g,"\n");
 	 	var utftext = "";

  		for (var n = 0; n < string.length; n++) {
   			var c = string.charCodeAt(n);
   			if (c < 128) {
    				utftext += String.fromCharCode(c);
 			} else if((c > 127) && (c < 2048)) {
  				utftext += String.fromCharCode((c >> 6) | 192);
  				utftext += String.fromCharCode((c & 63) | 128);
 			} else {
  				utftext += String.fromCharCode((c >> 12) | 224);
  				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
 	 			utftext += String.fromCharCode((c & 63) | 128);
 			}
 	}

		return utftext;
	},

 	// private method for UTF-8 decoding
 	_utf8_decode : function (utftext) {
 		 var string = "";
 		 var i = 0;
 		 var c = c1 = c2 = 0;

  		while ( i < utftext.length ) {
  			 c = utftext.charCodeAt(i);
   			if (c < 128) {
    				string += String.fromCharCode(c);
    				i++;
  			 } else if((c > 191) && (c < 224)) {
 				   c2 = utftext.charCodeAt(i+1);
    				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
    				i += 2;
  			 } else {
 				   c2 = utftext.charCodeAt(i+1);
    				c3 = utftext.charCodeAt(i+2);
    				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
   				 i += 3;
 			  }
		  }
		return string;
	 }
}

jQuery.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
	$cont.css('overflow','hidden').width();
	opts.before.push(function(curr, next, opts, fwd) {
		jQuery.fn.cycle.commonReset(curr,next,opts);
		opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
		opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
	});
	opts.cssFirst = { left: 0 };
	opts.cssBefore= { top: 0 };
	opts.animIn   = { left: 0 };
	opts.animOut  = { top: 0 };
};

