jQuery.fn.exists = function() { return (this.length > 0); };
jQuery.fn.replace = function(o) { return this.after(o).remove(); };
jQuery.postJSON = function(url, data, callback) {   return jQuery.post(url, data, callback, "json"); };
Math.base = function(n, to, from) {return parseInt(n, from || 10).toString(to);};
var object_type_names = {unit_acq_lsn:'Acquisition Lesson', unit_ext_lsn:'Extending Thinking Lesson', unit:'Unit', course:'Course', curriculum:'Curriculum',
		folder:'Folder', graphic_organizer:'Document', unit_rubric:'Rubric'};
var uniqueIdCounter=0;
String.prototype.lpad = function(padString, length) {
	var str = this;
    while (str.length < length) str = padString + str;
    return str;
};
String.prototype.rpad = function(padString, length) {
	var str = this;
    while (str.length < length) str = str + padString;
    return str;
};
// 2 hours = 2 * 60 * 1000
var g_session_timeout = 2 * 60 * 60 * 1000;
var g_session_timeout_count_down_interval_id = null;
var g_session_timeout_id = null;

jQuery(document).ready( function() {
	jQuery().ajaxStart(resetSessionTimeout);
	resetSessionTimeout();
	// theme file inputs
	if(jQuery("input[type=file]").filestyle) {
		jQuery('input[type=file]').filestyle({ image: '/images/button/browse_up.png',imageheight : 21,imagewidth : 78,width : 200});
	}
	jQuery("#news_dialog").dialog({	bgiframe: true,
		autoOpen: false,
		modal: true,
		resizable: true,
		closeOnEscape: true,
		position: 'center',
		open: function(event, ui) {
			jQuery(this).parent().addClass('ui-dialog-large');
			jQuery(this).show();
			jQuery(this).dialog('option', 'position', 'center');
		},
		close: function(event, ui) {
			jQuery(this).hide();
		}
	});
	jQuery("#news_dialog_close").click(function(){jQuery("#news_dialog").dialog('close');});
});

function resetSessionTimeout() {
//	alert('resetting');
	if(g_session_timeout_id) clearTimeout(g_session_timeout_id);
	g_session_timeout_id = setTimeout(doConfirmTimeout,g_session_timeout);
}

function doConfirmTimeout() {
	// make sure we aren't on the login page
	if(!jQuery('#checkLogin').exists()) {
		// notify user they will be timed out
		lfAlert({message:'<div style="width:330px;">You will be timed out for inactivity in <span id="confirm_time_out_counter">10</span> seconds</div>', callback:handleConfirmTimeout});
		// start timer to do countdown / handle logout if user does not respond
		if(g_session_timeout_count_down_interval_id) clearInterval(g_session_timeout_count_down_interval_id);
		g_session_timeout_count_down_interval_id = setInterval(doCountDownTimeout,1000);
	}
}

function handleConfirmTimeout() {
	jQuery.unblockUI();
	// ping the server to keep the session alive
	var xml_http_request = jQuery.getJSON('/bin/login/getStatus.php', {}, handleGetStatus );
	lfLoading({message:'Updating session',xml_http_request:xml_http_request});
}

function handleGetStatus(json) {
	jQuery.unblockUI();
	if (json.error == true) {
		doError(json);
	} else {
		resetSessionTimeout();
	}
}

function doCountDownTimeout() {
	var time_left = parseInt(jQuery('#confirm_time_out_counter').html());
	time_left--;
	if(time_left < 1) {
		clearInterval(g_session_timeout_count_down_interval_id);
		jQuery.unblockUI();
		var xml_http_request = jQuery.get('/', {action:'login', sub_action:'logout'}, handleCountDownTimeout);
		lfLoading({message:"Signing Out",xml_http_request:xml_http_request});
	}
	jQuery('#confirm_time_out_counter').html(time_left);
}

function handleCountDownTimeout() {
	if(g_session_timeout_id) clearTimeout(g_session_timeout_id);
	jQuery.unblockUI();
	lfAlert({message:'Your session has been timed out due to inactivity. Click "Ok" to sign in again', callback:handleCompleteTimeout});
}

function handleCompleteTimeout() {
	document.location.href = "/?action=login";
}

