var PollingTime = 5*1000

jQuery(document).ready(function(){
	if( jQuery("#phone-connection-progress").length == 0)
		return
	
	
	// When MoSMS reintroduces extra info in subscription start smses,
	// remove the <form> and uncomment this for a more elegant solution.
	//setTimeout(pollConnectionStatus, PollingTime)
	
	jQuery("#manual-connect").submit(function() {
		if (jQuery("#phone-connection-progress").hasClass("before_checkout")) {
			connectManually("/pekpc/users/checkout")
			return false
		}
		
		connectManually("/pekpc/grid/")
		return false
	})
})

function blinkElement(element) {
	var flashy = jQuery(element)
	flashy.fadeOut("fast", function() {
		flashy.fadeIn("fast", function() {
			flashy.fadeOut("fast", function() {
				flashy.fadeIn("fast")
			})
		})
	})
}

/*
function pollConnectionStatus() {
	var xhr = jQuery.ajax({
		url: "/pekpc/users/connection_status",
		success: function(body) {
			done = xhr.getResponseHeader("X-Connection-Completed") == "True"
			
			jQuery("#phone-connection-progress").html(body)
			
			if(done) {
				blinkElement(jQuery("#iphone-connection-progress"))
				
				setTimeout(function() {
					document.location = "/pekpc/grid/"
				}, 4000)
				
			} else {
				setTimeout(pollConnectionStatus, PollingTime)
			}
		},
		error: function(req, errorMessage) {
			jQuery("#message").html(req.responseText || req.statusText)
			displayErrorBox(true)
			
			setTimeout(pollConnectionStatus, PollingTime)
		},
		cache: false
	})
}
*/

function connectManually(redirect_to) {
	var xhr = jQuery.ajax({
		url: "/pekpc/users/manual_connect",
		type: "POST",
		cache: false,
		data: {
			code: jQuery("#code")[0].value
		},
		success: function(newBody) {
			displayErrorBox(false)
			jQuery("#phone-connection-progress").html(newBody)
			
			blinkElement(jQuery("#phone-connection-progress"))
			
			setTimeout(function() {
				document.location = redirect_to
			}, 2000)
			
		},
		error: function(req, errorMessage) {
			displayErrorBox(true, req.responseText || req.statusText || "Ett oväntat fel inträffade", true)
		}
	})
}


