var event_details = "";
window.onload = function() {
	var hash = window.location.hash;
	
	if ( hash.length > 1) {
		window.location = hash.substr(1);
	}
	
    //~ console.log(window.location.hash);
};

$(document).ready(function() {
	window.onpopstate = function(event) {
		if (0) 
		if (event.state) {
			//~ console.log("onpopstate target:" + event.state);
			$.ajax({
				url: document.location,
				context: $(event.state),
				preventHistoryHandler: true,
				success: function(data) {
					//~ console.log("onpopstate ajax success!");
					$(this).html(data);
					
				}
			});
		}	
	};
	
	
	$(document).bind('ajaxSend', function(event, XHR, ajaxOptions) {
			if ((ajaxOptions.preventHistoryHandler == undefined) && ( ajaxOptions.type != "POST")) {
				 if (ajaxOptions.context) {
					 //~ console.log(ajaxOptions.context);
					 state = ajaxOptions.context;
				 } else {
					 state = "";
				 }
				 
				 
				 try {
					 history.pushState(state, "", ajaxOptions.url); // HTML5 History API ff4.0, chrome 9
				 } catch(err) {
					 window.location.hash = ajaxOptions.url;
				 }
		    }
			 
			 
			 });
	/** Authorization */
	$("#auth-form").live("submit", function() {
		/*$("#email_err").html("").hide();
		$("#pwd_err").html("").hide();*/
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				if (xhr.getResponseHeader('X-MOBBIT-ERROR')) {
					var json = eval(responseText);
					if (json.username !== undefined)
						$("#email_err").html(json.username[0]).show();
					if (json.password !== undefined)
						$("#pwd_err").html(json.password[0]).show();
					if (json.__all__ !== undefined)
						$("#email_err").html(json.__all__[0]).show();
				} else {
					window.location = xhr.getResponseHeader('X-MOBBIT-REDIRECT');
				}
			}
		});
		return false;
	});
	/* END */
	
	/** Registration */
	$("#reg-form").live("submit", function() {
		$("#reg-error").html("");
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				if ((responseText !== null) && (typeof(responseText) == "object")) {
					var json = eval(responseText);
					if (json.email !== undefined)
						$("#reg-error").html(json.email[0]);
				} else {
					$("#content").html(responseText);
				}
			}
		});
		return false;
	});
	/* END */
	
	/** Delete event participant */
	$("#delete-form").live("submit", function() {
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				$("#participants").html(responseText);
			}
		});
		return false;
	});
	/* END */
	
	$(".edit").live("focusin", function() {
		var def = $(this).siblings("input").val();
		if ($(this).val() == def)
			$(this).val("");
	});
	$(".edit").live("focusout", function() {
		var def = $(this).siblings("input").val();
		if ($(this).val() == "")
			$(this).val(def);
	});
	
	/** Calendar */
	$(".days a").live("click", function(event) {
		event.preventDefault();
		$(".days td").each(function(i, e) {
			$(this).removeClass("focused");
		});
		var href = $(this).attr("href");
		var strdate = href.slice(17);
		// Make me unsee it vvv 
		
		//~ var dd = strdate.slice(8, 10);
		//~ var dm = strdate.slice(5, 7);
		//~ var dy = strdate.slice(0, 4);
		//~ var b = false;
		//~ if (dy >= ty) if (dm >= tm) if (dd >= td) b = true;
		//~ if (!b) $("#add-event").hide(); else $("#add-event").show();
		
		
		var date = new Date(strdate);
		var today = new Date();

		today.setHours(0);
		today.setMinutes(0);
		today.setSeconds(0);
		today.setMilliseconds(0);
				
		
		if ( date < today) {
			$("#add-event").hide();
		} else {
			$("#add-event").show();
		}
		
		$("#add-event").attr("rel", strdate);
		$(this).parent("td").addClass("focused");
		if ($(this).parent("td").hasClass("has_events")) {
			$.ajax({
				url: $(this).attr("href"),
				context: "#events",
				success: function(data) {
					$("#event-details").html("");
					$(this+"").html(data).find("a:first").click();					
					
					
					
				}
			});
		} else {
			$("#events").html("");
			$("#event-details").html("");
		}
	});
	$(".month a").live("click", function(event) {
		event.preventDefault();
		$.ajax({
			url: $(this).attr("href"),
			context: "#calendar-table",
			success: function(data) {
				$(this+"").html(data);
				$(".days").find("a:first").click();
			}
		});
	});
	$("#events a").live("click", function(event) {
		event.preventDefault();
		$(this).addClass("focused").siblings("a").removeClass("focused");
		$.ajax({
			url: $(this).attr("href"),
			context: "#event-details",
			success: function(data) {
				$(this+"").html(data);
			}
		});
	});
	$("#join-form").live("submit", function() {
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				$("#participants").html(responseText);
			}
		});
		return false;
	});
	/* END */
	
	$("p.caption a").live("click", function(event) {
		event.preventDefault();
		var href = $(this).attr("href");
		$.ajax({
			url: href,
			context: "#right-block",
			success: function(data) {
				if (href === "/club/")
					$(this+"").html($(data).find("#right-block").html());
				else
					$(this+"").html(data);
			}
		});
	});
	
	/** Personal */
	$("#edit-click a").live("click", function(event) {
		event.preventDefault();
		var s = $(this).text();
		if ($(this).text() === "отмена") {
			$(this).text("редактировать");
			$("#edit-data").hide();
			$("#view-data").show();
		} else {
			$(this).text("отмена");
			$("#view-data").hide();
			$("#edit-data").show();
		}
	});
	$("#edit-data-form").live("submit", function() {
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				$("#user-data").html(responseText);
				//window.location.reload(true);
				//alert(responseText);
			}
		});
		return false;
	});
	
	$(".personal .menu ul li a").live("click", function(event) {
		event.preventDefault();
		$.ajax({
			url: $(this).attr("href"),
			context: "#content",
			success: function(data) {
				$(this+"").html(data);
			}
		});
	});

	
	
	/* END */
	
	/*$(".photo").live("mousemove", function(event) {
		var x = event.clientX;
		var w = $(this).find(".file").width();
		$(this).find(".file").offset({ left: x - w + 25 });
	});*/
	
	/** Events - Add event */
	$("#add-event").live("click", function(event) {
		event.preventDefault();
		var strdate = $(this).attr("rel");
		$.ajax({
			url: $(this).attr("href"),
			context: "#event-details",
			success: function(data) {
				$(this+"").html(data).find("#date_").val(strdate);
			}
		});
	});
	$("#event-edit-form").live("submit", function() {
		//OnUploadStart();
		$(this).ajaxSubmit({
			//target: "#event-details",
			dataType: "html",
			data: { __ajax: true },
			success: function(responseText, statusText, xhr) {
				//alert(responseText);
				window.location = "/calendar/";
			}
			//timeout: 5000
			//iframe: true
		});
		return false;
	});
	/* END */
	
	/** Events - Edit event */
	$("#edit-event").live("click", function(event) {
		event.preventDefault();
		event_details = $("#event-details").html();
		$.ajax({
			url: $(this).attr("href"),
			context: "#event-details",
			success: function(data) {
				$(this+"").html(data).append('<a id="cancel-edit-event" href="#">отмена</a>');
			}
		});
	});
	$("#cancel-edit-event").live("click", function(event) {
		event.preventDefault();
		$("#event-details").html(event_details);
	});
	/* END */
	
	/** Events - Delete event */
	$("#delete-event").live("click", function(event) {
		event.preventDefault();
		if (confirm("Удалить событие?")) {
			$(this).parent("form").ajaxSubmit({
				success: function(responseText, statusText, xhr) {
					$("#content").html(responseText);
				}
			});
		}
	});
	/* END */
	
	/** Resend registration details */
	$("#change-email").live("click", function(event) {
		event.preventDefault();
		var val = $(this).text();
		if (val == "отмена") {
			$(this).text("изменить");
			$("#email1").css("visibility", "visible");
		} else {
			$(this).text("отмена");
			$("#email1").css("visibility", "hidden");
		}
		$(".new-email").toggle();
	});
	$("#resend-reg").live("submit", function() {
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				$("#content").html(responseText);
			}
		});
		return false;
	});
	/* END */
	
	/** Datepicker */
	$(".datepicker").live("focusin", function() {
		$(this).datepicker({
			dateFormat: "yy-mm-dd"
		});
	});
	/* END */
	
	$("#sales-back-to-descr").live("click", function(event) {
		event.preventDefault();
		$(".discount-info").show();
		$(".sales_reg").show();
	});
	$("#buy-coupon").live("click", function(event) {
		event.preventDefault();
		$(".discount-info").hide();
		$(".sales_reg").hide();
	});
	
	/** Buttons - click effect */
	$(".clickable").live("mousedown", function(event) {
		$(this).css("background-position", "0 0");
	});
	$(".clickable").live("mouseup", function(event) {
		$(this).css("background-position", "0 -45px");
	});
	$(".clickable").live("mouseleave", function() {
		$(this).css("background-position", "0 -45px");
	});
	/* END */
	
	/** Remind password */
	$("#remind-pwd").live("click", function(event) {
		event.preventDefault();
		$.ajax({
			url: $(this).attr("href"),
			context: "#content",
			success: function(data) {
				$(this+"").html(data);
			}
		});
	});
	$("#remind-form").live("submit", function() {
		$(this).ajaxSubmit({
			success: function(responseText, statusText, xhr) {
				if (xhr.getResponseHeader('X-MOBBIT-ERROR')) {
					var json = eval(responseText);
					var s = '<ul class="errors">';
					for (var i = 0; i < json.email.length; i++)
						s += "<li>"+json.email[i]+"</li>";
					s += "</ul>";
					$("#remind-error").html(s);
				} else 
					$("#content").html(responseText);
			}
		});
		return false;
	});
	/* END */
	
	$("#check-coupon-form").live("submit", function(e) {
		e.preventDefault();
		$(this).ajaxSubmit({
			success: function(data, status, xhr) {
				$("#coupon_details").html(data);
				//alert(data);
			}
		});
	});
	$("#mark-coupon").live("submit", function(e) {
		e.preventDefault();
		$(this).ajaxSubmit({
			success: function(data, status, xhr) {
				
			}
		});
	});
	
	/** Select payment method */
	/*$("#pay-method div.item").live("click", function(event) {
		var ind = $(this).index() + 1;
		$(this).addClass("active").siblings(".item").removeClass("active");
		$(".pay-method").css('background-image', 'url(/img/pm'+ind+'.jpg)');
		if (ind > 1)
			$(this).parents("#pay-method").siblings(".description").find(".text").html("");
		else
			$(this).parents("#pay-method").siblings(".description").find(".text").html("Принимаются к оплате карты Visa, Master Card");
	});*/
	/* END */
	
	/** Tabcontrol */
	$("#tabs li").live("click", function(e) {
		$(this).addClass('active').siblings().removeClass('active').parents(".left").find("div.page").hide().eq($(this).index()).show();
	});
	
	$(".num").live("click", function(e) {
		e.preventDefault();
		$(this).siblings(".coupon_info").toggle();
	});
});

