//Lib
//
function copyrightString() {
	var workingYear = "2003";
	var currentDay = new Date();
	var currentYear = new String(currentDay.getFullYear(currentDay));
	if (workingYear != currentYear) {
		var string = new String(" " + workingYear + "  &mdash; " + currentYear);
	}
	else {
		var string = new String(" " + workingYear);
	}
	$("#copyright_string").append("" + string + "");
}
//Lib

$(document).ready(function() {
	copyrightString();
	$("#index_bunner").height($("#index :first-child").height());
	$(document).keydown(function(e) {
		NavigateThrough(e);
	});
	
	$("button").hover(function() {$(this).addClass("hover");
	},function() {$(this).removeClass("hover");
	});
	$("button").mousedown(function() {$(this).addClass("active");
	});
	$("button").mouseup(function() {$(this).removeClass("active");
	});
	$("#portfolio_switch a").click(function() {
		if($(this).hasClass("briefly")) {
			$("#content_space").removeClass("list");
			$("#portfolio_carousel").addClass("briefly");
			$("#portfolio_carousel").j_carousel({
				distance:"100px",
				startPoint:"page line"
			});
			$(this).addClass("briefly_disabled").siblings("a").removeClass("list_disabled");
		}
		else {
			$("#content_space").addClass("list");
			$("#portfolio_carousel").removeClass("briefly").removeClass("j_carousel").removeClass("j_carousel_over").css({height:"auto"}).find("div.j_carousel_item").removeClass("j_carousel_item").appendTo($("#portfolio_carousel"));
			$("#portfolio_carousel").append('<div class="clear"></div>').find("div.j_carousel_clip").remove().end().find("div.j_carousel_joystick").remove();
			$(this).addClass("list_disabled").siblings("a").removeClass("briefly_disabled");
		}
		return false;
	});
	$("#portfolio_switch a.briefly").click();
	/*$(window).resize(function() {
		$("#portfolio_carousel div.clip").width(840).width(280*Math.floor($("#portfolio_carousel").width()/280));
		var carouselW = $("#portfolio_carousel div.belt").width();
		var clipW = $("#portfolio_carousel div.clip").width();
		listPathValue = carouselW-clipW;
		
		if(carouselW < clipW) {
			listLeftValue = 0;
			$("#portfolio_carousel a.prev, #portfolio_carousel a.prev").addClass("disabled");
		}
		else if(carouselW+listLeftValue <= clipW) {
			listLeftValue = -carouselW + clipW;
			if(listLeftValue == 0) {$("#portfolio_carousel a.next").removeClass("disabled");
			}
			$("#portfolio_carousel a.next").addClass("disabled");
		}
		else if(carouselW+listLeftValue > clipW) {
			if(listLeftValue == 0) {$("#portfolio_carousel a.next").removeClass("disabled");
			}
			else {
				$("#portfolio_carousel a.prev, #portfolio_carousel a.next").removeClass("disabled");
			}
		}
		
		$(listObject).animate({marginLeft:listLeftValue}, "middle");
	});*/
		
	$("ul.bitrix_navigation li a").click(function() {
		$("#content_space").children(".bitrix").removeClass("act");
		$("#" + $(this).attr("rel")).addClass("act");
		$(this).parents("ul").children("li").removeClass("act");
		$(this).parent().addClass("act");
		return false;
	});
	$("div.authority div.pics img").click(function() {
		showHideLayer("top_layer");
		showHideLayer($(this).attr("class"));
	});
	$("div.authority_pic_layer").find("div.close_icon").children().click(function() {
		showHideLayer("top_layer");
		showHideLayer($(this).parents("div.authority_pic_layer").attr("id"));
	});
	// 
//	$("#calendar div.padding ul.years li a").click(function() {
//		var yearId = $(this).text();
//		$(this).parents("div.padding").children("ul.months").each(function() {
//			$(this).css({display:"none"});
//		});
//		$(this).parents("div.padding").children("#" + yearId).css({display:"block"});
//		$(this).parents("ul.years").children("li").each(function() {
//			$(this).removeClass("act");
//		});
//		$(this).parent().addClass("act");
//		return false;
//	});
	// 
//	$("#work_picture").css({width:$("#work_picture").parents("td.picture").children("img").attr("width") + "px", height:$("#work_picture").parents("td.picture").children("img").attr("height") + "px"});
/*
	var work_picture_over = 0;
	var work_picture_out = 0;
	$("div.work_picture").hover(function() {
		if (work_picture_out == 0) {
			work_picture_over = 1;
			var workPicture = $(this).children("img.picture");
			$(this).children("img.picture").css({display:"block"});
			$(this).children("img.spacer").css({display:"none"});
			var workImage = new Image();
			workImage.src = workPicture.attr("src");
			workImageWidth = workImage.width;
			workImageHeight = workImage.height;
			$(workPicture).animate({width:workImageWidth, height:workImageHeight}, "slow");
			$(this).animate({left:"-" + ((workImageWidth-$(workPicture).attr("width"))/2), top:"-" + ((workImageHeight-$(workPicture).attr("height"))/2)}, "slow");
		}
	}, function() {
		if (work_picture_over == 1) {
			work_picture_over = 0;
			work_picture_out = 1;
			var workPicture = $(this).children("img.picture");
			var workImage = new Image();
			workImage.src = $(this).parents("div.work_item").children("img").attr("src");
			workImageWidth = workImage.width;
			workImageHeight = workImage.height;
			
			$(this).animate({left:"0", top:"0"}, "slow");
			$(workPicture).animate({width:workImageWidth, height:workImageHeight}, "slow").animate({opacity:"hide"}, "fast");
			setTimeout(function() {$("#content_space").find("td.picture").children(".act").find("img.spacer").css({display:"block"}); work_picture_out = 0;}, 1200);
		}
	});
*/
	$("#work_list div.item a").hover(function(e) {
		$(this).parent().find("div.image").css({left:(e.pageX - $(this).parent().offset().left - 20)});
		$(this).parent().children("div.relative").css({display:"block"});
	}, function () {
		$(this).parent().children("div.relative").css({display:"none"});
	});
	$("#work_list div.item span").hover(function(e) {
		$(this).parent().find("div.image").css({left:(e.pageX - $(this).parent().offset().left - 20)});
		$(this).parent().children("div.relative").css({display:"block"});
	}, function () {
		$(this).parent().children("div.relative").css({display:"none"});
	});
	$("#work_switch li.backward").hover(function() {
		$(this).addClass("hover");
	}, function() {
		$(this).removeClass("hover");
	});
	$("#work_switch li.forward").hover(function() {
		$(this).addClass("hover");
	}, function() {
		$(this).removeClass("hover");
	});
	$("#work_switch li.backward").click(function() {
		$("#work_switch li.forward").css({visibility:"visible"});
		var actWork = $("#work_picrures").children("div.act");
		var firstWork = $("div.work_item:first");
		var prevWork = $(actWork).prev();
		$(actWork).removeClass("act");
		$(prevWork).addClass("act");
		if($(firstWork).attr("class").search("act") != -1) {
			$(this).css({visibility:"hidden"});
		}
	});
	$("#work_switch li.forward").click(function() {
		$("#work_switch li.backward").css({visibility:"visible"});
		var actWork = $("#work_picrures").children("div.act");
		var lastWork = $("div.work_item:last");
		var nextWork = $(actWork).next();
		$(actWork).removeClass("act");
		$(nextWork).addClass("act");
		if($(lastWork).attr("class").search("act") != -1) {
			$(this).css({visibility:"hidden"});
		}
	});
	//$("#work_picrures").k3dCarousel();
	$("a.bitrix_version").click(function() {
		showHideLayer("top_layer");
		showHideLayer($(this).attr("rel"));
		return false;
	});
	$("div.bitrix_version_layer").find("div.close_icon").children().click(function() {
		showHideLayer("top_layer");
		showHideLayer($(this).parents("div.bitrix_version_layer").attr("id"));
	});
	$("#top_layer").click(function() {
		showHideLayer("top_layer");
		$("div.bitrix_version_layer:visible").each(function() {
			showHideLayer($(this).attr("id"));
		});
		$("div.authority_pic_layer:visible").each(function() {
			showHideLayer($(this).attr("id"));
		});
		if(document.getElementById("work_big_photo")) {
			showHideLayer("work_big_photo");
			$("#work_big_photo").empty();
		}
		if(document.getElementById("loader")) {
			$("#loader").css({display:"none"});
		}
	});
	$("#compare").find("td[class!='name']").hover(function() {
		var tr = this.parentNode;
		var counter = 0;
		var thisNumber = 0;
		for (var i = 0; i < tr.childNodes.length; i++) {
			if (tr.childNodes[i].tagName == "TD") {
				if (tr.childNodes[i] == this) {
					thisNumber = counter; 
				}
				counter++;
			}
		}
		$("#compare").find("tr").each(function() {
			$(this).children("td:eq(" + thisNumber + ")").addClass("hover");
		});
		$(this).addClass("hover");
	}, function() {
		$("#compare").find("td").removeClass("hover");
	});
	$("#compare").find("td[class!='name']").click(function() {
		$("#compare").find("td").removeClass("click");
		var tr = this.parentNode;
		var counter = 0;
		var thisNumber = 0;
		for (var i = 0; i < tr.childNodes.length; i++) {
			if (tr.childNodes[i].tagName == "TD") {
				if (tr.childNodes[i] == this) {
					thisNumber = counter; 
				}
				counter++;
			}
		}
		$("#compare").find("tr").each(function() {
			$(this).children("td.name").removeClass("not_checked");
			$(this).children("td:eq(" + thisNumber + ")").addClass("click");
			var src = new String($(this).children("td.click").children("img").attr("src"));
			if (src.search("spacer") != -1) {
				$(this).children("td.name").addClass("not_checked");
			}
		});
		$(this).addClass("click");
	});
	$("div.opening_text a.no_link").click(function() {
		$(this).parent().parent().children("div.open_text").removeClass("open_text");
		$(this).parent().parent().find("div.text").slideUp("fast");
		$(this).parent().addClass("open_text");
		$(this).next("div.text").slideDown("fast");
		return false;
	});
	$("#user_number").keyup(function() {
		calculateSum(this);
	});
	$("#user_number").blur(function() {
		if ($(this).attr("value") == "") {
			$(this).attr({value:"25"});
		}
	});
	$("button").bind("click", function() {
		$(this).parents("form").submit();
		return false;
	});
	$("table.order").find("td.delete").children("input").click(function() {
		if (confirm("Удалить продукт?")) {
			$(this).prev("input").attr({checked:"checked"});
			return true;
		}
		else {return false;
		}
	});
	$("#registration_form div.button a[href='#']").click(function() {
		checkForm("registration_form");
		return false;
	});
	$("#authorization_form button").unbind("click").bind("click", function() {
		checkForm("authorization_form");
		return false;
	});
	$("#authorization_form").find("input.text").keypress(function(e) {
		if(e.which == 13){
			checkForm("authorization_form");
		}
	});
	$("#current_orders div.order_button div.button a").click(function() {
		$(this).parents("form").submit();
		return false;
	});
	$("#order_button").click(function() {
		if($("#conditions input").attr("value") == "N") {
			$("#conditions").addClass("attention");
			return false;
		}
		else {
			$(this).parents("form").submit();
			return false;
		}
	});
	$("#region_form div.button a[href='#'], #delivery_form a.button").click(function() {
		$(this).parents("form").submit();
		return false;
	});
	$("div.orders div.order div.head").bind("click", function() {
		$(this).parents("div.order").children("div.body").slideToggle("middle");
	});
	$("div.orders div.order div.head a").unbind("click").bind("click", function() {
		if ($(this).attr("href") == "#") {
			$(this).parents("div.order").children("div.body").slideToggle("middle");
			return false;
		}
	});
	$("div.tariffs div.tariff div.head div.name a").bind("click", function() {
		$(this).parents("div.tariff").children("div.body").slideToggle("middle");
		return false;
	});
	$("div.form_checkbox img").click(function() {
		activateCheckbox(this);
	});
	$("div.form_checkbox span").click(function() {
		activateCheckbox(this);
	});
	$("#conditions input").attr({value:"N"});
	$("table.order tbody tr td.number input").keyup(function() {
		checkNumberField(this);
	});
	$("div.delivery h2 a").click(function() {
		$(this).parents("div.delivery_block").find("div.delivery").each(function() {
			$(this).removeClass("chosen");
		});
		$(this).parents("div.delivery").addClass("chosen");
		$("#delivery_form").find(":radio").attr({checked:""});
		var delievryPlace = $(this).attr('rel');
		$("#delivery_form").find(":radio").each(function() {
			if ($(this).attr("value") == delievryPlace) {
				$(this).attr({checked:"checked"});
			}
		});
		return false;
	});
	$("#forget_form button").unbind("click").bind("click", function() {
		checkForgetForm();
		return false;
	});
	$("#get_password_form button").unbind("click").bind("click", function() {
		checkForm("get_password_form");
		return false;
	});
/*	$("a.work_image").click(function() {
		showHideLayer("top_layer");
		showWorkPhoto(this);
		return false;
	});*/
	$("#work_big_photo").click(function() {
		showHideLayer("top_layer");
		showHideLayer("work_big_photo");
	});
	$("#calendar div.padding ul.months li:not(.act) a").hover(function() {
		$(this).parent().removeClass("out");
	}, function() {
		$(this).animate({color:'#f15925'}, 700, function() {
			$(this).attr({style:""});
		});
		$(this).parent().animate({backgroundColor:'#ffffff'}, 700, function() {
			$(this).addClass("out").attr({style:""});
		});
	});
	$("#comment_form button").click(function() {
		checkForm("comment_form");
		return false;
	});
	$("#comment_form").find("input.text").keypress(function(e){
		if(e.which == 13){
			checkForm("comment_form");
		}
	});
	
	$("#hide_tr").find("th").click(function() {
		$("#hide_tr").parent().find("tbody").toggleClass("hide");
	});
	$("#years").change(function() {
		$(this).parent().children("ul.visible").removeClass("visible");
		$(this).parent().children("#" + this.value).addClass("visible");
	});
});
var listPathValue, listObject;
var listLeftValue = 0;
var sliderLeftValue = 0;