function isDataValid(data_type, value, options, form_item) {
	var bool = true;

	switch(data_type) {
		case 'string':
			if(options['max_size'] != 'undefined') {
				if(value.length > parseInt(options['max_size'])) {bool = false;}
			}
			if(options['min_value']  != 'undefined') {
				if(value.length < parseInt(options['min_size'])) {bool = false;}
			}
		break;
		case 'course_id':
			if(options['min_size'] != 'undefined') {
				if(value.length > parseInt(options['min_size'])) {bool = false;}
			}
			if(options['min_value']  != 'undefined') {
				if(value.length < parseInt(options['min_size'])) {bool = false;}
			}
		break;
		case 'unit_id':
			if(options['min_size'] != 'undefined') {
				if(value.length > parseInt(options['min_size'])) {bool = false;}
			}
			if(options['min_value']  != 'undefined') {
				if(value.length < parseInt(options['min_size'])) {bool = false;}
			}
		break;
		case 'numeric':
			var numeric_regex = /^\d+$/;
			if(value.match(numeric_regex)) {
				if(options['max_size'] != undefined) {
					if(parseFloat(value) > parseFloat(options['max_size'])) {bool = false;}
				}
				if(options['min_size'] != undefined) {
					if(parseFloat(value) < parseFloat(options['min_size'])) {bool = false;}
				}
			} else {
				bool = false;
			}
		break;
		case 'email':
			if(!(value.indexOf(".") > 2) || !(value.indexOf("@") > 0)) {
				bool = false;
			} 
		break;
		case 'phone':
			value = value.replace(/[- ().+]/g, "");
			var phone_regex = /^[2-9]\d{2}\d{3}\d{4}$/;
			if(!value.match(phone_regex)) {
				bool = false;
			}
		break;
		case 'radio':
			// make sure something is selected for radio buttons
			if(form_item != undefined) {
				value = jQuery("input[name='" + form_item.name + "']:checked").val();
			}
		break;
	}
	
	if(options['required'] != 'undefined' && options['required'] == 'true') {
		if(value == '' || value == undefined) {bool = false;};
	}
	
	return(bool);
}

function lfBlockUI(msg, object, css_attributes_array) {
	var css_array = {
			position: 'absolute',
			top:  '25%', 
			left: '25%',
			border: 'none', 
	        padding: '15px', 
	        backgroundColor: '#fff', 
	        '-webkit-border-radius': '10px', 
	        '-moz-border-radius': '10px', 
	        color: '#000',
	        cursor:'default'};
	
	// If an array of CSS attributes was passed in, lets add it to our default array...
	if (css_attributes_array) {
		for (css in css_attributes_array) {
			css_array[css] = css_attributes_array[css];
		}
	}
	
	// Combine the default array of information together before contining with the UI block
	var block_array = {
		message: msg, 
		css: css_array};

	// Do the blockage
	if(object){
		object.block({message: msg, 
			css: css_array});
	}
	else {
		jQuery.blockUI(block_array);
	}
}

function lfUnblock(object) {
	if ((object == undefined) || (object == null) || (object == "undefined")) {
		jQuery.unblockUI();
	} else {
		object.unblock();
	}
}
function lfLoading(args, object) {
	var msg = undefined;
	var xml_http_request = undefined;
	var unique_id = generateUniqueID();
	var cancel_html = '<span id="unique_' + unique_id + '" class="loading_dialog_cancel"><img src="/images/button/cancel.png"/> Cancel</span>';
	
	if(typeof(args) == 'object') {
		if(args) {
			if(args.message) msg = args.message;
			if(args.xml_http_request) xml_http_request = args.xml_http_request;
			if(args.block_object) object = args.block_object;
		}
	} else {
		msg = args;
	}
	
	if(!msg) {msg = 'Loading';}
    lfBlockUI(msg+'...<div style="text-align:center; padding:20px;"><img src="/images/ajax-loader.gif" />' + cancel_html + '</div>', object);
    
    // allow user to cancel ajax request
    setTimeout(function(){
	   	jQuery('#unique_'+unique_id).fadeIn('slow').click(function(){
	   		if(typeof(xml_http_request) == 'object') xml_http_request.abort();
	   		lfUnblock(object);
	   		lfAlert({message:'Your request has been cancelled. Since it may have partially executed before you cancelled it you should close Toolbox and reopen it before continuing your work.'});
	   	});
    }, 3000);
}

