var questionsList = "questionsList";

var BUTTONS = URL_PATH + "/includes/images/buttons";

function signup_school_switch(value){
	var show = value != "" ? "none" : "block";

	$("schoolFields").style.display = show;
}

function check_all(formName){
	var form = document.forms[formName];
	for(var i = 0; i < form.elements.length; i++) {
	    var e = form.elements[i];
	    if(e.type=='checkbox' && (!e.disabled)){
	    	e.checked = true;
	    }
	}
}

function uncheck_all(formName){
	var form = document.forms[formName];
	for(var i = 0; i < form.elements.length; i++) {
	    var e = form.elements[i];
	    if(e.type=='checkbox' && (!e.disabled)){
	    	e.checked = false;
	    }
	}
}

function order_questions(surveyID){
	$("questionsForm").formAction.value = "order";
	base_ajax("contents", ADMIN_PATH + "/questions/list.php", "surveyID=" + surveyID, "questionsList = new Sortables($(questionsList));");
}

function submit_questions_form(){
	var items = get_list_order("questionsList", "oid");
	//alert(items.join(","));
	$("questionsForm").order.value = items.join(",");
	$("questionsForm").submit();
}

var mouseX, mouseY;

function confirm_delete(formID){
	$(formID).formAction.value = "delete";
	$(formID).submit();
}


function escape_values(string){
	var str = "";
	var parts = string.split("&");
	for(var i = 0; i < parts.length; i++){
		var newparts = parts[i].split("=");
		if(i != 0){
			str += "&";
		}
		str += newparts[0] + "=" + escape(newparts[1]);
	}
	return str;
}

function evaluate_js(response){
	// first include any files that are needed
	//evaluate_js_headers(response);
	
	// now find the scripts that are needed
	var startTag = "<script type='text/javascript'>";
	var endTag = "</script>";
	
	var pos = response.indexOf(startTag);
	
	while(pos > -1){
		var endPos = response.indexOf(endTag, pos + 1);
		if(endPos > -1){
			var start = pos + startTag.length;
			var js = response.substr(start, endPos - start);
			//alert(js);
			eval(js);
			pos = response.indexOf(startTag, endPos);
		}
	}
}

function filter_adminList(module, id, queryStr){
//default params
	if (typeof(module) == 'undefined' || typeof(id) == 'undefined')
		return 0;
	base_ajax(id, MODULES_URL + "/"+module+"/controllers/adminList.php", "justListItems=true&"+queryStr);
}

function filter_search(form, id){
	var queryStr = form.toQueryString();
	
	base_ajax(id, form.redirectURL.value, "mode=search&" + queryStr);
	return false;
}

function form_field_change(value){
	$("formFieldOptions").style.display = (value == "select" || value == "multiple") ? "block" : "none";
}

function get_cookie(cookiename){
	var allcookies = document.cookie;
	var pos = allcookies.indexOf(cookiename + "=");
	if(pos != -1){
		var start = pos + (cookiename.length + 1);
		var end = allcookies.indexOf(";", start);
		if(end == -1){ end = allcookies.length; }
		var value = allcookies.substring(start, end);
		value = unescape(value);
		return value;
		
	}else{
		return false;
	}
}

function get_cookie_filter(module) {
	return get_cookie('cms_'+module+'_filter'); 
}

function get_list_order(theList, attributeName){
	var ar = new Array();
	var children = $(theList).childNodes;
	// clear the styles first
	for(i = 0; i < children.length; i++){
		if(children[i].nodeName == "LI"){	// make sure it is a list tag
			if(children[i].getAttribute(attributeName) != null){
				ar.push(children[i].getAttribute(attributeName));
			}
		}
	}
	return ar;	// return the array with the order
}

function go_to_anchor(anchorName){
	var url = window.location;
	url += "";
	var pos = url.indexOf("#" + anchorName);
	if(pos > -1){
		var anchor = url.substring(pos);
		//alert(anchor);
		window.location.href = anchor;
	}
}


function popUp(URL,width,height) {
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	var size = "width=" + width + ", height=" + height +" ,left=" + left + " ,top="+ top;
	insert_window = window.open(URL, 'popup', 'toolbar=0,scrollbars=1,statusbar=0,menubar=0,resizable=1,'+size);
//	insert_window = window.open(URL, 'insert_window', 'toolbar=1,scrollbars=1,statusbar=1,menubar=1,resizable=1,'+size);
	insert_window.focus();
}

function resize_content_area(){
	var size = Window.getSize();
	var headerSize = $("header").getCoordinates();
	//alert(headerSize.height);
	var adjustment = 60;
	var newSize = (size.size.y - (headerSize.height + adjustment));
	
	$("main").style.height = newSize + "px";
	//$("list").style.height = newSize + "px";
	$("listController").style.overflow = "auto";
	$("listController").style.height = (newSize - adjustment - 50) + "px";
}

function resize_elements(){
	resize_content_area();
}

function change_grading_question(){
	$("questionList").innerHTML = "<h4>Searching...</h4>";
	//alert(ADMIN_PATH + "/grading/fieldList.php");
	base_ajax("questionList", ADMIN_PATH + "/grading/fieldList.php", "surveyQuestionID=" + $("questionSelect").value, "");
}