function getyScroll() {
	var yScroll = 0;
	
	if (window.innerHeight && window.scrollMaxY) {
		yScroll = window.innerHeight + window.scrollMaxY;
		
		var deff = document.documentElement;
		var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
	
		yScroll -= (window.innerHeight - hff);
	} 
	else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
		yScroll = document.body.scrollHeight;
	} 
	else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
	}
	return yScroll;
}

function showHideLayer(layer_id) {
	var layer = document.getElementById(layer_id);
	if (layer.style.display == "none") {
		if (layer_id == "top_layer") {
			layer.style.height = $(document).height() + "px";
		}
		else {
			var layerHeight = layer.offsetHeight;
			if (document.documentElement.clientHeight > $(layer).height()) {
				layer.style.top = $(document).scrollTop() + (document.documentElement.clientHeight - $(layer).height())/2 + "px";
			}
			else {
				layer.style.top = $(document).scrollTop() + 20 + "px";
			}
		}
		layer.style.display = "block";
	}
	else {layer.style.display = "none";
	}
}

function calculateSum(input) {
	checkNumberField(input);
	
	if(input.value == "") {var users = "пользователей";}
	else {var number = new String(parseInt(input.value));
		if (/(10|11|12|13|14|15|16|17|18|19)$/.test(number)) {
			var users = 'пользователей';}
		else if (/.*1$/.test(number)) {
			var users = 'пользователь';}
		else if (/[2-4]$/.test(number)) {
			var users = 'пользователя';}
		else {var users = 'пользователей';}
	}
	
	var user_number = input.value - 25;
	if (user_number <= 0) {
		var discont = 0;
		user_number = 0;
	}
	else {
		if (user_number > 0 && user_number < 5) {
			var discont = 0;
			user_number = 5;
		}
		else {
			if (user_number < 25) {var discont = 0;}
			else {
				if (user_number < 50) {var discont = 10;}
				else {
					if (user_number < 100) {var discont = 15;}
					else {
						if (user_number < 500) {var discont = 25;}
						else {
							if (user_number < 1000) {var discont = 35;}
							else {
								if (user_number < 2000) {var discont = 45;}
								else {
									if (user_number < 5000) {var discont = 50;}
									else {var discont = 60;}
								}
							}
						}
					}
				}
			}
		}
	}
	var summ = user_number * (500*(100-discont)*0.01) + 34500;
	var summString = spacing(summ);
	$(input).parent().parent().parent().children("form").children("span.price").children("span.num").text("" + summString);
	$(input).parent().children("span").text(users);
}