function lfLoadingSimple(object) {
    lfBlockUI('<img src="/images/ajax-loader.gif" />', object);
}

function lfAlert(args) {
	var msg			= args && args.message	? args.message	: null;
	var callback	= args && args.callback	? args.callback	: null;
	
	jAlert(msg, null, callback);
	jQuery('#popup_ok').addClass('image_button image_button_apply');
	return(true);
}

function lfConfirm(args) {
	var msg			= args && args.message	? args.message	: null;
	var callback	= args && args.callback	? args.callback	: null;
	var title		= args && args.title	? args.title	: null;
	
	jConfirm(msg, title, callback);
	jQuery('#popup_ok').addClass('image_button image_button_apply');
	jQuery('#popup_cancel').addClass('image_button image_button_cancel');
}

function lfPrompt(args) {
	var msg			= args && args.message	? args.message	: null;
	var callback	= args && args.callback	? args.callback	: null;
	var title		= args && args.title	? args.title	: null;
	jPrompt(msg, null, title, callback);
	jQuery('#popup_ok').addClass('image_button image_button_apply');
	jQuery('#popup_cancel').addClass('image_button image_button_cancel');
}

function lfRadioPrompt(args) {
	var msg			= args && args.message	? args.message	: null;
	var callback	= args && args.callback	? args.callback	: null;
	var options		= args && args.options	? args.options	: new Array();
	var value		= args && args.value	? args.value	: null;
	var title		= args && args.title	? args.title	: null;
	jRadioPrompt(msg, value, title, options, callback);
	jQuery('#popup_ok').addClass('image_button image_button_apply');
	jQuery('#popup_cancel').addClass('image_button image_button_cancel');
}

function createUnit(unit_title) {
	var target_ops = jQuery('#target_object_permission_string').val();
	if(unit_title !== null) {
		if (unit_title == "") {
			lfAlert({message:'You must enter a title for the new unit before proceeding.', callback:function(result){
				if(result) {
					lfPrompt({message:'Please enter a title for this new unit', callback:createUnit});
				}
			}});
			return;
		} else if (target_ops == "000002|") {
			lfAlert({message:'Invalid user id detected.'});
			return;
		} else {
			jQuery.getJSON('/bin/explorer/newnode.php', {return_mode:'json', object_type:'unit', open_in_planner:'yes', created:'yes', object_title:escape(unit_title), target_object_permission_string:target_ops}, function(json){
				if (json.error == true) {
					doError(json);
				} else {
					lfLoading();
					document.location = '/?action=unit_planner&decision_name=' + json.decision_name + '&object_id=' + json.object_id;
				}
			});
		}
	}
}

function createLesson(args) {
	var lesson_type = args && args.lesson_type ? args.lesson_type : null;
	if(lesson_type) {
		createLessonStep2(args, lesson_type);
	} else {
		lfRadioPrompt({message:'Choose Lesson Type', options:{acq:'Acquisition Lesson', ext:'Extending Thinking Lesson'}, callback:function(type_result){
			if(type_result !== null) {
				if(type_result === undefined) {
					lfAlert({message:'You must choose a lesson type', callback:function(){createLesson(args);}});
				} else {
					createLessonStep2(args, type_result);
				}
			}
		}});
	}
}

function createLessonStep2(args, type_result) {
	lfPrompt({message:'Enter the Lesson Essential Question', callback:function(leq_result){
		if(leq_result !== null) {
			if(leq_result == '') {
				lfAlert({message:'You must enter the Lesson Essential Question', callback:function(){createLessonStep2(args, type_result);}});
			} else {
				var standalone = args && args.standalone ? args.standalone : false;
				if(standalone != false) {
					jQuery.getJSON('/bin/my_toolbox/create_lesson/create_lesson.php' , {standalone:true, type:type_result, leq:leq_result}, createLessonStep3);
				} else {
					var object_id	= args && args.object_id							? args.object_id	: null;
					var concept_id	= args && args.concept_id || args.concept_id === 0	? args.concept_id	: null;
					
					if(!is_numeric(object_id)) {
						doError({message:'invalid object id: ' + object_id});
						return(false);
					} else if(!is_numeric(concept_id)) {
						doError({message:'invalid concept id: ' + concept_id});
						return(false);
					} else {
						jQuery.getJSON('/bin/my_toolbox/create_lesson/create_lesson.php' , {type:type_result, leq:leq_result, object_id:object_id, concept_id:concept_id}, createLessonStep3);												
					}
				}
			}
		}
	}});
}

