$(document).ready(function(){

	if($("ul.dropdown").length) $("ul.dropdown li").dropdown();

	$("form.validate").live('submit', function() {

		var self = $(this);

		var valid = true;
		var email_pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/i;

		$(".alert", this).removeClass("alert");

		$(this).find(".required").each(function() {
			var value = $(this).val();
			if(value == "" || ($(this).is(".email") && !email_pattern.test(value))) {
				valid = false;
				$(this).addClass("alert");
			}
		});

		if(!valid) {
			$("#alert", this).show().css('visibility', 'visible');
			return false;
		}

		if($(".curtain", self).length) {

			var datastr = self.serialize();
			var query =  $(this).attr("action");

			$.ajax({
				type: "POST",
				url: query,
				data: datastr,
				dataType: "html",
				success: function(data){
					var result = data.toString();
					$(".curtain .result", self).text(result);
				},
				complete: function() {
					$("#alert", self).hide();
					$(".curtain", self).fadeIn();
					self.clearForm();
				}
			});
		}

		return false;

	});

	$(".curtain .close").live("click",function(){
		$(this).closest(".curtain").fadeOut();
		return false;
	});

	if($(".mycarousel").length) {

		$("#mycarousel1").jcarousel({
			scroll: 1,
			animation: 2000,
			wrap: 'both',
			auto: 8,
			itemVisibleInCallback: {
				onAfterAnimation: function(c, o, i, s) {
					var i = c.index(i);
					--i;
					$('a.on', c.list).removeClass('on');
					$('li:eq('+i+') a', c.list).addClass('on');
				}
			}
		});

		$(".jcarousel-container").prepend('<div class="frame"></div>');
	}

	if($("#banner .carousel-holder").length) {

		$("#banner .carousel-holder .frame").click(function(e){
			e.preventDefault();
			var b = $(this).closest("#banner");
			location.href = $("a.on", b).attr('href');
		});
	}

});

$.fn.dropdown = function() {

	$(this).hover(function(){
		$(this).addClass("hover");
		$('> .dir',this).addClass("open");
		$('ul:first',this).css('visibility', 'visible');
	},function(){
		$(this).removeClass("hover");
		$('.open',this).removeClass("open");
		$('ul:first',this).css('visibility', 'hidden');
	});

}

$.fn.clearForm = function() {
  return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
	  return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea')
	  this.value = '';
	else if (type == 'checkbox' || type == 'radio')
	  this.checked = false;
	else if (tag == 'select')
	  this.selectedIndex = -1;
  });
};