function checkNumberField(input) {//проверяем чтобы в поле вводились только цифры
	var inputValue = input.value;
	if (inputValue != "") {
		var numberRegex = /([\d])$/i;
		if(!inputValue.match(numberRegex) || inputValue.length > 4){
			input.value = inputValue.slice(0,inputValue.length-1);
			checkNumberField(input);
		}
	}
}

function spacing(number) {//для проставления пробелов в денежных суммах
	var numberString = new String(number);
	var counter = Math.floor((numberString.length-1)/3);
	var subArray = new Array();
	for (var i = 0; i < counter; i++) {
		subArray[i] = numberString.substr(numberString.length-3*i-3, 3);
	}
	subArray[counter] = numberString.substr(0, numberString.length - 3*counter);
	subArray.reverse();
	var summString = new String(subArray.join(" "));
	return summString;
}

var sendFormFlag = 0;
var firstElement;
function checkForm(form_id) {
	var form = document.getElementById(form_id);
	sendFormFlag = 0;
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type != "hidden") {
			if (form.elements[i].value == "") {
				if (form.elements[i].disabled) {
					imgDisplay(form.elements[i]);
				}
				else {imgDisplay(form.elements[i],1);
				}
			}
			else {
				if (form.elements[i].name.toUpperCase().search('EMAIL') != -1) {
					var mail = form.elements[i].value;
					var mailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
					if(!mail.match(mailRegex)){
						errorFlag = 1;
						imgDisplay(form.elements[i],1);
					}
					 else {
						imgDisplay(form.elements[i]);
					};
				
				}
				else {
					imgDisplay(form.elements[i]);
				}
			}
		}
	}
	if (sendFormFlag == 0) {
		form.submit();
	}
	else {
		$(window).scrollTop($(firstElement).offset().top - 50);
	}
}
function imgDisplay (form_element,flag_value) {
	var formElement = form_element;
	var fieldDiv = formElement.parentNode;
	var fieldDivChildren = fieldDiv.childNodes;
	for (var j = 0; j < fieldDivChildren.length; j++) {
		if (fieldDivChildren[j].tagName == "H5") {
			var fieldH = fieldDivChildren[j];
			var fieldHChildren = fieldH.childNodes;
			for (var a = 0; a < fieldHChildren.length; a++) {
				if (fieldHChildren[a].tagName == "SPAN") {
					if(flag_value){
						$(fieldDiv).addClass("attention");
						if (sendFormFlag == 0) {
							firstElement = $(fieldDiv);
						}
						sendFormFlag = flag_value;
					}
					else {$(fieldDiv).removeClass("attention");
					}
				}
			}
		}
	}
}