function createLessonStep3(json) {
	// open new lesson
	if (json.error == true) {
		doError(json);
	} else {
		lfLoading();
		document.location = '/?action=unit_planner&decision_name=' + json.lesson_type + '&object_id=' + json.object_id + '&id=' + json.id;
	}
}

function tobase36(num) {
	return Math.base(num,36,10).lpad('0',6);
}
function frombase36(num) {
	return Math.base(num,10,36);
}
function is_numeric(value) {
	var numeric_regex = /^\d+$/;
	if(value === null || value === undefined) return false;
	value = String(value);
	return(value.match(numeric_regex));
}
function ucfirst (str) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}
function outputDebug(str){
	var divDebug = jQuery('#divDebug'); 
	divDebug.show();
	divDebug.unbind();
	divDebug.click(function(){divDebug.html('').hide();});
	divDebug.append('<p>' + str + '</p>');
}
function backupEvents(obj) {
	var events = obj.data('events');
	if (jQuery.data(obj[0], 'events_backup') == undefined && events) {
		var events_backup = Array();
		jQuery.each(events, function(key, val) {
			events_backup[key] = Array();
			for(var fn_key in val) { 
				events_backup[key].push(val[fn_key]);
			};
		});
		jQuery.data(obj[0], 'events_backup', events_backup);
	}
}
function restoreEvents(obj, key_list) {
	restoreEventsTo(obj, obj, key_list);
}
function restoreEventsTo(src_obj, target_obj, key_list) {
	var events_backup = jQuery.data(src_obj[0], 'events_backup');
	if(!key_list) key_list = events_backup;
	for(var event_key in events_backup) { 
		for(var fn_key in events_backup[event_key]) {
			target_obj.bind(event_key, events_backup[event_key][fn_key]);
		}
	};
}
function suspendEvents(id) {
	if(id != false) {
		var obj = jQuery('#' + id);
		if(obj.exists()) {
			backupEvents(obj);
			obj.unbind();
		}
	}
}
function resumeEvents(id) {
	if(id != false) {
		var obj = jQuery('#' + id);
		if(obj.exists()) {
			restoreEvents(obj);
		}		
	}
}


function checkAll(field) {
	for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

function unCheckAll(field) {
	for (i = 0; i < field.length; i++)
	field[i].checked = false ;
}

function AnySelected(field) {
	for (i = 0; i < field.elements.length; i++) {
		if (field.elements[i].checked) return true;
	}
	return false;
}
function js_array_to_php_array (a) {
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";

    return a_php;
}
function doError(json, object, extra) {
	var cancel_action	= "jQuery.unblockUI();";
	var retry_action	= "lfLoading({message:'Retrying'});";
	if(json.message == 'changed') {
		doDataChanged(json, object, extra);
	} else {
		if(object) {
			// round about way of getting the current object for the link
			cancel_action	= "jQuery('#" + object.attr('id') + "').unblock();";
			retry_action	= "object=jQuery('#" + object.attr('id') + "');lfLoading({message:'Retrying',block_object:object});";
		}
		lfBlockUI('<p><img src="/images/exclamation.png" width="16" height="16"/> An error has occured. (' + json.message + ')</p><p><input type="button" value="Retry" class="image_button image_button_retry" onclick="' + retry_action + 'doError(json);"/><input type="button" value="Cancel" class="image_button image_button_cancel" onclick="' + cancel_action + '"/></p>', object);
	}
}
function getObjectTypeName(object_type) {
	if(object_type_names[object_type]) {
		return(object_type_names[object_type]);
	} else {
		// default wording if not defined
		return('item');
	}
}
function generateUniqueID() {
	uniqueIdCounter++;
	return uniqueIdCounter.toString(16);
}