window.showAlert = true;

$(function() {
	preload('ajax-loader');

	fixAcademics();
	
	bindEvents();
	bindOutstanding();

});

$('body').ajaxError(function(event, request, settings){
    $('#loading').fadeOut('slow',function(){$('#loading').remove()});
});


function bindOutstanding() {
	$('[id ^= del-out-task-]').bind('click', function () {


		if ($(this).attr('checked') == true) {
			if (!confirm('Are you sure it is OK to mark this task as complete?')) {
				return $(this).attr('checked', false);
			} 
		}

		_id = $(this).attr('id').replace('del-out-task-', '');

	//	siblings = $('#out-task-' + _id).siblings();
	//	$('#out-task-' + _id).remove();

		get('/profile/sequence-ajax/remove-event/', {
			'event_id' : _id
		});

	//	if (siblings.length == 0) {

	// remove outstanding task from the list
	//	$('#time-period-' + _id).remove();

//		}

	});
}

function bindEvents() {
	$('[id ^= remove-event-]').bind('click', function () {

		if ($(this).attr('checked') == true) {
			if (!confirm('Are you sure it is OK to mark this task as complete?'))
				return false;
		}
	//	$(this).attr('disabled', true);

		get('/profile/sequence-ajax/remove-event/', {
			'event_id' : $(this).val()
		});

		getOutstanding();
		getReminders();

	});
}


function preload(image) {
	pic = new Image();
	pic.src = '/images/' + image;

	delete pic;
}

function get(url, settings) {
	var ajaxMessage;

	time = new Date().getTime();

	ajaxRequest = $.ajax({
		url : url + '?' + time,
		async : false,
		data : settings,
		cache : false,
		type : 'POST',
		dataType : 'html'
	});

	response = ajaxRequest.responseText;

	if (response == '')
		response = '{}';

	result = eval('(' + response + ')');

	return result;
}

/**
 *  if under academics (left col of profile related pages) section no any records so just hide this from view
 */
function fixAcademics() {
	
	if ($.trim($('#academics-content').html()) == '') {
		$('#academics').remove();
		
	}

}

function ajax(url, settings, async) {
    var ajaxRequest;

	time = new Date().getTime();

	ajaxRequest = $.ajax({
		url : url + '?' + time,
		async: false,
		data: settings,
		cache: false,
		type: 'POST',
		dataType: 'html'
	});

	return ajaxRequest.responseText;
}

function makeJson(object) {

	var length = object.length;

	val = '{';
	iteration = 0;

	for (i in object) {
		val += '"' + i + '" : ' + (typeof object[i] == 'object' ? makeJson(object[i]) : ('"' + clean(object[i]) + '"')) + (iteration == length ? '' : ', ');

		iteration ++;
	}

	val = val.substring(0, val.length - 2);
	val += '}';

	return val;
}

function clean(text) {
	text = text.replace(/}/g, '');
	text = text.replace(/{/g, '');
	text = text.replace(/'/g, '&quot;');
	text = text.replace(/"/g, '&quot;');

	return text;
}

function dublicate(elem) {

	iteration = (typeof iteration == 'undefined') ? 1 : iteration;

	clone = $('#' + elem).clone();
	clone_id = clone.attr('id').replace('-0', '');;

	clone.attr('id', clone_id + '-' + iteration);

	clone.find('input, textarea, select').each(function () {
		$(this).val('');

		if ($(this).attr('type') == 'checkbox')
			$(this).attr('checked', false);

		id = $(this).attr('id').replace('-0', '');

		$(this).attr('id', id + '-' + iteration);
	});
	
	clone.iteration = iteration;

	iteration++;

	return clone;
}

function getValues(form) {
	data = new Object();

	errors = '';

	i = 0;
	$('[id ^= ' + form + ']').each(function(){
		var vals = new Object();

		$(this).find('input, textarea, select').each(function(){
			key = $(this).attr('id').replace(/-[\d]+/, '');

			// podporka
			// FIXME
			key = key.replace('-', '_');
			key = key.replace('-', '_');

			if (($(this).attr('type') == 'checkbox')){
				if ($(this).attr('checked'))
					vals[key] = $(this).val();
			} else {

				// get value
				t = $.trim($(this).val());

				// if empty
				if (t == '') {

					// mark borders with red color and assign error
					errors = 'Please, fill in all fields!';
					$(this).addClass('input-error');

					// unmark on click
					$(this).bind('click', function () {
						$(this).removeClass('input-error');
					});

				} else { 
					vals[key] = $(this).val();
				}
			}
			
		});

		data[i] = vals;
		i++

		delete vals;
	});

	// if errors throw an exception to prevent future execution of code.
	if (errors)
		//throw (errors);
		return data;
	else
		return data;
	
}

// remove form by id
function remove(elem) {
	$('#' + elem).remove();
}

function reset(elem) {
	$('#' + elem).find('input, textarea').each(function () {
		$(this).val('');
	});
}

function gameOver (elem, text) {
	$('#' + elem).hide();
	$('#question-text').html(text);
	$('#add-more').hide();
	reset(elem);

	$('#proceed').text('Continue').unbind('click').bind('click', function () {
		getStep($('#step-yes').val());
	});
}


function fixQuestion() {
	$('#qtitle').remove();
}

var request;

var data;

/**
* Load XMLDoc function
* Здесь в качестве параметра url при вызове мы должны указать
* backend-скрипт, который, собственно, и получит данные с сервера
*/

function load(url) {
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
    request.onreadystatechange = processRequestChange;
    request.open("GET", url, false);
    request.send(null);
  } else if (window.ActiveXObject) {
    request = new ActiveXObject("Microsoft.XMLHTTP");
    if (request) {
      request.onreadystatechange = processRequestChange;
      request.open("GET", url, false);
      request.send();
    }
  }

  return request.responseText;
}

/**
* Get request state text function
*/
function getRequestStateText(code) {
  switch (code) {
    case 0: return "Uninitialized."; break;
    case 1: return "Loading..."; break;
    case 2: return "Loaded."; break;
    case 3: return "Interactive..."; break;
    case 4: return "Complete."; break;
  }
}

function processRequestChange(a) {
abortRequest = window.setTimeout("request.abort();", 10000);
// если выполнен
	if (request.readyState == 4) {
		clearTimeout(abortRequest);
		// если успешно
		if (request.status == 200) {
			a = request.responseText;
		}
	} else {
	  //alert("Не удалось получить данные:n" + request.statusText);
	}
}