function activateCheckbox(element) {
	var img = $(element).parent().children("img");
	var attr2 = new String($(img).attr("src"));
	if (attr2.search('_act') != -1) {
		$(img).attr({src:"/images/checkbox.gif"});
		$(img).next("input").attr({value:"N"});
	}
	else {
		$(img).attr({src:"/images/checkbox_act.gif"});
		$(img).next("input").attr({value:"Y"});
	}
}

function checkForgetForm() {
	var form = $("#forget_form");
	var loginField = $("form").find("input[name='login']");
	var mailField = $("form").find("input[name='e-mail']");
	if ($(loginField).attr("value") != "") {
		form.submit();
	}
	else {
		if ($(mailField).attr("value") != "") {
			var mail = $(mailField).attr("value");
			var mailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
			if(!mail.match(mailRegex)) {
				$(mailField).parent().addClass("attention");
			}
			 else {
				 form.submit();
			};
		}
	}
}

function showWorkPhoto(link_obj) {
	showHideLayer("loader");
	var img = new Image();
	img.src = $(link_obj).attr("href");
	$(img).load(function() {
		$("#loader").removeClass("load");
		$("#work_big_photo").html('<img src="' + img.src + '" width="' + img.width + '" height="' + img.height + '" alt="">');
		$("#work_big_photo").css({margin:"-" + img.height/2 + "px 0 0 -" + img.width/2 + "px"});
		showHideLayer("work_big_photo");
		$("#work_big_photo img").animate({opacity:"show"}, "middle");
		showHideLayer("loader");
	});
}
//k3dCarousel
(function(a){a.fn.k3dCarousel=function(b){return this.each(function(){var c=0,d,e,f,g,h,i=[],j=0,k=this.offsetWidth,l=a(this).css("position","relative").find("img").css({position:"absolute",opacity:0,display:"block"}),m={r:k*0.3,cX:k/2,cY:this.offsetHeight/2,sT:1e3,wT:2e3};b&&a.extend(m,b),l.each(function(b,c){c.oW=c.offsetWidth,c.oH=c.offsetHeight,a(c).css({left:m.cX-c.oH/2,top:0})}),g=l.length,h=Math.PI/(g/2);for(;c<g;++c)d=Math.sin(h*c),i.push({l:m.cX+Math.cos(h*c)*m.r,z:parseInt(50*d+50),t:d*10+10,o:0.45*d+0.55,m:0.4*d+0.6}),l[c]=a(l[c]);function n(){for(c=0;c<g;++c)e=i[c],f=e.m*l[c][0].oW,l[(c+j)%g].animate({left:e.l-f/2,opacity:e.o,top:e.t,width:f,height:e.m*l[c][0].oH},m.sT).css("z-index",e.z);j++,setTimeout(n,m.wT+m.sT)}n()})}})(jQuery)