$(function() {
	$(".sales_carousel .wrap .carousel").jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev",
		speed: 850,
		visible: 4
	});
});

function autoSubmit() {
	$("#auth-form").ajaxSubmit({
		success: function(responseText, statusText, xhr) {
			if (xhr.getResponseHeader('X-MOBBIT-ERROR')) {
				var json = eval(responseText);
				if (json.username !== undefined)
					$("#email_err").html(json.username[0]).show();
				if (json.password !== undefined)
					$("#pwd_err").html(json.password[0]).show();
				if (json.__all__ !== undefined)
					$("#email_err").html(json.__all__[0]).show();
			} else {
				window.location = xhr.getResponseHeader('X-MOBBIT-REDIRECT');
			}
		}
	});
}

/*var uploadStarted = false;
function OnUploadStart() {
	uploadStarted = true;
}

function OnUploadComplete(state,message) {
	if (state == 1)
		alert("Success: "+message);     
	else
		if (state == 0 && uploadStarted)
			alert("Error:"+( message ? message : "unknow" ));
}*/

var params = {
	changedEl: ".cbstyled",
	visRows: 20,
	scrollArrows: true
}

//cuSel(params);


//===== sales ===
function sales_recalculate() {
	quantity = parseInt($('#sales-quantity').val());
	if (quantity > 0) {
		price = parseInt($('#sales-price').text());
		total = quantity * price;
		$('#sales-total').text(total);
		$('#sales-total2').text(total);
		$('#sales-total3').text(total);
		$('#sales-total4').text(total);
		
		balance = parseFloat($('#account-balance').val());
		if (total > balance) {
			$('#method-imobbit').removeClass('active');
		} else {
			$('#method-imobbit').addClass('active');
		}
		
		
		
	}		 
}
$('#sales-quantity').live('click', sales_recalculate);
$('#sales-quantity').live('keyup', sales_recalculate);
$('#sales-quantity').live('blur', function() { 
		val = parseInt($('#sales-quantity').val());
		if (!(val > 0)) {
			val = 1;
		}
		
		if (val > 100) {
			val = 100;
		}
		
		
		$('#sales-quantity').val(val); 
		sales_recalculate();
		 });
			


$('input.quantity').live('keydown', function (event) {
	if (event.keyCode == 38 ) {
		val = parseInt($(this).val())
		if (val < 100) {
			$(this).val(val+1);
		}
	} else if (event.keyCode == 40 ) {
		val = parseInt($(this).val())
		if (val > 1){
			$(this).val(val-1);
		}
	}
}) ;

$("#purchase_button").live('click', function (event) {
	$(this).attr("disabled", "disabled");
	quantity = $('input.quantity').val();
	sale_id = $(this).attr('sale');
	btn = $(this);
	$.ajax({
		url: "/sales/pay_masterbank",
		type: "POST",
		dataType: 'json',
		data: { "count" : quantity, "sale" : sale_id},
		success: function(data) {
			console.log(data.url);
				console.log(data.post);
				var form = document.createElement('form');
				form.setAttribute('action', data.url);
				form.setAttribute('method', 'POST');
				for (name in data.post) {
					var input = $('<input name="' + name + '" type="hidden" value="' + data.post[name] + '"/>');
					form.appendChild(input[0]);
				}
				document.body.appendChild(form);
				//btn.removeAttr("disabled");
				form.submit();
		}
	});
	
});