function say_hi(){
	alert("hi");
}

function select_school(id, name){
	$("selectedSchool").innerHTML = "<h3>" + name + "<a href=\"javascript:use_school(" + id + ")\"><img src='" + BUTTONS + "/addExistingSchool.png' alt='Add Existing School' class='addSchoolButton' /></a></h3>";
}

function select_person(id, name){
	$("selectedSchool").innerHTML = "<h3>" + name + "<a href=\"javascript:use_person(" + id + ")\"><img src='" + BUTTONS + "/combinePeople.png' alt='Combine People' class='addSchoolButton' /></a></h3>";
}

function use_school(id){
	$("addSchool").schoolID.value = id;
	$("addSchool").submit();
}

function use_person(id){
	$("addPerson").combinePersonID.value = id;
	$("addPerson").submit();
}

function add_school(){
	$("addSchool").submit();
}

function set_cookie(name, value, domain, expires){
	if(expires == undefined){ 
		var days = 1; //default life of cookie, in days
		expires = new Date();
		expires.setTime( expires.getTime() + (days * 1000 * 60 * 60 * 24) ); //foolproof, avoids "if (day+1) > 31" cases
	}
	var str = name + "=" + value +"; path=/; expires=" + expires.toGMTString();
	str += ((domain)  ? "; domain=" + domain : "");
	document.cookie = str;
}

function set_cookie_filter(module, val) {
	set_cookie('cms_'+module+'_filter', val); 
}

function set_height(id, h){
	$(id).style.height = h + "px";
}

function set_left(id, h){
	$(id).style.left = h + "px";
}

function set_top(id, h){
	$(id).style.top = h + "px";
}

function set_width(id, w){
	$(id).style.width = w + "px";
}

function show_form_errors(form, jsonObj){
	var fields = jsonObj.fields;
	// reset the fields
	var x = 0;

	for(var i = 0; i < fields.length; i++){
		if($("field_" + fields[i].field) != undefined){
			var temp = $("field_" + fields[i].field).className;

			$("field_" + fields[i].field).className = temp.replace("warning", "");
		}
		
		// reset the error message
		if($("message_" + fields[i].field)){
			$("message_" + fields[i].field).innerHTML = "";
		}
	}
	
	var errors = jsonObj.errors;
	for(var i = 0; i < errors.length; i++){
		// change style to warning
		//alert(errors[i].field);
		if($("field_" + errors[i].field) != undefined && $("field_" + errors[i].field).className.indexOf("warning") < 0){
			$("field_" + errors[i].field).className += " warning";
		}
		
		// output the error message
		if($("message_" + errors[i].field)){
			$("message_" + errors[i].field).innerHTML = errors[i].message;
		}
	}
}

function show_school_results(){
	
}

function do_question_delete(id){
	$("questionDelete").questionID.value = id;
	$("questionDelete").submit();
}

function show_question_delete(id){
	showHide("confirmDelete" + id);
}

function showHide(id){
	var elem = $(id);

	//alert(elem.className+ "," + id);
	if(elem.style.display == "none" || elem.style.display == ""){
		showHideDivs(id, "show");
	}else{
		showHideDivs(id, "hide");
	}
}

function showHideDivs() { //v6.0
	var i,p,v,obj,args=showHideDivs.arguments;
	for (i=0; i < (args.length-1); i+=2) {
		if((obj = $(args[i])) != undefined){ 
			v=args[i+1];
			if (obj.style) { 
				obj=obj.style; 
				v=(v=='show')?'block':(v=='hide')?'none':v; 
			}
			obj.display=v;
		}
	}
}

function try_text_focus(form, field){
	if($defined($(form))){
		eval("var field = $('" + form + "')." + field + ";");
		if(field != undefined){
			field.focus();
		}
	}	
}

function upper_case_first(text){
	return text.substr(0, 1).toUpperCase() + text.substr(1);
}

function validate_require_all(form) {
	var readyVar = true;
	for (i=0; i<form.elements.length; i++) {
		if (form.elements[i].type != "hidden" && form.elements[i].type != "submit")
			if (form.elements[i].value=="") {
				form.elements[i].parentNode.className += " warning";
				readyVar = false;
			}
	}
	return readyVar;
}

function validate_reset_password(form){
	var errorMessage = false;
	if(form.newpassword.value == "" || form.newpassword2.value == ""){
		errorMessage = "Please enter your new password twice.";
	}
	else if(form.newpassword.value != form.newpassword2.value){
		errorMessage = "Passwords do not match. Please enter your new password twice.";
	}
	
	if(errorMessage == false){
		form.submit();
	}else{
		$("forgotPasswordMessage").innerHTML = errorMessage;
	}
}

String.prototype.reverse = function(){
	var newString = "";
	var counter = this.length;
	
	for(var i = counter; i > 0; i--){
	   newString += this.substring(i - 1, i); 
	}
	
	return newString;
}



// handle memory leaks
Function.prototype.closure = function(obj){
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};