//навигация с помощью стрелок
function NavigateThrough(event) {
	if (!document.getElementById) return;
	if (window.event) event = window.event;
	if (event.ctrlKey) {
		if(document.getElementById("portfolio_carousel") && document.getElementById("portfolio_carousel").className == "briefly") {
			switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
				case 0x25: $("#portfolio_carousel a.prev").click(); break;
				case 0x27: $("#portfolio_carousel a.next").click(); break;
			}
		}
		/*else {
			var link = null;
			var href = null;
			switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
				case 0x25: link = document.getElementById ('PrevLink'); break;
				case 0x27: link = document.getElementById ('NextLink'); break;
				case 0x24: href = '/'; break;
			}
			if (link && link.href) document.location = link.href;
			if (href) document.location = href;
		}*/
	}
}

function jPageY(element) {
	if(!element) {var element = $(this)[0];
	}
	return element.offsetParent ?
	element.offsetTop + jPageY( element.offsetParent ) :
	element.offsetTop;
}
function jPageX(element) {
	if(!element) {var element = $(this)[0];
	}
	return element.offsetParent ?
	element.offsetLeft + jPageX( element.offsetParent ) :
	element.offsetLeft;
}

(function($) {
	var defaults = {
		position:"over",//"over" or "built in"
		itemClass:"item",//class name for item objects
		startPoint:"0px",//first element position (i.e. 30px) or "page line" � left side of the page body
		endPoint:"0px",//last element position (i.e. 30px - pixels from right side) or "page line" - right side of the page body
		alignCenter:false,//if true the line starts from the center position
		distance:"50px",//value of joystick distance in one direction
		maxSpeed:"1",//px per 1000 ms
		stepTime:30,
		circle:false//true if we want the line to have no end
	};
	
	$.fn.j_carousel = function(params) {
		
		$(this).each(function() {
			var
			methods = {
				val:function(cssValue) {return parseInt(/^-*[0-9]*/.exec(cssValue), 10);},
				animateBelt:function() {
					var left = Math.floor($belt.left-speed*options.stepTime);
					if((left>-($belt.path-$belt.start) && left<$belt.start) || (left==-($belt.path-$belt.start)&&speed>0) || (left==$belt.start&&speed<0)) {
						$belt.left = left;
						$belt.css({marginLeft:$belt.left + "px"});
					}
					else if(left<-($belt.path-$belt.start)) {
						$belt.left = -($belt.path-$belt.start);
						$belt.css({marginLeft:$belt.left + "px"});
					}
					else if(left>$belt.start) {
						$belt.left = $belt.start;
						$belt.css({marginLeft:$belt.left + "px"});
					}
				},
				start:function() {
					$belt.path = $belt.width() - $clip.width()-methods.val($this.find(".j_carousel_item:last").css("marginRight"));
					if (options.startPoint != "center") {$belt.path += $belt.start + $belt.end;}
					$a.stop();
					intervalID = setInterval(function() {methods.animateBelt()}, options.stepTime);
				},
				drag:function() {
					$joystick.left = methods.val($a.css("left"));
					$belt.left = methods.val($belt.css("marginLeft"));
					speed = ($joystick.left-methods.val(options.distance))/methods.val(options.distance);},
				stop:function() {
					clearInterval(intervalID);
					speed = 0;
					$a.stop().animate({left:options.distance});
				}
			},
			options = $.extend({}, defaults, params),
			intervalID='',
			incSpeed='',
			speed=0,
			keydown=false,
			
			$this = $(this),
			$itemObject = $this.find("." + options.itemClass).addClass("j_carousel_item"),
			
			//max width and height of item-element
			maxWidth=0, maxHeight=0, beltWidth=0;
			
			$itemObject.each(function() {
				var $this = $(this);
				maxWidth = Math.max($this.outerWidth(), maxWidth);
				maxHeight = Math.max($this.outerHeight(), maxHeight);
				beltWidth += $this.outerWidth()+methods.val($this.css("marginLeft"))+methods.val($this.css("marginRight"));
			});
			
			//html structure
			var
			$clip = $('<div class="j_carousel_clip"></div>').height(maxHeight).width("100%"),
			$belt = $('<div class="j_carousel_belt"></div>').width(beltWidth).height(maxHeight),
			$joystick = $('<div class="j_carousel_joystick"><span></span><a href="#"></a></div>'),
			$a = $joystick.children("a").click(function() {return false;}).css({left:options.distance + "px"}),
			$span = $joystick.children("span");
						
			$clip.append($belt.append($itemObject).append('<div class="j_clear"></div>'))
			$this.empty().addClass("j_carousel").append($clip).append($joystick).css({height:$belt.height() + "px"});
			
					
			//position
			if(options.position == "over") {
				$this.addClass("j_carousel_over");
				$clip.css({top:$this.offset().top+methods.val($this.css("border-top-width"))+methods.val($this.css("padding-top")) + "px"});
				$a.css({top:maxHeight+10 + "px"});
				$span.css({top:methods.val($a.css("top"))-0.5*($span.outerHeight()-$a.outerHeight()) + "px"})
				$this.height(methods.val($a.css("top"))+$a.outerHeight());
			}
			
			//start point
			if(options.startPoint == "page line") {
				$belt.css({marginLeft:$this.offset().left + "px"});
				$belt.start = $this.offset().left;
			}
			else {
				$belt.css({marginLeft:options.startPoint});
				$belt.start = methods.val(options.startPoint);
			}
			$belt.left = methods.val($belt.css("marginLeft"));
			
			//end point
			if(options.endPoint == "center") {$belt.end = 0;}
			else if(options.endPoint == "page line") {$belt.end = $(window).width()-($this.offset().left+$this.width());}
			else {$belt.end = methods.val(options.endPoint);}
			
			//align center
			if(options.alignCenter == true) {
				$belt.css({marginLeft:"-"+($belt.width()/2 - $clip.width()/2) +"px"});
			}
			
			//joystick
			$joystick.width(methods.val(options.distance)*2 + $a.width()).children("a").css({left:options.distance});
			$span.width(methods.val(options.distance)*2 + $a.width()+"px");
			
			$a.draggable({
				axis:'x',
				containment:'.j_carousel_joystick',
				start:methods.start,
				drag:methods.drag,
				stop:methods.stop
			});
			
			$(document).bind("keydown", function(e) {
				if(keydown===false) {
					if(e.which==37 || e.which==39) {
						methods.start();
						incSpeed = setInterval(function() {
							methods.drag();
						}, 100);
					}
					switch (e.which) {
						case 39:$a.stop().animate({left:$joystick.width()-$a.width()}, 1000); break;
						case 37:$a.stop().animate({left:"0"}, 1000); break;
					}
				}
				keydown=true;
			}).bind("keyup", function(e) {
				if(e.which==37 || e.which==39) {
					keydown=false;
					clearInterval(incSpeed);
					methods.stop();
				}
			});
		});
		
		return this;
	};
})(jQuery);

