/**
 *	Login Script by Jin Jun
 *	It simulates a popup window within an internet browser, and verifies login information through zboard system
 */
 
$(document).ready(
	function(){ JJ_LoadLogin(); }
);

function JJ_LoadLogin()
{
	String.prototype.between = function(prefix, suffix) {
		s = this;
		var i = s.indexOf(prefix);
		if (i >= 0) {
			s = s.substring(i + prefix.length);
		} else {
			return '';
		}
		
		if (suffix) {
			i = s.indexOf(suffix);
			if (i >= 0) {
				s = s.substring(0, i);
		
			} else {
				return '';
			}
		}
		
		return s;
	}
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
	String.prototype.ltrim = function() {
		return this.replace(/^\s+/,"");
	}
	String.prototype.rtrim = function() {
		return this.replace(/\s+$/,"");
	}

	
	var LoginPopup = document.createElement('div');
	var LoginContent = document.createElement('div');
	var windowWidth = $( window ).width();
	var windowHeight = $( window ).height();
	
	var date = new Date();
	var timestamp = date.getTime();
	
	$(LoginPopup).css({ 'width': '400px', 'height': '250px', 'position': 'absolute', 
						'top': '150px', 'left': ((windowWidth - 400) / 2) + 'px', 
						'display': 'block', 'background-color': 'white', 'border': '1px solid #333333', 
						'text-align': 'center'});
	$(LoginContent).css({ 'overflow': 'visible', 'margin': 'auto'});
	$(LoginPopup).hide();
	
	$('body').append(LoginPopup);
	$(LoginPopup).append(LoginContent);
	
	$('a#upcs_login').click(function(c){
		c.preventDefault();
		$.ajax({
			beforeSend: function() {
				$(LoginContent).html("Loading...");
				$(LoginPopup).show();	
			},
			url: "upcs_login.php?_t=" + timestamp, 
			error: function() {
				$(LoginContent).html("Error: Please try again.");
			},
			success: function(html) {
				$(LoginContent).html(html);
				PrepareSubmit();				
			}
		}); 
	});
	
	function PrepareSubmit()
	{
		$('#form_login').submit( function(c){
			c.preventDefault();
			timestamp = date.getTime();
			var dataString = $('#form_login').serialize();
			$.ajax({
				beforeSend: function(){
					$(LoginContent).html("Loading...");
				},
				type: "POST", 
				url: "upcs_login.php", 
				data: dataString, 
				success: function(html) {
					var status = html.between("[login_status]", "[login_status_end]");
					if(status.trim() == "success")
					{
						window.location = "upcs_cur_index.php";
						$(LoginContent).html("Redirecting.");
					} else {
						$(LoginContent).html(html);
						PrepareSubmit();						
					}
				}
			});
		});
	}
}