///-------------------////
/*!
 * jQuery UI 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

//Helper functions and ui object
$.extend( $.ui, {
	version: "1.8.4",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode ) {
				return;
			}

			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},

	contains: function( a, b ) {
		return document.compareDocumentPosition ?
			a.compareDocumentPosition( b ) & 16 :
			a !== b && a.contains( b );
	},

	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},

	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	},

	keyCode: {
		ALT: 18,
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		COMMAND: 91,
		COMMAND_LEFT: 91, // COMMAND
		COMMAND_RIGHT: 93,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		MENU: 93, // COMMAND_RIGHT
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38,
		WINDOWS: 91 // COMMAND
	}
});

//jQuery plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	enableSelection: function() {
		return this
			.attr( "unselectable", "off" )
			.css( "MozUserSelect", "" );
	},

	disableSelection: function() {
		return this
			.attr( "unselectable", "on" )
			.css( "MozUserSelect", "none" );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ) );
					if ( !isNaN( value ) && value != 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
			if ( border ) {
				size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$.style( this, type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$.style( this, type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

//Additional selectors
function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.curCSS( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr( element, "tabindex" );
		if ( "area" === nodeName ) {
			var map = element.parentNode,
				mapName = map.name,
				img;
			if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
				return false;
			}
			img = $( "img[usemap=#" + mapName + "]" )[0];
			return !!img && visible( img );
		}
		return ( /input|select|textarea|button|object/.test( nodeName )
			? !element.disabled
			: "a" == nodeName
				? element.href || !isNaN( tabIndex )
				: !isNaN( tabIndex ))
			// the element and all of its ancestors must be visible
			&& visible( element );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" );
		return ( isNaN( tabIndex ) || tabIndex >= 0 ) && $( element ).is( ":focusable" );
	}
});

})( jQuery );

/*!
 * jQuery UI Widget 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

var _remove = $.fn.remove;

$.fn.remove = function( selector, keepData ) {
	return this.each(function() {
		if ( !keepData ) {
			if ( !selector || $.filter( selector, [ this ] ).length ) {
				$( "*", this ).add( [ this ] ).each(function() {
					$( this ).triggerHandler( "remove" );
				});
			}
		}
		return _remove.call( $(this), selector, keepData );
	});
};

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.substring( 0, 1 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name ),
					methodValue = instance && $.isFunction( instance[options] ) ?
						instance[ options ].apply( instance, args ) :
						instance;
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					if ( options ) {
						instance.option( options );
					}
					instance._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			$.metadata && $.metadata.get( element )[ this.widgetName ],
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._init();
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.widget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				"ui-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			self = this;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, self.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return self;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );

/*!
 * jQuery UI Mouse 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.mouse", {
	options: {
		cancel: ':input,option',
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
});

})(jQuery);


/*
 * jQuery UI Draggable 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.draggable", $.ui.mouse, {
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false
	},
	_create: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.addClasses && this.element.addClass("ui-draggable"));
		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element
			.removeData("draggable")
			.unbind(".draggable")
			.removeClass("ui-draggable"
				+ " ui-draggable-dragging"
				+ " ui-draggable-disabled");
		this._mouseDestroy();

		return this;
	},

	_mouseCapture: function(event) {

		var o = this.options;

		// among others, prevent a drag on a resizable-handle
		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.positionAbs = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Trigger event + callbacks
		if(this._trigger("start", event) === false) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			if(this._trigger('drag', event, ui) === false) {
				this._mouseUp({});
				return false;
			}
			this.position = ui.position;
		}

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			dropped = $.ui.ddmanager.drop(this, event);

		//if a drop comes from outside (a sortable)
		if(this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}
		
		//if the original element is removed, don't bother to continue
		if(!this.element[0] || !this.element[0].parentNode)
			return false;

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				if(self._trigger("stop", event) !== false) {
					self._clear();
				}
			});
		} else {
			if(this._trigger("stop", event) !== false) {
				this._clear();
			}
		}

		return false;
	},
	
	cancel: function() {
		
		if(this.helper.is(".ui-draggable-dragging")) {
			this._mouseUp({});
		} else {
			this._clear();
		}
		
		return this;
		
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj == 'string') {
			obj = obj.split(' ');
		}
		if ($.isArray(obj)) {
			obj = {left: +obj[0], top: +obj[1] || 0};
		}
		if ('left' in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ('right' in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ('top' in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ('bottom' in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
			var ce = $(o.containment)[0]; if(!ce) return;
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		} else if(o.containment.constructor == Array) {
			this.containment = o.containment;
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return $.Widget.prototype._trigger.call(this, type, event, ui);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

});

$.extend($.ui.draggable, {
	version: "1.8.4"
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, 'sortable');
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
				if(this.shouldRevert) this.instance.options.revert = true;

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper == 'original')
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {
			
			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;
			
			if(this.instance._intersectsWith(this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };




					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					
					//Prevent reverting on this forced stop
					this.instance.options.revert = false;
					
					// The out event needs to be triggered independently
					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
					
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), o = $(this).data('draggable').options;
		if (t.css("cursor")) o._cursor = t.css("cursor");
		t.css("cursor", o.cursor);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if (o._cursor) $('body').css("cursor", o._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		var o = $(this).data('draggable').options;
		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data('draggable').options;
		if(t.css("opacity")) o._opacity = t.css("opacity");
		t.css('opacity', o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("draggable");
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	drag: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if(!o.axis || o.axis != 'x') {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
			}

			if(!o.axis || o.axis != 'y') {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
			}

		} else {

			if(!o.axis || o.axis != 'x') {
				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}

			if(!o.axis || o.axis != 'y') {
				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options;
		i.snapElements = [];

		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != i.element[0]) i.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options;
		var d = o.snapTolerance;

		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(o.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
			}

			var first = (ts || bs || ls || rs);

			if(o.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {

		var o = $(this).data("draggable").options;

		var group = $.makeArray($(o.stack)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
		});
		if (!group.length) { return; }
		
		var min = parseInt(group[0].style.zIndex) || 0;
		$(group).each(function(i) {
			this.style.zIndex = min + i;
		});

		this[0].style.zIndex = min + group.length;

	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("draggable").options;
		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
		t.css('zIndex', o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("draggable").options;
		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
	}
});

})(jQuery);


